Control Structures in Programming: If-Else, Loops and Functions
INTRODUCTION
Have you ever wondered how an ATM knows to reject your transaction when your account balance is too low? Or how a school portal automatically assigns grades to hundreds of students without anyone sitting down to mark each one manually? The answer lies in something called control structures — and once you understand them, you will start seeing them everywhere.
Control structures are the tools that programmers use to decide how a program flows. They tell the computer: "If this condition is true, do this. Otherwise, do that. And keep doing it until we are finished." Without control structures, every program would simply run from the first line to the last in one straight path — which, for most real problems, is completely useless.
For SSS 2 students in Nigeria, this topic is one of the most important building blocks in your Computer Studies curriculum. It appears in WAEC, NECO, and JAMB examinations, and it is the foundation on which every serious programmer builds. By the time you finish reading this lesson, you will understand what control structures are, how each type works, and how to apply them to real problems — the kind of problems Nigerians face every day.
LEARNING OBJECTIVES
By the end of this lesson, students should be able to:
- Define control structures and state their importance in programming.
- Identify the three main types of control structures: sequence, selection, and repetition.
- Explain how if-else statements are used to make decisions inside a program.
- Describe the differences between for loops, while loops, and do-while loops.
- Demonstrate how to define and call a function in a program.
- Apply control structures to solve simple, real-life problems using pseudocode or Python.
WHAT ARE CONTROL STRUCTURES?
A control structure is a feature of a programming language that determines the order in which instructions are executed. The word "control" here means exactly what it sounds like — you are controlling the direction and behaviour of your program.
There are three main types:
Sequence — Instructions are carried out one after the other, from top to bottom. This is the default behaviour of any program. Line 1 runs, then line 2, then line 3, and so on.
Selection — The program checks a condition and then chooses which path to follow. This is where the if-else statement comes in.
Repetition — A block of code is executed over and over again until a specific condition is no longer true. This is what loops are designed for.
Each of these types has a specific role, and experienced programmers learn to combine all three to build powerful software.
SELECTION: THE IF-ELSE STATEMENT
The if-else statement is the most common way a program makes decisions. It works exactly the way human decision-making works: if a certain condition is satisfied, one thing happens; otherwise, something else happens instead.
How It Works
The structure is straightforward. You give the computer a condition to check. If that condition is true, the program executes the first block of code. If it is false, the program executes the second block. Simple as that.
Real-Life Nigerian Example:
Imagine Bello is trying to register for his school's external examination. The school system checks: "Has this student paid all outstanding fees?" If yes, the system prints his examination card. If no, it sends a reminder to his parents. That checking process — that decision — is an if-else statement.
Here is how it looks in Python:
score = 55
if score >= 50: print("Congratulations, you passed!") else: print("Sorry, you did not pass. Study harder next time.")
The If-Elif-Else Chain
Sometimes you need more than just two choices. That is where elif (short for "else if") becomes useful. You can chain as many elif blocks as you need between the if and the final else.
Here is an example using the Nigerian school grading system:
score = 72
if score >= 70: print("Grade: A — Distinction") elif score >= 60: print("Grade: B — Credit") elif score >= 50: print("Grade: C — Pass") else: print("Grade: F — Fail")
The program checks each condition from the top downward. The moment it finds a condition that is true, it runs that block and ignores everything else below it. If no condition matches, the else block runs.
Important note: The conditions must be arranged logically — usually from the highest value to the lowest — otherwise the program may give wrong results.
REPETITION: LOOPS
Loops solve a very practical problem: how do you make a computer repeat a task without writing the same code over and over again? Imagine a teacher who needs to send the same reminder message to all 200 parents in her school's database. Writing the send command 200 times is impractical. A loop makes her write it once.
There are three main types of loops you need to know for your SSS 2 curriculum.
The For Loop
A for loop is used when you already know exactly how many times you want the code to repeat. You set a starting point, an ending point, and the loop takes care of the rest.
Example — Printing a welcome message five times:
for i in range(5): print("Welcome to Computer Studies class!")
Example — Printing the names of Nigerian states from a list:
states = ["Lagos", "Abuja", "Kano", "Enugu", "Port Harcourt"] for state in states: print(state)
The for loop goes through the list one item at a time and prints each state. No repetition in your code — the loop handles all of it.
The While Loop
A while loop is different. It does not run a set number of times. Instead, it keeps running for as long as its condition remains true. The moment the condition becomes false, the loop stops.
You use a while loop when you do not know in advance how many repetitions will be needed.
Example — A student keeps studying until their confidence level reaches 100:
confidence = 0
while confidence < 100: print("Still studying...") confidence += 20
print("Ready for the exam!")
Each time the loop runs, confidence increases by 20. When it reaches 100, the condition (confidence < 100) becomes false, and the loop ends.
Warning — Infinite Loops:
One of the most common beginner mistakes is creating a loop whose condition never becomes false. This is called an infinite loop, and it will cause your program to hang or crash. Always make sure that something inside your loop is changing the condition so the loop can eventually end.
The Do-While Loop
Python does not have a built-in do-while loop, but it is important for your WAEC examinations, so you should understand it in pseudocode.
The key difference between a while loop and a do-while loop is timing. A while loop checks its condition before running. A do-while loop runs first, and then checks the condition. This means a do-while loop always executes at least once, even if the condition is false from the very beginning.
Pseudocode example — Validating a JAMB score entry:
DO Display "Enter your JAMB score (0–400): " Accept score WHILE score < 0 OR score > 400
The student is shown the prompt at least once. If they enter an invalid number, the prompt appears again. This continues until a valid score is entered.
FUNCTIONS: REUSABLE BLOCKS OF CODE
Imagine you are writing a program that needs to calculate a student's average score in five different places — at the beginning of the program, after each term, and again in the final summary. If you write the calculation code five separate times, your program becomes long, messy, and hard to fix. Now imagine you make one tiny mistake in the formula. You would have to find and correct it in five different places.
This is exactly the problem that functions solve.
A function is a named, reusable block of code that performs a specific task. You define it once and call it as many times as you need from anywhere in the program. If there is ever a bug inside it, you fix it in one place — and the fix applies everywhere.
Think of it like a recipe. A cook writes down the steps for making jollof rice once. Every time jollof rice is needed, they follow the same recipe. They do not rewrite it from scratch each time.
Defining a Function in Python
To create a function in Python, you use the keyword def, followed by the function name and any inputs it needs (called parameters), then a colon, and then the code it should run.
def greet_student(name): print("Good morning, " + name + "! Welcome to today's lesson.")
greet_student("Chidinma") greet_student("Emeka") greet_student("Fatima")
This function greets any student by name. You define it once and call it three times — each time with a different name.
Functions That Return a Value
Sometimes a function needs to calculate something and send the result back to the rest of the program. You do this with the return keyword.
def calculate_average(scores): total = sum(scores) average = total / len(scores) return average
student_scores = [68, 74, 55, 90, 82] result = calculate_average(student_scores) print("The student's average score is:", result)
The function does the calculation internally and returns the answer. The rest of the program receives that answer and can use it however it needs to.
The DRY Principle
In programming, there is a principle called DRY — Don't Repeat Yourself. Functions are the most important tool for following this principle. Whenever you find yourself writing the same block of code in more than one place, that is a sign you should turn it into a function.
PRACTICAL APPLICATIONS IN REAL NIGERIAN LIFE
Control structures are not just academic concepts. They are running inside real systems that Nigerians interact with every day.
GTBank and other bank apps use if-else logic to check your account balance before every transaction. If the balance is sufficient, the transfer goes through. If not, you receive a decline message — all handled automatically by selection structures.
The JAMB e-registration portal uses loops to process thousands of student applications one by one. Functions handle specific tasks like generating registration numbers, sending confirmation SMS messages, and calculating cut-off scores.
DStv and other subscription platforms use while loops to monitor subscription status. The system keeps checking: "Has this account been renewed?" Once payment is confirmed, the loop ends and access is restored.
Ride-hailing apps like Bolt, which operates in several Nigerian cities, use loops to refresh driver locations every few seconds and if-else structures to match the nearest available driver to a waiting passenger.
WAEC and NECO result-checking portals use functions to calculate each candidate's total score, determine the grade for each subject, and generate a summary — all at the push of a button.
ADVANTAGES AND DISADVANTAGES OF CONTROL STRUCTURES
Advantages:
Control structures make programs flexible and capable of handling a wide range of situations. Loops eliminate the need to write repetitive code, which saves time and reduces the chance of errors. Functions make programs easier to read, maintain, and update. The combination of all three allows programmers to build complex, intelligent systems from relatively simple building blocks.
Disadvantages:
Writing incorrect conditions in an if-else statement can cause a program to make the wrong decisions entirely. Infinite loops — loops whose conditions never become false — can cause programs to freeze or crash. When if-else statements are heavily nested inside one another, the code can become very difficult to read and follow. Poorly designed functions can produce unexpected results if they receive the wrong type of input.
ETHICAL AND SAFETY CONSIDERATIONS
With programming ability comes responsibility. Here are some important things to keep in mind as you learn to use control structures:
Always write loops with a clear exit condition. Never intentionally create a loop that runs forever, as this wastes computing resources and can disrupt systems that other people depend on.
Validate user input using if-else checks. Before processing any data that a user enters, always check that it is the correct type and within the expected range. Unvalidated inputs are one of the most common causes of software security problems.
Do not use your programming skills to deceive or harm. Functions and loops can be used to automate the sending of spam messages, to generate fake online reviews, or to run internet scams. These are not just unethical — they are illegal under Nigeria's Cybercrimes Act 2015.
Respect people's data. If your program collects personal information — names, phone numbers, scores — you are responsible for storing and using that data ethically and securely.
CLASSROOM AND HOME ACTIVITIES
Activity 1 — Grade Calculator (If-Else): Write a program or pseudocode that accepts a student's examination score (0–100) and displays the appropriate WAEC grade. Use this scale: A1 for 75–100, B2 for 70–74, B3 for 65–69, C4 for 60–64, C5 for 55–59, C6 for 50–54, D7 for 45–49, E8 for 40–44, and F9 for below 40.
Activity 2 — Multiplication Table Generator (For Loop): Write a program that accepts any number from the user and uses a for loop to display its full multiplication table from 1 to 12. Test your program using the number 9.
Activity 3 — Password Validator (While Loop): Create a program that repeatedly asks a user to enter a password. The correct password is "Nigeria2024". Each time the user enters the wrong password, display the message "Incorrect. Try again." When the correct password is entered, display "Access granted" along with the total number of attempts it took.
Activity 4 — Area Calculator Function (Functions): Define a function called calculate_area that accepts two numbers — length and width — and returns the area of a rectangle (length multiplied by width). Call the function three times using three different sets of measurements and print each result.
ASSESSMENT QUESTIONS
Section A — Objective Questions
-
Which of the following is used to make a decision in a program? a) For loop b) If-else statement c) Function d) While loop Answer: b
-
Which type of loop is most appropriate when the exact number of repetitions is known in advance? a) While loop b) Do-while loop c) For loop d) Repeat loop Answer: c
-
What keyword is used in Python to create a function? a) function b) define c) def d) func Answer: c
-
An infinite loop is one in which: a) The loop runs exactly once b) The loop's stopping condition never becomes false c) The loop contains an if-else statement d) The function returns a value Answer: b
-
Which keyword is used inside a function to send a calculated result back to the calling code? a) send b) output c) print d) return Answer: d
Section B — Theory Questions
Theory Question 1: With the aid of pseudocode or a flowchart, explain how an if-elif-else control structure works. Use a Nigerian secondary school grading system (grades A through F) as your example to illustrate each branch of the structure.
Theory Question 2: Differentiate between a for loop and a while loop. State one situation in which each type is most appropriate and support your answer with a relevant example drawn from everyday Nigerian student life.
Theory Question 3: Explain what a function is and state two advantages of using functions in a program. Write a simple function in Python or pseudocode that accepts a student's name and score as parameters and prints a message showing the name and whether the student passed or failed (pass mark is 50).
SUMMARY
Control structures are the tools that programmers use to direct the flow of a program. There are three main types: sequence (the default top-to-bottom flow), selection (if-else decisions), and repetition (loops). The if-else statement allows a program to choose between different actions based on whether a condition is true or false. For loops are used when the number of repetitions is fixed and known in advance. While loops repeat as long as a condition remains true, and do-while loops always execute at least once before checking their condition. Functions are named, reusable blocks of code that perform specific tasks, can accept inputs through parameters, and can return results using the return keyword. Together, these three control structures form the core logic of virtually every program ever written.
CONCLUSION
Control structures may seem like a small topic when you first encounter them, but they are anything but. Every app you use, every website you visit, every automated system you interact with in Nigeria — from bank transfers to examination portals — is built on the same foundations you have just studied.
As an SSS 2 student, learning these concepts now puts you ahead. You are no longer just a consumer of technology; you are beginning to think the way builders think. Every major software engineer in the world — from the teams at Flutterwave and Paystack right here in Nigeria to developers at Google and Microsoft — built their careers on exactly these fundamentals.
Do not be satisfied with just reading. Open a code editor, type out the examples, make mistakes, fix them, and try your own variations. That hands-on practice is where real understanding comes from. Control structures are waiting to be mastered — and now, you have everything you need to do it.
FREQUENTLY ASKED QUESTIONS
Q: What is the difference between a for loop and a while loop? A: A for loop runs a specific number of times that you set in advance. A while loop continues running for as long as its condition remains true, which makes it ideal for situations where you do not know how many repetitions will be needed before the program starts running.
Q: Can I put an if-else statement inside a loop? A: Yes, and this is actually very common. For example, you might use a for loop to go through a list of 40 students and then use an if-else inside the loop to check each student's score and print the appropriate grade. Combining structures this way is called nesting.
Q: What happens if I write an if statement without an else? A: Nothing goes wrong. An else is optional. If the condition is false and there is no else block, the program simply skips over the if block entirely and continues with the next instruction. You only need an else when you want something specific to happen when the condition is not met.
Q: Why should I bother with functions when I can just write all my code in one place? A: Functions make your code reusable, organised, and easy to maintain. If you need to perform the same task in ten different places in your program, a function means you write the code once. If you later discover a mistake, you fix it once — inside the function — and the correction applies everywhere it is called.
Q: Do control structures work the same way in all programming languages? A: The concept is identical across all languages. Every programming language has some version of if-else, loops, and functions. The syntax — the exact words and symbols you use to write them — differs slightly between languages like Python, JavaScript, and C++, but the underlying logic is the same.
Q: Will control structures be tested in my WAEC, NECO, or JAMB examinations? A: Absolutely. Control structures are a core component of the Nigerian NERDC Computer Studies curriculum for Senior Secondary School. They appear regularly in WAEC, NECO, and JAMB exams, both as objective questions and as structured questions requiring flowcharts, pseudocode, or program traces. This is a topic worth mastering thoroughly.

0 Comments