Lecture1-C-Review
Lecture1-C-Review
Part 1:
Intro, Variables, Operators, Control Structures, Loops
Object files often also contain data for use by the code at runtime,
relocation information, program symbols (names of variables and
functions) for linking and/or debugging purposes, and other debugging
information.
Programming paradigms and languages
Many different programming languages have been developed
(including only a few):
C Pascal Modula
PL/I COBOL Ada SQL
LISP MirandaSimula Prolog
Java C++ SmallTalk
These languages are often grouped into conceptual
paradigms (ways of thinking and planning):
Procedural Functional Declarative
Logic Object Oriented ... and others
C is an example of a strongly typed, procedural
programming language.
5
Enumerated Types in C
C provides the enum as a list of named constant integer values (starting a 0
by default)
Names in enum must be distinct
Often a better alternative to #define
Example
enum boolean { FALSE, TRUE };
enum months { JAN = 1, FEB, MAR, APR, MAY, JUN, JUL, AUG, SEP,
OCT, NOV, DEC };
enum colors { RED, WHITE, BLACK, YELLOW };
The assignment operator must be used with care and attention to detail
◦ Avoid using = where you intend to perform a comparison for equivalence (equality) using ==
◦ You may use = more than once in a statement
This may be confusing and should be avoided when it is necessary to assure clarity of codes.
Coding standards
X == 5 -> not recommended
5 == X -> recommended
Arithmetic Operators
Arithmetic operators are used to express the logic of numerical operations
◦ This logic may depend on data type
◦ AFTER (POST) :
If an expression contains N++, the expression is evaluated using the value
stored at the location N. After the expression is evaluated, the value at N is
incremented by 1.
◦ BEFORE (PRE) :
If an expression contains ++N, the value at N is incremented by 1 and stored
at N, before any other parts of the expression are evaluated. The
expression is then evaluated using the new value at N.
Arithmetic Operators : ++ --
Assume the declarations with initial values specified
◦ int A, B, N = 4, M = 3 ;
◦ A = N++ ;
◦ B = ++M + N-- ; /* watch out ! */
◦ A = --A ;
◦ += and -=
◦ *=
◦ /= and %=
◦ In some cases they may lead to hardware optimization of
executable code.
Augmented Assignment Operators
Although these operations have a certain kind of elegance, they may create
ambiguity.
◦ However, programmers should ensure that programs have clarity.
◦ Examples:
◦ Longhand Shorthand
X=X+Y; X += Y ;
X=X*Y; X *= Y ;
X=X%Y; X %= Y ;
Relational Operators
Relational operators are used to express the concept of comparison of two values
◦ Based on the Boolean notions of True and False
Complement (Not) : !
◦ Unary !(X<Y)
(A > B ) ? 10 : 20
Example:
(1+5)*3–(4–2)%3
Expressions
Example:
(1+5)*3–(4–2)%3
(6)*3 - (2)%3
18 - 2
16
Expressions
Example:
(1+5)* (3–(4–2)/(5–1))%3
Expressions
Example:
(1+5)* ( 3–(4–2)/(5–1)) %3
6 * ( 3 - 0 ) % 3
6 * 3%3
18 % 3 = 0
C
Operator
Precedence
Program Control Structures
▪ Decision control
- (Nested) if-else control structures
- (Nested) switch control structure
▪ Repetition control
- While and do-while control structures
- The for control structure
If-Else If-Else Structure
If Statement is simple, using brace is not a must
if ( condition )
Statement ;
if ( condition ) {
Statement1 ;
......
StatementN ;
}
Indentation improves the readability (hence, understanding) of the code for humans.
Many styles exist – use one style consistently in program
code.
Review If ( condition ) {
T_stmts ;
} else {
Selection: F_stmts ;
}
if ( condition1 )
T_statement ; /* do when condition1 is True */
else if ( condition2 )
T_statement ; /* do when condition2 is True */
else
F_statement ; /* do when all previous conds are False
*/
switch ( Code ) {
case 1 : C = A + B ;
break ;
case 2 : C = A – B ;
break ;
case 3 : C = A * B ;
break ;
case 4 : C = A / B ;
break ;
default : printf ( “Error in input\n” ) ;
break ;
}
If - else if - else switch - case
Nested if-else control
structures
Problem:
Enter three integer values
and find out the smallest
one
All values inputted are
distinct
Repetition Control
Repetition logic may be of two forms
Pre-condition testing : enter, or re-enter, the loop body if the
condition is true.
Post-condition testing : enter the loop body in all cases (performing
the body a minimum of once), then repeat the loop body only if the
condition is true.
while ( condition_expression )
statement ;
FALSE
cond
while ( condition_expression ) {
statement1 ; TRUE
......
process
statementN ;
}
Repetition : do-while
do
statement ;
while ( condition_expression ) ;
process
do {
statement1 ; TRUE
......
statementN ; cond
} while ( condition_expression ) ;
FALSE
MUST execute the body (process) at least once!
Repetition : for
PROCESS
Repetition: While and Do While Examples
Repetition: For – Example Note:
Greatest Common Divisor (GCD) for(;;)
Nested if-else and for
control structures
Problem:
Check whether an
integer is prime or not
Break and Continue
C defines two instruction statements that cause immediate, non-sequential
alteration of normal sequential instruction processing
Break Logic
Execution of a break ; statement at any location in a loop-structure causes
immediate exit from the loop-structure. Break is also used to exit from a
switch structure.
Continue Logic
Execution of a continue ; statement at any location in a loop-structure
causes execution to continue at the beginning of the loop structure (at the
next loop iteration) while skipping the remaining statements.
Break and Continue
Continue Logic
Execution of a continue ; statement at any location in a loop-
structure causes execution to continue at the beginning of the loop
structure (at the next loop iteration) while skipping the remaining
statements.
Produces output : ?
Break
Break Logic
Execution of a break ; statement at any location in a loop-structure
causes immediate exit from the loop-structure
Produces output : ?
Break
Break Logic
Execution of a break ; statement at any location in a switch-structure
causes immediate exit from the switch-structure
switch ( cond ) {
......
Case 53 : Stmt ; .....
break ;
......
}
Break – Example
Least Common Multiple
Review: Algorithms & Programming
Part 2:
Arrays, Structs, Functions, Header Files, Pointers
ARRAYS
▪ An array is a collection of elements of the same type that
are referenced by a common name.
▪ Compared to the basic data type (int, float & char) it is
an aggregate or derived data type.
▪ All the elements of an array occupy a set of contiguous
memory locations.
▪ Why need to use array type?
▪ Consider the following issue:
49
ARRAYS
▪ By using an array, we just declare like this,
int studMark[1000];
50
ARRAYS
One Dimensional Array: Declaration
▪ The first example declares two arrays named xNum and yNum of type
int. Array xNum can store up to 20 integer numbers while yNum can
store up to 50 numbers.
▪ The second line declares the array fPrice of type float. It can
store up to 10 floating-point values.
▪ fYield is basic variable which shows array type can be declared
together with basic type provided the type is similar.
▪ The third line declares the array chLetter of type char. It can store a
string up to 69 characters.
▪ Why 69 instead of 70? Remember, a string has a null terminating
character (\0) at the end, so we must reserve for it.
53
ARRAYS
▪ArrayAn array may be initialized at the time of declaration.
Initialization
▪ For example:
int idNum[7] = {1, 2, 3, 4, 5, 6, 7};
float fFloatNum[5] = {5.6, 5.7, 5.8, 5.9, 6.1};
char chVowel[6] = {'a', 'e', 'i', 'o', 'u', '\0’};
▪ The first line declares an integer array idNum and it immediately assigns the values 1,
2, 3, ..., 7 to idNum[0], idNum[1], idNum[2],..., idNum[6] respectively.
▪ The second line assigns the values 5.6 to fFloatNum[0], 5.7 to fFloatNum[1],
and so on.
▪ Similarly the third line assigns the characters 'a' to chVowel[0], 'e' to chVowel[1],
and so on. Note again, for characters we must use the single apostrophe/quote (') to
54
enclose them. Also, the last character in chVowel is NULL character ('\0').
Example #1: Finding the
smallest element in an array
55
Example #2: Finding the second
largest element in an array
56
ARRAYS
Two Dimensional/2D Arrays
▪ A two dimensional array has two subscripts/indexes.
▪ The first subscript refers to the row, and the second, to the column.
▪ Its declaration has the following form,
data_type array_name[1st dimension size][2nd dimension size];
▪ For examples,
int xInteger[3][4];
float matrixNum[20][25];
▪ The first line declares xInteger as an integer array with 3 rows and
4 columns.
▪ Second line declares a matrixNum as a floating-point array with 20
rows and 25 columns.
57
ARRAYS
▪ For an array Name[6][10], the array size is 6 x 10 = 60 and equal to the
number of the colored square. In general, for
array_name[x][y];
ThreeDimArray[2][4][7] = 2 x 4 x 7 = 56.
▪ And if you want to illustrate the 3D array, it could be a cube with wide, long
and height dimensions.
58
AP1 AP2 OOP SWENG
Ahmet 43 31 12 32
Mehmet 66 5 6 7
Ayşe 8 4 10 11
Example
2-dimensional
Array
59
Structs
Definition, Nested Structs, Struct Arrays
60
Structures
There is no class in C, but we may still want non-homogenous structures
So, we use the struct construct
struct for structure
Example:
A student may have members: name (char[ ]), age (int), GPA (float or double),
sex (char), major (char[ ]), etc
61
The struct Definition
struct is a keyword for defining a structured declaration
Format:
struct name {
name1 and name2
type1 name1; are members of name
type2 name2;
…
};
For the first and last sets of code, point is a defined tag and can be used later (to
define more points, or to declare a type of parameter, etc) but in the middle code,
there is no tag, so there is no way to reference more examples of this structure
63
Accessing structs
A struct is much like an array
The structure stores multiple data
You can access the individual data, or you can reference the entire structure
64
typedef
typedef is used to define new types
The format is
typedef description name;
Where description is a current type or a structural description
such as an array declaration or struct declaration
Examples:
typedef char[10] String; // String is the name of a type for a character array of size 10
68
User-Defined Functions
// include statements
// function prototypes
// main() function
// function definitions
69
Absolute Value
#include <stdio.h>
int main(){
int num, answer;
printf("Enter an integer (0 to stop): “);
scanf(%d, &num);
while (num!=0){
answer = absolute(num);
printf("The absolute value of %d is: %d“, num, answer);
scanf(%d, &num); }
return 0;
}
71
Absolute Value (alternative)
#include “stdio.h”
int main(){
int num, answer;
printf("Enter an integer (0 to stop): “);
scanf(%d, &num);
while (num!=0){
answer = absolute(num);
printf("The absolute value of %d is: %d“, num, answer);
scanf(%d, &num);
}
return 0;
72
}
Function of three parameters
#include <stdio.h>
int main(){
double tot_sec = total_second(1,1.5, 2);
printf(“ %f”,tot_sec);
return 0;
}
73
Arrays as Funtion Parameters
// Program to calculate the average of ages by passing an array to a function
#include <stdio.h>
float average(int age[]);
int main()
{
float avg;
int age[] = {23, 55, 22, 3, 40, 18};
avg = average(age); // Only name of an array is passed as an argument
printf("Average age = %.2f", avg);
return 0;
}
sinOut = sin(radians);
cosOut = cos(radians);
}
int main()
{
double sin = 0.0;
double cos = 0.0;
return 0;
}
Return Multiple Values via Functions (2)
#include <stdio.h>
int main()
{
double areaOut = 0.0;
double circumOut = 0.0;
return 0;
}
Structs as Function Parameters and Return Values
We may pass structs as parameters and functions can return structs
Passing as a parameter:
void foo(struct point x, struct point y) {…}
notice that the parameter type is not just the tag, but
preceded by the reserved word struct
Returning a struct:
struct point createPoint(int a, int b) Structs differ from arrays as
{ structs are not pointed to!
struct point temp;
temp.x = a;
temp.y = b;
return temp;
}
78
Nested structs
In order to provide modularity, it is common to use already-defined structs as
members of additional structs
Recall our point struct, now we want to create a rectangle struct
the rectangle is defined by its upper left and lower right points
79
Arrays of structs
To declare an array of structs (once you have defined the
struct):
struct rectangle rects[10];
rects now is a group of 10 structures (that consist each of two points)
You can initialize the array as normal where each struct is initialized
as a { } list as in {5, 3} for a point or {{5, 3}, {8, 2}} for a rectangle
80
Example
struct point{
int x
int y;
};
struct rectangle {
struct point p1;
struct point p2;
};
void main( )
{
int i;
struct rectangle rects[ ] = {{{1, 2}, {3, 4}}, {{5, 6}, {7, 8}}}; // 2 rectangles
for(i=0;i<2;i++) printRect(rects[i]);
81
}
Function Overloading
82
Recursive Functions
Recursive Funcs
vs.
Iterations?
83
Header files
In applications with multiple C programs, function prototypes are typically
provided in header files
I.e., the ‘.h’ files that programmers include in their code
85
#include
#include <foo.h>
Search the system’s directories in order for a file of the name foo.h
Directories can be added with ‘-I’ switch to gcc command
E.g., gcc –I myProject/include foo.c
Precedes system directories in search order
#include "foo.h"
Search the directory where the source program is found first, before -I
and system directories
86
Pointers in C
87
Computer Memory
Computers store data in memory slots
Each slot has an unique address
Variables store their values like this:
88
Addressing Concept
int i = 5;
int *ptr; /* declare a pointer variable */
ptr = &i; /* store address-of i to ptr */
printf(“*ptr = %d\n”, *ptr); /* refer to referee of ptr */
89
What actually ptr is?
int i = 5;
int *ptr;
ptr = &i;
printf(“i = %d\n”, i);
printf(“*ptr = %d\n”, *ptr);
printf(“ptr = %p\n”, ptr);
90
Twin Operators
&: Address-of operator
Get the address of an entity
e.g. ptr = &j;
*: De-reference operator
Refer to the content of the referee
e.g. *ptr = 99;
92
An Illustration
int i = 5, j = 10;
int *ptr; /* declare a pointer-to-integer variable */
int **pptr;
ptr = &i;
pptr = &ptr;
*ptr = 3; Data Table
**pptr = 7; Name Type Description Value
ptr = &j; i int integer variable 5
**pptr = 9; j int integer variable 10
*pptr = &i; ptr int * integer pointer variable
*ptr = -2;
93
An Illustration
int i = 5, j = 10;
int *ptr;
int **pptr; /* declare a pointer-to-pointer-to-integer variable */
ptr = &i;
pptr = &ptr;
*ptr = 3; Data Table
**pptr = 7; Name Type Description Value
ptr = &j; i int integer variable 5
**pptr = 9; j int integer variable 10
*pptr = &i; ptr int * integer pointer variable
*ptr = -2;
pptr int ** integer pointer pointer variable
Double
Indirection 94
An Illustration
int i = 5, j = 10;
int *ptr;
int **pptr;
ptr = &i; /* store address-of i to ptr */
pptr = &ptr;
*ptr = 3; Data Table
**pptr = 7; Name Type Description Value
ptr = &j; i int integer variable 5
**pptr = 9; j int integer variable 10
*pptr = &i; ptr int * integer pointer variable address of i
*ptr = -2;
pptr int ** integer pointer pointer variable
*ptr int de-reference of ptr 5
95
An Illustration
int i = 5, j = 10;
int *ptr;
int **pptr;
ptr = &i;
pptr = &ptr; /* store address-of ptr to pptr */
*ptr = 3; Data Table
**pptr = 7; Name Type Description Value
ptr = &j; i int integer variable 5
**pptr = 9; j int integer variable 10
*pptr = &i; ptr int * integer pointer variable address of i
*ptr = -2;
pptr int ** integer pointer pointer variable address of ptr
*pptr int * de-reference of pptr value of ptr
(address of i)
96
An Illustration
int i = 5, j = 10;
int *ptr;
int **pptr;
ptr = &i;
pptr = &ptr;
*ptr = 3; Data Table
**pptr = 7; Name Type Description Value
ptr = &j; i int integer variable 3
**pptr = 9; j int integer variable 10
*pptr = &i; ptr int * integer pointer variable address of i
*ptr = -2;
pptr int ** integer pointer pointer variable address of ptr
*ptr int de-reference of ptr 3
97
An Illustration
int i = 5, j = 10;
int *ptr;
int **pptr;
ptr = &i;
pptr = &ptr;
*ptr = 3; Data Table
**pptr = 7; Name Type Description Value
ptr = &j; i int integer variable 7
**pptr = 9; j int integer variable 10
*pptr = &i; ptr int * integer pointer variable address of i
*ptr = -2;
pptr int ** integer pointer pointer variable address of ptr
**pptr int de-reference of de-reference of 7
pptr
98
An Illustration
int i = 5, j = 10;
int *ptr;
int **pptr;
ptr = &i;
pptr = &ptr;
*ptr = 3; Data Table
**pptr = 7; Name Type Description Value
ptr = &j; i int integer variable 7
**pptr = 9; j int integer variable 10
*pptr = &i; ptr int * integer pointer variable address of j
*ptr = -2;
pptr int ** integer pointer pointer variable address of ptr
*ptr int de-reference of ptr 10
99
An Illustration
int i = 5, j = 10;
int *ptr;
int **pptr;
ptr = &i;
pptr = &ptr;
*ptr = 3; Data Table
**pptr = 7; Name Type Description Value
ptr = &j; i int integer variable 7
**pptr = 9; j int integer variable 9
*pptr = &i; ptr int * integer pointer variable address of j
*ptr = -2;
pptr int ** integer pointer pointer variable address of ptr
**pptr int de-reference of de-reference of 9
pptr
100
An Illustration
int i = 5, j = 10;
int *ptr;
int **pptr;
ptr = &i;
pptr = &ptr;
*ptr = 3; Data Table
**pptr = 7; Name Type Description Value
ptr = &j; i int integer variable 7
**pptr = 9; j int integer variable 9
*pptr = &i; ptr int * integer pointer variable address of i
*ptr = -2;
pptr int ** integer pointer pointer variable address of ptr
*pptr int * de-reference of pptr value of ptr
(address of i)
101
An Illustration
int i = 5, j = 10;
int *ptr;
int **pptr;
ptr = &i;
pptr = &ptr;
*ptr = 3; Data Table
**pptr = 7; Name Type Description Value
ptr = &j; i int integer variable -2
**pptr = 9; j int integer variable 9
*pptr = &i; ptr int * integer pointer variable address of i
*ptr = -2;
pptr int ** integer pointer pointer variable address of ptr
*ptr int de-reference of ptr -2
102
Pointer Arithmetic
What’s ptr + 1?
➔ The next memory location!
What’s ptr - 1?
➔ The previous memory location!
What’s ptr * 2 and ptr / 2?
➔ Invalid operations!!!
103
Pass by Value vs. Pass by Reference
Modify behaviour in argument passing
104
Pointers Example #1
Pointers Example #2
Pointers Example #3