Programming Language & Its Applications — Introduction to C Programming, NEC licence examination syllabus (Nepal Engineering Council).
if, switch, and the dangling-else trap that has bitten every C programmer.
A program that runs the same instructions every time is a calculator, not software. Control statements let execution take different paths, and C gives you two mechanisms: if-else chains for arbitrary conditions, and switch for dispatching on a single integer value. Choosing between them matters for both readability and speed.
if that silently skipped SSL certificate validation on every iPhone and Mac, so anyone on your network could impersonate your bank. One missing pair of braces, in exactly this pattern. Look up "Apple goto fail SSL"; it is the most expensive brace in history and it makes "always use braces" stop feeling pedantic.#include <stdio.h>
int main(void) {
int marks;
printf("Marks: ");
if (scanf("%d", &marks) != 1) return 1;
/* order matters: check highest first */
if (marks >= 80) printf("Distinction\n");
else if (marks >= 60) printf("First division\n");
else if (marks >= 45) printf("Second division\n");
else if (marks >= 32) printf("Pass\n");
else printf("Fail\n");
/* the same thing as a ternary */
printf("Result: %s\n", marks >= 32 ? "PASS" : "FAIL");
return 0;
}
Input: 72
Output: First division
Result: PASS
#include <stdio.h>
int main(void) {
double a, b;
char op;
printf("Enter e.g. 12 * 4 : ");
if (scanf("%lf %c %lf", &a, &op, &b) != 3) return 1;
switch (op) {
case '+': printf("%.2f\n", a + b); break;
case '-': printf("%.2f\n", a - b); break;
case '*': printf("%.2f\n", a * b); break;
case '/':
if (b == 0) printf("Cannot divide by zero\n");
else printf("%.2f\n", a / b);
break;
default:
printf("Unknown operator '%c'\n", op);
}
return 0;
}
Input: 12 * 4
Output: 48.00
#include <stdio.h>
int main(void) {
char grade = 'B';
/* Several cases sharing one action - fall-through is
intentional and useful here */
switch (grade) {
case 'A':
case 'B':
case 'C':
printf("Passed\n");
break;
case 'D':
case 'F':
printf("Failed\n");
break;
}
/* ACCIDENTAL fall-through - the classic bug */
int day = 2;
switch (day) {
case 1: printf("Mon\n"); /* no break! */
case 2: printf("Tue\n"); /* no break! */
case 3: printf("Wed\n");
break;
}
return 0;
}
Output:
Passed
Tue
Wed <-- fell through from case 2!
Create a free account to tick topics off, take notes as you read, watch the video lessons and get a day-by-day study plan built around your exam date.
Loading…