Presentation is loading. Please wait.

Presentation is loading. Please wait.

Flow of Control Unless specified otherwise, the order of statement execution through a method is linear: one statement after another in sequence Some programming.

Similar presentations


Presentation on theme: "Flow of Control Unless specified otherwise, the order of statement execution through a method is linear: one statement after another in sequence Some programming."— Presentation transcript:

1 Flow of Control Unless specified otherwise, the order of statement execution through a method is linear: one statement after another in sequence Some programming statements allow us to: decide whether or not to execute a particular statement execute a statement over and over, repetitively These decisions are based on boolean expressions (or conditions) that evaluate to true or false The order of statement execution is called the flow of control

2 Conditional Statements
A conditional statement lets us choose which statement will be executed next Therefore they are sometimes called selection statements Conditional statements give us the power to make basic decisions The conditional statements are : if statement if-else statement switch statement

3 The if Statement The if statement has the following syntax:
The condition must be a boolean expression. It must evaluate to either true or false. if is a reserved word if ( condition ) statement; If condition is true: statement is executed. If condition is false: statement is skipped.

4 Logic of an if statement
condition evaluated false statement true

5 The if Statement An example of an if statement:
if (sum > MAX) delta = sum - MAX; cout<<“The sum is “<< sum; First the condition is evaluated -- the value of sum is either greater than the value of MAX, or it is not If the condition is true, the assignment statement is executed -- if it isn’t, it is skipped.

6 Indentation The statement controlled by the if statement is indented to indicate that relationship The use of a consistent indentation style makes a program easier to read and understand Although it makes no difference to the compiler, proper indentation is crucial

7 if ( a > 10 && b > 20 && c < 10 )

8 The if Statement What do the following statements do?
if (top >= MAXIMUM) top = 0; Sets top to zero if the current value of top is greater than or equal to the value of MAXIMUM if (total != stock + warehouse) inventoryError = true; Sets a flag to true if the value of total is not equal to the sum of stock and warehouse The precedence of the arithmetic operators is higher than the precedence of the equality and relational operators

9 The if-else Statement An else clause can be added to an if statement to make an if-else statement if ( condition ) statement1; else statement2; If the condition is true, statement1 is executed; if the condition is false, statement2 is executed

10 Logic of an if-else statement
condition evaluated false statement2 statement1 true

11 Block Statements Several statements can be grouped together into a block statement delimited by braces A block statement can be used wherever a statement is called if (total > MAX) { printf("Error!!"); errorCount++; }

12 Block Statements In an if-else statement, the if portion, or the else portion, or both, could be block statements if (total > MAX) { printf ("Error!!"); errorCount++; } else printf ("Total: " + total); current = total*2;

13 Nested if Statements The statement executed as a result of an if statement or else clause could be another if statement These are called nested if statements An else clause is matched to the last unmatched if (no matter what the indentation implies) Braces can be used to specify the if statement to which an else clause belongs

14 The switch Statement The switch statement provides another way to decide which statement to execute next The switch statement evaluates an expression, then attempts to match the result to one of several possible cases Each case contains one value (a constant) and a list of statements The flow of control transfers to statement associated with the first case value that matches

15 The switch Statement The general syntax of a switch statement is:
and case are reserved words switch ( expression ) { case value1 : statement-list1 case value2 : statement-list2 case value3 : statement-list3 case ... } If expression matches value2, control jumps to here

16 The switch Statement Often a break statement is used as the last statement in each case's statement list A break statement causes control to transfer to the end of the switch statement If a break statement is not used, the flow of control will continue into the next case Sometimes this may be appropriate, but often we want to execute only the statements associated with one case

17 The switch Statement An example of a switch statement: switch (option)
{ case 'A': aCount++; break; case 'B': bCount++; case 'C': cCount++; }

18 The switch Statement A switch statement can have an optional default case The default case has no associated value and simply uses the reserved word default If the default case is present, control will transfer to it if no other case value matches If there is no default case, and no other value matches, control falls through to the statement after the switch

19 The switch Statement The expression of a switch statement must result in an integral type, meaning an integer (byte, short, int, long) or a char It cannot be a boolean value or a floating point value (float or double) The implicit boolean condition in a switch statement is equality You cannot perform relational checks with a switch statement

20 #include<iostream> using namespace std; int main() { int A; cin >> A; if ( A == 10 ) cout << "is equal" << '\n'; return 0; } if ( A != 10 ) { cout << "Hello" << '\n'; cout << "Hello" << '\n'; }

21 #include<iostream> using namespace std; int main() { int A; cin >> A; if ( A == 10 ) { cout << "is equal" << '\n'; cout << "closing program" << '\n'; } else { cout << "not equal" << '\n'; cout << "closing program" << '\n'; } return 0; }

22 #include<iostream>
using namespace std; int main() { int a; cin >> a; if ( a <= 10 ) { cout << "Below 10" << '\n'; } else { if ( a < 60 ) { cout << "Below 60" << '\n'; } } return 0; }

23 #include<iostream> using namespace std; int main() { char myinput; cin >> myinput; switch (myinput) { case 'a': cout << "Run program 1\n"; break; case 'b': { cout << "Run program 2\n"; cout << "Please Wait\n"; break; } default: cout << "Invalid choice\n"; break; } return 0; }

24 if (total_test_score >=0 && total_test_score < 50) cout << "You are a failure - you must study much harder.\n"; else if (total_test_score < 60) cout << "You have just scraped through the test.\n"; else if (total_test_score < 80) cout << "You have done quite well.\n"; else if (total_test_score <= 100) cout << "Your score is excellent - well done.\n"; else cout << "Incorrect score - must be between 0 and 100.\n";

25 score_out_of_ten = total_test_score / 10; switch (score_out_of_ten) { case 0: case 1: case 2: case 3: case 4: cout << "You are a failure - you "; cout << "must study much harder.\n"; break; case 5: cout << "You have just scraped through the test.\n"; break; case 6: case 7: cout << "You have done quite well.\n"; break; case 8: case 9: case 10: cout << "Your score is excellent - well done.\n"; break; default: cout << "Incorrect score - must be between "; cout << "0 and 100.\n"; } ...

26 Repetition Statements
Repetition statements allow us to execute a statement multiple times Often they are referred to as loops Like conditional statements, they are controlled by boolean expressions three kinds of repetition statements: the while loop the do loop the for loop The programmer should choose the right kind of loop for the situation

27 The while Statement A while statement has the following syntax:
while ( condition ) statement; If the condition is true, the statement is executed Then the condition is evaluated again, and if it is still true, the statement is executed again The statement is executed repeatedly until the condition becomes false

28 Logic of a while Loop condition evaluated false statement true

29 The while Statement An example of a while statement:
int count = 1; while (count <= 5) { cout<<count; count++; } If the condition of a while loop is false initially, the statement is never executed Therefore, the body of a while loop will execute zero or more times

30 The while Statement Let's look at some examples of loop processing
A loop can be used to maintain a running sum A sentinel value is a special input value that represents the end of input A loop can also be used for input validation, making a program more robust

31 Infinite Loops The body of a while loop eventually must make the condition false If not, it is called an infinite loop, which will execute until the user interrupts the program This is a common logical error You should always double check the logic of a program to ensure that your loops will terminate normally

32 Infinite Loops An example of an infinite loop:
int count = 1; while (count <= 25) { cout<<count; count = count - 1; } This loop will continue executing until interrupted (Control-C) or until an underflow error occurs

33 Nested Loops Similar to nested if statements, loops can be nested as well That is, the body of a loop can contain another loop For each iteration of the outer loop, the inner loop iterates completely

34 Nested Loops How many times will the string "Here" be printed?
count1 = 1; while (count1 <= 10) { count2 = 1; while (count2 <= 20) cout<<"Here"; count2++; } count1++; 10 * 20 = 200

35 Nested Loops Nested loops consist of an outer loop with one or more inner loops. e.g., for (i=1;i<=100;i++){ for(j=1;j<=50;j++){ } The above loop will run for 100*50 iterations. Outer loop Inner loop

36 int x; main() { for (x=3;x>0;x--) { printf("x=%dn",x); } }
int x; main() { for (x=3;x>0;x--) { printf("x=%dn",x); } } ... outputs: x=3 x=2 x=1 ...to the screen

37 following are legal for statements in C
following are legal for statements in C. for (x=0;((x>3) && (x<9)); x++) for (x=0,y=4;((x>3) && (y<9)); x++,y+=2) for (x=0,y=4,z=4000;z; z/=10) The second example shows that multiple expressions can be separated a ,. In the third example the loop will continue to iterate until z becomes 0;

38 the while loop can accept expressions, not just conditions,
the following are all legal:-  while (x-); while (x=x+1); while (x+=5); Using this type of expression, only when the result of x-, x=x+1, or x+=5, evaluates to 0 will the while condition fail and the loop be exited. 

39   while (i++ < 10);   while ( (ch = getchar()) != `q')    putchar(ch); The first example counts i up to 10.  The second example uses C standard library functions The while loop will proceed to read from the keyboard and echo characters to the screen until a 'q' character is read.  NOTE: This type of operation is used a lot in C and not just with character reading

40 int x=3; main() { do { printf("x=%dn",x-); } while (x>0); }
int x=3; main() { do { printf("x=%dn",x-); } while (x>0); } ..outputs:- x=3 x=2 x=1 NOTE: The postfix x- operator which uses the current value of x while printing and then decrements x.

41 The do while Statement A do statement has the following syntax: do {
} while ( condition ); The statement is executed once initially, and then the condition is evaluated The statement is executed repeatedly until the condition becomes false

42 Logic of a do Loop statement true condition evaluated false

43 The do while Statement An example of a do loop:
int count = 0; do { count++; cout<<count; } while (count < 5); The body of a do while loop executes at least once

44 Comparing while and do The while Loop The do While Loop statement
true false condition evaluated The while Loop true condition evaluated statement false The do While Loop

45 The for Statement A for statement has the following syntax:
The initialization is executed once before the loop begins The statement is executed until the condition becomes false for ( initialization ; condition ; increment ) statement; The increment portion is executed at the end of each iteration

46 Logic of a for loop initialization condition evaluated false statement
true increment

47 The for Statement A for loop is functionally equivalent to the following while loop structure: initialization; while ( condition ) { statement; increment; }

48 The for Statement An example of a for loop:
for (int count=1; count <= 5; count++) cout<<count; The initialization section can be used to declare a variable Like a while loop, the condition of a for loop is tested prior to executing the loop body Therefore, the body of a for loop will execute zero or more times

49 The for Statement The increment section can perform any calculation
for (int num=100; num > 0; num -= 5) cout<< num; A for loop is well suited for executing statements a specific number of times that can be calculated or determined in advance

50 The for Statement Each expression in the header of a for loop is optional If the initialization is left out, no initialization is performed If the condition is left out, it is always considered to be true, and therefore creates an infinite loop If the increment is left out, no increment operation is performed

51 Omitting the logical expression in a for statement means that the for statement executes as an infinite loop. for(i=1; ;i=i+1) {

52 #include <iostream> using namespace std; int main() { int number; char character; for (number = 32 ; number <= 126 ; number = number + 1) { character = number; cout << "The character '" << character; cout << "' is represented as the number "; cout << number << " in the computer.\n"; } return 0; }

53 #include <iostream> using namespace std; int main() { int number; char character; number = 32; while (number <= 126) { character = number; cout << "The character '" << character; cout << "' is represented as the number "; cout << number << " in the computer.\n"; number++; } return 0; }

54 do { cout << "Enter the candidate's score: "; cin >> candidate_score; if (candidate_score > 100 || candidate_score < 0) cout << "Score must be between 0 and 100.\n"; } while (candidate_score > 100 || candidate_score < 0);

55 cout << "Enter the candidate's score: "; cin >> candidate_score; while (candidate_score > 100 || candidate_score < 0) { cout << "Score must be between 0 and 100.\n"; cin >> candidate_score; }

56 C provides two commands to control how we loop:
break -- exit form loop or switch. continue -- skip 1 iteration of loop.

57 The break and continue Statements
The break statement causes an exit from the innermost enclosing loop or switch statement. The continue statement causes the current iteration of a loop to stop and the next iteration to begin immediately.

58 Example Using a break Statement
while (1) { scanf(“%lf”, &x); if (x < 0.0) break; printf(“%f\n”, sqrt(x)); } /* break causes jump to next statement */ /* after the while loop */

59 Example Using a continue Statement
while (cnt < n) { scanf(“%lf”, &x); if (x > && x < +0.01) continue; /* disregard small values */ ++cnt; sum += x; /* continue transfers control to */ /* here to immediately begin the */ /* next iteration */ }

60 Consider the following example where we read in integer values and process them according to the following conditions. If the value we have read is negative, we wish to print an error message and abandon the loop. If the value read is great than 100, we wish to ignore it and continue to the next value in the data. If the value is zero, we wish to terminate the loop.

61   while (scanf( "%d", &value ) == 1 && value != 0) {   if (value < 0)
{ printf("Illegal valuen"); break; /* Abandon the loop */ }   if (value > 100) { printf("Invalid valuen"); continue; /* Skip to start loop again */ }   /* Process the value read */ /* guaranteed between 1 and 100 */ ....;   } /* end while value != 0 */

62 Comparison of Loop Choices (1/2)
Kind When to Use C Structure Counting loop We know how many loop repetitions will be needed in advance. while, for Sentinel-controlled loop Input of a list of data ended by a special value Endfile-controlled loop Input of a list of data from a data file

63 Comparison of Loop Choices (2/2)
Kind When to Use C Structure Input validation loop Repeated interactive input of a value until a desired value is entered. do-while General conditional loop Repeated processing of data until a desired condition is met. while, for

64 The goto Statement goto causes an unconditional jump to a labeled statement somewhere in the current function. Form of a labeled statement. label: statement Where label is an identifier.

65 Example of goto and label
while (scanf(“%lf”, &x) == 1) { if (x < 0.0) goto negative_alert; printf(“%f %f %f”, x, sqrt(x), sqrt(2 * x)); } negative_alert: printf(“Negative value encountered!\n”);

66 Same Example Without goto
while(scanf(“%lf”, &x) == 1 && x >= 0.0) printf(“%f %f %f\n”, x, sqrt(x), sqrt(2 * x)); if (x < 0.0) printf(“Negative value encountered!\n); && x >= 0.0 accomplishes what the goto accomplished, namely the printf() will not be executed if a negative number is entered.

67 When Should goto Be Used?
Almost never (it is never needed). gotos can make a program very difficult to read and understand. In rare instances such as exiting from a deeply nested inner loop to the outermost level, a goto can make a program execute with significantly greater efficiency.

68 Blocks and Scoping These braces have a special effect on variable declarations. A compound statement that contains one or more variable declarations is called a block, and the variables declared within the block have the block as their scope. In other words, the variables are "created" each time the program enters the block, and "destroyed" upon exit. If the same identifier has been used both for a variable inside and a variable outside the block, the variables are unrelated. While in the block, the program will assume by default that the identifier refers to the inner variable - it only looks outside the block for the variable if it can't find a variable declaration inside.

69 #include <iostream> using namespace std; int integer1 = 1; int integer2 = 2; int integer3 = 3; int main() { int integer1 = -1; int integer2 = -2; int integer1 = 10; cout << "integer1 == " << integer1 << "\n"; cout << "integer2 == " << integer2 << "\n"; cout << "integer3 == " << integer3 << "\n"; } cout << "integer3 == " << integer3 << "\n"; return 0;

70 #include <iostream> using namespace std; int main() { int number; for (number = 1 ; number <= 10 ; number++) { int multiplier; for (multiplier = 1 ; multiplier <= 10 ; multiplier++) { cout << number << " x " << multiplier << " = "; cout << number * multiplier << "\n"; } cout << "\n"; }

71 C EXAMPLE "FOR LOOP" WITH TWO CONTROL VARIABLES
#include<stdio.h> void main(void) { char letter; int number; for (letter = 'A', number = 2; letter < 'J'; letter++, number = number+5) { printf("%c(%d), %c(%d)\n",letter, letter,letter+number, letter+number); } A(65), C(67) B(66), I(73) C(67), O(79) D(68), U(85) E(69), [(91) F(70), a(97) G(71), g(103) H(72), m(109) I(73), s(115) C EXAMPLE "FOR LOOP" WITH TWO CONTROL VARIABLES

72 C POSTEST DO-WHILE LOOP EXAMPLE (FIBONACCI)
void main(void){ int numTerms=0, frstTerm, scndTerm, tempNum; do { if (numTerms == 0) { frstTerm = 0; printf(“0”); } else if (numTerms == 1) { scndTerm = 1; printf(“1”); else { tempNum = frstTerm+scndTerm; frstTerm = scndTerm; scndTerm = tempNum; printf("%d ",scndTerm); numTerms++; } while (numTerms < 11); printf("\n"); C POSTEST DO-WHILE LOOP EXAMPLE (FIBONACCI)

73 COMPARISON OF C PRE-TEST (WHILE) AND POST-TEST (DO-WHILE) LOOPS (Input example)
void main(void) { int number = 0; printf("Input an integer between 1 and 50 (inclusive)\n"); while (number < 1 || number > 50) { scanf("%d",&number); } printf("%d\n",number); void main(void) { int number; printf("Input an integer between 1 and 50 (inclusive)\n"); do { scanf("%d",&number); } while (number < 1 || number > 50); printf("%d\n",number); }

74 Delay Loop with Empty Statement
int i = 0; . . . printf(“Error: reenter data.\n”); while (++i < 10000) /* delay */ ; system(“clear”); /* while loop keeps message on */ /* the screen momentarily. */

75 Programs for practice

76 Write a program to read in 10 numbers and compute the average, maximum and minimum values.
Write a program to read in numbers until the number -999 is encountered. The sum of all number read until this point should be printed out. Write a program which will read an integer value for a base, then read a positive integer written to that base and print its value. Read the second integer a character at a time; skip over any leading non-valid (i.e. not a digit between zero and ``base-1'') characters, then read valid characters until an invalid one is encountered.

77 Sample loop questions 1: Write a program to calculate the integer square root of a number e.g. 7 integer square is 2 etc 2: Write a program which continually reads in integers until 45 is read in 3: Use a Do while loop to calculate the minimum of 100 integers being read in. 4: Read in 10 integers and output the largest of them 5: Keep reading in integers until one is input which is larger than 100 6: Read in 20 integers and count the even numbers 7:Write a program to calculate

78 Write a program to calculate
e = 1/1! + 1/2! + 1/3! Etc Do it for 6 terms

79 There are some goats and ducks in a farm
There are some goats and ducks in a farm. There are 60 eyes and 86 foot in total. Write a program to find number of goats and ducks in the farm. Write a C program to find a three digit number which is greater than the aggregate of its third, tenth and the twelfth parts by 58. Write a C program to find a two digit number, the second digit of which is smaller than its first digit by 4, and if the number was divided by the digits sum, the quotient would be 7. Consider the following number 45*45=2025; 20+25=45.Write a program to generate number between 32 and 99 that satisfies the above property. Rita has a money pouch containing Rs.700. There are equal number of 25 paise coins, 50 paise and one rupee coins. Write a C program to find how many of each are there?

80 A number of �Cats� got together and decided to kill between them mice. Every cat killed equal number of �mice�. Write a program to find number of cats. Bacteria are known to multiply very rapidly. If a certain container contains just one bacterium on the first day and there are twice as many on the next day. In this manner the number of bacteria in the container doubles itself everyday. Assuming that the container would be full on the 10th day with 13,312 bacteria, find the number of bacteria that was initially in the container on the first day. Write a C program to find a peculiar two digit number which is three times the sum of its digits.

81 Example The program is designed to assist in monitoring the gasoline supply in a storage tank at the Super Oil Company refinery. The program is to alert the supervisor when the supply of gasoline in the tank falls below 10% of the tank’s 80,000 barrel storage capacity. The barrel used in the petroleum industry equals 42 U.S. gallons

82 Program to Monitor Gasoline Storage Tank

83 Program to Monitor Gasoline Storage Tank (cont’d)
Loop repetition Program to Monitor Gasoline Storage Tank (cont’d)

84 Program to Monitor Gasoline Storage Tank (cont’d)
Warning message after running out of the loop in monitor_gas


Download ppt "Flow of Control Unless specified otherwise, the order of statement execution through a method is linear: one statement after another in sequence Some programming."

Similar presentations


Ads by Google