Repeating a message with for loop
Using for loop construct the same code piece can be repeated a fixed number of times.
Learning Objectives
- Understanding for loop structure and 3 parts of it.
- Running a loop with one instruction and why one instruction loop doesn’t need a braces block.
Source Code
Run Output
Code Understanding
for(int n=0;n<10;n++)
cout<<“Hello developer!”<<endl;
Here we give three separate instructions in the for loop.
int n=0; is the declaration and initialisation instruction which is executed only once when the loop entry is made.
n<10; is the condition check instruction which is done at every entry and re-entry of the loop. until this condition is met the loop will keep running. So this particular loop will run for 10 times as it begins from 0 and runs til n is below 10 or it goes up to 9.
n++ instruction does not have a separate semicolon but it is full instruction which does the job of making the loop move to next level of checking. Here it increases the value by 1 each time a loop completes.
cout<<“Hello developer!”<<endl;
This is the instruction inside the loop. Since here we are writing only 1 instruction so { } of making a loop block may not required.
Notes
- Some teachers recommend use of braces even when only one instruction is given like this.
for(int n=0;n<10;n++)
{
cout<<“Hello developer!”<<endl;
}
Common Errors
- Many students incorrectly put a semicolon (;) immediately after the loop like this –
for(int n=0;n<10;n++) ;
cout<<“Hello developer!”<<endl;
This is incorrect and this will not be able to run the instruction after the loop. By the way this is called an empty loop and it may have a different purpose in some cases.
Suggested Filename(s): repeat-message.cpp
