Important Points
- Use for a loop when a number of iterations are known beforehand, i.e. the number of times the loop body is needed to be executed is known.
- Use while loops, where an exact number of iterations is not known but the loop termination condition, is known.
- Use do while loop if the code needs to be executed at least once like in Menu-driven programs
C++ Loops
In Programming, sometimes there is a need to perform some operation more than once or (say) n number of times. Loops come into use when we need to repeatedly execute a block of statements.
For example: Suppose we want to print “Hello World” 10 times. This can be done in two ways as shown below:
Manual Method (Iterative Method)
Manually we have to write cout for the C++ statement 10 times. Let’s say you have to write it 20 times (it would surely take more time to write 20 statements) now imagine you have to write it 100 times, it would be really hectic to re-write the same statement again and again. So, here loops have their role.
C++
// C++ program to Demonstrate the need of loops #include <iostream> using namespace std; int main() { cout << "Hello World\n" ; cout << "Hello World\n" ; cout << "Hello World\n" ; cout << "Hello World\n" ; cout << "Hello World\n" ; return 0; } |
Hello World Hello World Hello World Hello World Hello World
Time complexity: O(1)
Space complexity: O(1)
Using Loops
In Loop, the statement needs to be written only once and the loop will be executed 10 times as shown below. In computer programming, a loop is a sequence of instructions that is repeated until a certain condition is reached.