Nested Loops In C++ Programming Language
Nested Loops In C++ Programming Language
We have studied about loops in C++ programming language. There are three looping statements that we worked with so far i.e, while loop, do-while loop, and for loop. We know that we use loops when we want to repeat or iterate some piece of code according to our programming logic and requirement.
Now the first question arises that what is a nested loop. At this point so far we already have knowledge about loops. Nested loops are nothing they are just a loop that is placed or resides completely inside another loop. In simple words it is a loop inside another loop. And remember one important point, the inner loop completes all of its iterations every single time the outer loop runs once.
Basic Syntax Of Nested Loops In C++ Programming Language
Now we will look at syntax of for loop, while loop, and do-while loop.
Below is a syntax of for nested for loop in C++ programming language
Below is a syntax for nested while loop in C++ programming language
Below is the syntax for nested do-while loop in C++ programming language
Now we will look at the basic working of nested loops. We know that loops are used to repeat or iterate some piece of code.
Now we will look at three simple coding examples 1) for loop, 2) while loop, 3) do-while loop.
In the above coding example we have used the nested for loop. It means a for loop is nested inside another loop which in this case is also a for loop. In this example a for loop is nested inside another for loop. Now remember we have an outer for loop and an inner for loop. Both the loops will iterate 3 times, now when the outer for loop will run first time the control goes to inner for loop, but here is an interesting thing to remember, the inner loop will run three times when all the three iterations of inner for loop will complete then the control goes to outer for loop, now the outer for loop will iterate second time and again this time the control goes to inner for loop which again iterate three times and after that the control again shifts to outer for loop. Now the outer loop will run or iterate third time and again the inner for loop will iterate three times. After this the control shifts to the outer for loop and according to the given outer for loop condition the for loop exits because the condition is false i.e, i <= 3. So this is how the nested for loop will run and executed successfully.
In the next two coding examples we will see the while loop and the do-while loop. But the logic remains the same in these examples and so the working of nested loops.
Below is nested while loop example
Below is nested do-while loop example
Congratulations like always we have successfully executed the nested loops in C++ programming language.



Comments
Post a Comment