C ProgrammingUnit 313 min read
Input/Output & Control Structures in C: Functions, Decisions & Loops
Unit 3 of C Programming covers essential I/O functions (scanf, printf, getchar, putchar) and control structures (if-else, switch, loops) with real-world applications, syntax rules, and debugging techniques. Learn how to structure logic for decision-making and repetition in programs.
TAKEAWAYS:
- Master 8 core I/O functions and their syntax, including formatted (
scanf,printf) and character-level (getchar,putchar) operations. - Understand 3 control structures (selection, iteration, branching) and their use cases, with visual flowcharts for each.
- Apply nested conditions and switch-case for multi-way branching, avoiding common pitfalls like missing
break. - Trace loop execution (for, while, do-while) step-by-step using variable tables, including infinite-loop detection.
- Solve real problems like menu-driven calculators (eSewa-style), password validation (Khalti), and transaction logs (NTC billing).
- Debug logical errors in control flow using
printfdebugging and rubber-ducking techniques.
1. Input/Output Functions in C
Input/Output (I/O) functions allow programs to interact with users or external devices. C provides standard library functions in <stdio.h> for this purpose.
1.1 Key I/O Functions
| Function | Description | Example Usage |
|---|---|---|
printf() |
Prints formatted output to the console. | printf("Sum: %d", sum); |
scanf() |
Reads formatted input from the user. | scanf("%d", &num); |
getchar() |
Reads a single character (including whitespace). | ch = getchar(); |
putchar() |
Prints a single character. | putchar('A'); |
gets() |
Reads a string (unsafe; use fgets() instead). |
gets(str); |
puts() |
Prints a string followed by a newline. | puts("Hello"); |
fopen()/fclose() |
Opens/closes files for I/O. | FILE *fp = fopen("file.txt", "r"); |
fprintf()/fscanf() |
File-specific versions of printf/scanf. |
fprintf(fp, "Data: %d", x); |
1.2 Worked Example: Menu-Driven Calculator (eSewa-Style)
Problem: Write a program that mimics an eSewa payment menu, where the user selects an operation (add, subtract, multiply, divide) and inputs two numbers.
#include <stdio.h>
int main() {
int choice, num1, num2, result;
printf("eSewa Payment Menu:\n");
printf("1. Add\n2. Subtract\n3. Multiply\n4. Divide\n");
printf("Enter choice (1-4): ");
scanf("%d", &choice);
printf("Enter two numbers: ");
scanf("%d %d", &num1, &num2);
switch(choice) {
case 1: result = num1 + num2; break;
case 2: result = num1 - num2; break;
case 3: result = num1 * num2; break;
case 4:
if (num2 != 0) result = num1 / num2;
else { printf("Error: Division by zero!\n"); return 1; }
break;
default: printf("Invalid choice!\n"); return 1;
}
printf("Result: %d\n", result);
return 0;
}
Trace Table for choice = 3, num1 = 5, num2 = 4:
| Step | choice |
num1 |
num2 |
result |
Action |
|---|---|---|---|---|---|
| 1 | 3 | 5 | 4 | - | User inputs choice and numbers. |
| 2 | 3 | 5 | 4 | - | switch checks case 3. |
| 3 | 3 | 5 | 4 | 20 | result = 5 * 4 executed. |
| 4 | 3 | 5 | 4 | 20 | Prints "Result: 20". |
Visual Flowchart:
flowchart TD
A["Start"] --> B["Display Menu"]
B --> C["Read choice"]
C --> D{"choice == 1?"}
D -->|"Yes"| E["Add: result = num1 + num2"]
D -->|"No"| F{"choice == 2?"}
F -->|"Yes"| G["Subtract: result = num1 - num2"]
F -->|"No"| H{"choice == 3?"}
H -->|"Yes"| I["Multiply: result = num1 * num2"]
H -->|"No"| J{"choice == 4?"}
J -->|"Yes"| K["Divide: result = num1 / num2"]
J -->|"No"| L["Invalid choice"]
E --> M["Print result"]
G --> M
I --> M
K --> M
L --> N["End"]
M --> N2. Control Structures
Control structures dictate the flow of execution in a program. They include:
- Selection (
if,else if,else,switch) - Iteration (
for,while,do-while) - Branching (
break,continue,goto)
2.1 Selection Structures
2.1.1 if-else Ladder
Used for multi-way decisions. Example: Khalti transaction validation (check if balance ≥ amount).
#include <stdio.h>
int main() {
float balance = 5000, amount;
printf("Enter amount to transfer: ");
scanf("%f", &amount);
if (amount > balance) {
printf("Insufficient funds!\n");
} else if (amount <= 0) {
printf("Invalid amount!\n");
} else {
balance -= amount;
printf("Transfer successful. New balance: %.2f\n", balance);
}
return 0;
}
Visual:
flowchart TD
A["Start"] --> B["Read amount"]
B --> C{"amount > balance?"}
C -->|"Yes"| D["Print 'Insufficient funds'"]
C -->|"No"| E{"amount <= 0?"}
E -->|"Yes"| F["Print 'Invalid amount'"]
E -->|"No"| G["Update balance"]
G --> H["Print success message"]
D --> I["End"]
F --> I
H --> I2.1.2 switch-case
Used for discrete choices (e.g., menu options). Example: NTC billing system (monthly plans).
#include <stdio.h>
int main() {
int plan;
printf("NTC Monthly Plans:\n1. Basic (Rs. 500)\n2. Premium (Rs. 1000)\n3. Unlimited (Rs. 1500)\n");
printf("Choose plan (1-3): ");
scanf("%d", &plan);
switch(plan) {
case 1: printf("Billed: Rs. 500\n"); break;
case 2: printf("Billed: Rs. 1000\n"); break;
case 3: printf("Billed: Rs. 1500\n"); break;
default: printf("Invalid plan!\n");
}
return 0;
}
Common Pitfalls:
- Missing
break: Causes fall-through (executes all subsequent cases).switch(x) { case 1: printf("One"); // Missing break → executes case 2 too! case 2: printf("Two"); } - Default case: Should handle invalid inputs.
2.2 Iteration Structures
Loops repeat a block of code until a condition is met.
2.2.1 for Loop
Syntax:
for (initialization; condition; increment) {
// Loop body
}
Example: Print Ncell call logs (first 10 calls).
#include <stdio.h>
int main() {
for (int i = 1; i <= 10; i++) {
printf("Call %d: Duration %.1f minutes\n", i, (float)i * 2.5);
}
return 0;
}
Trace Table:
| Iteration | i |
Condition (i <= 10) |
Action |
|---|---|---|---|
| 1 | 1 | True | Prints "Call 1: Duration 2.5" |
| 2 | 2 | True | Prints "Call 2: Duration 5.0" |
| ... | ... | ... | ... |
| 10 | 10 | True | Prints "Call 10: Duration 25.0" |
| 11 | 11 | False | Loop exits. |
2.2.2 while Loop
Syntax:
while (condition) {
// Loop body
}
Example: Pathao driver earnings (calculate total until target is met).
#include <stdio.h>
int main() {
float target = 500, earnings = 0, fare;
while (earnings < target) {
printf("Enter fare earned: ");
scanf("%f", &fare);
earnings += fare;
}
printf("Target achieved! Total earnings: %.2f\n", earnings);
return 0;
}
Visual:
flowchart TD
A["Start"] --> B["Initialize earnings = 0"]
B --> C{"earnings < target?"}
C -->|"Yes"| D["Read fare"]
D --> E["earnings += fare"]
E --> C
C -->|"No"| F["Print success message"]
F --> G["End"]2.2.3 do-while Loop
Executes at least once. Example: Password validation (retry until correct).
#include <stdio.h>
#include <string.h>
int main() {
char password[20], input[20];
strcpy(password, "secure123");
do {
printf("Enter password: ");
scanf("%s", input);
if (strcmp(input, password) != 0) {
printf("Wrong password! Try again.\n");
}
} while (strcmp(input, password) != 0);
printf("Access granted!\n");
return 0;
}
Trace Table:
| Iteration | input |
strcmp result |
Action |
|---|---|---|---|
| 1 | "wrong" | Non-zero | Prints "Wrong password!" |
| 2 | "hackme" | Non-zero | Prints "Wrong password!" |
| 3 | "secure123" | Zero | Loop exits. Prints "Access granted!". |
3. Branching Statements
| Statement | Purpose | Example |
|---|---|---|
break |
Exits the nearest loop/block. | for (...) { if (x > 10) break; } |
continue |
Skips to the next iteration. | while (...) { if (x % 2 == 0) continue; } |
goto |
Jumps to a labeled statement. | if (error) goto error_handler; |
Example: Daraz Order Processing (Skip Out-of-Stock Items)
#include <stdio.h>
int main() {
int items[5] = {10, 0, 5, 0, 8}; // 0 = out of stock
for (int i = 0; i < 5; i++) {
if (items[i] == 0) {
printf("Item %d: Out of stock. Skipping...\n", i+1);
continue; // Skip to next iteration
}
printf("Processing item %d\n", i+1);
}
return 0;
}
Output:
Item 1: Out of stock. Skipping...
Processing item 2
Processing item 3
Item 4: Out of stock. Skipping...
Processing item 5
## In the Real World
eSewa/Khalti:
- Idea Used:
switch-casefor menu-driven payment options (e.g., mobile recharge, bill payment, transfer). - How: The app presents a list of services (like
case 1: recharge,case 2: pay bill), and the user’s choice triggers the corresponding logic.
- Idea Used:
NTC Billing System:
- Idea Used:
if-elseladder to validate SIM cards and apply different tariffs (e.g.,if (plan == "Basic") { charge = 500; }). - How: The system checks the user’s plan type and calculates the bill accordingly, with error handling for invalid inputs.
- Idea Used:
Pathao Driver App:
- Idea Used:
whileloop to accumulate earnings until the driver reaches their daily target. - How: The app continuously updates the driver’s earnings after each ride (
earnings += fare) and stops prompting for new rides once the target is met.
- Idea Used:
Bank Loan Interest Calculation:
- Idea Used:
forloop to compute compound interest overnyears. - Example Code:
#include <stdio.h> #include <math.h> int main() { float principal = 100000, rate = 0.05, amount; int years; printf("Enter loan duration (years): "); scanf("%d", &years); for (int i = 1; i <= years; i++) { amount = principal * pow(1 + rate, i); printf("Year %d: Amount = %.2f\n", i, amount); } return 0; } - Trace for
years = 3:Year amountCalculationOutput 1 100000 * (1.05)^1 = 105000.00 Year 1: Amount = 105000.00 2 100000 * (1.05)^2 = 110250.00 Year 2: Amount = 110250.00 3 100000 * (1.05)^3 = 115762.50 Year 3: Amount = 115762.50
- Idea Used:
## Exam Tip
I/O Functions:
- Always include
<stdio.h>for I/O functions. - Use
%dfor integers,%ffor floats,%cfor characters, and%sfor strings inscanf/printf. - Common Mistake: Forgetting the
&before variables inscanf(e.g.,scanf("%d", &x)).
- Always include
Control Structures:
if-else: Useelse iffor multiple conditions. Example:if (marks >= 80) printf("A"); else if (marks >= 60) printf("B"); else printf("C");switch: Ensure everycaseends withbreakunless fall-through is intentional.- Loops: Initialize loop variables correctly. Example:
// Wrong: for (int i; i < 5; i++) → Error! // Correct: for (int i = 0; i < 5; i++)
Debugging:
- Use
printfto print variable values during execution (e.g.,printf("i = %d\n", i);). - Infinite Loop Check: Ensure loop conditions can eventually become false (e.g.,
while (x > 0)withx--inside the loop).
- Use
Real-World Scenarios:
- Menu Systems: Always use
switch-casefor clear, readable options. - Validation: Use
if-elseto validate user inputs (e.g., age ≥ 18, balance ≥ amount). - Repetition: Use
forfor known iterations (e.g., printing patterns),whilefor unknown iterations (e.g., user input loops).
- Menu Systems: Always use
Avoid
goto:- Examiners dislike
gotounless absolutely necessary (e.g., error handling in large programs). Prefer structured loops.
- Examiners dislike
Practice Question: Write a program to simulate a bank ATM where:
- The user enters a PIN (3 attempts max).
- If correct, display a menu:
- Check balance
- Withdraw cash
- Transfer money
- Use
switch-casefor the menu andif-elsefor PIN validation. Hint: Use awhileloop for PIN attempts andbreakto exit on success/failure.
Based on the TU BIT syllabus for C Programming (BIT102), unit 3.
Discussion
Loading…