OBJECTIVES Illustration of the Concept of Control Flow Types of Control Flow Knowledge about...

Post on 04-Jan-2016

216 views 0 download

Transcript of OBJECTIVES Illustration of the Concept of Control Flow Types of Control Flow Knowledge about...

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. Sequence2. 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

TRUECondition

? Statement 1 Statement 2

Statement 1

Statement 2

One course-of-action

FALSE

Another course of action

7

Selection Statements

If StatementSwitch CaseNote: 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.

9The Iteration Construct

FALSECondition

?

Statement 1

Statement 2

TRUE

The Loop Body

The exit Condition

10

Iteration Statements

For LoopWhile LoopDo- While Loop

11

Logical Expressions which may include:

6 Relational Operators< <= > >= ==

!=

3 Logical Operators! && ||

12

Conditional Statements

1. If StatementSyntax

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<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 Menu1. Fahrenheit to Celsius2. Celsius to Fahrenheit

Enter your choice : 1

Enter temperature in Fahrenheit : 98The temperature in Centigrade is : 36.66

15

OUTPUT – When user choice is 2

Temperature Conversion Menu1. Fahrenheit to Celsius2. Celsius to Fahrenheit

Enter your choice : 2

Enter temperature in Centigrade : 37The temperature in Fahrenheit is : 98.6

16

Nested IfsSyntax

if (expression1){

:if(expresssion2) statement1;[ else

statement2;] :

} else

body of else;if (expression1){

body of ifif(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 : 93Enter the operator (+,-,*,?) : /The Calculated result is : 3

20

The ? : Operator – Alternative to ifThe operator can be used to replace if-else statementsif(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 StatementSyntax

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) : 5Thursday

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 = 4uc = 5 fail = 6

26

Iteration Statements

1.For Loop2.While-Loop3.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 loopInitialization

Expression(s)

Test Expression

Test Expression

Exit

Bodyof the Loop

Update Expression(s)

FalseFalse

TrueTrue

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;

}

30

2. While-Loop

Syntaxwhile (expression) statement ;

31

// compute sum = 1 + 2 + ... + 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<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 :

1. Return2. Goto3. Break4. 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<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 : 13It is a Prime Number.

Enter the Number : 24Not a Prime Number.

Progarm to check whether a number is prime or not.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 StatementThe Working of a Break Statement

45

4. ContinueThe 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 StatementThe Working of Continue Statement

47

The exit() FunctionThis 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 : 13It is a Prime Number.

Enter the Number : 24Not 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.) 1 1 2 1 2 3 1 2 3 4 1 2 3 45

(i.) 1 1 2 1 2 3 1 2 3 4 1 2 3 45

(ii.) ***************

Questions for high achiever1. 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

SOLUTIONSWrite a program to input age and check

whether a person is major or minor.

1. # include <iostream.h>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.) 1 1 2 1 2 3 1 2 3 4 1 2 3 45

53

54

(i.)#<iostream.h>void main(){

for(int r =1;i>=5;i++) {

for(int c=1;c>=r;c++) {

cout<<c; } cout <<“\n”; } }

54

55

(ii.)#<iostream.h>void main(){

for(int r =1;i>=5;i++) {

for(int c=1;c>=r;c++) {

cout<<“*”; } cout <<“\n”; } }

5656

#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 : 13It is a Prime Number.

Enter the Number : 24Not a Prime Number.

3. Progarm to check whether a number is prime or not.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<iostream.h>int main( ) { int n, num , digit , rev =0; cout << “\n Input the number (max.32767 ) : ” ; 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