For example to check the value of the variable marks and print the message

# For example to check the value of the variable marks

This preview shows page 5 - 8 out of 11 pages.

For example, to check the value of the variable marks and print the message accordingly, we would write if (marks >= 75) printf (“Distinction\n”) ; else if (marks >= 60) printf (“Pass\n”) ; else if (marks >= 50) printf (“Average\n”) ; else printf (“Fail\n”) ; Nested if statements: There can be if statements inside if and else statements which can be used to implement decisions with several alternatives . For example, if ( x > 2.5 ) { p = p + 1 ; if ( x < 3.5 ) n = n + 1; else m = m + 1; } else { if ( x > 1.5 ) s = s + 1 ; else t = t + 1; } In the above example, if x is greater than 2.5 then 1 is added to p and it is checked if x is less than 3.5 . If it is so, then 1 is added to n . If x is more than 3.5 , 1 is added to m . If x is less than 2.5 , the execution comes directly to the else part Page 5 of 11
without doing anything to p, n, m and it is checked if x is more than 1.5 . If it is so 1 is added to s else 1 is added to t . Multiple selection using the switch statement: Syntax: switch (expression) { case value 1: statement 1; break ; case value 2: statement 2; break ; : : case value n: statement n; break ; default: statement e; } Here it is checked whether the value of expression matches any of the case values. For example , to check the value of the character variable color and print the message accordingly, we write switch (color) { case ‘R’: printf (“red\n”) ; break ; case ‘B’: printf (“blue\n”) ; break ; case ‘Y’: printf (“yellow\n”) ; break ; default: printf (“black\n”) ; break ; } Page 6 of 11
The single quotes ‘R’,’B’,’Y’ are used because of the color being character variable. If color is ‘R’ then red is printed and the other cases are not checked , however if color is not red then other cases are checked until a match is found. If no match is found then the default value of black is printed. Solved Examples: Use of Control Structures (Selection Structures) Example#1: /******************************************************************* Write a program that calculates and displays the reciprocal of an integer, both as a common fraction and a decimal fraction. A typical output line would be : The reciprocal of 2 is 1/2 or 0.500

#### You've reached the end of your free preview.

Want to read all 11 pages?

• Spring '10
• zaman
• Equals sign, relational operator, printf
Stuck? We have tutors online 24/7 who can help you get unstuck.
Ask Expert Tutors You can ask You can ask You can ask (will expire )
Answers in as fast as 15 minutes