CSC 230 Exam 1

Pataasin ang iyong marka sa homework at exams ngayon gamit ang Quizwiz!

Make this a macro int area = 42;

#define AREA 42

header to use character feature

#include <ctype.h>

Header to use boolean feature

#include <stdbool.h>

for a 32 bit, what is the problem with this int x = -2147483648; x = -x;

-2147483648 is max valid negative value the positive value is one less than it

Describe the process of executing C Programs

A C compiler translates each source file directly into an object file containing native machine code for the target processor. During program execution, a linker combines these object files, along with any necessary library files, to create a single executable program. This executable can then be loaded into memory and run directly on the hardware, starting from the main function.

Definition

A declaration that also allocates memories (variables) or provides implementation (functions).

Flow-of-Control for Break Statement

Break lets you bail out on the innermost loop early

Boolean Variable C98 vs C99

C98 was the default where 0 is false and any other value would be true. It used int rather than bool keyword Ex: int isspace(int); C99 was added which created bool, true, and false keywords. Uses the header, #include <stdbool.h>

Describe the difference between a centralized and decentralized revision control system, and where does git and github follow under

Centralized revision control system only lets one person check out a file for editing, decentralized revision control systems let multiple people rent out copies of the project. Git and github are decentralized.

What is an IDE

Integrated development environment - a piece of software that allows you to edit, compile, link, execute, and debug a program without leaving the environment (like command line requires)

Can you bypass it with cast? like: char c = 'H'; int i = 273; char *cPtr; int *iPtr; cPtr = (char *) &i; iPtr = (int *) &c; *cPtr = 'J'; *iPtr = 291;

No, cast will just suppress compiler warnings, but it will just create nonsense for memory Other words pointer variables should only point to the same type of variable

Does strings need & for scanning?

No, since it is a char array and char arrays are automatically passed by reference

Do pointers look like 12 or 26 in memory addresses?

No, they are usually more bits depending on architecture. On a 32-bit machine it will look like 0xAC8B2E38 or on a 64-bit machine like 0xAC8B2E38F3274E38

Token

Represents the smallest individual unit (does not include white space and comments) - An identifier (e.g., a variable or a function name) - A keyword (e.g., void or while) - A literal value (e.g., 3.1415, or "Hello World") - An operator (e.g., *, ++ or >=) - An explicit separator (e.g., (, } or ;)

(gdb) run Starting program: /home/brandon/git/230_CSC/buggy [Thread debugging using libthread_db enabled] Using host libthread_db library "/lib/x86_64-linux-gnu/libthread_db.so.1". Program received signal SIGFPE, Arithmetic exception. 0x00005555555551e3 in ethel (a=0, b=10) at buggy.c:46 46 i += 100 % a; (Exception received) Which line did the crash occur on, and what were a and be equal to?

The crash happens on line 46 when a = 0 and b = 10.

Whats wrong with this function that returns a pointer as return type int *getLarger( int a, int b ) { if ( a > b ) return &a; else return &b; } write the code to fix it

The local variables a and b go out of scope resulting in it returning random stack space

Common Platform

The platform used by an organization to increase portability for their work environment.

Decentralized Revision Control System

There's a central repository where your project's repository lives and each user can copy the whole project and modify it and commit (so you aren't limited to one user per file for editing) An example is git and github

Centralized Revision Control System

There's a server where your project's repository lives and each file in it can be checked out by one user to be edited

True/False: Automatically convert types lower than int to int

True

What does long long + float equal?

float

Terminal command to active gdb to myProgram.c

gcc -Wall -std=c99 -g myProgram.c -o myProgram gdb ./myProgram

Write terminal command to add a break on 34 and run the code to there, then list the code around it, change variable i to 82 then run the program to the end and quit it. Now run file input-file.txt on it and have the output sent to file output-file.txt

gcc -Wall -std=c99 -g myProgram.c -o myProgram gdb ./myProgram (gdb) break 34 (gdb) run (gdb) list 34 (gdb) set variable i=82 (gdb) run (gdb) quit (gdb) run < input-file.txt > output-file.txt

Write this in expanded form then answer the questions for it: int i, *ip; double d, *dp; char c, *cp; Which of these make sense? // Pretend we initialize all of these i = *cp; dp = &i; *cp = *dp; &i = ip;

int i; int * ip; double d; double *dp; char c; char *cp; These works since values can convert i = *cp; *cp = *dp; This won't work since different point types can't hold eachother dp = &i; This fails since you can NEVER move where a variable lives &i = ip;

dereference operator

inverse of address variable where it references the value of a pointer and has keyword * "give me the value of this address" int a = 10; int * ptr = &a; // pointer int x = *ptr; // gets value of pointer which is 10 Can also be used to change a value *ptr = 7; now a equals 7

How can you tell a signed overflow?

neg + neg = pos pos + pos = neg neg - pos = pos

Can you do the following operations? list2 = list1; list 3 = list1 + list2;

no.

preprocessor

operates on source code before compiler sees it, this includes headers and expands macros Preprocessor Directive: Starts with #, tells compiler to read the file prior to translating rest of code

Standard Library

pre-defined functions, macros, and types provided by the C language, not automatically imported where you have to manually call the header files

Given the following variable declarations in C: float w, x = 2.6087; int y = 15; char z = 'g'; long m; Write a single statement to read in values for w and m from standard input Write a single statement to output the values of x and y on separate lines, format x to be 2 decimal values output of printf("the value of z is: %c", z++);

scanf("%f%ld", &w, &m); printf("%.2f\n%d", x, y); the value of z is: g (this is g and not h since the ++ is after not prior to g since it adds after it prints it)

How many bits are the following: signed char unsigned char signed short unsigned short signed int unsigned int signed long unsigned long signed long long unsigned long long

signed char 8 unsigned char 8 signed short 16 unsigned short 16 signed int 32 unsigned int 32 signed long 64 unsigned long 64 signed long long 64 unsigned long long 64

Explain the types for x and y int * x, y;

x is a pointer and y is a int to make both a int you would have to type int * x, * y;

What is partial initialization

you initialize some values then the rest are automatically initialized to 0 Ex: int a[5] = {7, 14}; Other words a = {7, 14, 0, 0, 0}

Pointer to null

#include <stddef.h> any pointer can be assigned to null and evaluates to false DON'T TRY TO DE-REFERENCE IT used for files, sorting, and pass-by-reference

What is the header for printf, scanf, int getchar, int putchar, and defines EOF

#include <stdio.h>

What is the header for return EXIT_SUCCESS and EXIT_FAILIURE, and void exit(#)?

#include <stdlib.h>

header to use strings

#include <string.h>

address-of operator

&var; extracts address of variable

How many bytes is a pointer?

8 bytes

What does gcc do? What does -o do? What does -c do?

Gcc tells the program to compile -o sets the name of the output file -c tells it to compile src file into object file (necessary to compile files independently and link later, if you dont use c then it will make the file an executable)

Put the following in order for the C compilation process and briefly explain them: Lexical Analysis, Assembling, Linking, Code Generation, Parsing, Preprocessing

Preprocessing: Occurs before the actual compilation process and inserts code from headers and replaces macro names with values Lexical Analysis: breaks source code into tokens Parsing: builds a parse tree from the tokens and detects errors Code generation: translates parse tree into assembly code Assembling: Turns assembly code into object code Linking: follows compilation process and combines object code and libraries to create a single executable program (a.out by default)

What are the differences between signed and unsigned?

Signed supports negative and positive numbers while unsigned only supports positive. unsigned supports higher numbers than signed since it is same size, for example signed char supports up to 127 while unsigned supports up to 255 Variables are declared signed by default

What happens if you don't initialize stack allocated arrays?

Stack allocated arrays contain previous memory (garbage) if you don't initialize it. You can fill the values in one at a time to fix it a[0] = 1; a[1] = 2; etc...

How do you read types?

Start at the variable name and work out based on precedence

Statically-Allocated Array

Statically-Allocated array located outside function and it retains values between function calls This is preferred for large arrays since the static memory space is larger than the stack space.

Redirecting Standard Streams

Streams can be redirected to or from files. Input from file: $ myProgram < input_file.txt Output to file: $ myProgram > output_file.txt

Can you switch between constant and non-constant for parameter input?

Yes if you use a cast, but for a parameter you can't remove the const (since it's a promise to not to modify the value)

pointer variable

a variable whose content is a memory address * keyword int * ptr; can ONLY hold the memory location of the specified type

What is the name of the executable file produced when a C source code file is compiled?

a.out

What does long - unsigned long equal?

unsigned long

What types does C guarantee how they should be represented?

unsigned types

Identifiers

variable, functions, or other names. We choose these names but have to follow rules Can only consist of letters, digits, or underscores Case sensitive, myValue is not the same as myvalue A variable can't start with a digit (so x2_ and x2 are valid but 2_x isn't)

Write the command line to compile and link main.c and helper.c simultaneously to main Explain Compile-Time and Link-Time errors that can result from this

$ gcc -Wall -std=c99 -g main.c helper.c -o main Compile-Time: You forget to declare a extern value or prototype from the header file "implicit declaration of ..." Link-Time: You forget to provide a definition in the source code (so it is a empty function/ macro) "undefined reference to ..."

write the command line input to do the following for a program called myProgram Set up gdb for it Add a break for someFunctionname Add a break on line 25 Run the program with I/O redirection with input, input.txt, to a file called output.txt Now run the program regularly Now print the value for the variable i in the program Change the value of i to 5 Print the stack trace Look at surrounding source code for line 70 Resume running code Run the program until line 50 Up-oh you ran into a bug, kill the program exit the current program

$ gdb ./myProgram (gdb) break someFunctionName (gdb) break 25 (gdb) run <input.txt> output.txt (gdb) run (gdb) print i (gdb) set variable i = 5 (gdb) backtrace (gdb) list 70 (gdb) continue (gdb) run until 50 (gdb) kill (gdb) quit

printf() What are the following % %c %d %ld %f %s

% Comes before conversion specifier %c char %d decimal %ld long int %f float or double %s string

* has three jobs in C It's used for multiplication It's used to de-reference pointers It creates new types, explain this third point

* can be used to create infinitely many new types

void clamp(int *x, int bound) { if ( *x > bound ) *x = bound; } int *p; int b = 5; clamp(p, b); What is the issue with this?

*p is uninitialized so it will point to a random int in memory you can fix it by either using a direct address clamp(&c, b); or making p point to a address int *p = &c; clamp(p, b);

Explain importance of addresses for: Reading, modifying, access, and dynamic allocation.

- know where things are stored allowing you to read and modify values - let you access nearby values in memory (how arrays work) - dynamic memory allocation REQUIRES you to work with addresses

What do the following mean -Wall -std=c99 -g

-Wall tells compiler to producd all warning messages -std=c99 tells compiler we are using standard version of c99 -g tells it to include debugging information

Write the binaries for 0: 1: 2: 3:

0: 00000000 1: 00000001 2: 000000010 3: 00000011

Variable a is stored in bytes 12-15 Variable b is stored in bytes 26-29 int a = 1; int b = 5; int * ptr = &a; *ptr = 10; ptr = &b; ++*ptr; 1) what does a equal? 2) what does b equal? 3) what does ptr equal?

1) what does a equal? 10 2) what does b equal? 6 3) what does ptr equal? 26

Write the following values for 8 bit using two's complement: 1 -1 5 -5

1: 0000 0001 -1: 1111 1110 + 1 = 1111 1111 5: 0000 0101 -5: 1111 1010 + 1 = 1111 1011

Stream

A file or device we can use to read or write, has 3 default types: input, output, and error. Standard input: input from terminal Standard output: output to terminal Standard error: output to terminal

Strings

A string is a sequence of character codes stored as a char array, strings auto put a null terminator at the end of \0, this takes up a character though so char string[10] can only store 9 characters Ex: char myString[] = "Hello, World"; The null terminators purpose is to help with iteration where it marks the end of the string's body (not size, so if you have unused space it will come prior to it), this helps with iteration, also due to the terminator we don't need to give the size of the array when processing it in a function

What is a Revision Control System

A tool used in software development to manage changes to source code efficiently. All revision control systems define a repository where master copy of project files are maintained, contain working trees, and a commit mechanism

ASCII

ASCII: American Standard Code for Information Interchange, standard for what numbers go with each symbol, the table groups similar symbols together, for example controls, lower-case, capitals, and digits. The table also doesn't store all 256 numbers, the remaining values are application/ platform dependent.

Statically-Allocated Memory

Allocated at program start-up and lifetime of whole program

Example of Arrays being passed by reference

Arrays are "passed-by-reference} so you can use them as a parameter, and if the value is modified in the function then the changes will remain even after the function returns The array size in parameter does not need to be listed, sizeof() doesn't work in the function for it though so you usually use a secondary parameter for length

Parameters for array

Arrays are "passed-by-reference} so you can use them as a parameter, and if the value is modified in the function then the changes will remain even after the function returns You can let the compiler determine the array size for the row dimension, not the columns. This is because the column dimension is used by the compiler to write the index code. (Inner-most parameter can be blank)

What happens if you go out of bounds in an array

Arrays have no bound checks in C, so if you access a non-existent element in an array a[-2] it will return a value in memory from the stack, and if you modify the value then you can overwrite memory for other variables in your program! And since the memory may not be used instantly, you may not spot it instantly which can make debugging tough. (hackers can use this to change the data or behavior of a program) Buffer overflow: A program writes over memory past the end of an array

Hexadecimal

Binary Values 0-15 using 4 bits a hex char. 0-9 are represented by 0-9 10-15 represent A-5 When you have a number that isn't 4 bits, it will add 0 prior to it

Disadvantages of Makefiles

Build instructions in shell hurt portability Other tools perform the same kind of task like CMake, Ant, Maven, etc. which are less manual

Pass-By-Reference explained using pointers

By passing pointers to functions we can let them modify the values pointed to

How can you cheat the const-ness parameter?

By type casting it away inside the function, const is NOT a security feature but more of a "promise" between programmers to coorperate

Which of the following are C/Java, and describe what it is: Imperative language Procedural Object Oriented

C and Java are Imperative (uses a sequence of instructions) C and Java are Procedural (goes step by step and focuses on organizing code into methods/ functions) C is NOT Object Oriented where it does not use classes and it has a clear separation between functions and data, Java is Object Oriented!

Compare C and Java for the following: Security Memory Allocation Language-type Initialization

C has very little security, but gives a lot of control over memory allocation and deallocation compared to Java. Java is a high-level language while C is a intermediate language. Java auto-initializes variables, but C doesn't and sets them to whatever is left-over in memory.

Static Typing vs Dynamic Typing

C uses Static typing where every variable must be declared as a type that cannot change, this is more efficient and catches errors during compilation rather than at runtime Python uses dynamic typing where variables can change their type as the program runs, this is more flexible.

Character Variable: range: Initialization:

Character Int Range: a char variable holds a small integer value from 0-255 and each one represents a unique symbol Initialization: can be initialized using ASCII ( char ch = 84; ) or using a literal (char ch = 'T')

What does the compiler do for size if given a list like int a[] = {7, 14, 21, 28, 34}

Compiler can determine the size automatically if you give it a list

Makefiles

Consist mainly of rules, they give a target (something that can be built), a list of prerequisites (indicates what the target needs and when it must be rebuilt) and a list of shell commands (instructions for rebuilding the target from its dependency) Make has default rules for building common targets from sources Target file.o usually depends on target.c with gcc -c used to build it Objects can be linked to build executable targets

Flow-of-Control for Continue Statement

Continue lets you skip the rest of the innermost loop's iteration

If you have two of the same signed-ness what do you do?

Convert to the higher type

If both operands are floating-point type what should you do?

Convert to the wider one

What do you do if one operand is floating point type and the other isn't?

Covert to the floating type

Reading symbols from ./loopy... (gdb) run Starting program: /home/brandon/git/230_CSC/loopy [Thread debugging using libthread_db enabled] Using host libthread_db library "/lib/x86_64-linux-gnu/libthread_db.so.1". (Program freezes) What should you do when the program freezes?

Ctrl+C

What is GDB?

Debugger for low-level languages that can be ran in terminals. Usually built into IDE tools.

Storage Class Static (global) vs Auto (local)

Determines a variable's lifetime, where it's allocated, and how it is initialized Static Storage (Global Variables): Automatically initialized to zero, if you do initialize them you must use a constant expression Auto Storage (Local Variables): Don't automatically initialize and the value will be whatever is left over in that part of stack memory. If you do initialize them then the value is evaluated each time control passes the declaration Static keywords can give a variable a lifetime of a global variable but scope of a stack variable. The value is stored in memory the whole life cycle of the program execution but can only be accessed when in scope

Binary Numbers as Octal

Each digit is 3 bits and it represents 0-7

Explain how addresses are stored in memory

Each memory location is a byte and each byte has a address. Values that need more than a byte will store multiple addresses that are joined together.

Positional number system for unsigned values in binary

Each place to the left uses base 2 with 0 meaning off and 1 on (so you only add 1's)

EOF

End of File, and is a amcro defined in #define <stdlib.h>

Ternary operator

Expression ? outcome1 : outcome2 Acts as if statement where expression prior to ? is evaluated, if true then outcome 1 occurs, else outcome 2 will occur

True/False: variables in C auto-initialized

False

Write the command line to separately compile and link main.c and helper.c separately to main

First use -c to tell it to compile the code $gcc -Wall -std=c99 -c main.c $gcc -Wall -std =c99 -c helper.c Next use -o to tell the compiler to link them to main $gcc main.o helper.o -o main

void clamp(int x, int bound) { if (x > bound) { x = bound; } } vs void clamp(int *x, int bound) { if (*x > bound) { *x = bound; } } When is it better to use pass-by-reference?

First version using x is pass-by-value and creates a copy of x in the function. Second version using *x is pass-by-reference and this modifies the memory for the variable rather than making a copy pass-by-reference is good for data structures since it avoids making unnecessary copies of data. Ex appending element: points to to an array and directly modifies it void append(int *array, int size, int element) { array[size] = element; }

Literal Value

For variable the declaration determines type For values the compiler will determine the type, for example if it is whole numbers it will go with int, if int isn't big enough then long, then long long, etc. while f it sees a decimal it will assume double You can control values if you want by adding a type to it, for example 3.14F for float

Describe the process of executing Java Programs (mention Interpreted Code and JIT)

Java programs are compiled into platform-independent bytecode, which is then executed by the Java Virtual Machine (JVM) that interprets this bytecode into native machine code. With Just-In-Time (JIT) compilation, Java methods are compiled into native machine instructions just before their first execution, enhancing performance by reducing the overhead of bytecode interpretation. Interpreted Code: this is bytecode and is run on the JVM JIT: compiles bytecode into native machine code

Flow-of-Control for Goto Statement

Lets you place a label and jump to it from anywhere in the program. Can simplify error handling and improve performance, but it makes it more difficult to understand loops and termination in the program when debugging.

Local Variables vs Global Variables

Local variables are defined withen a block, has keyword auto (implied), and has scope from point of declaration to the end of the block, and its lifetime is only during the execution of the bock. Global Variables are defined outside of blocks and are accessible from any part of the program with a lifetime of the execution of the program. Has a storage class of static (not declared)

Internal Linking

Makes variables invisible to the linker where you can't access them (good for privacy). These are global variables (so not MACROS)

Stack-Allocated Memory

Memory is allocated on the call stack and has a lifetime of withen the function

Dissecting arrays apart

Multidimensional arrays are just arrays of arrays so you can dissect them into their elements, this can be used to find size of a element

Does C have a standard for representing signed values?

No

You need to create code to read a 2D point and count the number of points that are inside a 20 x 20 square centered on the origin. Each point is given on an input line as two values of type double representing x and y coordinates, and we can say a point is in the square if the absolute value of its coordinates are both <= 10. the four functions you will write: int main() // this will print the countPoints() function int countPoints() reads an input of two doubles, x and y. If it is not a pair then it returns 0, if it is a pair then adds one to countpoints if it is withen the square (use helper method inside for this) int inside(double x, double y) // returns 1 if given x, y points are inside the 20 x 20 square, use absolute helper method double absolute (double val) // returns the absolute value of a double

Notice countpoints use recursion to add all points!

Does scanf use Pass-by-value or Pass-by-reference?

Pass-by-reference

Pass-by-Value vs pass-by-reference

Pass-by-value is scanf("%d", val) and doesn't work since it receives a copy of the argument not the address of the argument Pass-by-reference is scanf("%d", &val), the &val uses the address of argument which allows it to modify the value (this is what C uses)

Address-of operator and pointer variable working together

Pointer variable can hold the address-of operator int a; int * ptr = &a;

Write what the following prints printf( "value: %6.2f\n", 3.1415926 ); printf( "value: %-6.2f\n", 3.1415926 );

Solution for a: __3.14(width of 6, so 3.14 is four, so 2 extra spaces at start to make total 6) Solution for b: 3.14__ (width of 6, so 3.14 is four, so 2 extra spaces at end to make total 6)

Indirection

The ability to reference a value or container. Pointers use indirection where they can give you something like the value, or they can tell you where it is located

When you get the address for a multi-byte location, which address do you reference?

The address to the first byte of the memory. so if variable a is 4 bytes and occupies memory address 12-15 then you will modify address 12

What happens if you try to cheat a const-ness and modify the value for a const parameter?

The compiler will notice and throw an error

Tokenization and Maximum Munch

Tokenization/ Scanning: The compiler breaks the source code into tokens and reads left to right Maximal Munch: The scanner reads left to right and grabs largest token it can, below it breaks down the linea +++b>=c - - -d

Shadowing

Two variables can have the same name as long as they are declared in different scopes, the compiler uses the one in the narrowest surrounding scope where it shadows the wider scope

Two's complement

Typical way hardware represents signed numbers. It means you want n and -n to add up to zero with the carry out of the high-order bit When you add one to the largest value you end up at 0 and subtracting 1 from 0 gives you the largest number. So it works kind of like a negative value with the negative being the inverse + 1, so for 8-bit 1 is equal to 000000001 and -1 is equal to 11111111. When you convert back it is the same operation of flipping and adding 1 Basically signed cuts the maximum value in half (sacrificing the left most value) so it can represent positive/negative if it starts with a 1 then it is negative, if it starts with 0 it is positive

Function Prototype

Typing information for a function to let the compiler learn about its name, return, and parameter types. These can be included withen the header or at the start of a file the function resides in if the function is called prior to reaching it You do not need to define variable names in it so you can do (int, int)

Header File

Used to access source code from other files

extern

Used to tell the compiler a variable with a specific type exists, for example extern int x; tells the compiler that variable x is type int. Used to declare global variables that can be accessed across multiple files withen the same program has extern keyword Ex: extern int someVar;

Between C and Java: Usually Compiles Code Faster: Greater platform independence: Better support for debugging and error messages: Better for code analysis and optimization at compile-time: Easier to write

Usually Compiles Code Faster: C Greater platform independence: Java Better support for debugging and error messages: Java Better for code analysis and optimization at compile-time: C Easier to write: Java

Flow-of-Control for constant expressions

Values that can be determined at compile time (ex: switch statement), the value must be determined BEFORE compilation . The compiler will create a jump table and each index will point to the predetermined value (for example the case values in a switch statement)

Variable-length array

Variable-length arrays, these arrays are determined during runtime not compile time so they can't be initialized. Size is determined at time of creation and it can't be changed, but you can use it to create multiple arrays. The for-loop will create a new array each loop of size n, and the for loop prompts user to enter a value to change and so it can make different size arrays

Sign Extensions

When switching to a higher signed value, you extend the 1's, and to a lower will subtract it

Overflow for addition and subtraction

When you exceed or barrow passed fixed amount. Programs won;t tell you when it overflows so bits will be lost

which of the following variables are valid: 2_X X_2 _X2 x-2 X_2

X_2 _X2 X_2

Can a pointer point to a pointer?

Yes, you just use another * for each level

Make Variables CC CFLAGS LDLIBS

You can configure the default rules with variables CC: the default compiler to use CFLAGS: The default flags to compile with LDLIBS: options for the linker (libraries, e.g., -lm)

Termination

You can use return 0; to show a successful termination. Can use #include <stdlib.h> to use keywords EXIT_FALIURE and EXIT_SUCCESS, and lets you use exit outside of the maain function.

How should you use a for loop to iterate through a string? for (int i =0; i < strlen(word); i++) { or for (int i =0; i < word[i]; i++) {

You should use for (int i =0; i < word[i]; i++) { assuming you are iterating to a specified letter. If you want to iterate over the whole string then you use for (int i =0; i < strlen(word); i++) {

What does this array equal int a[] = {1, [7] = 10, [2] = 40, [5] = 35};

a = {1, 0, 40, 0, 0, 35, 0, 10}

printf()

a function from <stdio.h> that generates a formatted output

scanf()

another function from <stdio.h> that reads formatted input, the conversion specifiers indicate a value to fill through pass-by-reference

#include <stdbool.h> #include <ctype.h> Write the boolean expressions to check if character ch is a letter, is a whtie space, is a digit, and is printable.

bool isalpha(ch); // checks if char is letter bool isspace(ch); // checks if char is whitespace bool isdigit(ch); // checks if char is digit bool isprint(ch); // checks if char is printable

char a[20], b[16]; Character arrays a and b both have a null character terminator at end Write code to swap the contents of a and b

char c[20]; strcpy(c, a); // copy a to c strcpy(a, b); // copy b to a strcpy(b, c); // copy old a to b b[15] = '\0'; (not 16 since 0 index)

Which of the following properly initializes a static storage char g = 'g'; int g = 15 + (39 % 3); int g = k + 1;

char g = 'g'; int g = 15 + (39 % 3); The reason int g = k + 1; is wrong is because k is not a constant value.

Write following string commands for string myStringA Create myStringA with the string "Hello" Find the string length Create string myStringB with size 20 Copy the string to another string named myStringB Compare two strings and what will the comparison equal? What is the length and size of both?

char myStringA[] = "Hello"; int lengthA = strlen(myStringA); char myStringB[20]; strncpy(myStringB, myStringA, sizeof(myStringB) - 1); int compareResult = strcmp(myStringA, myStringB); which is 0 String A and B have a length of 5, String A has a size of 6 but String B has a size of 20

const type

const isn't a constant since it can get a new value each time it is initialized (so they arn't compile-time constants) it just means you can't change the value of the variable during its lifetime it acts as a promise not to mess with your values in functions, just look at them

If signed type is higher than unsigned type then

convert to signed type

If signed type is equal or lower than unsigned type then

convert to unsigned type

Map which functions go to ctype.h and which go to stdio.h for character commands int getchar(void) int putchar( int c) int tolower(int c) int toupper(int c) bool isalpha(int c) bool isspace(int c) bool isdigit(int c)

ctype.h: int tolower(int c) int toupper(int c) bool isalpha(int c) bool isspace(int c) bool isdigit(int c) stdio.h int getchar(void) int putchar( int c)

Whats wrong with this char c = 'a'; float f = 1.23; short s = 123; char *cp = &c; float *fp = &f; short *sp = &s; fp = &c; sp = &f; cp = &s;

fp = &c; sp = &f; cp = &s; are wrong since you can't convert types for pointers since pointers keep up with size (for example a character pointer points to 1 byte while a int will modify 4 bytes)

Tournament.c includes game.h, input.h, summary.h game.c includes summary.h draw the mapping Write the command line to compile and link the four components together to tournament Does tournament.c include summary,h header? or does it not need to since it already includes game.c header which links to summary.h header?

gcc -Wall -std=c99 -g tournament.c game.c summary.c input.c -o tournament YES it should include summary.h regardless. The reason is that it may use features of summary.h outside of calling game.c so for these reasons it is safe to have it separately call it.

Terminal command to compile myProgram.c

gcc myProgram.c -o myProgram

Type cast implicit vs explicit

implicit means the conversion was done by the compiler, Ex: 3 * 4.0 will turn it into a float explicit means it is manually done, Ex: 3 * (double)4 will result in a double

int i, *ip; double d, *dp; char c, *cp; write this in expanded form

int i; int * ip; double d

Stack-Allocated Array

lifetime is confined to duration of function call

Write the function to print the numeric value of pointer ptr

printf( "%p\n", ptr );

strlen() vs sizeof

strlen() tells you how many elements are filled in excluding the null terminator, sizeof() tells you the memory space including the null terminator

Declaration

tells the compiler about the existence of an entity without allocating memory or describing the implementation (function prototypes and extern variables are examples where the compiler just knows their structure, not its values or implementations)

write a clamp function using x's memory location and a int bound to check if the value of x is greater than bound, if it is then it sets the new value of x to bound. Write the function to call it for var c

void clamp(int *x, int bound) { if ( *x > bound ) *x = bound; } clamp( &c, 5 );


Kaugnay na mga set ng pag-aaral

Chapter 3: Ebusiness: Electronic Business Value

View Set

Organizational Behavior Quizzes for Exam 1

View Set

Health Insurance: Chapter 6 (Underwriting) - Test Cram Session

View Set

Module Four- Postmodern and cultural criminology

View Set

MQM 220 Final Exam Study Guide (ISU Fall 2017 Ruszkowski)

View Set