while writing code, we face situations where we need to repeat things a number of times. In such situations, we can use loops to make our work easy and fast. If we try to handle such situations manually then it can be hardly possible for easy and small tasks. But its not possible when we are solving complex problems(1 thousand repetitions). Let's consider some situations to understand why loops are so important in programming.
- Consider a simple program to print numbers from 1 to 5. This is very easy and one can solve this program using cout statements without using loops. At the same time, if we consider a program to print numbers from 1 to 1000 then only we can understand the importance of loops. It's impossible to print numbers from 1 to 1000 using cout statements because it needs 1000 cout statements. It's tedious and wastage of our precious time.
- Consider a program where you have an array of size 10 storing marks of a class. You want to calculate the average marks of the whole class. In this situation, we need a loop to iterate 10 times for calculating the sum of all 10 numbers. Then we will divide the sum with 10(total numbers) to get the final answer.
int main() { //printing numbers from 1 to 5 without using loops cout << "We are printing " << 1 << endl; cout << "We are printing " << 2 << endl; cout << "We are printing " << 3 << endl; cout << "We are printing " << 4 << endl; cout << "We are printing " << 5 << endl; //printing numbers from 1 to 1000 with loop for (int i = 1; i <= 1000; i++) { cout <<"We are printing "<< i <<endl; } return 0; }
int main() { // array storing marks of students int marks[10] = {20,21,23,22,27,26,25,19,24,17}; //variables for storing sum and avg int sum=0; int avg = 0; //for loop for calculating sum for (int i = 0; i < 10; i++) { sum = sum + marks[i]; } //calculating average //:. formula avg=sum/array size(no of students) avg = sum / 10; cout << "sum of marks:\t" << sum<<endl; cout << "average marks are:\t" << avg << endl; system("pause"); return 0; }
loops examples |
Now I am sure you are all clear about why we use loops in c++ and programming. Both of the cases were very simple and do not reflect the real programming scenarios but still, it shows the importance of loops. To summarize, loops are useful when you want to
- Repeat similar code several times.e.g( print hello world 100 times)
- Repeat code when a certain condition is met.e.g( print "its even" only if the number is even)
- Repeat code until it reaches its maximum limit using increment and decrement.e.g( calculate the sum of numbers from 1 to 10).
- We can implement loops with previously specifying and defining the number of repetitions/iterations. In this case, the number of iterations are known. For example, consider a program to print hello world 100 times. The number of iterations are already defined(100 iterations).
- We can implement loops with a variable specifying the number of iterations. In this case, the number of iterations are always unknown.
Loops in c++
C++ language has three most popular loops used to repeat or iterate block of code under certain conditions. Let's discuss each of them one by one.for loop in c++
In c++, for loop parentheses is comprised of three statements. The first statement initializes the loop counter variable to some initial value and executes before the execution of the block of code. The second one is used to define conditions for the execution of code. Once the block of code is executed, the third statements update the loop counter variable for the next iteration.e.g(i++,i--). This statement is executed after the execution of the code block.
int main() { for (int x = 0; x <= 10; x++) { cout <<"value of x is "<< x <<endl; } return 0; }
For loop is preferred over a while loop when you know exactly how many times you want to iterate through the code block. If the number of iteration is known, for loop can be effectively used to get the job done. One easy example is demonstrated in the above code.
while loop in c++
The while loop loops through the instructions until its expression which is a condition is true. The while expression is a boolean expression which is either true or false. This condition is checked before the execution of the code block. The code is executed only if the expression returns true.
int main() { int x = 0; int a; cout << "how many times you want to print your name" << endl; cin >> a; while(x!=a) { cout << "My Name"<< endl; x++; } return 0; }
While loop should be preferred when the number of iteration is unknown and depends on some variable. This type of situations are very easy to code through while loop as you can see in the above code.
While and for loops are quite similar to each other in action but do-while loop has something different to do than while and for loops.
Do-while loops in c++
The do-while loop executes its code block once without checking its boolean expression(condition).
Once the code is executed for the first time, it checks the boolean condition to iterate the loop further.
int main() { int choice = 0; do { cout << "enter your choice" << endl; cout << "1: to enter the program" << endl; cout << "0: to to exit the program" << endl; cin >> choice; } while (choice!=0); return 0; }
Do-while loops are used in menu-driven programs. They are used in programs where the code needs to be executed at least once. You can understand do-while loops easily from the above code. The cout statements are written inside the do-while loop body still it will be printed for the first time. And then the next iteration will be according to the input of user and loop condition.
Nested loops in c++
When a loop is written in the body or bases({}) of another loop then such loops are called nested loops. In nested loops, we have an outer independent loop and an inner dependent loop. The inner loop is dependent because it's working completely depends on the outer loop. The inner loop cannot execute until the outer loop is executed.
int main() { for (int j = 0; j < 5; j++) { for (int x = 0; x <= j; x++) { cout << "#"; } cout << endl; } system("pause"); return 0; }
What is the difference between break and continue statements in c++?
The break statement is used to terminate the loop. No further iteration takes place when the break statement is written within the braces of a loop. In nested loops, If we write the break statement in the braces of child/inner loop then only the inner/child loop will terminate and not the outer parent loop.
The parent loop will further iterate.
The continue statement is very different from the break statement. It only skips one iteration of the loop but does not terminate the loop completely. When written inside the braces of the child/inner loop in nested loops, it only skips the child loop once.
int main() { for (int j = 0; j <= 8; j++) { if (j == 2) { continue; } else if (j == 6) { break; } cout << "current number is :\t" << j << endl; } system("pause"); return 0; }
See output of this program
break and continue statements in c++ |
The break and continue statements are usually used with conditional statements like if, switch, etc.
Why we use while true?
As we have already discussed that while loop expression is a boolean expression and is evaluated to true or false. When we write true instead of any condition then it means the while loop will iterate infinitely. Such loops are called infinite loops.
int main() { while (true) { cout << "it is infinte loop." << endl; } system("pause"); return 0; }
Infinite loops are used to run code over and over again. These loops can be terminated using a break statement when some undesired action is done. e.g (when the user enters the wrong input ). It is probably used when there is no condition available.
0 Comments