Usage of the While Loop in the C Programming Language
We have tried to explain the usage of the while loop in the C programming language with the help of the following three examples:
Example # 1: Printing a Series of Numbers
We will try to print a series of numbers from 1 to 10 in this example with the help of the while loop in C. The script shown in the following image has been designed to serve this purpose:
In this program, we have defined an integer variable “num” and assigned the number “1” to it. Then, by using the while loop, we have incremented this variable in every iteration till “10” so that a series of numbers from 1 to 10 can be printed on the terminal.
Then, we created an object file of this program with the following command:
To execute this object file, we used the following command:
The series of numbers is shown in the following image:
Example # 2: Infinite While Loop
You can also make a while loop infinite by using it in the manner shown in the following C script:
The statement “while(1)” in this loop evaluates to true in every iteration of the loop, because of which the body of this loop will always be executed, i.e., the message “Hello World” will be printed on the terminal for infinite many times.
This can be confirmed with the following output:
Note: To break this loop or to force stop the program execution, in this case, you will have to press Ctrl+ C in your terminal.
Example # 3: While Loop Without an Iterating Condition
A while loop in the C programming language must have a proper iterating condition. In the following example script, we will try to find out what happens if we miss that iterating condition.
In this example, we have simply removed the iterating condition from the C program used in our second example.
When we compiled this C program, we received a compile time error prompting us to provide a proper iterating condition, as shown in the following image:
Conclusion
In this article, we tried to explore the working of the while loop in the C programming language in three different aspects. After understanding these cases, you can easily use the while loop while writing your programs in C.