Welcome to the C while Loop lesson! In this tutorial, we'll explore one of the most fundamental loop structures in C programming – the while loop. By the end of this tutorial, you'll have a solid understanding of how to use while loops, why they're useful, and how to apply them in real-world projects. 📝
A while loop is a control structure that repeatedly executes a block of code as long as a specified condition is true. The loop continues to run as long as the condition remains true, and it stops once the condition becomes false.
Here's the general syntax for a while loop in C:
while (condition) {
// code to be executed while the condition is true
}In the above syntax, condition is an expression that gets evaluated before each iteration of the loop. If the condition is true, the code block inside the loop is executed. Once the condition becomes false, the loop stops.
Let's illustrate how a while loop works with an example. We'll write a simple program to print numbers from 1 to 10.
#include <stdio.h>
int main() {
int counter = 1;
while (counter <= 10) {
printf("%d\n", counter);
counter++;
}
return 0;
}In this example, we initialize a variable counter to 1 and set up a while loop that continues as long as counter is less than or equal to 10. Inside the loop, we print the value of counter, increment it by 1, and continue the loop until counter is 11.
Now that you understand the basics of while loops, let's look at a more advanced example: computing the Fibonacci series. The Fibonacci series is a sequence of numbers in which each number is the sum of the two preceding ones, usually starting with 0 and 1.
#include <stdio.h>
int main() {
int number1 = 0, number2 = 1, nextNumber;
printf("Fibonacci Series:\n");
while (nextNumber <= 20) {
printf("%d ", number1);
nextNumber = number1 + number2;
number1 = number2;
number2 = nextNumber;
}
return 0;
}In this example, we initialize two variables number1 and number2 to 0 and 1, respectively. We then set up a while loop that continues as long as nextNumber is less than or equal to 20. Inside the loop, we print the current number, compute the next number as the sum of number1 and number2, and update the values of number1 and number2 for the next iteration.
What is the purpose of a while loop in C programming?
Now that you've learned about while loops in C, you can use them to create efficient and powerful programs. In the next lesson, we'll explore another loop structure, the for loop, and see how it differs from the while loop.
Happy coding! 🎉