DEV Community

AravindhBalakrishnan
AravindhBalakrishnan

Posted on

DS - while loop

Let's discuss about while loop.

We need to print a particular value say 5 for 10 times.

print(5)
print(5)
print(5)
print(5)
print(5)
print(5)
print(5)
print(5)
print(5)
print(5)

Output : 

5
5
5
5
5
5
5
5
5
5
Enter fullscreen mode Exit fullscreen mode

writing the above code give the expected output as expected, but if we need to print the same for 10000 times or 1000000 times we can write that many lines which will take more time to write and it is difficult to know whether we have written the exact number of times to print the same line.

In order to over this difficulty and to perform the same repeated task over and over again we can use ** while ** loop. It provides us to write repeated task in few lines of code.

count = 1
while count<=10000:
      print(5)
      count = count+1
Enter fullscreen mode Exit fullscreen mode

This will print 5 for 10000

Extra Insight -
This print statement will print every 5 in new line , if we want to print it in same line we need to change the default value of the end is\n in print statement to end = " " this is will give space after every print function

count = 1
while count<=100:
      print(5 , end = " ")
      count = count+1
Enter fullscreen mode Exit fullscreen mode

In the above 5 will be printed in the same line with space between them.

Lets us see a different program to print 1 2 3 4 5 6 7 8 9 10 instead
of 5 5 5 5 5 5 5 5 5

count = 1;
while count <= 10:
      print(count , end = " ")
      count = count + 1 

Output : 1 2 3 4 5 6 7 8 9 10 

Enter fullscreen mode Exit fullscreen mode

To perform loop we need 3 important sections in a program :

  • Initialisation
  • Condition
  • Increment / Decrement condition.

Lets discuss other examples for while loop

count = 1
while count < = 5:
     print (count+5 , end = "  ")
     count = count + 1

Output :  6 7 8 9 10 
Enter fullscreen mode Exit fullscreen mode

Lets us do another task to print table of 3 . h

1 * 3 = 3
2 * 3 = 6
.
.
.
.
10 * 3 = 30

Here we perform repeated task to print * 3 = in all the output line but value of 1 and 3 in first line is change to 2 and 6 in the second line which continues to go on till 10 and 30 in line 10. so we can use while loop to perform the same action and do it.

count = 1
while count <= 10:
     print(count, " * 3 = " , count * 3)
     count = count +1 

Output : 
1  * 3 =  3
2  * 3 =  6
3  * 3 =  9
4  * 3 =  12
5  * 3 =  15
6  * 3 =  18
7  * 3 =  21
8  * 3 =  24
9  * 3 =  27
10  * 3 =  30

Enter fullscreen mode Exit fullscreen mode

While going through the above context and examples we can clearly understand the concept of loop and how loop is written to reduce the work of the programmer and to do repeated task until the condition fails.

Top comments (0)