C While Loop

1. What is a while Loop?

  • A while loop repeats a block of code as long as a condition is true.

  • Syntax:

while (condition) {
// code to execute repeatedly
}
  • The condition is evaluated first, and if it is true (non-zero), the loop executes.

  • If the condition is false (0) initially, the loop body may never execute.


2. Simple Example

#include <stdio.h>

int main() {
int i = 1;

while (i <= 5) {
printf(“i = %d\n”, i);
i++; // increment to avoid infinite loop
}

return 0;
}

Output:

i = 1
i = 2
i = 3
i = 4
i = 5

Note: Incrementing i is important to eventually make the condition false.


3. Infinite while Loop

  • If the condition never becomes false, the loop will run forever.

#include <stdio.h>

int main() {
while (1) { // always true
printf(“This will run forever!\n”);
}
return 0;
}

  • Use break to exit an infinite loop safely.

#include <stdio.h>

int main() {
int i = 1;

while (1) {
printf(“%d\n”, i);
i++;
if (i > 5) {
break; // exit loop
}
}

return 0;
}


4. Using while with Input

#include <stdio.h>

int main() {
int number;

printf(“Enter numbers (0 to stop): \n”);

scanf(“%d”, &number);
while (number != 0) {
printf(“You entered: %d\n”, number);
scanf(“%d”, &number);
}

printf(“Loop stopped.\n”);
return 0;
}

Sample Input/Output:

Enter numbers (0 to stop):
5
You entered: 5
3
You entered: 3
0
Loop stopped.

5. Key Points

  1. Condition is checked first → may skip loop if false initially.

  2. Always update loop control variables to avoid infinite loops.

  3. Useful for repeated tasks where number of iterations is unknown.

  4. Can combine with break and continue for more control.

CodeCapsule

Sanjit Sinha — Web Developer | PHP • Laravel • CodeIgniter • MySQL • Bootstrap Founder, CodeCapsule — Student projects & practical coding guides. Email: info@codecapsule.in • Website: CodeCapsule.in

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *