Computer ScienceUnit 88 min read
Control Structures & Arrays in C: Loops, Decisions & 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 practical examples and NEB-style questions.
TAKEAWAYS:
- Control structures (if-else, loops) make programs decide and repeat actions without writing the same code again.
- Arrays let you store lists of values (like grades of 50 students) using a single variable name with an index.
- The
forloop is best for count-controlled repetition (e.g., "run 10 times"), whilewhile/do-whileare for condition-controlled loops (e.g., "keep asking until correct"). - 2D arrays store tables (e.g., a 3×3 matrix), accessed with
array[row][column]. - Common mistakes: off-by-one errors in loops, uninitialized arrays, and forgetting array bounds.
---
## **1. Control Structures: Making Decisions and Loops**
### **1.1 Decision-Making: `if`, `if-else`, `else-if` (Ladder)**
Programs often need to **choose** between actions based on conditions. C uses:
- `if (condition)` → Executes if `condition` is **true** (non-zero).
- `else` → Runs if `if` is false.
- `else-if` → Checks multiple conditions (like a ladder).
```c
// Example: Check if a number is positive, negative, or zero
#include <stdio.h>
int main() {
int num = -5;
if (num > 0)
printf("%d is positive.", num);
else if (num < 0)
printf("%d is negative.", num);
else
printf("Number is zero.");
return 0;
}
Output:
-5 is negative.
How it works:
- Check
num > 0→ False → go toelse-if. - Check
num < 0→ True → print and exit.
1.2 Loops: Repeating Actions
Loops repeat a block of code until a condition is met.
A. for Loop (Count-Controlled)
Best for known iterations (e.g., "print numbers 1 to 10"). Syntax:
for (initialization; condition; increment) {
// Code to repeat
}
Example: Print numbers 1 to 5.
for (int i = 1; i <= 5; i++) {
printf("%d ", i);
}
Output: 1 2 3 4 5
B. while Loop (Condition-Controlled)
Runs while a condition is true. Use when you don’t know how many iterations are needed.
Example: Keep asking for input until the user enters 0.
int num;
while (num != 0) {
printf("Enter a number (0 to stop): ");
scanf("%d", &num);
}
C. do-while Loop (Post-Test Loop)
Runs at least once, then checks the condition.
Example: Menu that runs until the user chooses 3.
int choice;
do {
printf("\n1. Add\n2. Subtract\n3. Exit\nEnter choice: ");
scanf("%d", &choice);
// Perform action based on choice
} while (choice != 3);
flowchart TD
A["Start"] --> B["Run code block"]
B --> C["Check condition (choice != 3)"]
C -->|"True"| B
C -->|"False"| D["Exit"]1.3 Nested Loops (Loops Inside Loops)
Used for multi-dimensional tasks (e.g., printing a multiplication table). Example: Print a 3×3 multiplication table.
for (int i = 1; i <= 3; i++) {
for (int j = 1; j <= 3; j++) {
printf("%d ", i * j);
}
printf("\n");
}
Output:
1 2 3
2 4 6
3 6 9
2. Arrays: Storing Multiple Values
Arrays store multiple values of the same type under one name. Syntax:
data_type array_name[size];
Example: Store 5 student marks.
int marks[5] = {85, 90, 78, 92, 88};
2.1 1D Arrays (Single-Dimensional)
- Access elements using index (starts at
0). - Example: Print all marks.
for (int i = 0; i < 5; i++) {
printf("Marks %d: %d\n", i+1, marks[i]);
}
Output:
Marks 1: 85
Marks 2: 90
...
2.2 2D Arrays (Multi-Dimensional)
- Store tables (rows × columns).
- Example: 2×3 matrix.
int matrix[2][3] = {{1, 2, 3}, {4, 5, 6}};
- Access:
matrix[row][column]. - Example: Print the matrix.
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 3; j++) {
printf("%d ", matrix[i][j]);
}
printf("\n");
}
Output:
1 2 3
4 5 6
2.3 Common Array Operations
| Operation | Example Code | Description |
|---|---|---|
| Initialize | int arr[3] = {10, 20, 30}; |
Store values at declaration. |
| Access | printf("%d", arr[1]); |
Get value at index 1 (20). |
| Modify | arr[0] = 100; |
Change value at index 0. |
| Input | scanf("%d", &arr[i]); |
Take user input for arr[i]. |
| Traverse | for (i=0; i<5; i++) |
Loop through all elements. |
| Size | sizeof(arr)/sizeof(arr[0]) |
Calculate number of elements. |
Example: Find the sum of array elements.
int sum = 0;
for (int i = 0; i < 5; i++) {
sum += marks[i];
}
printf("Total = %d", sum); // Output: 433
3. Common Mistakes and How to Avoid Them
| Mistake | Example | Fix |
|---|---|---|
| Off-by-one error | for (i=0; i<=5; i++) |
Use < 5 (arrays are 0 to 4). |
| Uninitialized array | int arr[5]; (no values) |
Initialize: int arr[5] = {0}; |
| Array index out of bounds | marks[5] (only 5 elements) |
Check i < 5 in loops. |
Forgetting & in scanf |
scanf("%d", arr[i]); |
Use scanf("%d", &arr[i]); |
4. NEB-Style Solved Examples
Example 1: Find the Largest Number in an Array
#include <stdio.h>
int main() {
int numbers[5] = {12, 45, 67, 23, 89};
int largest = numbers[0];
for (int i = 1; i < 5; i++) {
if (numbers[i] > largest)
largest = numbers[i];
}
printf("Largest number: %d", largest);
return 0;
}
Output: 89
Example 2: Print a Pyramid Pattern
#include <stdio.h>
int main() {
for (int i = 1; i <= 4; i++) {
for (int j = 1; j <= i; j++) {
printf("* ");
}
printf("\n");
}
return 0;
}
Output:
*
* *
* * *
* * * *
Example 3: 2D Array (Matrix Addition)
int A[2][2] = {{1, 2}, {3, 4}};
int B[2][2] = {{5, 6}, {7, 8}};
int C[2][2];
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 2; j++) {
C[i][j] = A[i][j] + B[i][j];
}
}
// C = {{6, 8}, {10, 12}}
5. NEB Board-Style Questions
Short Answer (2 marks each)
What is the output of the following code?
int x = 5; while (x > 0) { printf("%d ", x--); }Answer:
5 4 3 2 1Write a
forloop to print even numbers from 10 to 20. Answer:for (int i = 10; i <= 20; i += 2) { printf("%d ", i); }What is the difference between
whileanddo-while? Answer:Feature whiledo-whileCheck Before execution After execution Guarantee May not run once Runs at least once Use case Unknown iterations Menu-driven programs
Programming (5 marks)
Write a program to find the sum of all even numbers in a 1D array of 10 elements.
#include <stdio.h>
int main() {
int arr[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
int sum = 0;
for (int i = 0; i < 10; i++) {
if (arr[i] % 2 == 0)
sum += arr[i];
}
printf("Sum of even numbers: %d", sum);
return 0;
}
Output: 30 (2 + 4 + 6 + 8 + 10)
Explain (3 marks)
Explain the use of nested loops with an example. Answer: Nested loops are used when a task requires repetition inside repetition. For example:
- Printing a multiplication table (outer loop for rows, inner loop for columns).
- Processing a 2D array (e.g., matrix operations). Example: Print a 2×2 identity matrix.
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 2; j++) {
printf("%d ", (i == j) ? 1 : 0);
}
printf("\n");
}
Output:
1 0
0 1
Exam Tip
For loops:
- Always initialize, test, and update the loop variable.
- Common mistake:
for (i=0; i=5; i++)(usei<=5ori<5).
Arrays:
- Remember index starts at 0 (e.g.,
arr[3]is the 4th element). - Use
sizeof(array)/sizeof(array[0])to find array size dynamically.
- Remember index starts at 0 (e.g.,
Nested loops:
- The outer loop controls rows, the inner loop controls columns.
- Example: For a 3×3 matrix, outer loop runs 3 times, inner loop runs 3 times per outer iteration.
NEB loves:
- Pattern printing (pyramids, stars).
- Array traversal (find max/min, sum).
- Matrix operations (addition, multiplication).
Avoid:
- Magic numbers (use
const int SIZE = 5;instead of hardcoding5). - Uninitialized variables (always set default values).
- Magic numbers (use
Based on the NEB +2 Science syllabus for Computer Science (Comp), unit 8.
Discussion
Loading…