Upcoming SlideShare
×

# Dti2143 chap 4 control structures aka_selection

• 902 views

• Comment goes here.
Are you sure you want to
• cool! i like it!
Are you sure you want to
Be the first to like this

Total Views
902
On Slideshare
0
From Embeds
0
Number of Embeds
0

Shares
73
1
Likes
0

No embeds

### Report content

No notes for slide

### Transcript

• 1. Control Structures
• 2. Control Structures
• A control structure refers to the way in which the Programmer specifies the order of executing the statements
• 3. The following approaches can be chosen depending on the problem statement:
• 4. Sequential
• 5. In a sequentialapproach, all the statements are executed in the same order as it is written
• 6. Selectional
• 7. In a selectional approach, based on some conditions, different set of statements are executed
• 8. Iterational (Repetition)
• 9. In an iterational approach certain statements are executed repeat
• Selectional Control Structures
There are two select ional control structures
If statement
Switch statement
• 10. 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
Syntax:
if (condition)
{
Statement(s);
}
Next Statement;
if (iDuration >= 3) {
/* Interest for deposits equal to or more than 3 years
is 6.0% */
fRateOfInterest = 6.0;
}
• 11. 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
• 12. The statement ‘else’ provides the same
Syntax:
if (condition)
{
Statement set-1;
}
else
{
Statement set-2;
}
Next Statement;
• 13. 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;
}
• 14. else if Statement (1 of 2)
• The ‘else if’ statement is to check for a sequence of conditions
• 15. When one condition is false, it checks for the next condition and so on
• 16. When all the conditions are false the ‘else’ block is executed
• 17. 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;
}
• 18. 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
• 19. Example (1 of 2 )
#include<stdio.h>
#include<conio.h>
main()
{
int result;
scanf("%d",&result);
if (result >=55)
{
printf("Passedn");
printf("Congratulationsn");
}
else
{
printf("Failedn");
printf("Good luck repeating this subject :D n");
}
getch();
return 0;
}
77
55
48
21
• 20. 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) {
}
else if (result>=70) {
}
else if (result >=55) {
}
else {
printf("Failedn");
}
getch();
return 0;
}
• 21. 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
• 22. 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
• 23. 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
• 24. This helps in trapping the error at compile time itself, even before it goes to unit testing
• 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”);
}
• 25. Nested if Statement
• An ‘if’ statement embedded within another ‘if’ statement is called as nested ‘if’
• 26. 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”);
}
• 27. #include<stdio.h>
#include<conio.h>
main()
{
intiDuration, dPrincipalAmount;
printf("Enter value for iDuration:");
scanf("%d",&iDuration);
if (iDuration > 6 ) {
printf("What is youtdPrincipalAmount:");
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 if
iDuration=9
dPrincipalAmount=26000
iDuration=10
dPrincipalAmount=21000
iDuration=4
dPrincipalAmount=21000
• 28. Example Nested if
What the output if
num1=55
num2=55
num1=25
num2=89
num1=90
num2=10
#include<stdio.h>
#include<conio.h>
main()
{
int num1;
int num2;
printf("Num1:");
scanf("%d",&num1);
printf("Num2:");
scanf("%d",&num2);
if(num1<=num2) {
if(num1<num2) {
printf("%d < %dn", num1,num2); }
else {
printf("%d==%dn",num1,num2);
}
}
else {
printf("%d > %dn",num1, num2);
}
getch();
return 0;
}
• 29. 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???
• 30. Switch case Statement
• The ‘switch’ statement is a type of decision control structure that selects a choice from the set of available choices
• 31. It is very similar to ‘if’ statement
• 32. But ‘switch’ statement cannot replace ‘if’ statementin 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;
}
• 33. What is the output of the following code snippet?
intiNino= 2;
switch(iNino){
case 1:
printf(“ONE”);
break;
case 2:
printf(“TWO”);
break;
case 3:
printf(“THREE”);
break;
default:
printf(“INVALID”);
break;
}
Output:
TWO
• 34. 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 departmentCodeis 115 and find the output
• What is the output of the following code snippet?
intiNum = 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
• 35. 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
• 36. 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;
}
• 37. 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”);
}
• 38. 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
1…Happy Hari Raya
2…Happy Deepavali
3… Happy New Year
Other than that…….
You choose wrong choice
• 39. Iteration Control Structures
• Iterational (repetitive) control structures are used to repeat certain statements for a specified number of times
• 40. The statements are executed as long as the condition is true
• 41. These kind of control structures are also called as loop control structures
• 42. are three kinds of loop control structures:
• 43. while
• 44. do while
• 45. for
• 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;
• 46. do while Loop Control Structure
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 returnstatement 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.
• 47. 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);
• 48. Difference between while and do while loops
• 49. do – while and whileExample
#include<stdio.h>
#include<conio.h>
int main(void)
{
int x=1;
do{
printf("%d", x++);
}
while (x<5);
getch();
return 0;
}
#include<stdio.h>
#include<conio.h>
int main(void)
{
int x=1;
while(x<5){
printf("%d", x);
x++;
}
getch();
return 0;
}
2
3
4
• 50. 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 beexecuted a specific number of times
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;
• 51. Syntax: for (Initialization; Termination-Condition; Increment-Step) { Set of statement(s); } Next Statement;
In executing a for statement, the computer does the following:
Initializationis executed.
Then the Termination-conditionis evaluated. If it computes to zero the loop is exited.
If the (1)Termination-conditiongives a nonzero value, the (2)LoopBody is executed and then the (3)Increment-stepis evaluated.
The Termination-condition is again tested. Thus, the LoopBody is repeated until the Termination-condition computes to a zero value.
• 52. for Loop Control Structure
Example:
int iCount;
for (iCount = 1; iCount <= 10; iCount++) {
printf(“%dn”,iCount);
}
1
2
3
4
5
6
7
8
9
10
1
2
3
4
5
6 7 8 9 10
• 53. 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)
{
intiCounter, 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 subjectsn", 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 - PASSESn", iCounter);
else
printf("Student %d - FAILSn", iCounter);
}
getch();
return 0;}
• 54. for Loop Control Structure
#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;
}
O 1
• 55. for Loop Control Structure
#include<stdio.h>
#include<conio.h>
int main(void)
{
int x;
for(x=1;x<5;x++)
printf("%d",x);
getch();
return 0;
}
1 2 3 4
• 56. 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
• 57. What is the output of the following code snippet?
for(iCount=0;iCount<10;iCount++);
{
printf("%dn",iCount);
}
The output is 10
int iCount;
for(iCount=0;iCount<10;iCount++)
{
printf("%dn",iCount);
}
The output is 0 1 2 3 4 5 6 7 8 9
• 58. for and while loops
Rewrite it using while statement
#include<stdio.h>
#include<conio.h>
int main(void)
{
intiSum,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;
}
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;
}
• 59. Quitting the Loops – break Statement
The break statement is used to:
Force thetermination of a loop.
When a break statement is encountered in a loop, the loop terminates immediately and the execution resumes the next statementfollowing 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
• 60. What is the output of the following code snippet?
int iCounter1=0;
int iCounter2;
while(iCounter1 < 3) {
for (iCounter2 = 0; iCounter2 < 5; iCounter2++) {
printf("%dt",iCounter2);
if (iCounter2 == 2){
break;
}
}
printf("n");
iCounter1 += 1;
}
0 1 2
0 1 2
0 1 2
• 61. 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
• 62. In case of for loop, continue makes the execution of the increment portion of the statement and then evaluates the conditional part.
• 63. 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.
• 64. Comparison of break, continue and exit
• 65. What is the output of the following code snippet?
1
2
3
4
5
6
7
8
9
Case 1:
Case 3:
1
3
5
7
9
iCount = 1;
do {
printf(“%dn”,iCount);
iCount++;
if (iCount == 5) {
continue;
}
} while(iCount < 10);
for (iCount=1;iCount <= 10; iCount++) {
if (iCount % 2 == 0) {
continue;
}
printf(“%dn”,iCount);
}
Case 4:
Case 2:
for (iCount=1;iCount <= 5; iCount++) {
for (iValue =1; iValue <= 3; iValue++) {
if (iValue == 2) {
break;
}
printf(“%dn”,iValue);
}
}
iCount = 1;
while (iCount < 10) {
if (iCount == 5) {
continue;
}
printf(“%dn”,iCount);
iCount++;
}
1
2
3
4
1
1
1
1
1
• 66. 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
• 67. 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
• 68. 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
• End of SLIDE