While loop programs




















One is for printing the values of i and the another statement is for updating the value of i. We are not reading anything from the user. But suppose, instead of 50, we have to print the numbers up to n. The value n means any number. So, that number can be read from the user. In this c program, we have to print the values like 5 10 15 and so on. I am going to make changes in the above program.

Change the value of i from 1 to 5 because we need to start printing from 5. Because, we need to print the multiples of 5. The while condition remains the same.

See the following program. We can calculate factorial of any number using any loop or recursion. Here, we are not going in detail about factorial. If we want to know in detail, then click Factorial Program in C.

These are all examples, where we are using while just like for loop. The benefits of while over for loop is I explained above. Now, we will see such examples here. In this program, the user is prompted to enter a number, which is stored in the variable number.

In order to store the sum of the numbers, we declare a variable sum and initialize it to the value of 0. The while loop continues until the user enters a negative number. During each iteration, the number entered by the user is added to the sum variable.

When the user enters a negative number, the loop terminates. Finally, the total sum is displayed. The do Here, the do When the number is negative, the loop terminates; the negative number is not added to the sum variable. The body of the do If the condition of a loop is always true , the loop runs for infinite times until the memory is full. For example,. In the above programs, the condition is always true. Jump Statements in Java. Arrays in Java. Strings in Java. OOPS in Java. Constructors in Java.

Interfaces in Java. Keywords in Java. Exception Handling in Java. Collection Framework. Multi-threading in Java. Table of Contents. Improve Article.

Save Article. Like Article.



0コメント

  • 1000 / 1000