Repetitive Flow / Loop
Repetitive tasks is boring & time consuming, therefore we can use computer to help us do a repetitive tasks.In C++, we can implement a loops or repetitive flow to help us complete the repetitive tasks.
There are 3 type of loops in C++ which are
- For loop
- While loop
- Do While loop
Basically, we can categorise them into entry controlled loop and exit controlled loop. Entry controlled loop will check the conditions before execute the block but exit controlled loop will execute the block one times before checking the conditions.
Entry controlled Loop
- While
- For
Exit Controlled Loop
- Do While
While
While loop usually used for condition other than number of times or times of loops is unknown.
Format
while(condition) {
//block to execute
}
Example
While loop is suitable for read file content, since we don't know the number of lines of file in most of time. The file will be read line by line until reaching the end of file.
In this example we will read "hello.txt" file and output the file content.
hello.txt
1st line
Hello World
I love programming
.
.
.
Last line of file
Source Code
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main() {
//Open "hello.txt" for reading
ifstream textFile("hello.txt");
string content;
//Loop until End of File
while (!textFile.eof()) {
getline(textFile, content);
cout << content << "\n";
}
return 0;
}
For
For loop usually used for situation where the times of task repetition is known.
Format
Initialization will execute before entering For loop, condition will be check each times of loop, and update statement will be execute at the end of each loop.
for(initialization; condition; update) {
//block to execute
}
Example
In this example we will use for loop to calculate sum from 1 to 100, since the number of loops is known, n = 100.
Source Code
#include <iostream>
using namespace std;
int main() {
int sum = 0;
//Loop for 100 times
for (int i = 0; i <= 100; i++) {
sum = sum + i;
}
//Output result of sum
cout << "Sum: " << sum;
return 0;
}