Вы находитесь на странице: 1из 23

Flow control structures Generally the flow of any program is in a sequence.

But in some situations it becomes necessary to make decisions and change the flow of the program according to the conditions. If statements: The if statement allows you to control if a program enters a section of code or not based on whether a given condition is true or false. Basic if Statement Syntax The structure of an if statement is as follows: if (conditional expression ) { <one or more statements> } The (simple) if statement is used to check one condition. For example, if (Age == 20) { cout << "I am twenty years old.; } To have more than one statement execute after an if statement, that evaluates to true, use braces. Anything inside braces is called a compound statement, or a block. #include <iostream> int main() { int Number; cout << "Enter a non zero number: "; cin >> Number; if(Number) cout << "\nYou entered this no." << Number << endl; 1

cout << endl; return 0; } If-else statement: Sometimes when the condition in an if statement evaluates to false, it would be nice to execute some code instead of the code executed when the statement evaluates to true. The "else" statement effectively says that whatever code after it (whether a single line or code between brackets) is executed if the if statement is FALSE. if (<conditional expression >) { <one or more statements> } else { <one or more statements> }

Else If Another use of else is when there are multiple conditional statements that may all evaluate to true, yet you want only one if statement's body to execute. You can use an "else if" statement following an if statement and its body; that way, if the first statement is true, the "else if" will be ignored, but if the if statement is false, it will then check the condition for the else if statement. If the if statement was true the else statement will not be checked. It is possible to use numerous else if statements to ensure that only one block of code is executed. if (<conditional expression #1>) { <one or more statements> 2

} else if (<conditional expression #2>) { <one or more statements> } else { <one or more statements> } #include <iostream> void main() { int age; cout<<"Please input your age: "; cin>> age; if ( age < 100 ) { cout<<"You are pretty young!\n"; } else if ( age == 100 ) { cout<<"You are old\n; } else { cout<<"You are really old\n"; } getch(); } 3

Nested if Else: It is possible to insert an if- else statement inside anther if else Statement .This is called nested if else and is used in programs where we need to cheek multiple condition. Syntax: if(Condition) { if(Condition) { Do this; } else { Do this; } } else { if(Condition) { do this; } else { Do this; } }

Q. WAP to find the largest of 4 numbers. #include<iostream.h> #include<conio.h> void main() {

clrscr(); int a,b,c,d; cout<<enter any four no: ; cin>>a>>b>>c>>d; if(a>b) { if(a>c) { if(a>d) cout<<\nLargest=<<a; else cout<<\nLargest=<<d;

} else { if(c>d) cout<<\nLargest=<<c; else cout<<\nLargest=>>d; } else { if(b>c) { if(c>d) cout<<\nLargest=<<b; else cout<<\nLargest=<<d } else { if(c>d) 5

cout<<\nLargest=<<c; else cout<<\nLargest=<<d; } } }//end of outer else.

getch(); } //end of main program. The Else-If Ladder: There is another way of putting ifs together when multiple decesions are involved. Syntax: If(condition1) Statements; else if(condition2) statements; else if(condition3) statements; else statements; The conditional expressions are evaluated from top to downwards. As soon as a true condition is found, the statement associated with it is extended, and the rest of the ladder is by passed. If none of the condition is true, then final else statement will be executed. Example 1: Q.WAP Program to find out grades as per the following conditions. Average Marks 75 to 100 60 to 74 50 to 59 40 to 49 0 to 39 Grade Distinction First Class Second Class Third Class Fail

#include<iostream.h> #include<conio.h> 6

void main() { clrscr(); float avg; cout<<\nEnter the average marks: ; cin>>avg; if(avg>=75) cout<<\nPassed with Distinction; else if(avg>=60) cout<<\nPassed with First Class; else if(avg>=50) cout<<\nPassed with Second Class; else if(avg>=40) cout<<\nPassed with Third Class; else cout<<\nFailed; getch(); }

Example 2: A program to display the name of the day in a week, depending upon the number which is entered by the keyboard using else-if ladder #include<iostream.h> #include<conio.h> void main() { int day; cout<<\nEnter a no. between 1 to 7; cin>>day; if(day==1) cout<<\nMonday; else if(day==2) cout<<\nTuesday;

else if(day==3) cout<<\nWednesday; else if(day==4) cout<<\nThursday; else if(day==5) cout<<\nFriday; else if(day==6) cout<<\nSaturday; else if(day==7) cout<<\nSunday; else cout<<\nWrong entry!; getch(); }

The switch statement The switch statement is multi-way decision making statement in C++. It allows several conditions to be evaluated within one statement rather than using series of ifelse statements. A case expression can be repeatedly used in a switch statement. The use of break statement in every case is used to quit the switch statement after a particular case is matched. Thus only one case gets executed. If the break case is not used, then all the case will get executed. Thus break statement is compulsory for the proper execution of the switch statement. Syntax: switch(exp) { case 1: { statement; break; } case 2: { statement; break; } . . 8

default: Statement; } statement x; EX: #include <iostream> #include<conio.h> void playgame() { cout << "Play game called"; } void loadgame() { cout << "Load game called"; } void playmultiplayer() { cout << "Play multiplayer game called"; } void main() { int input; cout<<"1. Play game\n"; cout<<"2. Load game\n"; cout<<"3. Play multiplayer\n"; cout<<"4. Exit\n"; cout<<"Selection: "; cin>> input; switch ( input ) { case 1: // Note the colon, not a semicolon playgame(); break; case 2: // Note the colon, not a semicolon loadgame(); break; case 3: // Note the colon, not a semicolon playmultiplayer(); break; case 4: // Note the colon, not a semicolon cout<<"Thank you for playing!\n"; break; default: // Note the colon, not a semicolon 9

cout<<"Error, bad input, quitting\n"; break; } getch(); } Counting and Looping Loop control structure This involves repeating some portion of the program either a specified number of times or until a particular condition is being satisfied. This repetitive operation is done through a loop control statement. A looping process, in general, would involve the following four steps: 1. Setting and initialization of a counter. 2. Execution of the statement in the loop. 3. Test for a specified condition for execution of the loop. 4. Incrementing the counter. There are three methods by way of which we can repeat a part of a program. They are: (a) Using a for statement (b) Using a while statement (c) Using a do-while statement 1. The while Statement The while is an entry controlled loop statement. The test condition is evaluated and only if the condition is true the body is executed. After execution of the body, the test condition is once again evaluated and if it is true the body is evaluated. This process repeats until the test condition becomes falls and the control is transferred out of the loop. The general form of while is as shown below: initialise loop counter ; while ( test loop counter using a condition ) { Statements; increment loop counter ; }

10

Example: void main() { int x; clrscr(); x=1; while(x<=10) { cout<<x; x++; } getch(); }

To execute this expression, the compiler first examines the Condition. If the Condition is true, then it executes the Statement. After executing the Statement, the Condition is checked again. AS LONG AS the Condition is true, it will keep 11

executing the Statement. When or once the Condition becomes false, it exits the loop. Here is an example: int Number; while( Number <= 12 ) { cout << "Number " << Number << endl; Number++; }

An example would be: #include <iostream> #include<conio.h> void main() { int Number= 0;

while( Number <= 12 ) { cout << "Number " << Number << endl;

12

Number++; }

} 2. The do...while Statement The do - while is an exit controlled loop statement almost same as the while loop. This statement does something first and then test if we have to continue. The result is that the statements get executed at least once because the condition test comes at the end. The general form of while is as shown below: initialise loop counter ; do { Statements; increment loop counter ; }while(condition);

The dowhile condition executes a Statement first. After the first execution of the Statement, it examines the Condition. If the Condition is true, then it executes the Statement again. It will keep executing the Statement AS LONG AS the Condition is true. Once the Condition becomes false, the looping (the execution of the Statement) would stop. If the Statement is a short one, such as made of one line, simply write it after the do keyword. Like the if and the while statements, the Condition being checked must be included between parentheses. The whole 13

dowhile statement must end with a semicolon. Another version of the counting program seen previously would be: #include <iostream.h> using namespace std;

void main() { int Number = 0;

do cout << "Number " << Number++ << endl; while( Number <= 12 );

return 0; } If the Statement is long and should span more than one line, start it with an opening curly bracket and end it with a closing curly bracket. The dowhile statement can be used to insist on getting a specific value from the user. For example, since our ergonomic program would like the user to sit down for the subsequent exercise, you can modify your program to continue only once she is sitting down. Here is an example on how you would accomplish that: #include <iostream> using namespace std; int main() { char SittingDown;

cout << "For the next exercise, you need to be sitting down\n"; do {

14

cout << "Are you sitting down now(y/n)? "; cin >> SittingDown; } while( !(SittingDown == 'y') );

cout << "\nWonderful!!!";

} Distinction between while loop and do while loop While loop 1. 2. 3. 4. It is entry control loop First condition is checked then statements are executed. Statements may not be executed. Semi colon should not be given after while statement. Do while loop It is a exit control loop. First statements are executed then condition is checked. Statements are executed at least once. Semi colon is required after a do while statement.

1. 2. 3. 4.

The for Statement The for statement is typically used to count a number of items. At its regular structure, it is divided in three parts. The first section specifies the starting point for the count. The second section sets the counting limit. The last section determines the counting frequency. The syntax of the for statement is: for( Start; End; Frequency) { Statement; } The Start expression is a variable assigned the starting value. This could be Count = 0; The End expression sets the criteria for ending the counting. An example would be Count < 24; this means the counting would continue as long as the Count variable is less than 24. When the count is about to rich 24, because in this case 24 is excluded, the counting 15

would stop. To include the counting limit, use the <= or >= comparison operators depending on how you are counting. The Frequency expression would let the compiler know how many numbers to add or subtract before continuing with the loop. This expression could be an increment operation such as ++Count. Here is an example that applies the for statement: #include <iostream.h> #include<conio.h> int main() { for(int Count = 0; Count <= 12; Count++) cout << "Number " << Count << endl;

return 0; } The C++ compiler recognizes that a variable declared as the counter of a for loop is available only in that for loop. This means the scope of the counting variable is confined only to the for loop. This allows different for loops to use the same counter variable. Here is an example: #include <iostream> #include<conio.h>

int main() { for(int Count = 0; Count <= 12; Count++) cout << "Number " << Count << endl; cout << endl;

for(int Count = 10; Count >= 2; Count--) cout << "Number " << Count << endl;

16

return 0; } Some compilers do not allow the same counter variable in more than one for loop. The counter variables scope spans beyond the for loop. With such a compiler, you must use a different counter variable for each for loop. An alternative to using the same counter variable in different for loops is to declare the counter variable outside of the first for loop and call the variable in the needed for loops. Here is an example: #include <iostream> #include<conio.h>

int main() { int Count;

for(Count = 0; Count <= 12; Count++) cout << "Number " << Count << endl; cout << endl;

for(Count = 10; Count >= 2; Count--) cout << "Number " << Count << endl;

return 0; }

17

Nested for loop Syntax: for(i=1;i<=5;i++) { .. .. for(j=1;j<=5;j++) { . . } Rules of the nested loop 1. Inner and outer loop should not overlap 2. Running variables used in the loops are to be independent or separate. 3. Direct jump from inner loop to outer loop is allowed but jump from outer loop to inner loop is not allowed. 4. We can use for loop within while loop or do while loop and vice versa. 5. If total iteration of the outer loop is n and iteration of the inner loop is m then body of inner loop is executed m*n times.

WAP to generate the following pattern * *** *** ** **** *** #include<iostream.h> #include<conio.h> void main() { clrscr(); int r,c,p,q; for(r=1;r<=5;r++) { for(c=1;c<=5-r;c++) { cout<<" "; } for(p=1;p<=r;p++) { cout<<"*"; } for(q=p-2;q>=1;q--) { cout<<"*"; } cout<<endl; 18

} getch(); }

Jumps in loops Sometimes, when executing a loop it becomes desirable to skip a part of the loop or to leave the loop as soon as certain condition occurs. a) break The break statement is used to jump out of a loop. When break statement is encountered within a loop, execution of the loop stops and statements following the loop are executed. It can be used to end an infinite loop, or to force it to end before its natural end. The syntax of the break statement is simply: break; within a loop it takes the following form, while() {. . if (condition) break; .. Exit from the loop, execution continues with statements following the loop. .. } Example 1: #include<iostream.h> #include<conio.> void main() { int n; for(n=10; n>0; n--) { cout<<n<< , ; if(n==4) { cout<<\n countdown stopped!; break; } 19

} getch(); } Output: 10, 9, 8, 7, 6, 5, countdown stopped! b) continue statement The keywords continue skips a particular iteration and continues with the next. When continue statement is encountered in a loop, execution of that iteration is skipped and the loop continues with the next iterations. Syntax of the statement is , continue; within a loop it takes the following form:while() {. . if (condition) continue; .. .} Example 2:

Exit from loop, execution continues with remaining iterations.

#include<iostream.h> #include<conio.> void main() { int n; for(n=10; n>0; n--) { if(n==7 || n==4) continue; cout<<n<< , ; } getch(); } Output: 10, 9, 8, 6, 5, 3, 2, 1 The difference between break and continue statement. Break statement is used to terminate a loop; break statement takes the control to the next statement after the loop. Continue statement is used to ignore the remaining loop and will continue with the next repetition. 20

c) goto statement:The goto statement transfers the program control directly to a labeled statement. A common use of go to is to transfer control to a specific label. It is also useful to get out of the deeply nested loops. Execution control is transferred when goto label statement is encountered and is continued from the label: statement between the goto label and label are skipped. Syntax of the statement is goto label; .. .. .. label: For example

#include <iostream> #include<conio.h> void main() { for(int Count = 0; Count <= 12; ++Count) { cout << "Count =" << Count << endl;

if( Count == 5 ) goto ccc; }

ccc: cout << "Stopped at 5";

getch(); } 21

Output: Count=1 Count=2 Count=3 Count=4 Stopped at 5 Example 3: #include<iostream.h> #include<conio.h> void main() { clrscr(); int n; aa: cout<<\n enter a no.:; cin>>n; if(n>10 || n<1) { cout<<\n enter a no. between 1 and 10; goto aa; } cout<<\n Your no. is : <<n; getch(); } Output Run1 Enter a no. : 12 Enter a no.between 1 and 10 Run 2 Enter a no : 6 Your no. is 6 d) return:The return statement terminates the execution of a function and returns control to the calling function. Execution resumes in the calling function at the point immediately following the call. A return statement can also return a value to the calling function. Eg. return 0 Example 4: #include<iostream.h> #include<conio.h> int main() { clrscr(); cout<<hello world; return 0; getch(); 22

23

Вам также может понравиться