0% found this document useful (0 votes)
5 views

While Loop

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

While Loop

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 3

while loop

A while loop in C is a control flow statement that allows code to be executed repeatedly based
on a given condition. The while loop keeps executing as long as the condition remains true.
When the condition becomes false, the loop stops.

Syntax of while Loop

while (condition) {
// Statements inside the loop
}

● The condition is evaluated before each iteration.


● If the condition is true, the loop executes the block of statements inside it.
● If the condition is false, the loop stops.

Example of while Loop

Here is a simple example that prints numbers from 1 to 5 using a while loop

int main() {
int i = 1;

// While loop to print numbers 1 to 5


while (i <= 5) {
printf("%d\n", i);
i++; // increment the value of i
}

return 0;
}

Output:

1
2
3
4
5
How It Works:

1. Initialization: The variable i is initialized to 1.


2. Condition Check: The while loop checks the condition i <= 5.
○ If the condition is true, it enters the loop.
○ If the condition is false, the loop ends.
3. Execution: Inside the loop, it prints the value of i and then increments i by 1 (i++).
4. Repeat: The process continues until the condition i <= 5 becomes false.

Key Points:

● If the condition is initially false, the loop body won't be executed even once.
● You must ensure that the loop condition eventually becomes false, or you will get an
infinite loop.

Infinite Loop Example:

If the condition never becomes false, the loop will run indefinitely, causing an infinite loop.

#include <stdio.h>

int main() {
int i = 1;

// Infinite loop because i is always <= 5


while (i <= 5) {
printf("%d\n", i);
}

return 0;
}

This will keep printing 1 indefinitely because i is not being incremented, so the condition i <=
5 is always true.
Common Use Cases of while Loop:
Reading input until a specific condition is met:

int num;
printf("Enter numbers (enter -1 to stop): ");
scanf("%d", &num);

while (num != -1) {


printf("You entered: %d\n", num);
scanf("%d", &num);
}

This loop continues taking input until the user enters -1.

Summing numbers in a range:

int sum = 0, i = 1;

while (i <= 10) {


sum += i; // add i to sum
i++; // increment i
}

printf("Sum of numbers from 1 to 10 is: %d\n", sum);

The loop runs until i exceeds 10, calculating the sum of numbers from 1 to 10.

You might also like