1 / 58

Flow of Control – C++

Flow of Control – C++. OBJECTIVES. Illustration of the Concept of Control Flow Types of Control Flow Knowledge about conditional and repetitive statements. Make more proficient in handling programs in Control Flow. Develop Logic building skill.

daryl
Download Presentation

Flow of Control – C++

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Flow of Control – C++

  2. OBJECTIVES Illustration of the Concept of Control Flow Types of Control Flow Knowledge about conditional and repetitive statements. Make more proficient in handling programs in Control Flow. Develop Logic building skill.

  3. Flow is the term used for the order that the computer executes the lines of codes in a program. • In any programming language three types of control flow occurs. • Sequence • Selection • Iteration

  4. 1. SEQUENCE CONSTRUCT • In this type of construct the statements are executed sequentially. • i.e. Statement1 followed by Statement 2 , and Statement 2 followed by Statement3 and so on. Statement 1 Statement 2 Statement 3

  5. 2. SELECTION CONSTRUCT • Selection construct means – execution of statement(s) depending upon a condition test. If a condition evaluates to true, a course of action will be followed (set of statements) otherwise another course of action (different set of action ) will be followed. • This is also called as Conditional Construct or Decision Construct.

  6. TRUE One course-of-action Condition ? Statement 1 Statement 2 FALSE Statement 1 Another course of action Statement 2

  7. Selection Statements • If Statement • Switch Case Note: In certain circumstances , conditional operator called as ternary operator (? :) is used as an alternative to IF statement.

  8. 3. ITERATION/ REPETITIVE CONSTRUCT • Iteration Construct means repetition of a set of statements depending upon a condition test. • Till the condition is true a set of statements are repeated again and again. • As soon as the condition becomes false, the iteration stops. • This construct is also called as Looping Construct. • The set of statements that are repeated again and again is called the body of the loop. The condition on which the execution or exit of loop depends is called exit condition or test condition.

  9. The Iteration Construct FALSE Condition ? The exit Condition TRUE Statement 1 The Loop Body Statement 2

  10. Iteration Statements • For Loop • While Loop • Do- While Loop

  11. Logical Expressions which may include: • 6 Relational Operators < <= > >= == != • 3 Logical Operators ! && ||

  12. Conditional Statements 1. If Statement Syntax if (expression) statement1else statement2 else clause is optional

  13. Program – Write a Temperature Conversion Program in C++ that gives user the option of converting Fahrenheit to Celsius or Celsius to Fahrenheit. #include<iostream.h> void main() { int choice; float temp, countemp; cout << “Temperature Conversion Menu” <<“\n”; cout << “1. Fahrenheit to Celsius” <<“\n”; cout << “2. Celsius to Fahrenheit” <<“\n”; cout << “Enter your choice. Press either 1 or 2” ; cin >>choice; if (choice ==1) { cout << “\n” <<“Enter Temperature in Fahrenheit :”; cin >>temp; countemp = (temp-32)/1.8; cout <<“\n” <<“ The temperature in Celsius is : ” << countemp <<“\n”; } else { cout << “\n” <<“Enter Temperature in Celsius :”; cin >>temp; countemp = 1.8 * temp + 32; cout <<“\n” <<“ The temperature in Fahreheit is : ” << countemp <<“\n”; }

  14. OUTPUT - When user choice is 1 Temperature Conversion Menu 1. Fahrenheit to Celsius 2. Celsius to Fahrenheit Enter your choice : 1 Enter temperature in Fahrenheit : 98 The temperature in Centigrade is : 36.66

  15. OUTPUT – When user choice is 2 Temperature Conversion Menu 1. Fahrenheit to Celsius 2. Celsius to Fahrenheit Enter your choice : 2 Enter temperature in Centigrade : 37 The temperature in Fahrenheit is : 98.6

  16. Nested Ifs Syntax if (expression1) { : if(expresssion2) statement1; [ else statement2;] : } else body of else; if (expression1) { body of if if(expresssion2) statement1; [ else statement2;] : } else body of else; Part shown in [] is optional

  17. Example – Program to create the equivalent of a four – function Calculator. The program requires the user to enter two numbers and an operator. It then carries out the specified arithmetic operation : addition, subtraction, multiplication or division of the two numbers . Finally it displays the result . • #include<iostream.h>#include<conio.h>int main(){clrscr();char ch;float a,b,result;cout <<“Enter any two numbers:”;cin>>a>>b;cout<<“\n”<<“Enter the operator(+,-,*,/)”;cin >>ch;cout<<“\n”;if (ch==‘+’) result=a+b;else if(ch==‘-’) result=a-b; else if(ch==‘*’) result=a*b; else if(ch==‘/’) result=a/b;

  18. else{cout<<“\n”<<“Wrong operator!”<<“\n”;goto lb;}cout<<“\n”<<“The Calculated result is :”<<“\n”<<result<<“\n”;lb:return 0;}

  19. OUTPUT Enter two numbers : 9 3 Enter the operator (+,-,*,?) : / The Calculated result is : 3

  20. The ? : Operator – Alternative to if The operator can be used to replace if-else statements if(expression1) expression2; else expression3; The above form of if can be alternatively written using ?: as follows: expression1? expression2: expression3; It works as If statement does i.e If expression1 is true, epression2 gets evaluated otherwise expression3 will be evaluated.

  21. Switch – Case Statement Syntax switch(expression) { case constant1: Statement Sequence 1; break; case constant2: Statement Sequence 2; break; case constant3: Statement Sequence 1; break; [ default : Statement Sequence n;] }

  22. Example - switch (letter) { case ‘N’: cout < “New York\n”; break; case ‘L’: cout < “London\n”; break; case ‘A’: cout < “Amsterdam\n”; break; default: cout < “Somewhere else\n”; break; }

  23. WAP to input number of week’s day (1-7) and translate to its equivalent name of the day of the week(eg. 1 to Sunday, 2 to Monday ----7 to Saturday). # include<iostream.h> void main() { int dow; cout <<“Enter number of week’s day(1-7) :”; cin >>dow; switch (dow) { case 1: cout << “\n” <<“Sunday”; break; case 2: cout << “\n” <<“Monday”; break; case 3: cout << “\n” <<“Tuesday”; break; case 4: cout << “\n” <<“Wednesday”; break; case 5: cout << “\n” <<“Thursday”; break; case 6: cout << “\n” <<“Friday”; break; case 7: cout << “\n” <<“Saturday”; break;

  24. default : cout <<“\n” <<“Wrong number of day”; break; } } OUTPUT Enter number of week’s day(1-7) : 5 Thursday

  25. Program to illustrate the working of switch in the absence of break statement. #include<isotream.h> void main() { int i = 0, ub = 0, fail = 0; while ( I <= 5) { switch (i++ ) { case 1 : case 2 : ++ua ; case 3 : case 4 : ++ub ; case 5 : ++uc ; default : ++fail ; } } cout << “ua =“ << “ua << “\t” << “ub =“ << ub ; cout << “uc =“ << “ua << “\t” << “fail =“ << fail; } OUTPUT ua = 2 ub = 4 uc = 5 fail = 6

  26. Iteration Statements 1.For Loop 2.While-Loop 3.Do While Loop

  27. 1.For Loop Syntax for(intialization expression(s); test expression; update expression(s)) body of the loop;

  28. Initialization Expression(s) Test Expression Exit Body of the Loop Update Expression(s) Outline working of for loop False True

  29. Example // compute sum = 1 + 2 + ... + n // using for loop # include<iostream.h> void main() { int sum = 0; for (int i = 1; i <= n; ++i) { sum += i; } cout << “/n” <<“sum =“ << sum; } i doesn't exist here!

  30. 2. While-Loop Syntax while (expression) statement ; It's a pre-test loop.

  31. // compute sum = 1 + 2 + ... + n // using a while loop int i; int sum = 0; i = 1; while (i <= n) { sum += i; i++; } loop termination condition. body of the loop increment of the value

  32. 3.Do While Loop In some situations, it is wanted that the loop-body is executed at least once, no matter what the initial state of the test-expression is. In such cases, the do-while loop is used.

  33. It's a post-test loop Syntax do { Statements; } while (test-expression); It is also called as exit-controlled loop

  34. Example # include<iostream.h> void main() { char ch = ‘A’; do { cout << “\n” <<ch; ch++; } while (ch <=‘Z’); } The above codes prints characters from ‘A’ onwards until the condition ch<=‘Z’ becomes false.

  35. The most common use of do-while loop is menu selection routine, where the menu is flashed at least once. Program to display a menu rectangle operations and perform according to user’s response. #include<iostream.h> #include<math.h> #include<process.h> void main() { char ch, ch1; float l,b,peri,area,diag; cout <<\n Rectangle Menu”; cout <<\n 1. Area”; cout <<\n 2. Perimeter”; cout <<\n 3. Diagonal”; cout <<\n 4. Exit” << “/n”; cout <<\n Enter your choice”;

  36. do { cin >>ch; if(ch==‘1’ || ch ==‘2’ || ch==‘3’) { cout <<“Enter length & breadth :”; cin >> l >> b; } switch(ch) { case ‘1’ : area = l*b; cout << “Area = “ << area; break; case ‘2’ : peri = 2*(l + b); cout <<“Perimeter = “ <<peri; break; case ‘3’ : diag = sqrt( (l * l) + (b * b)); cout <<“Dialog = “ <<diag; break; case’4’ : cout<< “Breaking”; exit(0); default : cout << “Wrong choice !!!!!!”; cout << “Enter a valid one” ; break; } // end of switch. cout << “\n want to enter more (y/n) ?”; cin >> ch1;

  37. if( ch1 == ‘y’ || ch1 == ‘Y’) cout << “Again enter choice (1-4) :”; } while(ch1 == ‘y’ ||ch1 == ‘Y’); // end of Do loop }// main ends

  38. Jump Statements • These statements unconditionally transfer control within function . • In C++ four statements perform an unconditional branch : • Return • Goto • Break • Continue

  39. 1. Return The return statement is used to terminate the function whether or not it returns a value. It is useful in two ways: (i.) An immediate exit from the function and the control passes bact to the operating system which is main’s caller. (ii.) It is used to return a value to the calling code.

  40. Progarm to check whether a number is prime or not. #include<iostream.h> #include<process.h> int main() { int num,I; cout<< “\n Enter the Number :”; cin >> num; for(i = 2; i<= num/2 ; ++i) if(num % i == 0) { cout << “\n Not a Prime Number !!!”; exit(0); } cout <<“\n It is a Prime Number.”; return 0; } Enter the Number : 13 It is a Prime Number. Enter the Number : 24 Not a Prime Number.

  41. 2. Goto Statement • A goto Statement can transfer the program control anywhere in the program. • The target destination of a goto statement is marked by a label. • The target label and goto must appear in the same function.

  42. Syntax goto label; : label : Example : a= 0; start : cout<<“\n” <<++a; if(a<50) goto start;

  43. 3. Break • The break statement enables a program to skip over part of the code. • A break statement terminates the smallest enclosing while, do-while, for or switch statement. • Execution resumes at the statement immediately following the body of the terminated statement.

  44. while (test expression) { statement1; if (val>2000) break; . . statement2; } statement3; The following figure explains the working of break statement: do { statement1; if (val>2000) break; statement2; } while (expression); statement3; for (int;expression;update) { statement1; if (val>2000) break; statement2; } statement3; The Working of a Break Statement

  45. 4. Continue • The continue is another jump statement like the break statement as both the statements skip over a part of the code. • But the continue statement is somewhat different from break. • Instead of forcing termination, it forces the next iteration of the loop to take place, skipping any code in between.

  46. The following figure explains the working of continue statement: while (expression) { statement1; if (condition) continue; statement2; } statement3; for (int;expression;update) { statement1; if (condition) continue; statement2; } statement3; do { statement1; if (condition) continue; statement2; } while (expression); statement3; The Working of Continue Statement

  47. The exit() Function • This function causes the program to terminate as soon as it is encountered, no matter where it appears in the program listing. • The exit() function has been defined under a header file process.h which must be included in a program. • The exit() function does not have any return value. • Its argument, which is 0 in the above program, is returned to the operating system. • This value can be tested in batch files where ERROR LEVEL gives the return value provided by exit(). • Generally, the value 0 signifies a successful termination and any other number indicates some error.

  48. Progarm to check whether a number is prime or not. #include<iostream.h> #include<process.h> main() { int num,I; cout<< “\n Enter the Number :”; cin >> num; for(i = 2; i<= num/2 ; ++i) if(num % i == 0) { cout << “\n Not a Prime Number !!!”; exit(0); } cout <<“\n It is a Prime Number.”; } Enter the Number : 13 It is a Prime Number. Enter the Number : 24 Not a Prime Number.

  49. The above program accepts a number and tests whether it is prime or not. If the number is divisible by any number from 2 to half of the number, the program flashes a message that the number is not prime and exists from the program as it is caused by exit function.

  50. Questions for Slow achievers • Write a program to input age and check whether a person is major or minor. • Write a program to print the following patterns (ii.) * ** *** **** ***** (i.) 1 1 2 1 2 3 1 2 3 4 1 2 3 45

More Related