Another example of an algorithm with conditional statements

Let’s take another example of an algorithm which involves conditional statements

Problem definition

Ask the user to enter two numbers from the keyboard. Compare both the numbers, if the first number is greater than the second then subtract both the numbers and print the result. If the second number is greater than the first number then add both the numbers and print the result.

Let’s understand the problem first

Here we have been asked to get two numbers from the user. The user will be entering these two numbers from the keyboard. A simple question to ask here is that how will the computer remember these two numbers? The answer to this question is – by using variables. Always remember that during the functioning of the computer program the variables hold the data. Therefore if the user will be entering two numbers from the keyboard we will have to create two variables to hold these two numbers when our program will be running. So let’s assume these two numbers to be A and B.

Our first steps are to get two numbers from the user and store them in A and B variables. Then we need to compare A and B and find out which is greater. According to the problem if A is greater than B then we have to subtract these two numbers but if B is greater than A then we have to add these two numbers.

Again there is a simple question to ask here. How will the computer remember the result after adding or subtracting these numbers? And again the answer is – by using variables. We will have to take a third variable and store the result of the operation in that variable. Let’s call this variable as C. Therefore as per the problem definition in the end we have to print the value of C.

Writing the algorithm

Now that we have understood the problem definition properly we are ready to write the algorithm. Below is one of the many possible ways in which you can write this algorithm. Remember that there are no hard and fast rules to write algorithms. You can write it in your own language as long as it is written properly to solve the problem.

Our final algorithm

Start
Step1 : Get the first number from user and store it in A
Step2 : Get the second number from user and store it in B
Step3 : If A > B then set C = A – B. Goto Step 5
Step4 : If A < B then set C = A + B. Goto Step 5
Step5 : Print the value of C
End.

The above algorithm is self explanatory and easy to understand.

Quick Links

E-Magazines

@

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..

Ok

Login to Open ESchool OR Create your account    Login   SignUp