2Unit 2

Input/Output & Control Structures

8h

Class hours

8

Topics

0%

0/8 done

Progress0/8 topics

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 (condition) { // runs if condition is true }

if-else

if (condition) { // true branch } else { // false branch }

if-else-if ladder (multi-way decision)

if (condition1) { // runs if condition1 is true } else if (condition2) { // runs if condition2 is true } else if (condition3) { // runs if condition3 is true } else { // runs if none of the above are true }

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

main.cGrade Calculator

Enter marks from 0 to 100 in stdin.

stdin:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
▶ Output
Press Run ▶ to execute
Ctrl+Enter to run · Tab for indent
Exam Tip

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

if (outer_condition) { if (inner_condition) { // both conditions true } else { // outer true, inner false } } else { // outer false }

switch-case syntax

switch (expression) { case value1: // statements break; // exits switch case value2: // statements break; case value3: case value4: // fall-through: same action for v3 and v4 // statements break; default: // runs if no case matches }

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).
  • break is NOT mandatory — but without it the code "falls through" to the next case.
  • Fall-through is sometimes intentional (sharing code between cases).
  • default is 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

main.cDay of Week

Enter a number 1-7 in stdin.

stdin:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
▶ Output
Press Run ▶ to execute
Ctrl+Enter to run · Tab for indent

Calculator using switch

main.cCalculator (switch)

Type: 8 * 3 (try +, -, /, *) in stdin.

stdin:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
▶ Output
Press Run ▶ to execute
Ctrl+Enter to run · Tab for indent
Exam Tip

"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

for (initialization; condition; update) { // body — executes while condition is true } // Execution order: // 1. initialization (runs once at start) // 2. condition check (if false, exit loop) // 3. body (run the statements) // 4. update (increment/decrement) // 5. go back to step 2

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

main.cMultiplication Table

Enter a number in stdin to print its table.

stdin:
1
2
3
4
5
6
7
8
9
10
11
12
▶ Output
Press Run ▶ to execute
Ctrl+Enter to run · Tab for indent

Pattern Programs (Nested Loops) — TU Exam Favourite

main.cPattern Programs

Enter number of rows (try 5). Generates triangle, number pyramid, and inverted triangle.

stdin:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
▶ Output
Press Run ▶ to execute
Ctrl+Enter to run · Tab for indent
Exam Tip

"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

initialization; while (condition) { // body update; }

Equivalent for loop

for (initialization; condition; update) { // body } // for and while are interchangeable. // while is preferred when init/update // are complex or at different places.

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

main.cSum of Digits & Reverse

Enter any integer in stdin (try 12345 or 9801).

stdin:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
▶ Output
Press Run ▶ to execute
Ctrl+Enter to run · Tab for indent
Exam Tip

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

do { // body (always runs at least once) } while (condition); // <-- semicolon required!

Key Differences

Featurewhiledo-while
Test typePre-testPost-test
Min executions0 (may skip)1 (always runs)
SemicolonNoYes (after while)
Best forUnknown countMenu 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

main.cMenu-Driven Calculator

Type choices and numbers: e.g. enter '1' then '10 20' — the menu loops until you choose 4.

stdin:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
▶ Output
Press Run ▶ to execute
Ctrl+Enter to run · Tab for indent
Exam Tip

"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

main.cPrime + break/continue

Enter a positive integer to check if it is prime. Also prints odd numbers up to N.

stdin:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
▶ Output
Press Run ▶ to execute
Ctrl+Enter to run · Tab for indent
Exam Tip

"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.

1

What is the difference between if-else and switch?

2

What happens if you forget break in a switch case?

3

What is the difference between while and do-while?

4

When would you use a for loop vs a while loop?

5

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 marks

Write a C program using switch to perform +, -, *, / based on user-input operator.

5 marks

Differentiate for, while, and do-while loops with syntax and one example each.

5 marks

Quick 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

FFor — Fixed count iteration (for i=1 to 10)
WWhile — Watches a condition, pre-test
DDo-While — Does it first, then decides (post-test)

break vs continue — the B and C rule

BB · CC

BBBreak Bails — exits the loop completely
CCContinue Carries on — skips to next iteration
Think: break = emergency exit, continue = skip this floor

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.

case 1: action1; // no break! case 2: action2; // also runs if case 1 matched!
🍽️

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.

do { show_menu(); // always shown once } while (choice != 4);
🔑

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.

for (set; check; change) body;
🧮

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.

outer loop = rows (i) inner loop = cols (j) Total ops ≈ O(n²)
🪴

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.

switch (grade) works switch (3.14) — ERROR (float!)
♾️

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.

while (1) { get_input(); if (quit) break; }

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

Know difference between if-else (any condition) and switch (int/char constants only)
Know break is NOT mandatory in switch — fall-through concept
Can write for, while, do-while with correct syntax including do-while semicolon
Know difference: while is pre-test (0+ runs), do-while is post-test (1+ runs)
Know break exits loop entirely; continue skips to next iteration
Can write multiplication table using for loop
Can write sum-of-digits and reverse-number using while loop
Can write menu-driven program using do-while + switch
Can write nested loop star/number triangle patterns
Know when goto is valid concept (TU theory) and why to avoid it in practice
BCAStudyHub

Your complete interactive study guide for TU BCA Semester I — covering all subjects with interactive tools, past papers, and exam prep.

TU BCASemester I

Program Info

University
Tribhuvan University
Program
BCA — Bachelor in Computer Application
Semester
I (First)
Subjects
5 (4 live, 1 coming soon)

Made by SawnN