Upcoming SlideShare
×

# Dti2143 chap 4 control structures aka_selection

1,081 views

Published on

1 Comment
0 Likes
Statistics
Notes
• Full Name
Comment goes here.

Are you sure you want to Yes No
• cool! i like it!

Are you sure you want to  Yes  No
• Be the first to like this

Views
Total views
1,081
On SlideShare
0
From Embeds
0
Number of Embeds
2
Actions
Shares
0
77
1
Likes
0
Embeds 0
No embeds

No notes for slide

### Dti2143 chap 4 control structures aka_selection

1. 1. Control Structures<br />
2. 2. Control Structures<br /><ul><li>A control structure refers to the way in which the Programmer specifies the order of executing the statements
3. 3. The following approaches can be chosen depending on the problem statement:
4. 4. Sequential
5. 5. In a sequentialapproach, all the statements are executed in the same order as it is written
6. 6. Selectional
7. 7. In a selectional approach, based on some conditions, different set of statements are executed
8. 8. Iterational (Repetition)
9. 9. In an iterational approach certain statements are executed repeat</li></li></ul><li> Selectional Control Structures<br />There are two select ional control structures <br />If statement<br />Switch statement<br />
10. 10. Simple if Statement<br /> In a simple ‘if’ statement, a condition is tested<br /> If the condition is true, a set of statements are executed<br /> If the condition is false, the statements are not executed and the program control goes to the next statement that immediately follows if block<br />Syntax:<br />if (condition) <br />{<br /> Statement(s);<br />}<br />Next Statement; <br />if (iDuration >= 3) {<br />/* Interest for deposits equal to or more than 3 years <br /> is 6.0% */<br />fRateOfInterest = 6.0;<br />}<br />
11. 11. else Statement (1 of 2)<br /><ul><li>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. 12. The statement ‘else’ provides the same</li></ul>Syntax:<br /> if (condition) <br /> {<br /> Statement set-1;<br /> }<br /> else <br /> {<br /> Statement set-2;<br /> }<br /> Next Statement;<br />
13. 13. else Statement (2 of 2)<br /><ul><li>Example:</li></ul> if (iDuration >= 3) {<br />/* If duration is equal to or more than 3 years, <br /> Interest rate is 6.0 */<br />fRateOfInterest = 6.0;<br /> }<br /> else {<br />/* else, Interest rate is 5.5 */<br />fRateOfInterest = 5.5;<br /> }<br />
14. 14. else if Statement (1 of 2)<br /><ul><li>The ‘else if’ statement is to check for a sequence of conditions
15. 15. When one condition is false, it checks for the next condition and so on
16. 16. When all the conditions are false the ‘else’ block is executed
17. 17. The statements in that conditional block are executed and the other ‘if’ statements are skipped </li></ul>Syntax:<br />if (condition-1) <br />{<br /> Statement set-1;<br />}<br />else if (condition-2) <br />{<br />Statement set-2;<br />}<br />………………………………<br />else if (condition-n) <br />{<br />Statement set-n;<br /> }<br />else <br /> {<br /> Statement set-x;<br /> }<br />
18. 18. else if Statement (2 of 2)<br /><ul><li> Always use ‘else if’ when a sequence of conditions has to be </li></ul> tested. <br /><ul><li>Using only ‘if’ will make the compiler to check all the conditions. </li></ul> This increases the execution time<br />
19. 19. Example (1 of 2 )<br />#include<stdio.h><br />#include<conio.h><br />main()<br />{<br />int result;<br />printf("Enter your mark:");<br />scanf("%d",&result);<br /> if (result >=55)<br /> {<br />printf("Passedn");<br />printf("Congratulationsn");<br /> }<br /> else<br />{<br />printf("Failedn");<br />printf("Good luck repeating this subject :D n");<br />}<br />getch();<br />return 0;<br />}<br />77<br />55<br />48<br />21<br />
20. 20. Example (2 of 2 )<br />#include<stdio.h><br />#include<conio.h><br />main()<br />{<br />int test1,test2;<br />int result;<br />printf("Enter your mark for Test 1:");<br />scanf("%d",&test1);<br />printf("Enter your mark for Test 2:");<br />scanf("%d",&test2);<br /> result=(test1+test2)/2;<br /> if(result>=80) {<br />printf("Passed: Grade An");<br /> }<br /> else if (result>=70) { <br />printf("Passed: Grade Bn");<br /> }<br /> else if (result >=55) { <br />printf("Passed: Grade Cn");<br /> }<br /> else {<br />printf("Failedn");<br /> } <br />getch();<br />return 0;<br />}<br />
21. 21. Assignment(=) vs. Equality Operator (==) (1 of 3)<br />The operator ‘=’ is used for assignment purposes whereas the operator ‘==’ is used to check for equality <br />It is a common mistake to use ‘=’ instead of ‘==’ to check for equality <br />The compiler does not generate any error message<br />Example:<br /> if (interest = 6.5) {<br />printf(“Minimum Duration of deposit: 6 years”);<br /> }<br /> else if (interest = 6.0) {<br />printf(“Minimum Duration of deposit: 3 years”);<br /> }<br /> else {<br />printf(“No such interest rate is offered”);<br /> } <br /> The output of the above program will be <br />“Minimum Duration of deposit: 6 years” <br /> the control structure Is ignored <br />
22. 22. Assignment(=) vs. Equality Operator (==) (2 of 3)<br /><ul><li>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. 23. Example:</li></ul> if (6.5 = interest) {<br />printf(“Minimum Duration of deposit: 6 years”);<br /> }<br /> else if (6.0 = interest) {<br />printf(“Minimum Duration of deposit: 3 years”);<br /> }<br /> else {<br />printf(“No such interest rate is offered”);<br /> } <br /><ul><li>When the above code is compiled it generates compilation errors because the variable’s value is being assigned to a constant
24. 24. This helps in trapping the error at compile time itself, even before it goes to unit testing </li></li></ul><li>Assignment(=) vs. Equality Operator (==) (3 of 3)<br /><ul><li>Corrected Code:</li></ul> if (6.5 == interest) {<br />printf(“Minimum Duration of deposit: 6 years”);<br /> }<br /> else if (6.0 == interest) {<br />printf(“Minimum Duration of deposit: 3 years”);<br /> }<br /> else {<br />printf(“No such interest rate is offered”);<br /> } <br />
25. 25. Nested if Statement<br /><ul><li>An ‘if’ statement embedded within another ‘if’ statement is called as nested ‘if’
26. 26. Example:</li></ul> if (iDuration > 6 ) <br />{<br />if (dPrincipalAmount > 25000) <br />{<br />printf(“Your percentage of incentive is 4%”);<br /> }<br /> else <br /> {<br />printf(“Your percentage of incentive is 2%”);<br /> }<br /> else <br /> {<br />printf(“No incentive”);<br />}<br />
27. 27. #include<stdio.h><br />#include<conio.h><br />main()<br />{<br />intiDuration, dPrincipalAmount;<br />printf("Enter value for iDuration:");<br />scanf("%d",&iDuration);<br />if (iDuration > 6 ) {<br />printf("What is youtdPrincipalAmount:");<br />scanf("%d",&dPrincipalAmount);<br /> if (dPrincipalAmount > 25000) {<br />printf("Your percentage of incentive is 4%");<br /> }<br /> else {<br />printf("Your percentage of incentive is 2%");<br /> }<br /> }<br />else {<br />printf("No incentive");<br /> }<br />getch();<br />return 0;<br />}<br />What the output if<br />iDuration=9<br />dPrincipalAmount=26000<br />iDuration=10<br />dPrincipalAmount=21000<br />iDuration=4<br />dPrincipalAmount=21000<br />
28. 28. Example Nested if<br />What the output if<br />num1=55<br /> num2=55<br />num1=25<br /> num2=89<br />num1=90<br /> num2=10<br />#include<stdio.h><br />#include<conio.h><br />main()<br />{<br />int num1;<br />int num2;<br />printf("Please enter two integersn");<br />printf("Num1:");<br />scanf("%d",&num1);<br />printf("Num2:");<br />scanf("%d",&num2);<br /> if(num1<=num2) {<br />if(num1<num2) {<br />printf("%d < %dn", num1,num2); }<br />else {<br />printf("%d==%dn",num1,num2);<br />}<br />}<br />else {<br />printf("%d > %dn",num1, num2);<br /> } <br />getch();<br />return 0;<br />}<br />
29. 29. What is the output of the following code snippet?<br />iResult = iNum % 2;<br />if ( iResult = 0) {<br />printf("The number is even");<br />}<br />else {<br />printf("The number is odd");<br />}<br />CASE 1: When iNum is 11<br />CASE 2: When iNum is 8<br />The output is<br /> "The number is odd"<br />The output is<br /> "The number is odd"<br />Explains???<br />
30. 30. Switch case Statement<br /><ul><li>The ‘switch’ statement is a type of decision control structure that selects a choice from the set of available choices
31. 31. It is very similar to ‘if’ statement
32. 32. But ‘switch’ statement cannot replace ‘if’ statementin all situations </li></ul>Syntax:<br />Switch(integer variable or integer expression or character variable) {<br /> case integer or character constant-1 : <br /> Statement(s);<br /> break;<br /> case integer or character constant-2 :<br /> Statement(s);<br /> break;<br /> ……………<br /> case integer or character constant-n : <br /> Statement(s); break;<br /> default: <br /> Statement(s);<br /> break; <br />}<br />
33. 33. What is the output of the following code snippet?<br />intiNino= 2;<br />switch(iNino){<br /> case 1:<br />printf(“ONE”);<br /> break;<br /> case 2:<br />printf(“TWO”);<br /> break;<br /> case 3:<br />printf(“THREE”);<br /> break;<br /> default:<br />printf(“INVALID”);<br /> break;<br />}<br />Output:<br />TWO<br />
34. 34. What is the output of the following code snippet?<br />switch (departmentCode){<br /> case 110 :<br />printf(“HRD”);<br /> break;<br /> case 115 : <br />printf(“IVS”);<br />break; <br /> case 125 :<br />printf(“E&R”);<br />break; <br /> case 135 : <br />printf(“CCD”);<br />}<br /><ul><li>Assume departmentCodeis 115 and find the output</li></li></ul><li>What is the output of the following code snippet?<br />intiNum = 2;<br />switch(iNum) {<br /> case 1.5:<br />printf(“ONE AND HALF”);<br /> break;<br /> case 2:<br />printf(“TWO”);<br /> break;<br /> case ‘A’ :<br />printf(“A character”);<br />}<br />Case 1.5: this is invalid <br />because the values in <br />case statements must be <br />integers<br />
35. 35. What is the output of the following code snippet?<br />unsigned int iCountOfItems = 5;<br />switch (iCountOfItems) {<br /> case iCountOfItems >=10 : <br /> printf(“Enough Stock” );<br /> break;<br /> default : <br /> printf(“Not enough stock”);<br /> break;<br /> } <br />Error: Relational Expressions cannot be used in switch statement<br />
36. 36. An Example – switch case<br />#include<stdio.h><br />#include<conio.h><br />main()<br />{<br />char ch;<br />printf("Enter the vowel:");<br />scanf("%c",&ch);<br />switch(ch) {<br /> case 'a' : printf("Vowel");<br /> break;<br /> case 'e' : printf("Vowel");<br /> break;<br /> case 'i' : printf("Vowel");<br /> break;<br /> case 'o' : printf("Vowel");<br /> break;<br /> case 'u' : printf ("Vowel");<br /> break;<br /> default : printf("Not a vowel");<br />} <br />getch();<br />return 0;<br />}<br />
37. 37. An Example – switch case<br />char ch=‘a’;<br />switch(ch) {<br /> case ‘a’ : printf(“Vowel”);<br /> break;<br /> case ‘e’ : printf(“Vowel”);<br /> break;<br /> case ‘i’ : printf(“Vowel”);<br /> break;<br /> case ‘o’ : printf(“Vowel”);<br /> break;<br /> case ‘u’ : printf (“Vowel”);<br /> break;<br /> default : printf(“Not a vowel”);<br />} <br />char ch=‘a’;<br />switch(ch) {<br /> case ‘a’ :<br /> case ‘e’ :<br /> case ‘i’ :<br /> case ‘o’ :<br /> case ‘u’ : printf(“Vowel”);<br /> break;<br /> default : <br /> printf(“Not a <br /> vowel”);<br />}<br />
38. 38. An Example – switch case<br />#include<stdio.h><br />#include<conio.h><br />main()<br />{<br />int greeting;<br />printf("Enter the number of your desired greetings :");<br />scanf("%d",&greeting);<br /> switch (greeting){<br /> case 1:<br />printf("Happy Hari Raya");<br /> break;<br /> case 2: <br />printf("Happy Deepavali");<br /> break;<br /> case 3:<br />printf("Happy New Year");<br /> break;<br /> default:<br />printf("You choose wrong choice");<br /> break; <br />}<br />getch();<br />return 0;<br />}<br />If you choose <br />1…Happy Hari Raya<br />2…Happy Deepavali<br />3… Happy New Year<br />Other than that…….<br />You choose wrong choice<br />
39. 39. Iteration Control Structures<br /><ul><li>Iterational (repetitive) control structures are used to repeat certain statements for a specified number of times
40. 40. The statements are executed as long as the condition is true
41. 41. These kind of control structures are also called as loop control structures
42. 42. are three kinds of loop control structures:
43. 43. while
44. 44. do while
45. 45. for</li></li></ul><li>do while Loop Control Structure<br />The ‘do while’ loop is very similar to ‘while’ loop. In ‘do while’ loop, the condition is tested at the end of the loop <br />Because of this, even when the condition is false, the body of the loop is executed at least once <br />This is an exit-controlled loop <br />Syntax:<br />do {<br /> Set of statement(s);<br /> } while (condition);<br /> Next Statement;<br />
46. 46. do while Loop Control Structure<br />Execution proceeds as follows: <br />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<br />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:<br />do{ <br /> a = b ; <br /> b = b – 1; <br />} while ( b > 0 );<br />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.<br />
47. 47. do while Loop Control Structure Example<br /> int iNumber, iSum = 0;<br /> do {<br /> printf(“Enter a number. Type 0(zero) to end the input ”);<br /> scanf(“%d”,&iNumber);<br /> iSum = iSum + iNumber;<br /> } while (iNumber != 0);<br />
48. 48. Difference between while and do while loops<br />
49. 49. do – while and whileExample<br />#include<stdio.h><br />#include<conio.h><br />int main(void)<br />{<br />int x=1;<br />do{<br />printf("%d", x++);<br /> }<br />while (x<5);<br />getch();<br /> return 0;<br /> }<br />#include<stdio.h><br />#include<conio.h><br />int main(void)<br />{<br />int x=1;<br />while(x<5){<br />printf("%d", x);<br /> x++;<br /> }<br />getch();<br /> return 0;<br /> }<br /> 2 <br /> 3<br /> 4<br />
50. 50. for Loop Control Structure <br />The ‘for’ loops are similar to the other loop control structures <br />The ‘for’ loops are generally used when certain statements have to beexecuted a specific number of times <br />Advantage of for loops:<br />All the three parts of a loop (initialization, condition and increment) can be given in a single statement <br />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 <br />Syntax:<br /> for (Initialization; Termination-Condition; Increment-Step) {<br /> Set of statement(s);<br /> }<br /> Next Statement;<br />
51. 51. Syntax: for (Initialization; Termination-Condition; Increment-Step) { Set of statement(s); } Next Statement;<br />In executing a for statement, the computer does the following:<br />Initializationis executed.<br />Then the Termination-conditionis evaluated. If it computes to zero the loop is exited.<br />If the (1)Termination-conditiongives a nonzero value, the (2)LoopBody is executed and then the (3)Increment-stepis evaluated.<br />The Termination-condition is again tested. Thus, the LoopBody is repeated until the Termination-condition computes to a zero value.<br />
52. 52. for Loop Control Structure <br />Example:<br />int iCount;<br />for (iCount = 1; iCount <= 10; iCount++) {<br /> printf(“%dn”,iCount);<br />}<br />1<br />2<br />3<br />4<br />5<br />6<br />7<br />8<br />9<br />10<br />1<br />2<br />3<br />4<br />5<br />6 7 8 9 10<br />
53. 53. for Loop Control Structure /* Check for n number of students, whether they have passed or not */<br />#include<stdio.h><br />#include<conio.h><br />int main(void)<br />{<br />intiCounter, iNoOfStudents;<br /> float fMark1, fMark2, fMark3, fAvg, fSum;<br /> for(iCounter=1; iCounter<=iNoOfStudents; iCounter++) {<br />/* Accepting the marks scored by the students in 3 subjects */<br /> /* Display a message before accepting the marks*/<br />printf("Enter the marks scored by the student %d in 3 subjectsn", iCounter);<br />printf("Subject1:");<br />scanf("%f",&fMark1);<br />printf("Subject2:");<br />scanf("%f",&fMark2);<br />printf("Subject3:");<br />scanf("%f",&fMark3);<br />/* calculating the average marks */<br />fSum=fMark1+fMark2+fMark3;<br />fAvg=fSum/3;<br />/* compare the average with 65 and decide whether student has passed or failed */<br /> if ( fAvg >= 65.0)<br />printf("Student %d - PASSESn", iCounter);<br /> else<br />printf("Student %d - FAILSn", iCounter);<br /> }<br />getch();<br />return 0;}<br />
54. 54. for Loop Control Structure <br />#include<stdio.h><br />#include<conio.h><br />int main(void)<br />{<br />int x, y;<br />for(x=0,y=1;x<y;x++)<br />printf("%d %d",x,y);<br />getch();<br />return 0;<br />}<br />O 1<br />
55. 55. for Loop Control Structure <br />#include<stdio.h><br />#include<conio.h><br />int main(void)<br />{<br /> int x;<br /> for(x=1;x<5;x++)<br /> printf("%d",x);<br /> getch();<br /> return 0;<br /> }<br />1 2 3 4<br />
56. 56. What is the output of the following code snippet?<br />int iNum;<br /> int iCounter;<br /> int iProduct;<br /> for(iCounter=1; iCounter<= 3; iCounter++) {<br /> iProduct = iProduct * iCounter;<br /> }<br /> printf("%d", iProduct);<br />The output is a junk value -- WHY???<br />This is because iProduct is not initialized<br />
57. 57. What is the output of the following code snippet?<br />for(iCount=0;iCount<10;iCount++);<br />{<br /> printf("%dn",iCount);<br />}<br />The output is 10<br />int iCount;<br /> for(iCount=0;iCount<10;iCount++)<br />{<br /> printf("%dn",iCount);<br />}<br />The output is 0 1 2 3 4 5 6 7 8 9<br />
58. 58. for and while loops<br />Rewrite it using while statement<br />#include<stdio.h><br />#include<conio.h><br />int main(void)<br />{<br />intiSum,iCtr,iNum;<br />iSum=0,iCtr=0;<br />while(iCtr<10){<br />printf("Enter mark: ");<br />scanf("%d",&iNum);<br />iSum=iSum+iNum;<br />iCtr=iCtr+1;<br />}<br />printf("%d",iSum);<br />getch();<br />return 0;<br />}<br />Given<br />#include<stdio.h><br />#include<conio.h><br />int main(void)<br />{<br /> int iSum,iCtr,iNum;<br />for(iSum=0,iCtr=0;<br /> iCtr<10;iCtr=iCtr+1){<br /> printf("Enter mark: ");<br /> scanf("%d",&iNum);<br /> iSum=iSum+iNum;<br />}<br />printf("%d",iSum);<br />getch();<br />return 0;<br />}<br />
59. 59. Quitting the Loops – break Statement<br />The break statement is used to:<br />Force thetermination of a loop. <br />When a break statement is encountered in a loop, the loop terminates immediately and the execution resumes the next statementfollowing the loop.<br />Note:<br />Break statement can be used in an if statement only when the if statement is written in a loop<br />Just an if statement with break leads to compilation error in C<br />
60. 60. What is the output of the following code snippet?<br />int iCounter1=0;<br />int iCounter2;<br />while(iCounter1 < 3) {<br /> for (iCounter2 = 0; iCounter2 < 5; iCounter2++) {<br /> printf("%dt",iCounter2);<br /> if (iCounter2 == 2){<br /> break;<br /> }<br /> }<br /> printf("n");<br /> iCounter1 += 1;<br />}<br />0 1 2<br />0 1 2<br />0 1 2<br />
61. 61. Continuing the Loops - continue Statement<br /><ul><li>‘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. 62. In case of for loop, continue makes the execution of the increment portion of the statement and then evaluates the conditional part.
63. 63. In case of while and do-while loops, continue makes the conditional statement to be executed.</li></ul>Example:<br />for(iCount = 0 ; iCount < 10; iCount++) {<br /> if (iCount == 4) {<br /> continue;<br /> }<br /> printf(“%d”, iCount);<br />} <br />The above code displays numbers from 1 to 9 except 4.<br />
64. 64. Comparison of break, continue and exit<br />
65. 65. What is the output of the following code snippet?<br />1<br /> 2<br /> 3<br /> 4 <br /> 5<br /> 6<br /> 7<br /> 8<br /> 9<br />Case 1:<br />Case 3:<br />1<br /> 3<br /> 5 <br /> 7 <br /> 9<br />iCount = 1;<br />do {<br /> printf(“%dn”,iCount);<br /> iCount++;<br /> if (iCount == 5) {<br /> continue;<br /> }<br />} while(iCount < 10);<br />for (iCount=1;iCount <= 10; iCount++) {<br /> if (iCount % 2 == 0) {<br /> continue;<br /> }<br /> printf(“%dn”,iCount);<br />}<br />Case 4:<br />Case 2:<br />for (iCount=1;iCount <= 5; iCount++) {<br /> for (iValue =1; iValue <= 3; iValue++) {<br /> if (iValue == 2) {<br /> break;<br /> }<br /> printf(“%dn”,iValue);<br /> }<br />}<br />iCount = 1;<br />while (iCount < 10) {<br /> if (iCount == 5) {<br /> continue;<br /> }<br /> printf(“%dn”,iCount);<br /> iCount++;<br />}<br />1 <br />2 <br />3<br />4 <br />1 <br />1 <br />1 <br />1 <br />1<br />
66. 66. Selecting between while, do while and for loops<br /><ul><li>A ‘for’ loop is used when the number of times the loop is executed is well known
67. 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. 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</li></li></ul><li>End of SLIDE<br />