Example of an algorithm with conditional statements

When writing computer programs you have to evaluate many conditions in order to correctly implement your logic. Even in our day to day lives we use conditional statements in our normal conversations. For example your mother will tell you to get brown bread from the local grocery store. If by chance the brown bread is not available then get the normal break. See how the “if” condition appears in this very simple conversation.

In this tutorial let’s understand about algorithms which involve conditional operations. By conditions we mean if-else statements. You have to check some conditions and do some operations depending on if those conditions are true or false.

Problem definition

Write an algorithm to teach your computer how to greet a person when he starts the program. If the time is between 12 am and 12 pm wish good morning, between 12pm and 4 pm wish good afternoon, between 4pm and 9pm wish good evening and after 9 pm wish good night.

Just by reading the above statement you can understand what has to be done. There are multiple conditions which you have to evaluate when you will be writing your algorithm. To evaluate these conditions you will have to ask questions using if statement and the answer return will be either true or false. You will take some action if the answer is true and a different action if the answer is false.

Let’s write the algorithm

Step 1 : Take a variable T to store the current time of the day
Step 2 : If T > 12am and T < 12pm print “Good morning”. Goto Stop
Step 3 : If T > 12pm and T < 4pm print “Good afternoon”. Goto Stop
Step 4 : If T > 4pm and T < 9pm print “Good evening”. Goto Stop
Step 5 : If T > 9pm print “Good night”

Notice how we have stored the current time of the day in the T variable before writing the algorithm. This is because to evaluate the conditions you need to use if statements which can only be used on some variables. The whole algorithm revolves around the If conditions. Goto Stop statement instructs the program to jump to the last step and skip all other steps. This is because when one condition matches we should not be evaluating the other conditions.  

Quick Links



Total Followers
Study Group Created
Study Group Joined
Following Teacher
Following Organization
Blog Articles Added
Questions Asked
Questions Answered
Jobs Posted
Total Members in Group
Questions asked by members
Tasks added in this Group

Please wait..


Login to Open ESchool OR Create your account    Login   SignUp