0% found this document useful (0 votes)
66 views

Control Flow: Branching

Control flow statements like if-else and switch-case allow a program to make decisions and change the flow of execution based on conditions. The if statement executes a block of code if the condition is true, else-if allows evaluating multiple conditions, and else handles the false case. Switch-case matches a variable against case labels and executes the corresponding block. Well-structured conditional logic and proper use of break statements are important to avoid errors. Operators like ++ and -- can increment or decrement a variable as a prefix or postfix operation.

Uploaded by

sukla_satapathy
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
66 views

Control Flow: Branching

Control flow statements like if-else and switch-case allow a program to make decisions and change the flow of execution based on conditions. The if statement executes a block of code if the condition is true, else-if allows evaluating multiple conditions, and else handles the false case. Switch-case matches a variable against case labels and executes the corresponding block. Well-structured conditional logic and proper use of break statements are important to avoid errors. Operators like ++ and -- can increment or decrement a variable as a prefix or postfix operation.

Uploaded by

sukla_satapathy
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 38

Control Flow: Branching

CS10001: Programming & Data Structures

Pallab Dasgupta Professor, Dept. of Computer Sc. & Engg., Indian Institute of Technology Kharagpur
Dept. of CSE, IIT KGP

Statements and Blocks


An expression followed by a semicolon becomes a statement. x = 5; i++; printf (The sum is %d\n, sum) ; Braces { and } are used to group declarations and statements together into a compound statement, or block. {

sum = sum + count; count++; printf (sum = %d\n, sum) ;

}
Dept. of CSE, IIT KGP

Control Statements: What do they do?


Branching:
Allow different sets of instructions to be executed depending on the outcome of a logical test. Whether TRUE (non-zero) or FALSE (zero).

Looping:
Some applications may also require that a set of instructions be executed repeatedly, possibly again based on some condition.

Dept. of CSE, IIT KGP

How do we specify the conditions?


Using relational operators.
Four relation operators: Two equality operations: <, <=, >, >= ==, !=

Using logical operators / connectives.


Two logical connectives: Unary negation operator: &&, | | !

Dept. of CSE, IIT KGP

Expressions
(count <= 100) ((math+phys+chem)/3 >= 60) ((sex == M) && (age >= 21)) ((marks >== 80) && (marks < 90)) ((balance > 5000) | | (no_of_trans > 25)) (! (grade == A))

Dept. of CSE, IIT KGP

The conditions evaluate to


Zero
Indicates FALSE.

Non-zero
Indicates TRUE. Typically the condition TRUE is represented by the value 1.

Dept. of CSE, IIT KGP

Branching: The if Statement


if (expression) statement; if (expression) { Block of statements; }

The condition to be tested is any expression enclosed in parentheses. The expression is evaluated, and if its value is non-zero, the statement is executed.

Dept. of CSE, IIT KGP

A decision can be made on any expression.


print Passed true print Good luck

zero - false nonzero - true

marks >= 40

false

if (marks>=40) { printf(Passed \n); printf(Good luck\n); } printf (End\n) ;

Dept. of CSE, IIT KGP

Branching: if-else Statement


if (expression) { Block of statements; } else { Block of statements; } if (expression) { Block of statements; } else if (expression) { Block of statements; } else { Block of statements; }

Dept. of CSE, IIT KGP

Grade Computation
START

READ MARKS

if (marks >= 80) printf (A) ; else if (marks >= 60) printf (B) ; else if (marks >=60) printf (C) ; else printf (Failed) ; printf (\nEnd\n) ;
NO
MARKS 40?

MARKS 80?

NO

MARKS 60?

NO

YES
OUTPUT A

YES
OUTPUT B

YES
OUTPUT C OUTPUT F

STOP
Dept. of CSE, IIT KGP

STOP

STOP

STOP

int main () { int marks; scanf (%d, & marks) ; if (marks>= 80) { printf (A) ; printf (Good Job!) ; } else if (marks >= 60) printf (B) ; else if (marks >=60) printf (C) ; else { printf (Failed) ; printf (Study hard for the supplementary) ; } printf (\nEnd\n) ;

}
Dept. of CSE, IIT KGP

Find the larger of two numbers


START

int main () { int x, y; scanf (%d%d, &x, &y) ; if (x>y) printf (%d\n, x); else printf (%d\n, x); }
OUTPUT Y

READ X, Y

YES

IS X>Y?

NO

OUTPUT X

STOP

STOP

Dept. of CSE, IIT KGP

Example 3: Largest of three numbers


START

READ X, Y, Z

YES

IS X > Y?

NO

Max = X

Max = Y

YES
OUTPUT Max STOP
Dept. of CSE, IIT KGP

IS Max > Z?

NO
OUTPUT Z STOP

START

READ X, Y, Z

YES

IS X > Y?

NO

Max = X

Max = Y

YES
OUTPUT Max STOP

IS Max > Z?

NO
OUTPUT Z STOP

int main () { int x, y, z, max; scanf (%d%d%d,&x,&y,&z); if (x>y) max = x; else max = y; if (max > z) printf (%d, max) ; else printf (%d,z); }

Dept. of CSE, IIT KGP

Example
#include <stdio.h> main() { int a,b,c; scanf (%d %d %d, &a, &b, &c); if ((a>=b) && (a>=c)) printf (\n The largest number is: %d, a); if ((b>=a) && (b>=c)) printf (\n The largest number is: %d, b); if ((c>=a) && (c>=b)) printf (\n The largest number is: %d, c); }

Dept. of CSE, IIT KGP

Confusing Equality (==) and Assignment (=) Operators Dangerous error


Does not ordinarily cause syntax errors. Any expression that produces a value can be used in control structures. Nonzero values are true, zero values are false.

Example:
if ( payCode == 4 ) printf( "You get a bonus!\n" ); if ( payCode = 4 ) printf( "You get a bonus!\n" );

WRONG

Dept. of CSE, IIT KGP

Nesting of if-else Structures


It is possible to nest if-else statements, one within another. All if statements may not be having the else part.
Confusion??

Rule to be remembered:
An else clause is associated with the closest preceding unmatched if. Some examples shown next.

Dept. of CSE, IIT KGP

Dangling else problem


if (exp1) if (exp2) stmta else stmtb
if (exp1) { if (exp2) stmta else stmtb } if (exp1) { if (exp2) stmta } else stmtb

OR

Which one is the correct interpretation?

Dept. of CSE, IIT KGP

Dangling else problem


if (exp1) if (exp2) stmta else stmtb
if (exp1) { if (exp2) stmta else stmtb }

Dept. of CSE, IIT KGP

More examples
if e1 s1 else if e2 s2 if e1 s1 else if e2 s2 else s3 if e1 if e2 s1 else s2 else s3 if e1 if e2 s1 else s2

Dept. of CSE, IIT KGP

Answers
if e1 s1 else if e2 s2 if e1 s1 else if e2 s2 else s3 if e1 if e2 s1 else s2 else s3 if e1 if e2 s1 else s2 if e1 s1 else { if e2 s2 } if e1 s1 else { if e2 s2 else s3 } if e1 { if e2 s1 else s2 } else s3 if e1 { if e2 s1 else s2 }

Dept. of CSE, IIT KGP

Common Errors
c = getchar( ); if ((c == y) && (c == Y)) printf(Yes\n); else printf(No\n);

c = getchar( ); if ((c != n) || (c != N)) printf(Yes\n); else printf(No\n);

Dept. of CSE, IIT KGP

The Conditional Operator ?:


This makes use of an expression that is either true or false. An appropriate value is selected, depending on the outcome of the logical expression. Example:
interest = (balance>5000) ? balance*0.2 : balance*0.1;

Returns a value
Equivalent to: if (balance > 5000) interest = balance*0.2; else interest = balance*0.1;

Dept. of CSE, IIT KGP

More examples
Examples: x = ((a>10) && (b<5)) ? a+b : 0 (marks>=60) ? printf(Passed \n) : printf(Failed \n);

Dept. of CSE, IIT KGP

The switch Statement


This causes a particular group of statements to be chosen from several available groups.
Uses switch statement and case labels. Syntax of the switch statement:
switch (expression) { case expression-1: { .. } case expression-2: { .. } case expression-m: { .. } default: { } }

where expression evaluates to int or char

Dept. of CSE, IIT KGP

Examples
switch ( letter ) { case 'A': printf ("First letter \n"); break; case 'Z': printf ("Last letter \n"); break; default : printf ("Middle letter \n"); break; }

Will print this statement for all letters other than A or Z

Dept. of CSE, IIT KGP

Examples
switch (choice = getchar()) { case r : case R: printf(Red); break; case b : case B : printf(Blue); break; case g : case G: printf(Green); break; default: printf(Black); Dept. of CSE, IIT KGP }

Since there isnt a break statement here, the control passes to the next statement (printf) without checking the next condition.

Another way
switch (choice = toupper(getchar())) { case R: case G: case B: default: } printf (RED \n); break; printf (GREEN \n); break; printf (BLUE \n); break; printf (Invalid choice \n);

Dept. of CSE, IIT KGP

Rounding a Digit
switch (digit) { case 0: case 1: case 2: case 3: case 4: result = 0; printf (Round down\n); break; case 5: case 6: case 7: case 8: case 9: result = 10; printf(Round up\n); break; }

Dept. of CSE, IIT KGP

case - : nt main () { result=operand1-operand2; int operand1, operand2; break; int result = 0; case * : char operation ; result=operand1*operand2; /* Get the input values */ break; printf (Enter operand1 :); case / : scanf(%d,&operand1) ; if (operand2 !=0) result=operand1/operand2; printf (Enter operation :); scanf (\n%c,&operation); else printf(Divide by 0 error); printf (Enter operand 2 :); break; scanf (%d, &operand2); default: switch (operation) { printf(Invalid operation\n); case + : } result=operand1+operand2; printf (The answer is %d\n,resul break; }
Dept. of CSE, IIT KGP

The break Statement


Used to exit from a switch or terminate from a loop. With respect to switch, the break statement causes a transfer of control out of the entire switch statement, to the first statement following the switch statement. Can be used with other statements also

Dept. of CSE, IIT KGP

Example: Pattern Matching


Write a program that reads an arbitrarily long sequence of bits terminated with a null character and counts the number of occurrences of the sequence 0100

0 0

1 1

s0 0

s1 1

s2 2

s3 3

s4 4

1 0

Dept. of CSE, IIT KGP

Example: Pattern Matching


1 0 0 1 1

s0 0

s1 s1

s2 s2

s3 s3

1 0

Dept. of CSE, IIT KGP

c = getchar( ); switch (state) { s4 s4 case 0: if (c == 0) state = 1 else state = 0; break case 1: if (c == 0) state = 1 else state = 2; break case 2: if (c == 0) state = 3 else state = 0; break case 3: if (c == 0) state = 4 else state = 2; count++; break; case 4: if (c == 0) state = 1 else state = 2; break }

Example: Pattern Matching


c = getchar( ); count = 0; state = 0; while (c != \0) { switch (state) { case 0: if (c == 0) state = 1; else state = 0; break; --------------case 3: if (c == 0) state = 4; else state = 2; count++; break; case 4: if (c == 0) state = 1; else state = 2; break; } c = getchar( ); } printf(No of matches: %d\n, count);
Dept. of CSE, IIT KGP

A Look Back at Arithmetic Operators: The Increment and Decrement

Dept. of CSE, IIT KGP

Increment (++) and Decrement (--)


Both of these are unary operators; they operate on a single operand. The increment operator causes its operand to be increased by 1.
Example: a++, ++count

The decrement operator causes its operand to be decreased by 1.


Example: i--, --distance

Dept. of CSE, IIT KGP

Pre-increment versus post-increment


Operator written before the operand (++i, --i))
Called pre-increment operator. Operator will be altered in value before it is utilized for its intended purpose in the program.

Operator written after the operand (i++, i--)


Called post-increment operator. Operator will be altered in value after it is utilized for its intended purpose in the program.

Dept. of CSE, IIT KGP

Examples
Initial values :: a = 10; b = 20; x = 50 + ++a; x = 50 + a++; x = a++ + --b; x = a++ ++a; a = 11, x = 61 x = 60, a = 11 b = 19, x = 29, a = 11 ??

Called side effects:: while calculating some values, something else get changed.
Dept. of CSE, IIT KGP

You might also like