Read Time:40 Second
The for loop is used when we know in advance how many times the code should run.
Syntax:
for (initialization part; condition part; re-initialization part) { //code to be executed }
Example:
The example below defines a loop that starts with i=1. The loop will continue to run as long as i is less than, or equal to 5. The value of i will increase by 1 each time the loop runs.
#include <iostream> using namespace std; int main() { int i; //for loop for (i = 1; i <= 5; i++) { cout << "The number is " << i << endl; } return 0; };
Output
The number is 1 The number is 2 The number is 3 The number is 4 The number is 5
[…] for loopΒ βΒ loops through a block of code a specified number of times […]