The program is an example ofinfinite while loop. Since the value of the variable var is same (there is no ++ or – operator used on this variable, inside the body of loop) the condition var<=2 will be true forever and the loop would never terminate. Examples of infinite while loop Ex...
A while loop can also be used to do a pre-checking process before allowing the program to continue. A real-world example of a while loop can be seen in video games. The loop continues until the player reaches a certain score or completes a task.Use...
In this example, the program asks the user to enter numbers continuously until they enter 0. It keeps calculating the sum of the entered numbers. Once the user enters 0, the loop terminates, and the program prints the total sum. The loop is executed at least once because the condition is...
A while loop is illustrated in Program in which squares and cubes of numbers from 1 to n are calculated and displayed. The value of n is entered by the user of the program. Four integer variables are declared: (i) the variable n the value of which is entered by the user, (ii and ...
The while loop loops through a block of code as long as a specified condition is true:Syntax while (condition) { // code block to be executed }In the example below, the code in the loop will run, over and over again, as long as a variable (i) is less than 5:...
Example 2: do...while loop // Program to add numbers until the user enters zero #include <stdio.h> int main() { double number, sum = 0; // the body of the loop is executed at least once do { printf("Enter a number: "); scanf("%lf", &number); sum += number; } while(...
ExampleOpen Compiler #include <iostream> using namespace std; int main () { // Local variable declaration: int a = 10; // while loop execution while( a < 20 ) { cout << "value of a: " << a << endl; a++; } return 0; } ...
Example: For loop in C Compiler // Program to print numbers from 1 to 10 #include <stdio.h> int main() { int i; for (i = 0; i < 10; i++) { printf("%d\n", i+1); } return 0; } Run Code >> The above code prints the numbers from 1 to 10 using a for loop in...
A basic example of the C++ while loop. 1 2 3 4 5 6 7 8 9 10 11 12 13 #include <iostream> usingnamespacestd; intmain() { intx = 0; while(x < 5) { cout << x << endl; x = x + 1; } return0; } 0 1 2 3
Example of while Loop in CThe following program prints the "Hello World" message five times.Open Compiler #include <stdio.h> int main(){ // local variable definition int a = 1; // while loop execution while(a <= 5){ printf("Hello World \n"); a++; } printf("End of loop"); ...