Basic programming course: Lesson #5 Control structures. Part 2. Cycles.
5 comments
Hello, my fellow programmers, it is the fifth week of the Steemit Engagement Challenge for season 20 and I'm delighted to be part of this week's contest organized by @alejos7ven which talks about Control Structures Part 2.
Explain the cycles in detail. What are they and how are they used? What is the difference between the While and Do-While cycle? |
---|
When we talk about the word cycle in programming, we are referring to loops. In programming, some codes continually repeat themselves until a certain condition is met, and this is what we call cycles or loops. This cycle is what helps to control the flow of the code as it checks to ensure that certain criteria are met before the code can be executed.
3 loops are majorly used in programming and these are the While Loop, Do While Loop, and the For Loop. All of these have their usage as they are used based on a certain condition which we are going to see as we progress.
While Loop
A good example of a while loop using Python programming language can be seen below.
Code
counter = 1
while counter <= 5:
print("Counter is:", counter)
counter += 1
Output:
Counter is: 1
Counter is: 2
Counter is: 3
Counter is: 4
Counter is: 5
Explanation:
Firstly, from the above code, the loop continues as the condition counter <= 5
is True
.
Secondly, there is a print of the current counter and the next counter is always increased by 1 and that is why we have counter += 1
Lastly, once the counter exceeds 5, the condition becomes false and the code will stop executing.
Do While Loop
Here I will be using a C++ language to show an example of this type of loop. So the code here runs at least once inside the loop before checking the condition let's consider the code example.
Code
#include
using namespace std;
int main() {
int counter = 1;
do {
cout << "Counter is: " << counter << endl;
counter++;
} while (counter <= 5);
return 0;
}
Output:
Counter is: 1
Counter is: 2
Counter is: 3
Counter is: 4
Counter is: 5
Explanation:
Firstly, as said earlier, the code line do
executes first before checking the condition.
Secondly, after the first has executed the condition counter <= 5
and if the condition is true the code runs again continuously provided it remains true.
Lastly, Once the condition becomes false the code will stop running.
For Loop
Let's also use the C++ programming language to show an example of how the for loop works.
Code
using namespace std;
int main() {
for (int counter = 1; counter <= 5; counter++) {
cout << "Counter is: " << counter << endl;
}
return 0;
}
Output:
Counter is: 1
Counter is: 2
Counter is: 3
Counter is: 4
Counter is: 5
Explanation:
Firstly, the counter starts with 1 and that is why we have the first code counter = 1
Secondly, it checks the condition counter <= 5
, if the condition is true then it goes ahead to perform more iteration.
After every loop, the counter will be incremented by 1 and that is why we have the (counter++
).
The code stops running immediately when counter
exceeds 5.
Difference between While Loop, Do While Loop, and the For Loop
In the case of the while loop, the conditions are checked first before the code can be executed while in the case of the do-while loop, the code is first executed before a check on the condition is done.
Investigate how the Switch-case structure is used and give us an example. |
---|
Switch case or switch statement is a statement used in most programming language which allows a certain variable to be compared among list of variables. So these Statement helps check block of code and execute them if the condition are met. We use the switch statement mainly instead of using multiple if-else
which makes our code more beautiful and presentable. So the switch statement makes our code cleaner and much presentable.
General Structure (Pseudocode):
switch (expression) {
case value1:
break;
case value2:
break;
case value3:
break;
default:
}
Explanation of Pseudocode
Switch: The switch structure starts here and it takes into consideration the expression which will be evaluated in the programme.
Case: Here the cases has an expression and if the expression meets the requirement of the value then the expression will be executed.
Break: This syntax is used to prevent the code from continuous execution. When a certain requirement is met then the code execute and exit.
Default: The last part of the case structure acts like the else statement. It is only useful if all the cases didn't meet the requirements. So it tells the code to run if none of the cases meets the requirements.
Example of switch statement using C:
int day = 2;
switch(day) {
case 1:
printf("Monday");
break;
case 2:
printf("Tuesday");
break;
case 3:
printf("Wednesday");
break;
default:
printf("Invalid day");
}
Code Explanation
The code here is very simple. If Day is 2, it should go ahead and print Tuesday else if no day matches 2, the default will take place by printing invalid day.
Explain what the following code does: |
---|
Algorithm switchcase
Define op, n, ns, a As Integer;
Define exit As Logic;
exit = False;
a=0;
Repeat
Print "Select an option:";
Print "1. Sum numbers.";
Print "2. Show results."
Print "3. End program.";
Read op;
Switch op Do
case 1:
Print "How much nums do you want to sum?";
Read n;
For i from 1 to n Do
Print "Enter a number: ";
Read ns;
a = a + ns;
EndFor
Print "Completed! Press any button to continue";
Wait Key;
Clear Screen;
case 2:
Print "This is the current result: " a;
Print "Press any button to continue.";
Wait Key;
Clear Screen;
case 3:
Clear Screen;
Print "Bye =)";
exit = True;
Default:
Print "Invalid option.";
Print "Press any button to continue";
Wait Key;
Clear Screen;
EndSwitch
Until exit
EndAlgorithm
From the above pseudocode, I will be explaining it below. Just by looking at the code you will notice that it is a switch statement and I want to explain what the pseudocode does step by step below.
Variable Declaration
op, n, ns, a As Integer
exit As Boolean flag to terminate the program
Initialize Variables
exit = False; here the exit is set to false to allow the programme to continue running until we are okay with it and wish to exit it.
a=0; here the variable a is set to zero to collect the sum of the numbers.
Start Loop
Repeat; this command helps to iterate the main programme which I will show below. The repetition continue until we decide to exit.
Menu Option
Here the program comes up with three options for the user to make a choice.
Option 01:
Sum Numbers
Option 02:
Show results
Option 31:
End program
Based on the option selected by the user which is the (op) it will select one of the cases below.
Case 1 (Sum Numbers):
The program ask the user How much nums do you want to sum? (This is what you will see on the screen)
Read n; You enter the number you wish the program to sum for you.
For i from 1 to n Do; it starts from 1 and sum till the number n you inputed.
Case 2 (Show Result):
This case will go ahead to print out the amount stored in (a) on the screen and the will prompt user to press any key to continue.
Case 3 (Exit the Program):
Here a message will be written on the screen saying Bye. Then the exit flag terminate the running program.
Default Case (Invalid Input):
When a user enters an incorrect option from the list provided in the menu it comes up with the message incorrect option and will prompt the user to press any button to continue.
Until Exit:
Here this line of code prompt the user to select one option among the list of options. Also it keeps promoting the user until exit is true before the code can be terminated.
Write a program in pseudo-code that asks the user for a number greater than 10 (Do-While), then add all the numbers with an accumulator (While) Example: The user enters 15. The program adds up to 1+2+3+4+5+6+7+8+9+10+11+12+13+14+15. |
---|
Below is a pseudo-code that perform the said function.
DECLARE number, sum, counter AS INTEGER
sum ← 0
counter ← 1
DO
PRINT "Enter a number greater than 10:"
READ number
WHILE number <= 10
WHILE counter <= number
sum ← sum + counter
counter ← counter + 1
END WHILE
PRINT "The sum of numbers from 1 to", number, "is:", sum
Explanation:
Do-While; here the program prompts the user to enter a number greater than 10 and if a user enters a number less than or equal to 10 then the program will keep asking for a number.
While; Here the code accumulate the sum of the numbers from 1 till the number entered by the user and it uses the sum variable and the the counter variable.
Output; After summing the numbers the program will then print the result of the sum of the number that has been entered. E.g if a user enter 11, the program will calculate the sum as 1+2+3+...+11 and the add it up and print the result.
C++ Code
#include<iostream>
using namespace std;
int main() {
int number, sum = 0, counter = 1;
do {
cout << "Enter a number greater than 10: ";
cin >> number;
} while (number <= 10);
while (counter <= number) {
sum += counter;
counter++;
}
cout << "The sum of numbers from 1 to " << number << " is: " << sum << endl;
return 0;
}
Code
Output
This is indeed a nice course as it reminds me a lot. I want to finally invite a few friends to also join the contest @josepha, @suboohi, and @solaymann.
Comments