Cont. Loop Types
Cont. Loop Types
1. Including the iostream header file in our code. It will allow us to read from and write to
the console.
2. Including the std namespace so as to use its classes and functions without calling it.
3. Calling the main() function inside which the logic of the program should be added.
4. The { marks start of body of the main() function.
5. Declaring two integer variables, num, and sum. The variable sum has been initialized
to 0.
6. Creating a do-while loop. The { marks start of loop body.
7. Printing the text “Enter a number:” on the console.
8. Reading user input from the console and storing the value in variable num. The cin
(console input) is a function that reads user input.
Code Explanation:
9. Adding the value of num to value of sum and storing result in variable sum.
10.The } marks the end of the loop body. The test expression has been added to the
end of the loop body. It tests whether the value entered by the user to make sure it’s
not 0. The != is the not equal to the operator. If the user enters a 0, the loop should
terminate.
11.Printing value of variable sum on the console alongside other text.
12.The main() function should return a value if the program runs fine.
13.End of the body of the main() function.
In an entry control loop, a
condition is checked before
executing the body of a loop. It is
also called as a pre-checking loop.
#include <stdio.h>
int main() {
int num = 5;
while (num > 0) {
if (num == 3)
break;
printf("%d\n", num);
Output:
num--;
5
}} 4
Which loop to Select?
Selection of a loop is always a tough task for a programmer, to select a loop do
the following steps: