47
CONTROL STRUCTURES

Dti2143 chap 4 control structures aka_selection

Embed Size (px)

Citation preview

Page 1: Dti2143 chap 4 control structures aka_selection

CONTROL STRUCTURES

Page 2: Dti2143 chap 4 control structures aka_selection

CONTROL STRUCTURES

A control structure refers to the way in which the Programmer specifies the order of executing the statements

The following approaches can be chosen depending on the problem statement:

◦ Sequential In a sequential approach, all the statements are executed in the same order as

it is written

◦ Selectional In a selectional approach, based on some conditions, different set of statements

are executed

◦ Iterational (Repetition) In an iterational approach certain statements are executed repeat

Page 3: Dti2143 chap 4 control structures aka_selection

SELECTIONAL CONTROL STRUCTURES

There are two select ional control structures If statement Switch statement

Page 4: Dti2143 chap 4 control structures aka_selection

SIMPLE IF STATEMENT In a simple ‘if’ statement, a condition is tested If the condition is true, a set of statements are executed If the condition is false, the statements are not executed

and the program control goes to the next statement that immediately follows if block

if (iDuration >= 3) {

/* Interest for deposits equal to or more than 3 years is 6.0% */ fRateOfInterest = 6.0;}

conditionTrue

False

Set ofStatement(s)

Next Statement

Syntax:if (condition) {

Statement(s);}Next Statement;

Page 5: Dti2143 chap 4 control structures aka_selection

ELSE STATEMENT (1 OF 2)

In simple ‘if’ statement, when the condition is true, a set of statements are executed. But when it is false, there is no alternate set of statements

The statement ‘else’ provides the same

Syntax:if (condition)

{Statement set-1;

}else {

Statement set-2;}Next Statement;

conditionTrue

False

Statement set-1

Statement set-2

Next Statement

Page 6: Dti2143 chap 4 control structures aka_selection

ELSE STATEMENT (2 OF 2)

Example:

if (iDuration >= 3) {/* If duration is equal to or more than 3 years,

Interest rate is 6.0 */fRateOfInterest = 6.0;

}else {

/* else, Interest rate is 5.5 */fRateOfInterest = 5.5;

}

Page 7: Dti2143 chap 4 control structures aka_selection

ELSE IF STATEMENT (1 OF 2)

The ‘else if’ statement is to check for a sequence of conditions

When one condition is false, it checks for the next condition and so on

When all the conditions are false the ‘else’ block is executed

The statements in that conditional block are executed and the other ‘if’ statements are skipped

Syntax:

if (condition-1) {Statement set-1;}

else if (condition-2) {Statement set-2;}

………………………………else if (condition-n)

{Statement set-n;}

else {Statement set-x;}

Page 8: Dti2143 chap 4 control structures aka_selection

ELSE IF STATEMENT (2 OF 2) Always use ‘else if’ when a sequence of conditions has to be tested. Using only ‘if’ will make the compiler to check all the

conditions. This increases the execution time

Professional code (Using ‘else if’)

if (iDuration >= 6) { fRateOfInterest = 6.5; } else if ((iDuration >= 3) && (iDuration < 6)) { fRateOfInterest = 6.0; } else if (iDuration == 2) { fRateOfInterest = 5.5; } else { fRateOfInterest = 5.0; }

Amateur code (Using only ‘if’)

if (iDuration >= 6) { fRateOfInterest = 6.5; } if ((iDuration >= 3) && (iDuration < 6)) { fRateOfInterest = 6.0; } if (iDuration == 2) { fRateOfInterest = 5.5; } if (iDuration == 1) { fRateOfInterest = 5.0; }

Page 9: Dti2143 chap 4 control structures aka_selection

EXAMPLE (1 OF 2 )

#include<stdio.h>#include<conio.h>main(){ int result; printf("Enter your mark:"); scanf("%d",&result); if (result >=55)

{printf("Passed\n");printf("Congratulations\n");

}else

{printf("Failed\n");printf("Good luck repeating this subject :D \n");

}getch();return 0;}

a) 77b) 55c) 48d) 21

Page 10: Dti2143 chap 4 control structures aka_selection

EXAMPLE (2 OF 2 )

#include<stdio.h>#include<conio.h>main(){ int test1,test2; int result; printf("Enter your mark for Test 1:"); scanf("%d",&test1); printf("Enter your mark for Test 2:"); scanf("%d",&test2); result=(test1+test2)/2; if(result>=80) { printf("Passed: Grade A\n"); } else if (result>=70) { printf("Passed: Grade B\n"); } else if (result >=55) { printf("Passed: Grade C\n"); } else { printf("Failed\n"); } getch();

return 0;}

Page 11: Dti2143 chap 4 control structures aka_selection

ASSIGNMENT(=) VS. EQUALITY OPERATOR (==) (1 OF 3)

The operator ‘=’ is used for assignment purposes whereas the operator ‘==’ is used to check for equality

It is a common mistake to use ‘=’ instead of ‘==’ to check for equality

The compiler does not generate any error message

Example:

if (interest = 6.5) {printf(“Minimum Duration of deposit: 6 years”);

}else if (interest = 6.0) {

printf(“Minimum Duration of deposit: 3 years”);}else {

printf(“No such interest rate is offered”);}

The output of the above program will be “Minimum Duration of deposit: 6 years” the control structure Is ignored

Page 12: Dti2143 chap 4 control structures aka_selection

ASSIGNMENT(=) VS. EQUALITY OPERATOR (==) (2 OF 3) To overcome the problem, when constants are compared with

variables for equality, write the constant on the left hand side of the equality symbol

Example:if (6.5 = interest) {

printf(“Minimum Duration of deposit: 6 years”);}else if (6.0 = interest) {

printf(“Minimum Duration of deposit: 3 years”);}else {

printf(“No such interest rate is offered”);}

When the above code is compiled it generates compilation errors because the variable’s value is being assigned to a constant

This helps in trapping the error at compile time itself, even before it goes to unit testing

Page 13: Dti2143 chap 4 control structures aka_selection

ASSIGNMENT(=) VS. EQUALITY OPERATOR (==) (3 OF 3)

Corrected Code:if (6.5 == interest) {

printf(“Minimum Duration of deposit: 6 years”);}else if (6.0 == interest) {

printf(“Minimum Duration of deposit: 3 years”);}else {

printf(“No such interest rate is offered”);}

Page 14: Dti2143 chap 4 control structures aka_selection

NESTED IF STATEMENT

An ‘if’ statement embedded within another ‘if’ statement is called as nested ‘if’

Example:if (iDuration > 6 )

{if (dPrincipalAmount > 25000) {printf(“Your percentage of incentive is 4%”);}else {printf(“Your percentage of incentive is 2%”);}else {printf(“No incentive”);}

Page 15: Dti2143 chap 4 control structures aka_selection

#include<stdio.h>

#include<conio.h>

main()

{

int iDuration, dPrincipalAmount;

printf("Enter value for iDuration:");

scanf("%d",&iDuration);

if (iDuration > 6 ) {

printf("What is yout dPrincipalAmount:");

scanf("%d",&dPrincipalAmount);

if (dPrincipalAmount > 25000) {

printf("Your percentage of incentive is 4%");

}

else {

printf("Your percentage of incentive is 2%");

}

}

else {

printf("No incentive");

}

getch();

return 0;

}

What the output ifa. iDuration=9

dPrincipalAmount=26000b. iDuration=10

dPrincipalAmount=21000c. iDuration=4

dPrincipalAmount=21000

Page 16: Dti2143 chap 4 control structures aka_selection

EXAMPLE NESTED IF

#include<stdio.h>#include<conio.h>main(){ int num1; int num2; printf("Please enter two integers\n"); printf("Num1:"); scanf("%d",&num1); printf("Num2:"); scanf("%d",&num2); if(num1<=num2) { if(num1<num2) { printf("%d < %d\n",

num1,num2); } else { printf("%d==%d\n",num1,num2); } } else { printf("%d > %d\n",num1,

num2); } getch();return 0;}

What the output ifa. num1=55

num2=55b. num1=25

num2=89c. num1=90

num2=10

Page 17: Dti2143 chap 4 control structures aka_selection

WHAT IS THE OUTPUT OF THE FOLLOWING CODE SNIPPET?

iResult = iNum % 2;

if ( iResult = 0) {

printf("The number is even");

}

else {

printf("The number is odd");

}

CASE 1: When iNum is 11

CASE 2: When iNum is 8

The output is "The number is odd"

The output is "The number is odd"

Explains???

Page 18: Dti2143 chap 4 control structures aka_selection

Switch case Statement

The ‘switch’ statement is a type of decision control structure that selects a choice from the set of available choices

It is very similar to ‘if’ statement But ‘switch’ statement cannot replace ‘if’ statement in all situations Syntax:Switch(integer variable or integer expression or character variable) {

case integer or character constant-1 : Statement(s);break;

case integer or character constant-2 :Statement(s);break;

……………case integer or character constant-n :

Statement(s); break;

default: Statement(s);

break;}

Page 19: Dti2143 chap 4 control structures aka_selection

WHAT IS THE OUTPUT OF THE FOLLOWING CODE SNIPPET?

int iNino = 2;

switch(iNino){case 1:

printf(“ONE”);break;

case 2:printf(“TWO”);break;

case 3:printf(“THREE”);break;

default:printf(“INVALID”);break;

}

Output:

TWO

Page 20: Dti2143 chap 4 control structures aka_selection

WHAT IS THE OUTPUT OF THE FOLLOWING CODE SNIPPET?

switch (departmentCode){case 110 :

printf(“HRD”);break;

case 115 : printf(“IVS”); break;

case 125 :printf(“E&R”); break;

case 135 : printf(“CCD”);

} Assume departmentCode is 115 and find the output

Page 21: Dti2143 chap 4 control structures aka_selection

WHAT IS THE OUTPUT OF THE FOLLOWING CODE SNIPPET?

int iNum = 2;switch(iNum) {

case 1.5:printf(“ONE AND HALF”);break;

case 2:printf(“TWO”); break;

case ‘A’ :printf(“A character”);

}

Case 1.5: this is invalid because the values in case statements must be integers

Page 22: Dti2143 chap 4 control structures aka_selection

WHAT IS THE OUTPUT OF THE FOLLOWING CODE SNIPPET?

unsigned int iCountOfItems = 5;

switch (iCountOfItems) {

case iCountOfItems >=10 :

printf(“Enough Stock” );

break;

default :

printf(“Not enough stock”);

break;

}

Error: Relational Expressions cannot be used in switch statement

Page 23: Dti2143 chap 4 control structures aka_selection

AN EXAMPLE – SWITCH CASE

#include<stdio.h>#include<conio.h>main(){char ch;printf("Enter the vowel:");scanf("%c",&ch);switch(ch) {

case 'a' : printf("Vowel"); break;

case 'e' : printf("Vowel"); break;case 'i' : printf("Vowel");

break;case 'o' : printf("Vowel");

break;case 'u' : printf ("Vowel");

break;default : printf("Not a vowel");

}getch();return 0;}

Page 24: Dti2143 chap 4 control structures aka_selection

AN EXAMPLE – SWITCH CASE

char ch=‘a’;

switch(ch) {

case ‘a’ : printf(“Vowel”);

break;

case ‘e’ : printf(“Vowel”);

break;

case ‘i’ : printf(“Vowel”);

break;

case ‘o’ : printf(“Vowel”);

break;

case ‘u’ : printf (“Vowel”);

break;

default : printf(“Not a vowel”);

}

char ch=‘a’;

switch(ch) {

case ‘a’ :

case ‘e’ :

case ‘i’ :

case ‘o’ :

case ‘u’ : printf(“Vowel”);

break;

default :

printf(“Not a

vowel”);

}

Page 25: Dti2143 chap 4 control structures aka_selection

AN EXAMPLE – SWITCH CASE#include<stdio.h>#include<conio.h>main(){ int greeting; printf("Enter the number of your desired greetings :"); scanf("%d",&greeting); switch (greeting){

case 1: printf("Happy Hari Raya"); break;

case 2: printf("Happy Deepavali");

break;case 3:

printf("Happy New Year"); break;default:

printf("You choose wrong choice"); break; }getch();return 0;}

If you choose a. 1…Happy Hari Rayab. 2…Happy Deepavalic. 3… Happy New Yeard. Other than that…….You choose wrong

choice

Page 26: Dti2143 chap 4 control structures aka_selection

ITERATION CONTROL STRUCTURES

Iterational (repetitive) control structures are used to repeat certain statements for a specified number of times

The statements are executed as long as the condition is true

These kind of control structures are also called as loop control structures

are three kinds of loop control structures:◦ while◦ do while◦ for

Page 27: Dti2143 chap 4 control structures aka_selection

DO WHILE LOOP CONTROL STRUCTURE

The ‘do while’ loop is very similar to ‘while’ loop. In ‘do while’ loop, the condition is tested at the end of the loop

Because of this, even when the condition is false, the body of the loop is executed at least once

This is an exit-controlled loop Syntax:

do {Set of statement(s);

} while (condition);Next Statement;

conditionTrue

False

Set of statements

Next Statement

Page 28: Dti2143 chap 4 control structures aka_selection

Execution proceeds as follows: First the loop is executed, next the condition is evaluated, if

condition evaluates to true the loop continues execution else control passes to the next statement following the loop

The do-while statement can also terminate when a break, goto, or return statement is executed within the statement body. This is an example of the do-while statement:

do{ a = b ; b = b – 1;

} while ( b > 0 ); In the above do-while statement, the two statements a = b; and b =

b - 1; are executed, regardless of the initial value of b. Then b > 0 is evaluated. If b is greater than 0, the statement body is executed again and b > 0 is reevaluated. The statement body is executed repeatedly as long as b remains greater than 0. Execution of the do-while statement terminates when b becomes 0 or –ve. The body of the loop is executed at least once.

DO WHILE LOOP CONTROL STRUCTURE

Page 29: Dti2143 chap 4 control structures aka_selection

DO WHILE LOOP CONTROL STRUCTURE EXAMPLE

int iNumber, iSum = 0;do {

printf(“Enter a number. Type 0(zero) to end the input ”);

scanf(“%d”,&iNumber);iSum = iSum + iNumber;

} while (iNumber != 0);

Page 30: Dti2143 chap 4 control structures aka_selection

Difference between while and do while loops

While loop do while loop The condition is tested before entering into the loop.

The condition is tested at the end of the loop.

When the condition is false at the initial stage, the loop statements are not executed at all.

The statements are executed at least once even when the condition is false.

It is an entry-controlled loop. It is an exit-controlled loop.

Page 31: Dti2143 chap 4 control structures aka_selection

#include<stdio.h>#include<conio.h>int main(void){ int x=1; do{ printf("%d", x+

+); }

while (x<5); getch(); return 0; }

DO – WHILE AND WHILE EXAMPLE

2

3

4

#include<stdio.h>#include<conio.h>int main(void){ int x=1; while(x<5){ printf("%d", x);

x++; } getch(); return 0; }

Page 32: Dti2143 chap 4 control structures aka_selection

FOR LOOP CONTROL STRUCTURE

The ‘for’ loops are similar to the other loop control structures

The ‘for’ loops are generally used when certain statements have to be executed a specific number of times

Advantage of for loops: All the three parts of a loop (initialization, condition and

increment) can be given in a single statement Because of this, there is no chance of user missing out

initialization or increment steps which is the common programming error in ‘while’ and ‘do while’ loops

Syntax:

for (Initialization; Termination-Condition; Increment-Step) {

Set of statement(s);

}

Next Statement;

Page 33: Dti2143 chap 4 control structures aka_selection

In executing a for statement, the computer does the following: Initialization is executed. Then the Termination-condition is evaluated. If it

computes to zero the loop is exited. If the (1)Termination-condition gives a nonzero

value, the (2)LoopBody is executed and then the (3)Increment-step is evaluated.

The Termination-condition is again tested. Thus, the LoopBody is repeated until the Termination-condition computes to a zero value.

SYNTAX:FOR (INITIALIZATION; TERMINATION-CONDITION;

INCREMENT-STEP) {SET OF STATEMENT(S);

}NEXT STATEMENT;

Page 34: Dti2143 chap 4 control structures aka_selection

FOR LOOP CONTROL STRUCTURE

conditionTrue

False

Set of statements

Next Statement

Initialization

Increment

Example:

int iCount;

for (iCount = 1; iCount <= 10; iCount++) {

printf(“%d\n”,iCount);

}

123456 7 8 9 10

12345678910

Page 35: Dti2143 chap 4 control structures aka_selection

FOR LOOP CONTROL STRUCTURE /* CHECK FOR N NUMBER OF STUDENTS, WHETHER THEY HAVE PASSED OR NOT */#include<stdio.h>#include<conio.h>

int main(void){ int iCounter, iNoOfStudents; float fMark1, fMark2, fMark3, fAvg, fSum; for(iCounter=1; iCounter<=iNoOfStudents; iCounter++) {

/* Accepting the marks scored by the students in 3 subjects */ /* Display a message before accepting the marks*/printf("Enter the marks scored by the student %d in 3 subjects\n", iCounter);printf("Subject1:");scanf("%f",&fMark1);printf("Subject2:");scanf("%f",&fMark2);printf("Subject3:");scanf("%f",&fMark3);/* calculating the average marks */fSum=fMark1+fMark2+fMark3;fAvg=fSum/3;/* compare the average with 65 and decide whether student has passed or failed */if ( fAvg >= 65.0)

printf("Student %d - PASSES\n", iCounter);else

printf("Student %d - FAILS\n", iCounter); }getch();return 0;}

Page 36: Dti2143 chap 4 control structures aka_selection

#include<stdio.h>

#include<conio.h>

int main(void)

{

int x, y;

for(x=0,y=1;x<y;x++)

printf("%d %d",x,y);

getch();

return 0;

}

FOR LOOP CONTROL STRUCTURE

O 1

Page 37: Dti2143 chap 4 control structures aka_selection

#include<stdio.h>

#include<conio.h>

int main(void)

{

int x;

for(x=1;x<5;x++)

printf("%d",x);

getch();

return 0;

}

FOR LOOP CONTROL STRUCTURE

1 2 3 4

Page 38: Dti2143 chap 4 control structures aka_selection

WHAT IS THE OUTPUT OF THE FOLLOWING CODE SNIPPET?

int iNum;

int iCounter;

int iProduct;

for(iCounter=1; iCounter<= 3; iCounter++) {

iProduct = iProduct * iCounter;

}

printf("%d", iProduct);

The output is a junk value -- WHY???

This is because iProduct is not initialized

Page 39: Dti2143 chap 4 control structures aka_selection

WHAT IS THE OUTPUT OF THE FOLLOWING CODE SNIPPET?

for(iCount=0;iCount<10;iCount++);

{

printf("%d\n",iCount);

}The output is 10

int iCount; for(iCount=0;iCount<10;iCount++){

printf("%d\n",iCount);}

The output is 0 1 2 3 4 5 6 7 8 9

Page 40: Dti2143 chap 4 control structures aka_selection

FOR AND WHILE LOOPS

Given

#include<stdio.h>

#include<conio.h>

int main(void)

{

int iSum,iCtr,iNum;

for(iSum=0,iCtr=0;

iCtr<10;iCtr=iCtr+1){

printf("Enter mark: ");

scanf("%d",&iNum);

iSum=iSum+iNum;

}

printf("%d",iSum);

getch();

return 0;

}

Rewrite it using while statement

#include<stdio.h>#include<conio.h>int main(void){ int iSum,iCtr,iNum;iSum=0,iCtr=0;while(iCtr<10){ printf("Enter mark: "); scanf("%d",&iNum); iSum=iSum+iNum; iCtr=iCtr+1;}printf("%d",iSum);getch();return 0;}

Page 41: Dti2143 chap 4 control structures aka_selection

QUITTING THE LOOPS – BREAK STATEMENT

The break statement is used to: Force the termination of a loop. When a break statement is encountered in a loop,

the loop terminates immediately and the execution resumes the next statement following the loop.

Note: Break statement can be used in an if statement

only when the if statement is written in a loop Just an if statement with break leads to compilation

error in C

Page 42: Dti2143 chap 4 control structures aka_selection

WHAT IS THE OUTPUT OF THE FOLLOWING CODE SNIPPET?

int iCounter1=0;

int iCounter2;

while(iCounter1 < 3) {

for (iCounter2 = 0; iCounter2 < 5; iCounter2++) {

printf("%d\t",iCounter2);

if (iCounter2 == 2){

break;

}

}

printf("\n");

iCounter1 += 1;

}

0 1 2

0 1 2

0 1 2

Page 43: Dti2143 chap 4 control structures aka_selection

CONTINUING THE LOOPS - CONTINUE STATEMENT

‘continue’ statement forces the next iteration of the loop to take place and skips the code between continue statement and the end of the loop

In case of for loop, continue makes the execution of the increment portion of the statement and then evaluates the conditional part.

In case of while and do-while loops, continue makes the conditional statement to be executed.

Example:

for(iCount = 0 ; iCount < 10; iCount++) {

if (iCount == 4) {

continue;

}

printf(“%d”, iCount);

}

The above code displays numbers from 1 to 9 except 4.

Page 44: Dti2143 chap 4 control structures aka_selection

COMPARISON OF BREAK, CONTINUE AND EXIT

break continue exit()

Used to quit an innermost loop or switch

Used to continue the innermost loop

Used to terminate the program

Can be used only within loops or switch

Can be used only within the loops

Can be used anywhere in the program

Page 45: Dti2143 chap 4 control structures aka_selection

WHAT IS THE OUTPUT OF THE FOLLOWING CODE SNIPPET?

Case 1:

Case 3:

Case 2:

iCount = 1;

do {

printf(“%d\n”,iCount);

iCount++;

if (iCount == 5) {

continue;

}

} while(iCount < 10);

for (iCount=1;iCount <= 10; iCount++) {

if (iCount % 2 == 0) {

continue;

}

printf(“%d\n”,iCount);

}

iCount = 1;

while (iCount < 10) {

if (iCount == 5) {

continue;

}

printf(“%d\n”,iCount);

iCount++;

}

for (iCount=1;iCount <= 5; iCount++) {

for (iValue =1; iValue <= 3; iValue++) {

if (iValue == 2) {

break;

}

printf(“%d\n”,iValue);

}

}

Case 4:

1

2

3

4

5

6

7

8

9

1

2

3

4

1

3

5

7

9

1

1

1

1

1

Page 46: Dti2143 chap 4 control structures aka_selection

SELECTING BETWEEN WHILE, DO WHILE AND FOR LOOPS

A ‘for’ loop is used when the number of times the loop is executed is well known

A ‘while’ loop is used when the number of times the loop gets executed is not known and the loop should not be executed when the condition is initially false

A ‘do while’ loop is used when the number of times the loop gets executed is not known and the loop should be executed even when the condition is initially false

Page 47: Dti2143 chap 4 control structures aka_selection

END OF SLIDE