Quiz 3
Query successful
C Programming Notes (COP 3223)
1. Conditional Statements (If Statements)
Boolean/Integer Expression:
C does not have a dedicated boolean type; conditional expressions are treated as integer expressions.
False is represented by a value of 0.
True is represented by any non-zero value.
Typical relational expressions include
x == y,x >= y,x <= y,x > y,x < y, andx != y.
Structure and Blocks:
The original
ifstatement allows only one statement inside.To execute more statements, curly braces
{}must be used. It is safer to always add braces.
elseStatement:The
elsestatement is optional.Matching
elseProblem: In C, anelsematches the nearestifstatement, even if ambiguous.
else ifLadder:When an
if/else-ifstructure is executed, the program finds the first expression that is TRUE.It executes the associated statement and then skips to the end of the whole construct.
If all expressions are FALSE, the statement in the final
else(if present) is executed, then the program moves on.
Short-Circuiting:
In a compound conditional expression using
&&(AND), if the first part is false, the rest of the expression is not evaluated.
2. Loops and Iteration
whileLoop:Ideal use: Situations where a task is repeated an unspecified number of times but based on a certain criteria. Examples include input checking until a valid choice is entered or accumulating a value until a goal is met.
Steps: 1. Evaluate the boolean expression. 2. If true, execute all statements inside the loop. 3. Go back to step 1. If not true, skip to the end of the loop.
forLoop:Structure:
for (init stmt; bool exp; inc stmt).Used for: A fixed number of iterations.
Steps: 1. Initialize the statement. 2. Check the Boolean Expression; if false, go to the end of the loop. 3. If the boolean expression is true, run all statements INSIDE the loop. 4. After running the statements, execute the increment statement. 5. Go back to step 2.
do-whileLoop:Guarantee: It is guaranteed to run at least once.
Steps: 1. Run the loop once (execute the statements). 2. Check the boolean expression. If true, go to step 1; else, go to the code after the loop.
Control Statements:
break: Executes immediately moves execution outside the loop (or switch).continue: Skips the rest of the current iteration and moves immediately to the next iteration of the loop.
Shorthand Operators:
var op= expris shorthand forvar = var op expr.Example:
Var += expris shorthand forVar = var + expr.
Summing Digits:
The last digit of an integer is obtained using the modulo 10 operator:
value % 10.The rest of the number is obtained by integer division by 10:
value / 10.
Perfect Numbers:
A perfect number is one where the sum of its proper divisors equals the number itself.
3. Functions
Advantages:
Code Reuse: Code can be encapsulated in a function and run again by "calling" it.
Bug Fixing: If a bug in the function is fixed, it gets fixed everywhere the function is called.
Readability: Makes code much easier to read.
Manageability: Breaking a program into different functions makes each subtask more manageable.
Calling a Function:
Must know: what input to provide the function and what (if anything) the function returns.
Actual Parameters: These are expressions. When calling the function, no type information is written down for them.
Function Execution Flow:
Evaluate the values of the actual parameters.
Copy those values into the corresponding formal parameter variables.
Give control to the function.
Function executes.
Upon the
returnstatement, the function's memory is destroyed, and the return value is sent back to the calling function.The calling function continues execution with the return value.
A function call that returns a value should NOT live by itself on a line of code.
Defining a Function:
Function Signature : Includes the return type and a list of formal parameters.
Formal Parameters: When defining the function, the type and variable name for each parameter are written down, separated by commas.
Pass by Reference (Pointers):
Swap Problem: A simple
swap(x, y)function where values are passed doesn't work because it does NOT have access to the memory locations ofxandyinmain.Pointers: To allow a function to modify a variable outside its scope (like in
swap), the address of the variable must be passed. This requires the formal parameter to be a pointer type (e.g.,int *ptrA), using the "address of" operator (&) for the actual parameter. The memory location is accessed inside the function using the dereferencing operator (*).
4. Arrays
Declaration and Purpose:
Arrays are used when one identifier (variable name) is needed for many storage boxes.
Declaration:
Type ArrayName [SIZE].The
SIZEmust be a constant (often defined with#define SIZE 247). DO NOT use a variable for the size.
Accessing Elements:
Array indices start at 0.
Access an element using
ArrayName[index], e.g.,Scores[0] = 90.
Arrays as Function Parameters:
When passing an array to a function, the array name and its length must be passed, as C does not store the length associated with the array's memory address.
Example function signature:
void init(int array[], int length, int val).
Frequency Array:
A frequency array can be used to count the occurrences of items.
To count letter frequencies, an array of size 26 (for the alphabet) can be used. When reading a character
ch, the index is calculated asch - 'a'(assuming lowercase letters) to map 'a' to index 0, 'b' to index 1, etc..
5. Sorting Algorithms (Arrays)
Three Algorithms Discussed: Bubble Sort, Insertion Sort, and Selection Sort.
Bubble Sort:
After the first iteration, the maximum value is in its correct spot at the end of the array.
It repeatedly swaps adjacent elements if they are in the wrong order.
Outer loop (for
i): determines the last index of the sub-array being sorted. Inner loop (forj): iterates through the sub-array performing swaps.
Insertion Sort:
Maintains a sorted sub-array (starting at size 1).
For each iteration, it takes the next unsorted element and "inserts" it into its correct position within the already sorted sub-array by shifting elements.
Selection Sort:
In each iteration, it finds the maximum value in the unsorted portion of the array.
It then swaps that maximum value with the element at the current last index being considered (
arr[i]).The outer loop progresses by correctly sorting one element (the maximum) into its final position in each pass.
6. File Input/Output (I/O)
Reading from a File:
Open the file: Use
FILE* inpFile = fopen("filename.txt", "r");where"r"is the read mode.Read data: Use
fscanf(inpFile, "format", &variable);, which is exactly likescanfbut uses the file pointer (inpFile).Close the file: Use
fclose(inpFile);.
Writing to a File:
Open the file: Use
FILE *ofp = fopen("myoutput.txt", "w");where"w"is the write mode. There is also an"a"(append) mode.Write data: Use
fprintf(ofp, "format\n");, which is the same asprintfbut uses the file pointer (ofp).Close the file: Use
fclose(ofp);.