Looks like no one added any tags here yet for you.
Types of computer languages (3)
Machine languages, assembly languages, high-level languages.
A computer can directly understand only its own machine language; assembly languages were developed to make programming easier.
Phases of executing C programs (6)
Edit, preprocess, compile, link, load, execute.
Compiling
Translates C program into machine language-code (AKA "object code").
Syntax error
Occurs when the compiler can't recognize a statement because it violates the rules of the language; caught by the compiler.
Linking
Uses gcc; links the object code with the code for missing functions contained elsewhere (e.g. standard libraries such as stdio.h or math.h) ; produces an executable image with no missing pieces.
int main (void)
Part of every C program; int denotes that an integer is returned.
Escape sequences
\n , \t , \a , \\ , \"
Starts with a backslash; denotes that the character after the slash will signify something unique (e.g. new line instead of the character n).
Executable
./a.out
Linked program that can be executed
Types of integers & decimals
Integers: short, int, long (used for different sized numbers); decimals: float, double (double has 2x the precision of float).
%d
Used as a placeholder when scanning/printing integers.
scanf( "%d" , &number ); scans in an integer that is assigned to number.
%f
Used as a placeholder when scanning/printing floats/doubles.
scanf( "%f" , &number ); scans a float/double
printf( "%.2f" , number ); denotes precision, will print 2 digits to the right of the decimal place, default precision is .6
Variable names are...
1) Made of letters, digits, underscores and do not begin with a digit, 2) Can be made any length, 3) Case sensitive.
Format control string
First argument in printf/scanf; indicates the type of data that should be input by the user (e.g. %d or %f).
scanf( "%d" , &integer1 ); %d denotes that the user should input an integer.
Conversion specifier
%d, %f
Indicates that the data should be an integer/float/double.
Address operator
'&' character used in scanf and other functions.
Arithmetic operators (operator, algebraic expression, and C expression)
Addition: + , f+7 , f+7
Subtraction: - , p-c , p-c
Multiplication: , bm , bm
Division: / , x/y , x/y
Remainder: % , r mod s , r%s
Integer division...
...ALWAYS yields integer result, unless typecasting is used. Any fractional part of the calculation will be lost/truncated.
int 1 / int 2 = integer result
(float) int 1 / (float) int 2 = float result
Precedence of arithmetic operators
Parenthesis ( ) : Evaluated first; if nested, the innermost parentheses are evaluated before the outer; if there are several sets of parenthesis not nested they're evaluated from left to right.
Multiplication * , division / , remainder % : Evaluated second, evaluated left to right if there are several.
Addition + , subtraction - : Evaluated last, evaluated left to right if there are several.
Sequential execution
Executed from top to bottom, in the order in which they're written.
Equality operators
Algebraic: = , in C: == , example: x == y , meaning: x is equal to y.
Algebraic: (not equal) , in C: != , example: x != y , meaning: x is not equal to y.
Relational operators
> , x > y , x is greater than y.
< , x < y , x is less than y.
>= , x >= y , x is greater than or equal to y.
<= , x <= y , x is less than or equal to y.
Assignment operator vs. equality operator
Assignment operator: = ("gets" or "is assigned the value of")
Equality operator: == ("double equals") , read right to left
Algorithm
A procedure for solving a problem in terms of the actions to be executed and the order in which these actions are to be executed.
Transfer of control
Ability to specify that the next statement to be executed may be other than the next one in the sequence.
Types of selection structures (3)
If statement: Single selection; either performs/selects an action if a condition is true or skips the action if the condition is false.
If...else statement: Double selection; performs an action if the condition is true and performs a different action if the condition is false.
Switch statement: Compound selection; performs one of many different actions depending on the value of an expression.
Repetition structures
While, do...while, for.
'if...else'
Allows you to specify that different actions should be performed when the condition is true or false.
- Else always attaches to the nearest if
- Cannot make one else correspond to two ifs
- Should never use a semicolon at the end
if ( grade >= 60 )
{
printf( "Passed" );
}
else
{
printf( "Failed" );
}
Conditional operator
?:
- Closely related to the if...else statement
- C's ONLY ternary operator
- First operand is a condition, second is the value if the condition is true, third is the value if the condition is false
printf( "%s" , grade >= 60 ? "Passed" : "Failed" );
Grade >= 60 is condition, "Passed" is printed if true, "Failed" is printed if false.
%s
Conversion specifier for printing a character string.
Compound statement/block
A set of statements contained within a pair of braces.
Logic error, nonfatal logic error
Has effect at execution time; produces unintended output. Nonfatal: program continues but produces incorrect results.
Control statements (7)
if, else if, switch, while, do...while, for, sequential.
'while' repetition statement
- Action is performed repeatedly while condition remains true.
- Repetition is terminated when the condition becomes false.
-Tests the condition at the beginning of the loop before the body of the loop is performed.
product = 3;
while (product <= 100)
{
product = 3*product
}
Program will loop until it finds the first power of 3 larger than 100.
Counter-controlled repetition
- Variable counter specifies the number of times a set of statements should execute
- AKA definite repetition; we know how many times it will loop before it begins executing.
- Counters are normally initialized to 0 or 1.
Total
Variable used to accumulate the sum of a series of values.
"Garbage" value
Contained by uninitialized variable; it's the last value that was last stored in memory that was reserved for that variable.
Sentinel-controlled repetition
AKA indefinite repetition, because we don't know how many times it will loop before it begins executing.
Sentinel value
AKA signal value, dummy value, flag value.
Indicates "end of data entry."
- Must be chosen so it can't be confused with input values (e.g. if user is entering grades such as 98, 96, etc., -1 would be an acceptable sentinel value).
Float
Data type that handles numbers with decimal points (AKA floating-point numbers). Introduces cast operator to handle averaging calculations.
e.g. average = (float) total / counter;
Cast operator
average = (float) total / counter;
- Cast operator (float) creates temporary floating point copy of its operand. Temporary - the value stored in variable total is still an integer.
- Associate from left to right, have same precedence as other unary operators (+ , -); have one level higher precedence than multiplicative operators (% , * , /).
Promotion
AKA implicit conversion.
Compiler does this to ensure that operands are of the same type; e.g. in an expression containing the data types int and float, copies of the int operands are made/promoted to the type float.
Assignment operators
Abbreviates assignment expressions, e.g. c = c + 3 can be abbreviated as c +=3.
The += operator adds the value of the expression on the right (3) to the value of the variable on the left (c) and stores the result in the variable on the left (c).
Any statement in the form 'variable = variable operator expression' can be written in the form 'variable operator= expression' using operators + - % * /
Arithmetic assignment operators
Operator, expression
+= , c = c + 7
-= , d = d - 4
= , e = e 5
/= , f = f * 3
%= , g = g % 9
Increment and decrement operators
Unary increment operator: ++ , can be used instead of c = c+1 or c += 1.
Unary decrement operator: -- , can be used instead of c = c-1 or c -= 1.
Only works for the number 1.
Pre increment , post increment operators
++c , --c
c++ , c--
Pre increment: bumps variable and then uses it.
Post increment: uses variable first, then bumps it (e.g. for next loop).
Loop-continuation condition
Must be true for a loop to continue.
Requirements of counter-controlled repetition
Name of a control variable (or loop counter), initial value of the control variable (usually 0 or 1), increment/decrement by which the control variable are modified each time through the loop, condition that tests for the final variable (i.e. whether or not the loop should continue).
'for' repetition statement
Handles all the details of counter-controlled repetition:
for( counter=1 ; counter <= 10 ; counter++)
Specifies each of the items needed for counter-controlled repetition with a control variable; contains initial value, condition and increment.
Off-by-one error
Logic error, e.g. writing counter<10 rather than counter<=10 , loop would only execute 9 times instead of 10.
General form of the for statement
for( expression1 ; expression2 ; expression3 )
statement
Comma operators
Commas used when a for statement uses expression1 and expression3 as a comma-separated list; guarantee that the lists evaluate from left to right.
Increments/decrements in for statements
counter = counter+1
counter += 1
++counter
counter++
are all equivalent in the increment part of a for statement; because the variable does not appear in a larger expression, all forms have the same effect.
pow( x,y )
Calculates the value of x raised to the y power; requires two double arguments. Included in the math.h library.
%21.2f
Conversion specifier %21.2f is used to print the value of the variable in the program (.2 denotes 2 digits after the decimal point); the value 21 denotes the field width in which the value will be printed.
'switch' multiple-selection statement
Consists of a series of case labels, an optional default case and statements to execute for each.
switch( grade )
case 'a' :
++aCount;
break;
only use ' ' for characters (case 'a' , case 1).
'getchar' function
From stdio.h; read one character from the keyboard and stores that character in an integer variable.
e.g. grade = getchar( )
Character is returned by getchar and assigned to the variable 'grade'.
%c
Prints/scans a character from the keyboard.
EOF
Used as sentinel value, normally has variable -1; symbolic integer constant defined in stdio.h
Choose to represent characters as ints because EOF has an integer value (usually -1).
'do...while' repetition statement
- Tests the loop-continuation condition after the loop body is performed; if you want to loop at least one time for sure, use a do...while repetition statement.
do
{
statement
}
while ( condition );
'break' statement
Causes an immediate exit from the statement when used in a while, do...while, for, or switch statement.
'continue' statement
Skips the remaining statements in the body of a control statement and performs the next iteration of the loop when used in a while, do...while, for, or switch statement.
- While and do...while: loop-continuation test is evaluated immediately after the continue statement is executed.
- For statement: increment expression is executed and then the loop-continuation is evaluated.
Logical operators
&& (logical 'and'), || (logical 'or'), ! (logical 'not' AKA logical negation). && has higher precedence than ||.
e.g. if( gender == 1 && age >=65 )
Both must be true
e.g. if( semesterAvg >= 90 || finalExam >= 90 )
One must be true
Binary operator
e.g. && and ||, combine two conditions
Unary operator
e.g. ! , only a single condition
"Divide and conquer"
Modularizing; constructing a program from smaller modules that are more manageable than the original program; e.g. using other functions outside of main.
Modules
Functions, e.g. printf, scanf, pow
Programmer-defined functions
Functions that the programmer creates (not included in stdio.h, math.h, etc.)
Function call
Specifies the function name and provides information (as arguments) that the called function needs to perform its designated task.
e.g. printf( "%d" , square(x) );
square(x) is called
Function parameters
Provide the means for communicating information between functions; local variables of a function.
Software reusability
Using existing functions as building blocks to create new programs; e.g. preexisting functions in stdio.h, math.h, etc.
Function prototype
-Tells the compiler how the function will be used; tells the type of data returned, the number of parameters the function expects to receive, the types of parameters, and order in which parameters are expected.
-Always use ; after a function prototype
-Technically optional, but recommended to prevent problems later on
e.g. int square( int y );
Local variables
Variables that belong only to the function in which they are used; they are created in destroyed within that function.
Function header
Function-name: any valid identifier
Return-value-type: data type of the result returned to the caller
Return-value-type, function-name, and parameter-list are referred to as the function header.
Function body
Definitions and statements within braces, AKA block.
'return: '
If a function does return a result,
return expression;
returns the value of expression to the caller.
If nothing is returned, it needs to say void (e.g. int main( void )).
Coercion of arguments
Forcing of arguments to the appropriate type; e.g. 'sqrt' can be called with an integer even though the prototype expects a double argument and it will still work correctly.
- Promotes to more precision (e.g. integer to float); will not make a float into an integer.
Mixed-type expressions
Expressions containing values of two or more data types.
- Type of each value in a mixed-type expression is automatically promoted to the "highest" type in the expression.
Promotion hierarchy
Data type, printf conversion, scanf conversion:
long double , %Lf , %Lf
double , %f , %2f
float , %f , %f
unsigned long int , %lu , %lu
long int , %ld , %ld
unsigned int , %u , %u
int , %d , %d
unsigned short , %hu , %hu
short , %hd , %hd
char , %c , %c
Stack
- Data structure (collection of related data items)
- Analogous to a pile of dishes
- Pushing: adding a dish
- Popping: removing a dish, always from the top
- AKA last-in first-out (LIFO) data structures
Program execution stack
AKA function call stack
- Return address of the calling function is located here; the called function uses this to know how to return to its caller
Activation record / stack frame
Data containing the local variables used in each invocation of a function during a program's execution.
Stack overflow
Occurs if more function calls occur than can have their activation records stored on the program execution stack
Call-by-value
A copy of the argument's value is made & passed to the called function; changes to the copy do not affect an original variable's value in the caller; technically all call-by-value in C.
Call-by-reference
Caller allows the called function to modify the original variable's value.
Side effects
Variable modifications; can occur when calling by reference.
Random number generation
Found in stdlib.h, 1 + rand( ) % 6
e.g. Simulating a six-sided die: 1 + rand ( ) % 6 produces integers from 0-5. 6 is called the scaling factor; the range of numbers is shifted by adding 1 to the previous result.