Input/Output & Control Structures
8h
Class hours
8
Topics
0%
0/8 done
Why This Unit Matters
Master formatted and unformatted I/O (printf, scanf, getchar, putchar, getch, gets), decision structures (if-else, switch), all three loop types, and jump statements.
If & If-Else Statements
Decision statements allow a program to choose between different paths of execution based on a condition. The condition is a relational or logical expression that evaluates to true (non-zero) or false (0).
Simple if
if-else
if-else-if ladder (multi-way decision)
How C evaluates conditions
- Any non-zero value is true; 0 is false.
- Relational operators return 1 (true) or 0 (false).
- Common mistake:
if (x = 5)assigns 5 and is always true. Use==for comparison. - Curly braces are optional for single-statement bodies — but always recommended to avoid bugs.
Grade Calculator — if-else-if ladder
Enter marks from 0 to 100 in stdin.
Know all three forms: simple if, if-else, and if-else-if ladder. "Write a C program to find the largest of two/three numbers using if-else" is a very common 5-mark question. Remember: braces are optional for single statements but required for multiple statements.
Nested If & Switch-Case
A nested if is an if statement inside another if or else. The switch-case statement is a cleaner alternative when selecting from multiple fixed values of an integer or character expression.
Nested if
switch-case syntax
switch-case — Key Rules
- The expression must evaluate to an integer or character (not float or string).
- Case values must be integer constants (not variables, not ranges).
breakis NOT mandatory — but without it the code "falls through" to the next case.- Fall-through is sometimes intentional (sharing code between cases).
defaultis optional but recommended; it handles all unmatched cases.- switch is generally faster than a long if-else-if ladder for integer dispatch.
Day of Week — switch example
Enter a number 1-7 in stdin.
Calculator using switch
Type: 8 * 3 (try +, -, /, *) in stdin.
"Is break mandatory in switch?" — Answer: No. Without break, execution falls through to the next case. This is a direct theory question. Also: switch cannot be used with float or string expressions, and case labels must be constant integer values.
For Loop
The for loop is the most compact loop in C. All three parts — initialization, condition check, and update — are written in a single line. Best used when the number of iterations is known in advance.
For loop syntax
Count 1 to 5
for (int i = 1; i <= 5; i++)
printf("%d ", i);Count backwards
for (int i = 5; i >= 1; i--)
printf("%d ", i);Even numbers
for (int i = 2; i <= 10; i += 2)
printf("%d ", i);Sum of 1 to N
int sum = 0;
for (int i = 1; i <= n; i++)
sum += i;
printf("Sum = %d", sum);Infinite loop
for (;;) {
// infinite — use break to exit
}Nested for
for (int i = 1; i <= 3; i++)
for (int j = 1; j <= 3; j++)
printf("(%d,%d) ", i, j);Multiplication Table
Enter a number in stdin to print its table.
Pattern Programs (Nested Loops) — TU Exam Favourite
Enter number of rows (try 5). Generates triangle, number pyramid, and inverted triangle.
"Write a C program to generate the following pattern" using nested for loops appears in almost every TU exam. Master: star triangle (right-angled), inverted triangle, number pyramid, Floyd's triangle. The outer loop controls rows; the inner loop controls columns (stars/numbers per row).
While Loop
The while loop is a pre-test (entry-controlled) loop — the condition is checked before the body executes. If the condition is false initially, the body never runs. Best used when the number of iterations is not known in advance.
While loop syntax
Equivalent for loop
while vs for — When to use which?
- for: When you know the number of iterations upfront (e.g., count 1 to 10).
- while: When you loop until some condition changes (e.g., read until 0, process digits of a number).
- Both are pre-test loops (check before entering).
Sum of Digits & Reverse Number
Enter any integer in stdin (try 12345 or 9801).
Classic while-loop programs in TU exams: sum of digits, reverse a number, check palindrome, count digits, print Fibonacci series, find GCD (Euclidean algorithm). For the reverse-number algorithm: digit = n%10; reversed = reversed*10 + digit; n /= 10;
Do-While Loop
The do-while loop is a post-test (exit-controlled) loop — the condition is checked after the body executes. This guarantees the body runs at least once, regardless of the condition.
Do-while syntax
Key Differences
| Feature | while | do-while |
|---|---|---|
| Test type | Pre-test | Post-test |
| Min executions | 0 (may skip) | 1 (always runs) |
| Semicolon | No | Yes (after while) |
| Best for | Unknown count | Menu loops |
When to use do-while
- Menu-driven programs (show menu, process, repeat)
- Input validation (keep asking until valid input)
- Game loops (play once, ask to continue)
- Any situation where you need to run the body first, then check
Menu-Driven Program
Type choices and numbers: e.g. enter '1' then '10 20' — the menu loops until you choose 4.
"What is the difference between while and do-while?" is a standard 4-mark theory question. Key answer: do-while is post-test (exits-controlled) and guarantees at least one execution. Don't forget the semicolon after } while(condition);
Break, Continue & Goto
Jump statements alter the normal flow of control within loops and switch statements.
break
Immediately exits the enclosing loop (for, while, do-while) or switch statement. Control jumps to the first statement after the loop/switch.
for (i = 1; i <= 10; i++) {
if (i == 5) break; // exits loop when i reaches 5
printf("%d ", i); // prints: 1 2 3 4
}continue
Skips the rest of the current iteration and jumps to the next iteration's condition check / update step. Does NOT exit the loop — just skips the current cycle.
for (i = 1; i <= 10; i++) {
if (i % 2 == 0) continue; // skip even numbers
printf("%d ", i); // prints: 1 3 5 7 9
}goto (avoid in practice)
Unconditional jump to a labelled statement. Makes code hard to read ("spaghetti code"). Avoid in modern programming — use structured loops and break/continue instead. Still appears in TU theory questions as a concept.
goto label; // jump to label
// skipped code
label: // destination
printf("Jumped here\n");Prime Checker + break & continue demo
Enter a positive integer to check if it is prime. Also prints odd numbers up to N.
"Explain break and continue with examples" is a 4-5 mark question. Key distinction: break exits the loop entirely; continue skips to the next iteration. For prime checking — the optimized check runs only up to √n using i * i <= n. goto is asked in theory only; the answer should note it causes unstructured code and should be avoided.
Practice & Quiz
Active Recall Questions
Try to answer each question from memory before revealing the answer. Active recall beats re-reading for long-term retention every time.
What is the difference between if-else and switch?
What happens if you forget break in a switch case?
What is the difference between while and do-while?
When would you use a for loop vs a while loop?
What does continue do vs break?
Exam-Style Questions
Questions matching the style and marks distribution of TU BCA (CACS 151) past papers. Attempt each before revealing the full solution.
Write a C program to print the multiplication table of a number n.
5 marksWrite a C program using switch to perform +, -, *, / based on user-input operator.
5 marksDifferentiate for, while, and do-while loops with syntax and one example each.
5 marksQuick Revision
How to Remember
How to Remember Unit 2
Unit 2 is about controlling the flow of your program: branching with if/switch and repeating with loops. These mnemonics and analogies make the distinctions stick.
Mnemonics
Three Loop Types — in order of control
FWD
break vs continue — the B and C rule
BB · CC
Memory Tricks
switch Fall-Through — The Leaky Faucet
A switch without break is like a leaky faucet — the water (execution) keeps flowing into the next case. You need break to plug the leak and stop it.
do-while Guarantees One Execution
do-while is like a buffet — you always take at least one plate before you check if you are full. The body runs first, then the condition is checked.
for Loop — Set, Check, Change
The three parts of a for loop have a simple pattern: Set the counter, Check the condition, Change (update) the counter. In that order, every iteration.
Nested Loop Complexity — Rows × Columns
In nested loops: the outer loop controls ROWS, the inner loop controls COLUMNS (or elements per row). For a pattern of n rows: outer runs n times, inner varies per row.
switch Cannot Test Ranges or Floats
switch is a jump table — it can only jump to exact integer or character values. It cannot test 'between 60 and 80' or float values. Use if-else for ranges.
Infinite Loops — When to Use Them
Use while(1) or for(;;) for intentional infinite loops that rely on break or return to exit. This is the standard pattern for event loops and menu programs.
Quick Syntax Reference
for
for (i=1; i<=n; i++) {
body;
}while
while (condition) {
body;
update;
}do-while
do {
body;
} while (cond); // ← ;Before the Exam: Unit 2 Checklist