OBJECTIVES  Illustration of the Concept of Control Flow  Types of Control Flow  Knowledge about conditional and repetitive statements.  Make more.

Slides:



Advertisements
Similar presentations
Fundamental of C programming
Advertisements

1 Engineering Problem Solving With C++ An Object Based Approach Chapter 3 Control Structures.
Iteration This week we will learn how to use iteration in C++ Iteration is the repetition of a statement or block of statements in a program. C++ has three.
Chapter 6 - Repetition. Introduction u Many applications require certain operations to be carried out more than once. Such situations require repetition.
Switch structure Switch structure selects one from several alternatives depending on the value of the controlling expression. The controlling expression.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
Objectives You should be able to describe:
Control Structures Control structures control the flow of program execution. 3 types of control structures: sequence, selection.
CLASS XI By Sumita Arora
Section 3 - Selection and Repetition Constructs. Control Structures 1. Sequence 2. Selection 3. Repetition.
JAVA Control Statement.
UNIT II Decision Making And Branching Decision Making And Looping
 Decision making statements Decision making statements if statement if...else statement Nested if...else statement (if...elseif....else Statement) 
Outlines Chapter 3 –Chapter 3 – Loops & Revision –Loops while do … while – revision 1.
Chapter 4 Program Control Statements
C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 4: Control Structures I (Selection)
Chapter 4: Control Structures I (Selection). Objectives In this chapter, you will: – Learn about control structures – Examine relational operators – Discover.
Lecture 4 Introduction to Programming. if ( grade ==‘A’ ) cout
Computer Science Department Relational Operators And Decisions.
1 Chapter 9 Additional Control Structures Dale/Weems/Headington.
Chapter 4: Control Structures I (Selection). Objectives In this chapter, you will: – Learn about control structures – Examine relational and logical operators.
DiagrammaticRepresentation Iteration Construct False True Condition Exit from Statement (s) loop Sequence construct Selection construct Statement 1 Statement.
Copyright © Nancy Acemian 2004 For Loops-Break-Continue COMP For loop is a counter controlled loop. For loop is a pretest loop. Used when number.
Additional Control Structures. Chapter 9 Topics Switch Statement for Multi-way Branching Do-While Statement for Looping For Statement for Looping Using.
1 Chapter 9 Additional Control Structures Dale/Weems.
1 Additional Control Structures. 2 Chapter 9 Topics  Switch Statement for Multi-way Branching  Do-While Statement for Looping  For Statement for Looping.
Switch Statement Is a selection control structure for multi-way branching. SYNTAX switch ( IntegralExpression ) { case Constant1 : Statement(s); // optional.
Chapter 7 Additional Control Structures. 2 2 void GetYesOrNo (/* out */ char& response) // Inputs a character from the user // Postcondition: response.
COMPUTER PROGRAMMING. Iteration structures (loops) There may be a situation when you need to execute a block of code several number of times. In general,
Program Flow Control - Looping Addis Ababa Institute of Technology Yared Semu April 2012.
Chapter 3. Outline Relational Operators Loops Decisions Logical Operators Precedence Summary.
1 COMS 261 Computer Science I Title: C++ Fundamentals Date: September 21, 2005 Lecture Number: 10.
Chapter 05 (Part III) Control Statements: Part II.
CMPSC 16 Problem Solving with Computers I Spring 2014 Instructor: Lucas Bang Lecture 5: Introduction to C: More Control Flow.
DEPARTMENT OF COMPUTER SCIENCE & TECHNOLOGY FACULTY OF SCIENCE & TECHNOLOGY UNIVERSITY OF UWA WELLASSA 1 ‏ Control Structures.
Conditional Structures UNIVERSITY OF THE PUNJAB (GUJRANWALA CAMPUS) ADNAN BABAR MT14028 CR
1 ELEC 206 Chapter 3 Control Structures 5-Step Problem Solving Methodology 1. State the problem clearly. 2. Describe the input and output. 3. Work a.
Control Structures Repetition or Iteration or Looping Part II.
More Selection Executing Statements Selectively Chap. 7 (Read § & Part of Picture: Boolean Logic and Digital Design) 1.
1 More Control Structures if and switch (Chap. 8) do-while and forever loops (Chap. 9)
Control Structures RepetitionorIterationorLooping Part I.
Quiz 3 is due Friday September 18 th Lab 6 is going to be lab practical hursSept_10/exampleLabFinal/
Chapter 5: Control Structures I (Selection). Objectives In this chapter you will: Learn about control structures Examine relational and logical operators.
Loops cause a section of a program to be repeated a certain number of times. The repetition continues while a condition remains true. When a condition.
Chapter 4: Control Structures I (Selection). Objectives In this chapter, you will: – Learn about control structures – Examine relational and logical operators.
Repetition Statements (Loops) The do while Loop The last iteration structure in C++ is the do while loop. A do while loop repeats a statement or.
Chapter : 9 Control Statements Control Flow: A control flow Statement regulates the order in which statements get executed. F Flow-order in which the computer.
Think Possibility 1 Iterative Constructs ITERATION / LOOPS C provides three loop structures: the for-loop, the while-loop, and the do-while-loop. Each.
 Control Flow statements ◦ Selection statements ◦ Iteration statements ◦ Jump statements.
Calvin College Controlling Behavior The if, switch and for Statements.
1 Programming in C++ Dale/Weems/Headington Chapter 9 Additional Control Structures (Switch, Do..While, For statements)
We have to discuss following:-  Statements  Statement flow control  Selection statement  Iteration statement.
More Selection Executing Statements Selectively Chap. 7 (Read § & Part of Picture: Boolean Logic and Digital Design) 1.
Control Statements: Part1  if, if…else, switch 1.
4 - Conditional Control Structures CHAPTER 4. Introduction A Program is usually not limited to a linear sequence of instructions. In real life, a programme.
CONTENTS Loop Statements Parts of a loop Types of Loops Nested Loops
BY ILTAF MEHDI(MCS,MCSE, CCNA) 1. INSTRUCTOR: ILTAF MEHDI (MCS, MCSE, CCNA, Web Developer) BY ILTAF MEHDI(MCS,MCSE, CCNA) 2 Programming Fundamentals Chapter.
Chapter 4 – C Program Control
‘C’ Programming Khalid Jamal.
Decisions Chapter 4.
Engineering Problem Solving with C++, Etter/Ingber
Chapter 2.1 Control Structures (Selection)
Chapter 2.2 Control Structures (Iteration)
Looping.
FLOW OF CONTROL.
TOPIC 4: REPETITION CONTROL STRUCTURE
Additional Control Structures
Chapter 4: Control Structures I (Selection)
Selection Control Structure
Presentation transcript:

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. 1.Sequence 2.Selection 3.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 Condition ? Statement 1Statement 2 Statement 1 Statement 2 One course-of-action FALSE Another course of action

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 ? Statement 1 Statement 2 TRUE The Loop Body The exit Condition

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) statement1 else statement2

13 Program – Write a Temperature Conversion Program in C++ that gives user the option of converting Fahrenheit to Celsius or Celsius to Fahrenheit. #include 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 #include int main() { clrscr(); char ch; float a,b,result; cout >a>>b; cout >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 to Saturday). # include 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 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 Outline working of for loop Initialization Expression(s) Test Expression Test Expression Exit Body of the Loop Update Expression(s) False True

29 Example // compute sum = n // using for loop # include void main() { int sum = 0; for (int i = 1; i <= n; ++i) { sum += i; } cout << “/n” <<“sum =“ << sum; }

30 2. While-Loop Syntax while (expression) statement ;

31 // compute sum = n // using a while loop int i; int sum = 0; i = 1; while (i <= n) { sum += i; i++; }

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 Syntax do { Statements; } while (test-expression);

34 Example # include 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 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 : 1.Return 2.Goto 3.Break 4.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 #include 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. Progarm to check whether a number is prime or not.

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 The following figure explains the working of break statement: while (test expression) { statement1; if (val>2000) break;. statement2; } statement3; for (int;expression;update) { statement1; if (val>2000) break; statement2; } statement3; do { statement1; if (val>2000) break; statement2; } while (expression); 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 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.

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

Questions for high achiever 1.Write a progarm to check whether a number is prime or not. 2.Write a program to check whether a string is palidrome or not.

52 SOLUTIONS Write a program to input age and check whether a person is major or minor. 1. # include void main() { int age; cin>> age; if (age >=18) cout<< “ You are major”; else cout <<“ You are minor”; } 52

2. Write a program to print the following patterns (i.) * ** *** **** ***** (ii.)

54 (i.) # void main() { for(int r =1;i>=5;i++) { for(int c=1;c>=r;c++) { cout<<c; } cout <<“\n”; } 54

55 (ii.) # void main() { for(int r =1;i>=5;i++) { for(int c=1;c>=r;c++) { cout<<“*”; } cout <<“\n”; }

56 #include 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. 3. Progarm to check whether a number is prime or not.

57 4. Write a program to check whether a string is palindrome or not. #include int main( ) {int n, num, digit, rev =0; cout << “\n Input the number (max ) : ” ; cin >> num ; do { digit =num %10; rev =( rev*10) + digit ; num = num / rev ; } while ( num ! =0); cout << “ The reverse of the number is : ” << rev << “ \n” ; if( n==rev) cout << “ the number is palindrome” ; else Cout << “\n the number is not a palindrome” ; return 0; }

58