C Language Part 2 (Minor modifications by the instructor) 1
Scope Rules A variable declared inside a function is a local variable Each local variable in a function comes into existence when the function is called, and it disappears when the function is exited Temporary storage for the lifetime of the function or block Its memory is allocated in the function s stack frame Such a variable is called an automatic variable Default and implicit int foo(int n) int i; 2
Scope Rules (contd.) Function parameters (e.g., variable n in foo) are also automatic variables If we put static in the declaration of a local variable, it remains in existence throughout the program Variable i in the example below is called a static local variable int foo(int n) static int i; 3
Scope Rules (contd.) A variable declared outside any function is an external variable Permanent storage for the lifetime of the program Implicit The scope of a variable or a function is the part of the program within which the variable or the function can be used The scope of a local variable is the function in which the variable is declared The scope of an external variable or a function is from the point of its declaration to the end of the file An external variable can be accessed by all functions that follow its declaration 4
Scope Rules (contd.) Because of the scope rule, a function should be defined before it is used (called) However, C allows a function to be declared before it is #include <stdio.h> defined Forward declaration int foo(int n); int main(void) int x; foo(x); int foo(int n) #include <stdio.h> int foo(int n) int main(void) int x; foo(x); 5
Scope Rules (contd.) When we have a newly declared variable in the scope of another variable x with the same name, new x hides old x in the scope of new x #include <stdio.h> int i; /* external variable */ int foo(int n); /* forward declaration */ int main(void) int x; x = i; /* i refers to the external variable i */ int foo(int n) /* function definition */ int i; i = n; 6
Static Scope and Block Structure A block is a grouping of declarations and statements Enclosed with and A declaration D belongs to a block B if B is the most closely nested block containing D D is located within B, but not within any block that is nested within B Static-scope rule If declaration D of name x belongs to block B, then the scope of D is all of B, except for any blocks B nested to any depth within B, in which x is re-declared A name x is re-declared in B if some other declaration D of the same name x belongs to B 7
Blocks in C main() int a = 1; int b = 1; int b = 2; int a = 3; printf( %d%d\n, a, b); int b = 4; printf( %d%d\n, a, b); printf( %d%d\n, a, b); printf( %d%d\n, a, b); 8
Sequential Flow of Control Unless otherwise stated, statements in a program are executed one after another in the order they placed in the program 9
If Statement The if statement has the following form: if ( expression ) statement1 else statement2 The else part is optional If expression is evaluated to true, then statement1 is executed If it is false, statement2 is executed If it is false and there is no else part, the if statement does nothing 10
If Statement (contd.) The following if statement sets abs to be the absolute value of x if (x > 0) abs = x; else abs = -x; The following example sets min to be the minimum of i and j min = i; if (j < min) min = j; 11
If Statement (contd.) statement1 or statement2 should be a single statement Compound statement A series of declarations and statements surrounded by braces declarations statements A compound statement itself is a (single) statement if (x < 0) temp = x; x = y; y = temp; 12
Cascaded if A cascaded if statement can be used to write a multi-way decision What does the program below do? #include <stdio.h> int main(void) char op; int a = 20, b = 4; printf("select operator (+, -, *, /) : "); scanf("%c", &op); if (op == '+') printf("20 %c 4 = %d\n", op, a+b); else if (op == '-') printf("20 %c 4 = %d\n", op, a-b); else if (op == '*') printf("20 %c 4 = %d\n", op, a*b); else if (op == '/') printf("20 %c 4 = %d\n", op, a/b); else printf("wrong operator!\n"); return 0; 13
Switch Statement The switch statement also describes a multi-way decision that tests whether an expression matches one of several values The default case is optional If the default case does not exist and none of the cases match, then no action will take place switch(op) case '+': printf("20 %c 4 = %d\n", op, a+b); break; case '-': printf("20 %c 4 = %d\n", op, a-b); break; case '*': printf("20 %c 4 = %d\n", op, a*b); break; case '/': printf("20 %c 4 = %d\n", op, a/b); break; default: printf("wrong operator!\n"); break; 14
Switch Statement (contd.) The break statement causes an immediate exit from the switch statement If break is absent in a case, execution falls through to the next case switch(op) case '+': printf("20 %c 4 = %d\n", op, a+b); break; case '-': printf("20 %c 4 = %d\n", op, a-b); break; case '*': printf("20 %c 4 = %d\n", op, a*b); break; case '/': printf("20 %c 4 = %d\n", op, a/b); break; default: printf("wrong operator!\n"); break; 15
For Statement The for statement is a convenient way to write a loop that has a counting variable for (expr1; expr2; expr3) statement expr1 is an initialization that is executed only once at the beginning of the loop expr2 is a termination condition expr3 is executed at the end of each loop iteration 16
For Statement (contd.) A for loop that computes the sum of integers from 1 to 100 #include <stdio.h> int main(void) int i, sum = 0; for (i=1; i<=100; i++) sum = sum + i; printf("1 + 2 +... + 99 + 100 = %d\n", sum); return 0; 17
While Statement The while statement has the following form while (expr) statement expr is evaluated If it is true (non-zero), statement is executed and expr is evaluated again This process continues until expr becomes false (zero) 18
While Statement (contd.) Finding the minimum integer i such that 1+2+ + i > 1000 In general, for loops are better if we know the number of iterations in advance, and while loops are better otherwise #include <stdio.h> int main(void) int i = 0, sum = 0; while (sum <= 1000) i = i + 1; sum = sum + i; printf("minimum i which satisfies (1+2+ +i) > 1000 is %d\n", i); return 0; 19
Do While Statement The do while statement is similar to the while statement, but expression is tested after the loop body (i.e., statement) do statement while (expression); the loop body is executed at least once 20
Break Statement Causes an exit from the innermost enclosing loop or switch statement while(1) scanf( %1f, &x); if (x < 0.0) break; printf( %f\n, x*x); 21
Continue Statement Causes the current iteration of a loop to stop and the next iteration of the loop begin Printing all integers less than 100 that are not divisible by 3 #include <stdio.h> int main(void) int i; for (i=0; i<100; i++) if ( i % 3 == 0) continue; printf("%d ", i); printf("\n"); return 0; 22
Arrays An array is a data structure containing a certain number of elements, all of which have the same type To declare an array, specify the type and number of the elements For example, int a[10]; declares a to be an array of 10 integers 23
Arrays (contd.) To access an element of an array, write the array name followed by a subscript In C, subscripts always start with 0 For example, the elements of array a are a[0], a[1],, a[9] 24
Arrays (contd.) An array is initialized by listing the values If the number of values is less than that of the array elements, the remaining elements are given value 0 int a[10] = 9, 8, 7, 6, 5, 4, 3, 2, 1, 0; int a[10] = 0; float a[3] = 0.1, 0.2, 0.0 ; int a[3] = 3, 4 ; int a[] = 2, -4, 1 ; int a[4] = 2, -4, 1 ; char s[] = abcd ; char s[] = a, b, c, d, \0 25
Finding Maximum The program below reads ten values into an array ab and then finds the maximum among the values #include <stdio.h> int main(void) int n, i, max; int ab[10]; printf("enter n: "); scanf("%d", &n); printf("enter n numbers: "); for (i=0; i<n; i++) scanf("%d", &ab[i]); max = ab[0]; for (i=1; i<n; i++) if (ab[i] > max) max = ab[i]; printf("max %d\n", max); return 0; 26
Bubble Sort Sorts array ab of n elements in non-decreasing order The first iteration of the inner for loop brings the maximum element to the last position, the second iteration brings the second maximum to the second-to-last position, etc. The three assignments inside the if statement exchange the values of ab[j] and ab[j+1] 27
Bubble Sort (contd.) for (i=1; i<n; i++) for (j=0; j<n-i; j++) if (ab[j] > ab[j+1]) temp = ab[j]; ab[j] = ab[j+1]; ab[j+1] = temp; 28
Insertion Sort void insertionsort( int a[], int n ) int i, j, val; for( i = 1; i < n; i++) val = a[i]; j = i - 1; while ( ( j >= 0 ) && ( a[j] > val ) ) a[j+1] = a[j]; j--; a[j+1] = val; printintarray( a, n ); 29
Insertion Sort (contd.) #include <stdio.h> #define N 10 void insertionsort( int *, int ); void printintarray( int *, int ); void printintarray( int a[], int n ) int i; for( i = 0; i < n; i++) printf("%4d ", a[i]); int main( void ) int a[n] = 23, -3, 5, 9, 11, 33, 87, -7, -24, 50 ; printintarray( a, N ); insertionsort( a, N ); return 0; printf("\n"); 30
Insertion Sort (contd.) 23-3 5 9 11 33 87-7 -24 50-3 23 5 9 11 33 87-7 -24 50-3 5 23 9 11 33 87-7 -24 50-3 5 9 23 11 33 87-7 -24 50-3 5 9 11 23 33 87-7 -24 50-3 5 9 11 23 33 87-7 -24 50-3 5 9 11 23 33 87-7 -24 50-7 -3 5 9 11 23 33 87-24 50-24 -7-3 5 9 11 23 33 87 50-24 -7-3 5 9 11 23 33 50 87 31
Search Suppose that n elements are stored in an array ab Given a new element x, we want to find if x is in array ab x is one of the elements stored in ab An easy solution for search is to scan the elements in array ab one by one and check if it is equal to x Linear search 32
Linear Search #include <stdio.h> int main(void) int n, i, x; int ab[100]; printf("enter n: "); scanf("%d", &n); printf("enter n numbers: "); for (i=0; i<n; i++) scanf("%d", &ab[i]); printf("enter x: "); scanf("%d", &x); for (i=0; i<n; i++) if (x == ab[i]) printf("%d\n", i); return 0; printf("%d\n", -1); return -1; 33
Binary Search If the elements in array ab are stored in nondecreasing order after sorting, we can solve the search problem more efficiently than linear search We first compare x with the element in the middle (i.e., median) If x is equal to the median, we have found it If x is smaller than the median, we are sure that x is not in the upper part of array ab, so we look for x in the lower part Otherwise, x is larger than the median, we look for x in the upper part Binary search is faster than linear search 34
Binary Search (contd.) low = 0; high = n-1; while (low <= high) mid = (low+high) / 2; if (x < ab[mid]) high = mid 1; else if (x > ab[mid]) low = mid + 1; else printf("%d\n", mid); return 0; printf("%d\n", -1); return -1; 35
Two-dimensional Arrays Two dimensional arrays can be visualized as a multicolumn table or grid or matrix int b[2][5]; Declares a two-dimensional array b that has 2 rows and 5 columns We can initialize a two-dimensional array as follows: int b[2][5] = 1,0,0,1,1,0,0,1,1,1; 36