Computer ScienceUnit 812 min read
C Control Structures & Arrays: Loops, Decisions, and Data Storage
Unit 8 of Computer Science teaches how to control program flow using loops (for, while, do-while) and decisions (if, else, switch), plus how to store multiple values in arrays (1D/2D) with indexing, initialization, and traversal. Includes syntax, logic traces, and practical applications like menu-driven programs and da
TAKEAWAYS:
- Control structures (
if,switch, loops) let programs make decisions and repeat tasks efficiently. - Arrays store multiple values of the same type under a single name using indices (starting at 0).
forloops are best for known iterations,whilefor unknown conditions, anddo-whilefor "at least once" execution.- Common mistakes include off-by-one errors in loops and forgetting array bounds.
- Arrays can be 1D (linear) or 2D (matrix-like), and must be declared with size.
- Always initialize arrays and validate loop conditions to avoid runtime errors.
1. Control Structures: Making Decisions and Loops
Control structures change the flow of a program based on conditions or repetition needs. They are the "brain" of programming—they decide what to do next.
1.1 Decision-Making Statements
These statements execute different blocks of code based on conditions.
A. if Statement
- Checks a condition. If true, executes the block inside
{}. - Syntax:
if (condition) { // code to execute if condition is true } - Example: Check if a number is even.
Output:#include <stdio.h> int main() { int num = 4; if (num % 2 == 0) { printf("%d is even.", num); } return 0; }4 is even.
B. if-else Statement
- Executes one block if the condition is true, another if false.
- Syntax:
if (condition) { // true block } else { // false block } - Example: Check if a number is positive or negative.
Output:#include <stdio.h> int main() { int num = -5; if (num >= 0) { printf("%d is positive.", num); } else { printf("%d is negative.", num); } return 0; }-5 is negative.
C. Nested if-else
ifstatements inside otherifstatements for multiple conditions.- Example: Check if a student passes, gets a distinction, or fails.
Output:#include <stdio.h> int main() { int marks = 85; if (marks >= 35) { if (marks >= 80) { printf("Distinction!"); } else { printf("Pass."); } } else { printf("Fail."); } return 0; }Distinction!
D. else if (Ladder)
- Multiple conditions checked in order.
- Syntax:
if (condition1) { // code } else if (condition2) { // code } else { // default code } - Example: Grade calculator.
Output:#include <stdio.h> int main() { int marks = 72; if (marks >= 90) { printf("Grade A"); } else if (marks >= 80) { printf("Grade B"); } else if (marks >= 70) { printf("Grade C"); } else { printf("Grade D"); } return 0; }Grade C
E. switch-case Statement
- Tests a variable against multiple possible values.
- Syntax:
switch (variable) { case value1: // code break; case value2: // code break; default: // default code } - Example: Menu-driven program.
Output:#include <stdio.h> int main() { char choice = 'B'; switch (choice) { case 'A': printf("Option A selected."); break; case 'B': printf("Option B selected."); break; default: printf("Invalid choice."); } return 0; }Option B selected.
1.2 Looping Statements
Loops repeat a block of code while a condition is true.
A. for Loop
- Used when the number of iterations is known.
- Syntax:
for (initialization; condition; increment/decrement) { // code to repeat } - Example: Print numbers 1 to 5.
Output:#include <stdio.h> int main() { for (int i = 1; i <= 5; i++) { printf("%d ", i); } return 0; }1 2 3 4 5
B. while Loop
- Repeats while the condition is true (may not execute at all).
- Syntax:
while (condition) { // code to repeat } - Example: Sum of numbers until user enters 0.
Output (if inputs: 10, 20, 30, 0):#include <stdio.h> int main() { int num, sum = 0; printf("Enter numbers (0 to stop): "); scanf("%d", &num); while (num != 0) { sum += num; scanf("%d", &num); } printf("Sum = %d", sum); return 0; }Sum = 60
C. do-while Loop
- Executes at least once, then checks the condition.
- Syntax:
do { // code to repeat } while (condition); - Example: Simple calculator (runs once before checking).
Output (if input: -5, then 10):#include <stdio.h> int main() { int num; do { printf("Enter a positive number: "); scanf("%d", &num); } while (num <= 0); printf("Valid number entered: %d", num); return 0; }Valid number entered: 10
| Feature | for Loop |
while Loop |
do-while Loop |
|---|---|---|---|
| Use Case | Known iterations | Unknown iterations | Execute at least once |
| Syntax | for (init; cond; inc) |
while (cond) |
do { } while (cond); |
| Check | Before execution | Before execution | After execution |
| Example | Counting 1 to 10 | Reading until EOF | Menu until 'Q' is pressed |
2. Arrays: Storing Multiple Values
Arrays store multiple values of the same data type in a single variable. Think of them as a list of boxes labeled array_name[0], array_name[1], etc.
2.1 One-Dimensional (1D) Arrays
- A list of elements accessed by index (starting at 0).
- Declaration:
data_type array_name[size]; - Example: Store 5 integers.
int marks[5]; // Declares an array of 5 integers
A. Initializing Arrays
- Assign values at declaration.
int numbers[3] = {10, 20, 30}; - Partial initialization (rest are 0):
int arr[5] = {1, 2}; // arr = {1, 2, 0, 0, 0}
B. Accessing Array Elements
- Use indices (0 to
size-1).printf("%d", numbers[1]); // Output: 20
C. Traversing an Array
- Loop through all elements.
Output:#include <stdio.h> int main() { int arr[3] = {5, 10, 15}; for (int i = 0; i < 3; i++) { printf("%d ", arr[i]); } return 0; }5 10 15
D. Input and Output in Arrays
- Input:
for (int i = 0; i < 5; i++) { scanf("%d", &marks[i]); } - Output:
for (int i = 0; i < 5; i++) { printf("%d ", marks[i]); }
Index: 0 1 2 3 4
Value: [10, 20, 30, 40, 50]
Label: "Array 'arr' with 5 elements"
2.2 Two-Dimensional (2D) Arrays
- A table (rows × columns) of values.
- Declaration:
data_type array_name[rows][columns]; - Example: 2×3 matrix.
int matrix[2][3] = { {1, 2, 3}, {4, 5, 6} };
A. Accessing 2D Array Elements
- Use
row[column].printf("%d", matrix[1][2]); // Output: 6
B. Traversing a 2D Array
- Use nested
forloops.
Output:#include <stdio.h> int main() { int mat[2][3] = {{1, 2, 3}, {4, 5, 6}}; for (int i = 0; i < 2; i++) { for (int j = 0; j < 3; j++) { printf("%d ", mat[i][j]); } printf("\n"); } return 0; }1 2 3 4 5 6
Row 0: [1, 2, 3]
Row 1: [4, 5, 6]
Label: "2D array 'matrix' with 2 rows and 3 columns"
2.3 Common Array Operations
| Operation | Example | Output/Description |
|---|---|---|
| Sum of elements | sum = arr[0] + arr[1] + arr[2]; |
sum = 60 (for {10, 20, 30}) |
| Largest element | max = arr[0]; for (i=1; i<5; i++) if (arr[i] > max) max = arr[i]; |
max = 50 (for {10, 30, 50}) |
| Search element | found = 0; for (i=0; i<5; i++) if (arr[i] == 20) found = 1; |
found = 1 if 20 exists |
| Reverse array | for (i=0; i<5/2; i++) swap(arr[i], arr[4-i]); |
{50, 40, 30, 20, 10} |
3. Common Mistakes and How to Avoid Them
| Mistake | Example | Fix |
|---|---|---|
| Array index out of bounds | int arr[5]; arr[5] = 10; |
Use arr[0] to arr[4] only. |
| Uninitialized array | int arr[3]; printf("%d", arr[0]); |
Initialize: int arr[3] = {0}; |
| Infinite loop | for (int i=0; i<=5; i--) |
Check loop condition carefully. |
Forgetting break in switch |
Missing break after case |
Always use break to exit case. |
4. Practical Applications
- Menu-Driven Programs
Use
switch-caseto create interactive menus (e.g., calculator, student records). - Data Analysis Store exam marks in an array, then compute average, highest, or lowest score.
- Pattern Printing
Use nested loops to print patterns like pyramids or stars.
Output:#include <stdio.h> int main() { for (int i=1; i<=3; i++) { for (int j=1; j<=i; j++) { printf("* "); } printf("\n"); } return 0; }* * * * * * - Game Development Arrays store game boards (e.g., Tic-Tac-Toe) or player scores.
5. Exam Tips
What to Remember
✅ Loop Conditions:
forloops are best for known iterations (e.g., "print 1 to 10").whileloops are for unknown conditions (e.g., "read until user enters 0").do-whileensures the loop runs at least once.
✅ Array Indexing:
- Arrays start at index 0, not 1.
- Always declare the correct size to avoid overflow.
✅ Common Questions:
- Trace the output of a given loop or
if-elseblock. - Find errors in a snippet (e.g., missing
breakinswitch). - Write code to perform tasks like:
- Sum of array elements.
- Find the largest/smallest number in an array.
- Print a pattern using loops.
NEB-Style Questions to Practice
Short Answer:
- What is the output of the following code?
Answer:int x = 5; if (x > 3) { printf("A"); } else { printf("B"); }A
- What is the output of the following code?
Programming:
- Write a program to print the multiplication table of a given number using a
forloop.#include <stdio.h> int main() { int num = 5; for (int i=1; i<=10; i++) { printf("%d x %d = %d\n", num, i, num*i); } return 0; }
- Write a program to print the multiplication table of a given number using a
Trace the Output:
- What will be printed?
Answer:int arr[3] = {10, 20, 30}; for (int i=0; i<=2; i++) { printf("%d ", arr[i]); }10 20 30
- What will be printed?
Error Identification:
- Find the error in this code:
Fix: Useint arr[5]; arr[5] = 100; // Error: Index out of boundsarr[0]toarr[4].
- Find the error in this code:
Array Application:
- Write a program to find the sum of all even numbers in an array.
Output:#include <stdio.h> int main() { int arr[5] = {1, 2, 3, 4, 5}, sum = 0; for (int i=0; i<5; i++) { if (arr[i] % 2 == 0) { sum += arr[i]; } } printf("Sum of evens: %d", sum); return 0; }Sum of evens: 6(2 + 4)
- Write a program to find the sum of all even numbers in an array.
Final Note: Control structures and arrays are the backbone of programming. Master them by:
- Writing small programs (e.g., calculators, games).
- Tracing loops and
if-elseblocks on paper. - Practicing NEB-style questions to recognize patterns.
Keep coding! 🚀
Based on the NEB +2 Management syllabus for Computer Science (Comp), unit 8.
Discussion
Loading…