C programming - while loop
In C programming, the while loop is used for iterative or repetitive purposes. It allows a program to execute a set of statements repeatedly while a specified condition is true. The basic syntax of the while loop is as follows:
while (condition) { // statements to be executed in each iteration }Sourcegi.www:iftidea.com
Here, the condition
expression is tested at the beginning of each iteration, and if it evaluates to true, the statements within the loop are executed. The loop will continue to execute as long as the condition
remains true. It's important to note that the condition
expression must eventually become false, or the loop will run indefinitely until the program is terminated or a break
statement is used.
Here's an example of using the while loop:
int i = 1; while (i <= 10) { printf("%d\n", i); i++; }
In this example, the loop will execute as long as i
is less than or equal to 10. In each iteration, the value of i
is printed to the console using the printf
function, and then i
is incremented by 1. The loop will repeat until i
is no longer less than or equal to 10.
It's important to note that if the condition
expression is initially false, the loop will not execute at all. Additionally, it's possible to create an infinite loop by omitting the increment/decrement
expression within the loop statements, so it's important to ensure that the condition
expression eventually becomes false.