For Loop
The C++ for loop is utilized to repeat a piece of the program a few times. Assuming the number of iteration is fixed, it is prescribed to use for loop than while or do-while loops.
Syntax:-
for(initialization; condition; incr/decr){
//code to be executed
}
For Loop Example in C++
#include <iostream>
using namespace std;
int main()
{
for(int i=1;i<=10;i++)
{
cout<<i <<"\n";
}
}
Output:
12
3
4
5
6
7
8
9
10
Nested For Loop in C++
In C++, we can utilize for loop inside one more for loop, it is known as nested for loop. The inner loop is executed completely when outer or external loop is executed one time. So assuming outer loop and inner loop are executed multiple times, inner loop will be executed multiple times for each outer loop for example. complete multiple times.
Example of Nested For Loop in C++
Let's see a simple example of nested for loop in C++ programming.
#include <iostream>
using namespace std;
int main () {
for(int i=1;i<=3;i++){
for(int j=1;j<=3;j++){
cout<<i<<" "<<j<<"\n";
}
}
}
Output:
1 11 2
1 3
2 1
2 2
2 3
3 1
3 2
3 3
Ranged Based for Loop in CPP
In C++11, a new range-based for loop was introduced to work with collections like arrays and vectors.
Its syntax is:
for (variable : collection) { // body of loop }Here, for every worth in the collection, the for loop is executed and the worth is assigned to the variable.
Example : Range Based for Loop
#include <iostream>
using namespace std;
int main()
{
int num_array[]={1,2,3,4,5,6,7,8,9,10};
for (int n : num_array)
{
cout << n << " ";
}
return 0;
}
Output:
1 2 3 4 5 6 7 8 9 10In the above program, we have proclaimed and instated an int array named num_array. It has 10 items.
Here, we have utilized a range-based for loop to get to all the items in the array.
Summary
- The for loop repeats a part of C++ code for a fixed number of times.
- The for loop runs as long as the test condition is valid.
- The instatement part of for loop is for declaring and initializing any loop control variables.
- The condition part of for loop should be valid for loop body to be executed.
- The increment part of the for loop can be supplanted with a semicolon.
0 Comments
🙏🙏please don't enter any spam links on the comment box.....