Fundamentals of Computer Programming - Old Questions

4. Difference between if and switch statement. Write a program to read the marks of four subjects then find total, percentage and division according to given condition. [1+5]

Percentage                                    Division

p ≥ 80                                             Distinction

80 > p ≥ 70                                     First division

70 > p ≥ 50                                     Second division

50 > p ≥ 40                                     Third division

Otherwise Fail.

Assume each subjects carrying 100 full marks and students must secure greater or equal to 40 in each subjects for division.

6 marks | Asked in 2070

Difference between if and switch statement

1. SWITCH statement is easier to express for lengthy conditions when compared to an IF statement which gets more complex as the number of conditions grow and the nested IF comes into play.

2. SWITCH statement allows easy proofreading while testing and removing bugs from the source code whereas IF statement makes editing difficult.

3. Expression is evaluated and SWITCH statement is run according to the result of the expression that can be integer or logical while IF statement is run only if the result of the expression is true.

4. SWITCH allows expression to have integer based evaluation while IF statement allows both integer and character based evaluation.

5. SWITCH statement can be executed with all cases if the ‘break’ statement is not used whereas IF statement has to be true to be executed further.

Program

#include <stdio.h> int main() { int phy, chem, bio, math; float p, total;

/* Input marks of five subjects from user */ printf("Enter four subjects marks: "); scanf("%d%d%d%d", &phy, &chem, &bio, &math);

/* Calculate total */ total= (phy + chem + bio + math); printf("Total marks = %f\\n", total); /* Calculate percentage */ p = (phy + chem + bio + math) / 4.0; printf("Percentage = %f\\n", p); /* Find division according to the percentage */ if(p >= 90) { printf("Division: Distinction"); } else if(p>=70 && p<80 ) { printf("Division: First division"); } else if(p>=50 && p<70) { printf("Division: Second division"); } else if(p>=40 && p<50) { printf("Division: Third division"); } else { printf("Fail"); } return 0; }