Control Structures Ppt

59
Control Control Structures Structures zero.m.magallon,cpe,ccna,cc zero.m.magallon,cpe,ccna,cc

Transcript of Control Structures Ppt

Page 1: Control Structures Ppt

Control Control StructuresStructures

zero.m.magallon,cpe,ccna,ccaizero.m.magallon,cpe,ccna,ccai

Page 2: Control Structures Ppt

Control structuresControl structures The sequence of steps in which a program runs is

known as an algorithm. The C++ statements which change the control ie.,

the sequence of execution of the program are called control structures.

There are several such structures like if, if-else etc. These statements if, else etc are called keywords Keywords are the ones which cannot be used as

variable or constant or function names.

Page 3: Control Structures Ppt

Control structuresControl structures

Key words common to C and C++ are

auto break case char constcontinue default do double elseenum extern float for gotoif int long register returnshort signed sizeof static structswitch typedef union unsigned voidvolatile while

Page 4: Control Structures Ppt

Control structuresControl structures

Keywords exclusive to C++ are

asm bool catch class const_castdelete dynamic-cast explicit false friendprivate mutable namespace new operatorstatic-cast template this throw truetry typeid typename using virtualwchar_t

Page 5: Control Structures Ppt

Control structuresControl structures

Control structures can be divided into 2 groups

Selection structures – if, if – else. If is a single selection structure, selects or ignores an action. If – else is a double selection structure, selects between two actions.

Repetition structures – while, do/while, for

Page 6: Control Structures Ppt

Conditional Conditional structuresstructures

Page 7: Control Structures Ppt

if structureif structure

Syntax:– if (bool value/condition)– {

– block– }

The bool value can be supplied directly like– if (1)– {

• Block;– }

Page 8: Control Structures Ppt

if structureif structure

a condition can also be given which results in a some value (which will be treated as true or false). E.g. by giving some expression which results in a boolean value like

– if (a>=3) or if (-1+1)– {

• Block;– }

The bool value can also be obtained by calling some function which returns a value (will be done later)

Page 9: Control Structures Ppt

if structureif structure The program execution structure will be as follows for an

if structure

Condition/boolvalue

cout<< "Passed\n";

truefalse

Page 10: Control Structures Ppt

if – else structureif – else structure In the if structure, an action is performed only if the

condition is true, otherwise the program goes to next instruction.

But in the if-else structure, we will be able to take some action if the condition is false also.

Syntax:if (condition){

Block;}else{

Block;}

Page 11: Control Structures Ppt

if – else structureif – else structure

The condition rules are same as that of if structure. The program execution sequence goes like this.

conditiontruefalse

{ block1}{ block2}

if (condition)

{

Block;

}

else

{

Block;

}

Page 12: Control Structures Ppt

Nested if – else statementsNested if – else statements

Having if structures or if-else structures inside if blocks or else blocks is known as nested if-else statements

Syntax:

if (condition)

{

Block;

}

else if (condition){

Page 13: Control Structures Ppt

Nested if – else statementsNested if – else statements

Block;

}

else if (condition){

Block;

}

else

statement;

Page 14: Control Structures Ppt

?: operator?: operator

To represent the if – else structure there is one operator ?:. Its usage is like this

(condition) ? (block1) : (block2) What happens here is if the condition results in a true

value (non-zero value) block1 will be executed otherwise (condition results in false) block2 will be executed.

This is similar to if-else structure and this operator can also be nested just like nested if-else statements.

Page 15: Control Structures Ppt

Repetitive structures Repetitive structures or loopsor loops

Page 16: Control Structures Ppt

while structurewhile structure This is repetition structure which means that certain

action will be repeated until certain criteria is satisfied.

Syntax

while (condition/expr)

{

Block of instructions;

} In the while case, the block will be executed as many

times as the condition/expr gives a true value ie., once condition is false, the loop terminates executing.

Page 17: Control Structures Ppt

while structurewhile structure

Flow chart is as follows

expr1 { C++block}true

false

while(condition)

{…statements to do;

…}

Page 18: Control Structures Ppt

– Take C++ code and turn it into a flow chart.

#include<iostream.h>#include<iostream.h>

int main()int main()

{{

int i=0;int i=0;

while(i<10)while(i<10)

{{

cout<<"i = "<<i<<endl;cout<<"i = "<<i<<endl;

i = i+1;i = i+1;

}}

return (0);return (0);

}}

Start

Stop

i = 0

Is i < 10 Output i

i = i + 1

No

Yes

Page 19: Control Structures Ppt

while structurewhile structure E.g.

int i=1;

while(i!=10)

{

cout<<“hi\n”;

}

How many times will the string “hi” will be printed on the screen.

Page 20: Control Structures Ppt

int x = 10;

while (x>0)

{

cout << x << ‘\n’;

x = x - 3;

}

Page 21: Control Structures Ppt

int x = 10;while (x>0){ cout << x << ‘\n’; x+=3; }

Page 22: Control Structures Ppt

Write a C++ source code that displays this output:15,14,13,12,11,10,9,8,7,6,5,4,3,2,1,0

Page 23: Control Structures Ppt

Summation Example

Write a source code for the case where a positive number N is input, and the sum from 1 to N is calculated and output to the screen.

Page 24: Control Structures Ppt

Summation Solution

Start

Stop

Input N

Output sum

i = i + 1

No

Yes

sum=0

i = 0

Is i < N+1 sum=sum+i

Page 25: Control Structures Ppt

Factorial Exercise

Write the flow diagram for the case where a positive number N is input, and the factorial of N is calculated and output to the screen.

Factorial of N = N! = N*(N-1)*(N-2)…1

So Factorial of 5 = 5! = 5*4*3*2*1 = 120.

Page 26: Control Structures Ppt

Factorial Exercise Solution

Start

Stop

Input N

Output F

i = i - 1

No

Yes

F=1

i = N

Is i > 0 F=F * i

Page 27: Control Structures Ppt

do-while structuredo-while structure

Like while structure do-while is also a repetition structure. Syntax is:

do

{

block;

}while (condition/expression); the loop will be executed as long as the

condition/expression remains true and stops once it becomes false.

Page 28: Control Structures Ppt

do-while structuredo-while structure The difference between while and do-while is that, in

while the condition is checked first and then depending on that the block is executed but in do-while, the block will be executed and then the condition will be checked.

Flow chart is :

expr1

{ C++block}

true

false

do

{

block of instructions;

} while(condition/expression);

Page 29: Control Structures Ppt

//number echoer#include<iostream.h>#include<conio.h>

void main(){unsigned long n;clrscr(); do { cout<<“ enter number (0 to end):”; cin>>n; cout<<“you entered: ”<<n<<‘\n’; }while(n!=0);getch();}

Page 30: Control Structures Ppt

do-while structuredo-while structure

E.g.int i=1,fact=1;do{

fact*=i;}while (++i != 10)

what is the output of the above program what is the output of the program with i++!=10 as the

condition.

Page 31: Control Structures Ppt

do-while structuredo-while structure

Result it will be the product of first 9 integers

(1*2*3*4*5*6*7*8*9). 10 will not be multiplied because once the condition returns false the block will not execute.

With the second one as the condition the result will be the product of first 10 integers.

Page 32: Control Structures Ppt

for loopfor loop Similar to while and do-while, for is also used for

repetition. Syntax:

for(expr1;condition;expr2)

{

Block of instructions;

} expr1 is usually an initialization for the loop condition will be either true or false and the block will be

executed only if the condition is true. expr2 will usually be the incrementation stage.

Page 33: Control Structures Ppt

for loopfor loop Flow chart is:

condcond

expr1expr1

truetrue

{ C++ block}{ C++ block}

falsefalse

expr2expr2

for(expr1;condition;expr2)

{

Block of instructions;

}

Syntax is:

Page 34: Control Structures Ppt

for loopfor loop

E.g.for(int i=0;i<10;i++){

block;}

at each stage, the condition is checked and then if it is true block will be executed and then the incrementation part will be executed

in this program, first it will be checked if i<10 or not, if it is, then block is executed and then ‘i’ is incremented and this continues till it is false.

Page 35: Control Structures Ppt

for loopfor loop The variable ‘i’ is declared in the loop statement itself it

can be declared before also. The above for loop is equivalent to:

int i=0;

for(;i<10;)

{

block;

i++;

} In this case, the initialization is done before the for

statement and the incrementation is done in the for loop.

Page 36: Control Structures Ppt

for loopfor loop

E.g.

for(int i=0;i<=10;i+=2)for(int i=0;i<=10;i+=2)

{{

cout<<“hi\n”;cout<<“hi\n”;

}} what is the output of the above program. hi will be printed 6 times

Page 37: Control Structures Ppt

for loopfor loop

E.g.

for(i=0;;i++)for(i=0;;i++)

{{

cout<<“hi\n”;cout<<“hi\n”;

}} what is the output of this code. This loop will execute infinite times and hi will printed

infinite times.

Page 38: Control Structures Ppt

#include<iostream.h>#include<conio.h> #define z 2 void main(){int cnt =0, i, j, k; clrscr(); for (i=0; i<=z; ++i)

for (j=0; j<=z; ++j)for (k=0; k<=z; ++k) if(i+j+k==z) { ++cnt; cout << i<<" "<< j<<" "<<k<<" "<<'\n'; }

cout <<"count: \t"<<cnt;getch();}

0 0 20 0 20 1 10 1 10 2 00 2 01 0 11 0 11 1 01 1 02 0 02 0 0Count: 6Count: 6

Page 39: Control Structures Ppt

break, continue and gotobreak, continue and goto

break and continue will give more exit points in loops

syntax:• break;

• continue;

• Goto label; label:

they are usually used with if or else statements.

Page 40: Control Structures Ppt

breakbreak Once a break is encountered in a loop, no other statement

inside that loop after break will be executed and execution will come out of the loop.

E.g. with while loopi=0;i=0;

while(1)while(1)

{{

i++;i++;

cout<<“hi\n”;cout<<“hi\n”;

}}

what is the output of the above code. The above loop is an infinite loop

Page 41: Control Structures Ppt

breakbreak E.g. with while loop

i=0;i=0;

while(1)while(1)

{{

i++;i++;

if (i>=5) break;if (i>=5) break;

cout<<“hi\n”;cout<<“hi\n”;

}} what is the output of the above code. Hi will be printed 4 times

Page 42: Control Structures Ppt

breakbreakint i=0;int i=0;

for(;;)for(;;)

{{if (i>5) break;if (i>5) break;

block;block;

i++;i++;

}}

int i=0;int i=0;

for(i=0;i<5;i++)for(i=0;i<5;i++)

{{block;block;

}}

The above two code segments are the same

Page 43: Control Structures Ppt

continuecontinue Once continue is encountered in a loop, remaining Once continue is encountered in a loop, remaining

statements in the loop will not be executed but proceeds statements in the loop will not be executed but proceeds to the next loop iteration.to the next loop iteration.

In case of while loop, loop-continuation test is evaluated In case of while loop, loop-continuation test is evaluated after continue.after continue.

In case of for loop, the increment expression will be In case of for loop, the increment expression will be executed (if is present in the for statement and not in executed (if is present in the for statement and not in the for loop after continue) and thenthe for loop after continue) and then the loop-the loop-continuation test will be evaluated.continuation test will be evaluated.

Page 44: Control Structures Ppt

continuecontinue// Using the continue statement in a for structureUsing // Using the continue statement in a for structureUsing

the continuethe continue statement in a for structure. Fig.2.27 of statement in a for structure. Fig.2.27 of text booktext book

#include <iostream.h>

int main()

{ for ( int x = 1; x <= 10; x++ )

{

if ( x == 5 )

continue; // skip remaining code in loop only if x is 5

cout << x << " ";

}

cout << "\nUsed continue to skip printing the value 5" << endl;

return 0;

}

Page 45: Control Structures Ppt

continuecontinue

ResultResult1 2 3 4 6 7 8 9 10

Used continue to skip printing the value 5

Page 46: Control Structures Ppt

#include <iostream.h> void main(){ int posNumber, Sum = 0; // Declare necessary variables cout << "Type 4 positive numbers.\n"; // Request 4 positive numbers from the userfor( int Count = 1; Count <= 4; Count++) // Make sure the user types 4 positive numbers { cout << "Number: "; cin >> posNumber;

if( posNumber < 0 ) // If the number typed is not positive, ignore it

continue;

Sum += posNumber; // Add each number to the sum } // Display the sumcout << "\nSum of the numbers you entered = " << Sum << "\n\n";}

Page 47: Control Structures Ppt

•It allows to make an absolute jump to another point in the program. You should use this feature carefully since its execution ignores any type of nesting limitation. •The destination point is identified by a label, which is then used as argument for the goto instruction. A label is made of a valid identifiervalid identifier followed by a colon colon (:) •This instruction does not have a concrete utility in structured or object oriented programming aside from those that low-level programming fans may find to it.

•For example, here is our countdown loop using goto:

The The gotogoto instruction. instruction.

Page 48: Control Structures Ppt

// goto loop example#include <iostream.h>int main (){ int n=10; loop: cout << n << ","; n--; if (n>0) goto loop; cout << "FIRE!"; return 0;}

Page 49: Control Structures Ppt

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

goto MamaMia; } 

MamaMia:cout << "Stopped at 5";}

Page 50: Control Structures Ppt

The Selective The Selective StructureStructure

Page 51: Control Structures Ppt

switch multiple selectionswitch multiple selection This is little similar to if-else structure. Syntax:

switch(variable/expression)switch(variable/expression)

{{

case value1: block of instructions;case value1: block of instructions;

break;break;

case value2: block of instructions;case value2: block of instructions;

break;break;

……

default : block;default : block;

}

Page 52: Control Structures Ppt

switch multiple selectionswitch multiple selection

In switch-case statements, one particular block is selected depending on the value of the expression or of the variable. The names value1,value2 etc. after the case indicate which block to choose depending on the value of the expression.

The last part which says default defines the action to be taken for all the remaining values of the expression. It is not compulsory to have a default part.

Break after each block is compulsory except after the last block. Reason is if it is not given irrespective of the value all remaining blocks will be executed till break is reached.

Page 53: Control Structures Ppt

switch multiple selectionswitch multiple selection

Flow chart is:

expr1expr1 11 22

33

44 defaultdefault

block1 block2

block3

block4

55

block5

block6

break; break;

break; break;

break;

Page 54: Control Structures Ppt

switch multiple selectionswitch multiple selection E.g.

int i;int i;cout << “give the value of I”;cout << “give the value of I”;cin >> i;cin >> i;switch (i)switch (i){{

case 1: cout<<“value entered is 1\n”;case 1: cout<<“value entered is 1\n”;break;break;

case 2: cout<<“value entered is 2\n”;case 2: cout<<“value entered is 2\n”;break;break;

default: cout<<“value entered is greater than 2\n”default: cout<<“value entered is greater than 2\n”}}

Page 55: Control Structures Ppt

switch multiple selectionswitch multiple selection

If you want to have same action to be taken for more than one cases the way you do it is:

switch(i)switch(i)

{{

case 1:case 1:

case 2: cout<<“ value entered is either 1 or 2”;case 2: cout<<“ value entered is either 1 or 2”;

break;break;

default: cout<<“value enterd is greater than 2”;default: cout<<“value enterd is greater than 2”;

}}

Page 56: Control Structures Ppt

switch multiple selectionswitch multiple selectionchar i;

int acount=0,bcount=0,othercount=0;

for(int a=0;a<3;a++){

cin>>i;

switch(i){

case ‘a’:

case ‘A’: ++acount;

case ‘b’:

case ‘B’: ++bcount;

break;

default: ++othercount;

}

}

how many times will the above loop run.

What will be the values of acount,bcount and othercount if ‘a’ is entered first, then ‘b’ and then ‘c’.

acount will be 1, bcount will be 2 and othercount will be 1.

Page 57: Control Structures Ppt

Important points

Having a semicolon immediately after an if statement will result in logical error for if structure and syntax error for if-else or nested if structures.

Having a semicolon after while statement may lead to the loop running infinite times.

Having a semicolon after a for loop will result in logical error (because no block will be executed for the for loop).

It is always a good idea to have parenthesis for each loop structure or selection structure or if-else structures.

Page 58: Control Structures Ppt

#include <iostream.h> int main(){

int Number;

cout << "Type a number between 1 and 3: ";cin >> Number;

switch (Number) {

case 1:cout << "\nYou typed 1.";break;

case 2:cout << "\nYou typed 2.";

case 3:cout << "\nYou typed 3.";break;

default:cout << endl << Number << " is out of the requested range.";

}

return 0;}

Page 59: Control Structures Ppt

#include <iostream.h> void main(){ char Letter;  cout << "Type a letter: "; cin >> Letter;  switch( Letter ) { case 'a': case 'A': case 'e': case 'E': case 'i': case 'I': case 'o': case 'O': case 'u': case 'U': cout << "The letter you typed, " << Letter << ", is a vowel\n"; break;  case 'b': case 'c': case 'd': case 'f': case 'g': case 'h': case 'j': case 'k': case 'l': case 'm': case 'n': case 'p': case 'q': case 'r': case 's': case 't': case 'v': case 'w': case 'x': case 'y': case 'z': cout << Letter << " is a lowercase consonant\n"; break;  case 'B':case 'C':case 'D':case 'F':case 'G':case 'H':case 'J': case 'K': case 'L':case 'M':case 'N':case 'P':case 'Q':case 'R':case 'S': case 'T': case 'V':case 'W':case 'X':case 'Y':case 'Z': cout << Letter << " is a consonant in uppercase\n"; break; default: cout << "The symbol " << Letter << " is not an alphabetical letter\n"; }}