Course Introduction to Programming
Command: while
In this lesson, you will learn your first repetition structure, while, learning topics like:
- Example of a problem;
- While structure;
- Coding.
Example of a Problem
Create a program that prints the first 20 positive numbers. Print a number on each line.
We can solve this exercise in two ways: manually printing the numbers, 1, 2, 3, 4, ..., 20, or use a repetition structure to automate printing.
While Structure
The while structure is a repetition structure, that is, a structure we can use to repeat a certain piece of code.
The while structure will repeat a code snippet while a certain condition is true.
See the syntax of the structure below.
while(condition){
// Code
}
When the code finds a while, the condition will be tested. If it is false, the while is not executed, but if it is true, the code between the braces will be executed and then the condition is checked again.
While the condition is true, the code will follow this loop, executing the code and testing the condition, and at the moment it is false the while stops being executed.
We will now see some similarities between the if selection structure, which we already know, and the while structure we are learning now.
int main(){
int i = 1;
if(i < 5) {
printf("%d\n", i);
}
}
The above code works as follows: the variable
We will now change the if to a while and verify the behaviour of the code.
int main(){
int i = 1;
while(i < 5) {
printf("%d\n", i);
}
}
Exchanging the if for a while, the code will have a peculiar behaviour, printing several 1's without stopping. This happens because the while works in a way that, while the condition is true, what is between the braces will be executed, and since the value of
It is important to note then that when writing a while you need a condition that at some point will be false, otherwise the program will repeat what is between the braces infinitely, generating what we call an infinite loop.
To make the code work, we then need to make the condition be false at some point. So if inside the braces, at each repetition, we increase the value of
int main(){
int i = 1;
while(i<5){
printf("%d\n", i);
i = i+1;
}
}
In the above code, the value of
When executing our algorithm, we can see it prints the numbers from 1 to 4, because when the value of
To solve the initial problem, which is to print the first 20 positive numbers, we only need to modify the code a little, changing the condition of the while.
int main(){
int i = 1;
while(i <= 20){
printf("%d\n", i);
i = i+1;
}
}
We can notice then that the while structure is very useful to repeat a piece of code a certain number of times, using a variable to serve as a counter, increasing its value gradually.
Now you already know how to use the while repetition structure to repeat code snippets a certain number of times.