chapter 3: control flow

42
Chapter 3: Control Flow S. M. Farhad

Upload: cody

Post on 08-Jan-2016

48 views

Category:

Documents


2 download

DESCRIPTION

S. M. Farhad. Chapter 3: Control Flow. Statements and Blocks. An expression becomes a statement when it is followed by a semicolon Braces { and } are used to group declarations and statements together into a compound statement or block - PowerPoint PPT Presentation

TRANSCRIPT

Page 1: Chapter 3: Control Flow

Chapter 3: Control Flow

S. M. Farhad

Page 2: Chapter 3: Control Flow

Statements and Blocks

An expression becomes a statement when it is followed by a semicolon

Braces { and } are used to group declarations and statements together into a compound statement or block

A block is syntactically equivalent to a single statement

Variables can be declared inside any block There is no semicolon after the right brace that ends

a block

Page 3: Chapter 3: Control Flow

if-else

The if-else statement is used to express decisions

Formally the syntax is

if (expression)

statement1

else

statement2

The else part is optional

Page 4: Chapter 3: Control Flow

if-else Contd.

The statement1 is executed if expression is true (having a non-zero value)

The statement2 is executed if expression is false (having a zero value)

Since if simply tests the numeric value of an expression coding shortcuts are possible

“if (expression)” and “if (expression != 0)” have the same results

Page 5: Chapter 3: Control Flow

if-else Contd. Dangling else problem

z = c;if (n > 0)

if (a > b)z = a;

elsez = b;

As the else part of an if-else is optional, there is an ambiguity when an else is omitted from a nested if sequence

This is resolved by associating the else with the closest previous else-less if

It is good idea to use braces when there are nested ifs.

Page 6: Chapter 3: Control Flow

else-if

if (expression)statement

else if (expression)statement

else if (expression)statement

elsestatement

The last else part handles the “none of the above” or default case (optional)

Page 7: Chapter 3: Control Flow

Binary Search

If a particular value x occurs in the sorted array v

The elements of v must be in increasing order

The function returns the position if x occurs in v, and -1 if not

Page 8: Chapter 3: Control Flow

Binary Search Step 1int binsearch(int x, int v[ ], int n){

int low, high, mid;low = 0;high = n -1;while(low <= high){

mid = (low + high)/2;if (x < v[mid])

high = mid – 1;else if(x > v[mid])

low = mid + 1;else return mid;

}return -1;

}

1 2 3 4 5

1 2 3 40

x = 4

low = 0, high = 5 – 1 = 4

Page 9: Chapter 3: Control Flow

Binary Search Step 1int binsearch(int x, int v[ ], int n){

int low, high, mid;low = 0;high = n -1;while(low <= high){

mid = (low + high)/2;if (x < v[mid])

high = mid – 1;else if(x > v[mid])

low = mid + 1;else return mid;

}return -1;

}

1 2 3 4 5

1 2 3 40

low = 0, high = 4

mid = (0 + 4) / 2 = 2

x = 4 > v[2] = 3

low = 2 + 1 = 3

3

Page 10: Chapter 3: Control Flow

Binary Search Step 1int binsearch(int x, int v[ ], int n){

int low, high, mid;low = 0;high = n -1;while(low <= high){

mid = (low + high)/2;if (x < v[mid])

high = mid – 1;else if(x > v[mid])

low = mid + 1;else return mid;

}return -1;

}

1 2 3 4 5

1 2 3 40

low = 3, high = 4

mid = (3 + 4) / 2 = 3

x = 4 = v[3]

return 3

4

Page 11: Chapter 3: Control Flow

Switch

The switch statement is a multi-way decision that tests whether an expression matches one of a number of constant integer valuesswitch (expression){

case const-expr: statementscase const-expr: statementsdefault: statements

} All case expressions must be different Default is executed if none of the cases match A default is optional

Page 12: Chapter 3: Control Flow

Switch Contd.

The break statement causes an immediate exit from the switch

Falling through cases is a mixed blessing Falling through one case to another is not robust Put a break after the last case even though it is

unnecessary A number is n, if n is even then show the number is

even if n is odd then show the number is odd

Page 13: Chapter 3: Control Flow

Loops-While and For

for(expr1; expr3; expr3)

statement

is equivalent to

expr1;

while (expr2) {

statement

expr3;

}

Page 14: Chapter 3: Control Flow

Loops-While and For

Although equivalent the syntax of while is

while (expr)

stmt

Page 15: Chapter 3: Control Flow

What We Practice

If-else

if (expression){

statement1

}

else{

statement2

} Similarly else-if

Page 16: Chapter 3: Control Flow

What We Practice Contd.

Loops

for(expr1; expr3; expr3) {

statement

}

while (expr) {

statement

}

Page 17: Chapter 3: Control Flow

Loops-While and For Contd.

While is most natural when there is no initialization or re-initialization

For is preferable there is a simple initialization and increment Since it keeps the loop control stmts close together and

visible at the top of the loop The index and limit of a C for loop can be altered from

within the loop The index variable retains its value when the loop

terminates any reason The for loop is not restricted to arithmetic progressions It is bad style to force unrelated computations into the

initialization and increment portion

Page 18: Chapter 3: Control Flow

int atoi(char s[ ]) convert s to integerint atoi(char s[ ]){

int i, n, sign;for(i = 0; isspace(s[i]); i++)

; /* skip white space */sign = (s[i] == ‘-’) ? -1 : 1;if(s[i] == ‘+’ || s[i] == ‘-’)

i++; /* skip sign */for(n = 0; isdigit(s[i]); i++)

n = 10 * n + (s[i] – ‘0’);return sign * n;

}

- 3 4 5

0 1 2 3 4

\0

5i

n = 10*0 + (51 – 48)

= 3

Page 19: Chapter 3: Control Flow

int atoi(char s[ ]) convert s to integerint atoi(char s[ ]){

int I, n, sign;for(i = 0; isspace(s[i]); i++)

; /* skip white space */sign = (s[i] == ‘-’) ? -1 : 1;if(s[i] == ‘+’ || s[i] == ‘-’)

i++; /* skip sign */for(n = 0; isdigit(s[i]); i++)

n = 10 * n + (s[i] – ‘0’);return sign * n;

}

- 3 4 5

0 1 2 3 4

\0

5i

n = 10*3 + (52 – 48)

= 34

Page 20: Chapter 3: Control Flow

int atoi(char s[ ]) convert s to integerint atoi(char s[ ]){

int I, n, sign;for(i = 0; isspace(s[i]); i++)

; /* skip white space */sign = (s[i] == ‘-’) ? -1 : 1;if(s[i] == ‘+’ || s[i] == ‘-’)

i++; /* skip sign */for(n = 0; isdigit(s[i]); i++)

n = 10 * n + (s[i] – ‘0’);return sign * n;

}

- 3 4 5

0 1 2 3 4

\0

5i

n = 10*34 + (53 – 48)

= 345

Page 21: Chapter 3: Control Flow

Nested Loop: Bubble Sort

void bubble(int s[ ], n){int i, j, temp;for(i = 1; i < n; i++)

for(j = n - 1; j >= i; j--)if(s[j-1] > s[j]){

temp = s[j-1];s[j-1] = s[j];s[j] = temp;

}}

8 2 5 4 1

1 2 3 40

Page 22: Chapter 3: Control Flow

Nested Loop: Bubble Sort Contd.void bubble(int s[ ], n){

int i, j, temp;for(i = 1; i < n; i++)

for(j = n - 1; j >= i; j--)if(s[j-1] > s[j]){

temp = s[j-1];s[j-1] = s[j];s[j] = temp;

}}

8 2 5 1 4

1 2 3 40

Page 23: Chapter 3: Control Flow

Nested Loop: Bubble Sort Contd.void bubble(int s[ ], n){

int i, j, temp;for(i = 1; i < n; i++)

for(j = n - 1; j >= i; j--)if(s[j-1] > s[j]){

temp = s[j-1];s[j-1] = s[j];s[j] = temp;

}}

8 2 1 5 4

1 2 3 40

Page 24: Chapter 3: Control Flow

Nested Loop: Bubble Sort Contd.void bubble(int s[ ], n){

int i, j, temp;for(i = 1; i < n; i++)

for(j = n - 1; j >= i; j--)if(s[j-1] > s[j]){

temp = s[j-1];s[j-1] = s[j];s[j] = temp;

}}

8 1 2 5 4

1 2 3 40

Page 25: Chapter 3: Control Flow

Nested Loop: Bubble Sort Contd.void bubble(int s[ ], n){

int i, j, temp;for(i = 1; i < n; i++)

for(j = n - 1; j >= i; j--)if(s[j-1] > s[j]){

temp = s[j-1];s[j-1] = s[j];s[j] = temp;

}}

1 8 2 5 4

1 2 3 40

Page 26: Chapter 3: Control Flow

Try Outputvoid pyramid(int n){

int i, j, k;for(i = 0; i < n; i++){

for(j = 0; j < (n - i); j++ ){printf(" "); // space

}for(k = 0, j = i + 1; k <= i; j++, k++){

printf("%d ", j % 10); //1st side of a row}for(k = 0, j -= 2; k < i; j--, k++){

printf("%d ", j % 10); //2nd side of a row}printf("\n");

}} Run

Page 27: Chapter 3: Control Flow

Loops--Do-while

The syntaxdo

stmtwhile (exp);

Tests the termination condition at the bottom after making each pass through the loop body

The body is always executed at least once The sequence of execution

Page 28: Chapter 3: Control Flow

Loops--Do-while Contd.

Do-while is much less used than while and for

From time to time it is valuable Itoa function

Page 29: Chapter 3: Control Flow

Itoa: convert n to string s

void itoa (int n, char s[ ]){if ((sign = n) < 0)

n = -n; /* make it positive */i = 0;do{

s [i++] = n % 10; + ‘0’;} while ((n /= 10) > 0);if (sign < 0) s [i++] = ‘-’;s [i] = ‘\0’;reverse (s);

}

Re write the do-while loop using while loop so that Integrity is

same

Menu OptionCorrection

Page 30: Chapter 3: Control Flow

Break and Continue

It is sometimes convenient to be able to exit from a loop other than by testing at the top or bottom

break statement provides an early exit from for, while, and do, just as from switch

A break causes the innermost enclosing loop or switch to be exited immediately

The function “trim” removes the trailing blanks, tabs, and new lines from the end of a string

Page 31: Chapter 3: Control Flow

Trim: remove trailing blanks, tabs, newlinesint trim (char s [ ]){

int n;

for (n = strlen (s) – 1; n >= 0; n--)

if (s [n] != ‘ ‘ && s [n] = ‘\t’ && s [n] != ‘\n’)

break;

s [n + 1] = ‘\0’;

return n;

}

Returns the length ofThe string s

Breaks the loop when any char other than

white spaces

Breaks the loop when any char other than

white spaces

When the entire string has been scanned

Page 32: Chapter 3: Control Flow

Continue Statement

It is related to break statement but less often used

It causes the next iteration of the enclosing for, while, or do loop to begin

In the case of while and do, this means that the test part is executed immediately

In the for, control passes to the increment step The continue statement applies only to loops,

not to switch

Page 33: Chapter 3: Control Flow

An Example with continue

The following fragment processes only the

non-negative elements in the array a;

negative values are skipped

for (i = 0; i < n; i++){

if (a[i] < 0)

continue;/* skip negative elements */

..... /* do positive elements */

}

Page 34: Chapter 3: Control Flow

What is the output?

for (i = 1; i < 5; i++){

for (j = 1; i < 5; j++){

if (i == j) break;

printf(“%d %d”, i, j);

}

printf (“\n”)

}

Page 35: Chapter 3: Control Flow

What is the output? With

Answerfor (i = 1; i < 5; i++){

for (j = 1; i < 5; j++){

if (i == j) break;

printf(“%d %d”, i, j);

}

printf (“\n”)

}

1 1

2 1 2 2

3 1 3 2 3 3

4 1 4 2 4 3 4 4

Page 36: Chapter 3: Control Flow

What is the output?

for (i = 1, x= 0; i <= 4; i++){

for (j = 1; i <= 3; j++){

if (i == j) continue;

printf (“i = %d j = %d,”, i, j);

x = x + i +j;

}

printf (“\nx = %d”, x);

}

printf (“\nx = %d”, x);

Page 37: Chapter 3: Control Flow

What is the output?

for (i = 1, x= 0; i <= 4; i++){

for (j = 1; i <= 3; j++){

if (i == j) continue;

printf (“i = %d j = %d,”, i, j);

x = x + i +j;

}

printf (“\nx = %d”, x);

}

printf (“\nx = %d”, x);

i=1 j=2, i=1 j=3

x = 7

i=2 j=1, i=2 j=3

x = 15

i=3 j=1, i=3 j=2

x = 24

...

Page 38: Chapter 3: Control Flow

Goto and Labels

C provides infinitely-abusable goto statement

and labels to branch to

Formally, the goto is never necessary

In practice, it is always easy to write code

without it

We will not allow to use goto statement to

used in our lab assignments

Page 39: Chapter 3: Control Flow

Goto and Labels Contd.

Nevertheless, there are a few situations where gotos

may find a place

The most common is to abandon processing in some

deeply nested structure

Breaking out of two or more loops at once

Code that relies on got statements is generally harder

to understand and to maintain than cod e without

gotos

Page 40: Chapter 3: Control Flow

Goto and Labels Contd.

for ( .. )

for ( .. ) {

if (disaster)

goto error;

}

...

error:

/* clean up the mess */

Page 41: Chapter 3: Control Flow

Goto and Labels Contd. As another example, consider the problem of

determining whether two arrays a and b have an element in common

for (i = 0, i < n; i++)

for (j = 0, j < m; j++)

if (a [i] == b [j])

goto found;

found: ...

Page 42: Chapter 3: Control Flow

The End of Chapter 3

Any Question?