Bachelor of Science in Computer Science
Course ContentLoops
Habari Class! Welcome to the World of Loops!
Mko poa? I hope you are ready for one of the most powerful ideas in programming. Imagine you have a DJ for your code. You tell this DJ, "Play this song 10 times!" Does the DJ press the 'play' button 10 separate times? No way! A good DJ hits a 'loop' button, and the song repeats automatically. In programming, loops are our 'loop button'. They allow us to command the computer to do repetitive tasks without writing the same code over and over again. It's how we make our programs efficient and powerful, saving us from a lot of "kazi ya kurudia rudia" (repetitive work)!
Image Suggestion: A vibrant, colourful digital art image of a futuristic, friendly robot tirelessly watering neat rows of sukuma wiki (kale) in a Kenyan shamba. In the background, a beautiful sunrise is happening over Mount Kenya. The robot has a small screen on its chest showing a looping arrow symbol. Style: Afrofuturism, optimistic.
Why Do We Need Loops Anyway?
Let's say your first task is to greet your user by printing "Jambo!" five times. Without loops, you would write:
#include <stdio.h>
int main() {
printf("Jambo!\n");
printf("Jambo!\n");
printf("Jambo!\n");
printf("Jambo!\n");
printf("Jambo!\n");
return 0;
}
That's okay for five times. But what if your lecturer asks for 1,000 "Jambo!" greetings? Hapo sasa! You will be copying and pasting the whole day. Loops are the smart way, the programmer's way, to handle this.
The 'for' Loop: When You Know the Exact Number of Repeats
The for loop is your best friend when you know exactly how many times you need to repeat an action. Think of it like planting maize in a shamba. You have a row, and you know you need to plant exactly 20 seeds, one step at a time.
The structure, or syntax, looks like this:
for (initialization; condition; increment/decrement) {
// Code to be repeated goes here
}
- Initialization: Where do we start? We create a counter variable, like
int i = 1;. This is like standing at the beginning of the shamba row. - Condition: How long do we continue? We set a rule, like
i <= 20;. We continue as long as this rule is true. This is like checking if you've reached the end of the 20-seed row. - Increment/Decrement: How do we move to the next step? We update our counter, usually by adding one (
i++). This is like taking one step forward to plant the next seed.
Real-World Scenario: A matatu conductor collecting fare. He knows there are 14 seats (minus the driver). He will start from seat 1 (initialization), continue as long as he hasn't reached seat 14 (condition), and move to the next seat after collecting from one passenger (increment).
Example: Printing "Jambo!" 5 times the smart way!
#include <stdio.h>
int main() {
// i is our counter
for (int i = 1; i <= 5; i++) {
printf("Jambo! (Greeting number %d)\n", i);
}
return 0;
}
How the computer calculates this step-by-step:
Step 1: Initialization
- Computer creates a variable `i` and sets it to 1.
Step 2: First Check (Iteration 1)
- Condition check: Is `i <= 5`? (Is 1 <= 5?). Yes, it's true.
- Execute code: Prints "Jambo! (Greeting number 1)"
- Increment: `i` becomes 2.
Step 3: Second Check (Iteration 2)
- Condition check: Is `i <= 5`? (Is 2 <= 5?). Yes, it's true.
- Execute code: Prints "Jambo! (Greeting number 2)"
- Increment: `i` becomes 3.
...and so on...
Step 6: Final Check (After Iteration 5)
- After printing for i=5, the increment runs. `i` becomes 6.
- Condition check: Is `i <= 5`? (Is 6 <= 5?). No, this is false.
- The loop stops. The program moves on.
The 'while' Loop: When You Repeat Based on a Condition
Sometimes you don't know how many times you need to do something. You just know you should continue while a certain condition is true. Think about fetching water from a well. You don't know if it will take 10 pulls or 15 pulls of the rope. You just keep pulling while the bucket is not yet full.
This is a "pre-test" loop. It checks the condition before running the code inside. If the condition is false from the very beginning, the loop might not run even once!
The syntax is simpler:
while (condition) {
// Code to be repeated goes here
// IMPORTANT: Something inside the loop must eventually
// make the condition false!
}
+------------------+
| Start Loop |
+------------------+
|
v
/-------\
----->|Is Condition|-----> (If False) Exit Loop
| True? |
\-------/
| (If True)
v
+------------------+
| Execute Code |
| in the Loop |
+------------------+
|
`-------------------
Example: Simple Ugali Cooking Program
Let's make a program that keeps adding flour until we have enough for our ugali.
#include <stdio.h>
int main() {
int flourScoops = 0;
int neededScoops = 5;
// We will keep adding flour WHILE we have less than we need.
while (flourScoops < neededScoops) {
flourScoops++; // Add one scoop of flour
printf("Adding one scoop. We now have %d scoops.\n", flourScoops);
}
printf("\nSawa! We have enough flour for ugali.\n");
return 0;
}
In this example, the loop continues until flourScoops is no longer less than neededScoops. If we forget the line flourScoops++;, we would create an infinite loop! The program would run forever, like a matatu that got lost and is just driving around endlessly. Always have a way to exit your `while` loops!
The 'do-while' Loop: Do it First, Ask Questions Later!
The do-while loop is a cousin of the while loop. It's a "post-test" loop. This means it will always execute the code inside the loop at least once before it checks the condition to see if it should repeat.
Think of it like tasting your chai to see if it has enough sugar. You have to take the first sip (the 'do' part) before you can decide if you need to add more sugar and stir again (the 'while' part).
Image Suggestion: A split-panel cartoon. On the left, a character labeled 'while loop' cautiously peeks through a keyhole of a door before deciding to enter. On the right, a confident character labeled 'do-while loop' has already walked through the door and is looking back to check who is there. Both are friendly, educational characters.
Here is the syntax. Notice the semicolon ; at the end!
do {
// This code ALWAYS runs at least once
} while (condition);
Example: A Simple Menu
This is perfect for menus where you want to show the options at least once.
#include <stdio.h>
int main() {
char choice;
do {
// This menu is always displayed at least once.
printf("\n--- M-Pesa Menu ---\n");
printf("1. Send Money\n");
printf("2. Withdraw Cash\n");
printf("3. Buy Airtime\n");
printf("Press 'x' to exit.\n");
printf("Your choice: ");
scanf(" %c", &choice); // space before %c is important!
// Process the choice here (we'll skip that for now)
printf("You chose %c\n", choice);
} while (choice != 'x'); // Repeat as long as the user does not press 'x'
printf("\nThank you for using M-Pesa!\n");
return 0;
}
The menu will show, the program will wait for your input, and only after you've done all that will it check if your choice was 'x'. If not, it loops back and shows the menu again.
So, Which Loop Should I Use?
- Use a
forloop when you know the exact number of iterations. (e.g., "Count from 1 to 100", "Process the 50 students in this class"). - Use a
whileloop when you want to loop based on a condition, and it's possible the loop might not run at all. (e.g., "Keep asking for a password while it's incorrect"). - Use a
do-whileloop when you need the code to run AT LEAST ONCE before checking the condition. (e.g., "Show a menu and ask the user if they want to do another transaction").
Haya basi, that's the introduction to loops! They are the engine of programming. They do the heavy lifting. Practice them, understand them, and you will be able to write truly amazing and complex programs. Any questions? Let's go and write some code!
Pro Tip
Take your own short notes while going through the topics.