while loop (Lesson-14)

In any programming language, loops are used to execute a set of statements many number of times. A while loop gets a condition and a block of code (called the body of the loop). It will continue executing the block of code again and again as long as the condition is true.
Syntax of while loop is:
while (condition)
{
//Statements
}

Usually, the condition in while loop is applied on a variable and the value of that variable is initialized out of the loop and its value is changed inside the body of the loop. Let's take an example:
Our program will input two big numbers and display their sum on the screen. After each output, the program will ask the user if he wants to input more numbers. If the user wants to input more numbers, the program will take the input again otherwise, the program will exit.



In the above example, you observed the use of while loop. Let's take another example. A program to display first 20 multiples of 17.

An evil idea:
Try this and tell me what happens


Practice Corner:
Write a program to input a number and display its table upto 10th multiple on the screen in the following format:
2 x 1 = 2
2 x 2 = 4
2 x 3 = 6
2 x 4 = 8
2 x 5 = 10
2 x 6 = 12
2 x 7 = 14
2 x 8 = 16
2 x 9 = 18
2 x 10 = 20

Post a Comment

0 Comments