| by Arround The Web | No comments

While Loop in C

The while loop in the C programming language performs a certain task until a specified condition holds true. This loop has an iterating condition and an iterator that increments or decrements (depending upon the logic of your code) in every iteration of the loop. In this guide, we will talk about the working of the while loop in the C programming language.

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:

$ gcc while.c –o while

To execute this object file, we used the following command:

$ ./while

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.

Share Button

Source: linuxhint.com

Leave a Reply