C - While Loop: Your Gateway to Repetitive Programming
Hey there, future coding superstar! Ready to dive into the wonderful world of loops? Today, we're going to explore one of the most fundamental concepts in programming: the while loop in C. Trust me, once you master this, you'll feel like you've unlocked a superpower in coding!
What is a While Loop?
Before we jump into the nitty-gritty, let's understand what a while loop is. Imagine you're playing a video game where you need to defeat 10 enemies to complete a level. Instead of writing the same "attack" code 10 times, wouldn't it be nice if you could just say, "Keep attacking while there are enemies left"? That's exactly what a while loop does in programming!
A while loop allows you to repeat a block of code as long as a certain condition is true. It's like telling your computer, "Hey, keep doing this until I tell you to stop!"
Syntax of C while Loop
Let's take a look at the basic structure of a while loop in C:
while (condition) {
// code to be repeated
}
It's that simple! The condition
is checked before each iteration of the loop. If it's true, the code inside the curly braces {}
is executed. This process repeats until the condition becomes false.
Flowchart of C while Loop
To visualize how a while loop works, let's look at a flowchart:
┌─────────────┐
│ Start │
└──────┬──────┘
│
▼
┌─────────────────┐
│ Check condition │
└────────┬────────┘
│
▼
┌───────────┐ No
┌───┤ Condition ├────────┐
│ │ true? │ │
│ └───────────┘ │
│ │ Yes │
│ ▼ │
│ ┌──────────────┐ │
│ │ Execute code │ │
│ └──────┬───────┘ │
│ │ │
└─────────┘ │
▼
┌──────────┐
│ End │
└──────────┘
This flowchart shows that the condition is checked first. If it's true, the code is executed, and then we go back to check the condition again. This cycle continues until the condition becomes false.
How while Loop Works in C?
Let's break down the process:
- The program encounters the while loop.
- It checks the condition inside the parentheses.
- If the condition is true, it executes the code inside the loop.
- After executing the code, it goes back to step 2.
- If the condition is false, it skips the loop and continues with the rest of the program.
Example of while Loop in C
Time for our first example! Let's create a simple countdown program:
#include <stdio.h>
int main() {
int countdown = 5;
while (countdown > 0) {
printf("%d...\n", countdown);
countdown--;
}
printf("Blast off!\n");
return 0;
}
Output:
5...
4...
3...
2...
1...
Blast off!
Let's break this down:
- We start with
countdown = 5
. - The while loop checks if
countdown > 0
(which is true). - It prints the current countdown value.
- We decrease
countdown
by 1 usingcountdown--
. - Steps 2-4 repeat until
countdown
becomes 0. - When
countdown
is 0, the condition becomes false, and we exit the loop. - Finally, we print "Blast off!"
Using while as Conditional Loop
The while loop is perfect for situations where you don't know exactly how many times you need to repeat something. Let's look at an example where we ask the user to guess a number:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main() {
srand(time(0)); // Seed for random number generation
int secret = rand() % 100 + 1; // Random number between 1 and 100
int guess = 0;
int attempts = 0;
printf("I'm thinking of a number between 1 and 100. Can you guess it?\n");
while (guess != secret) {
printf("Enter your guess: ");
scanf("%d", &guess);
attempts++;
if (guess < secret) {
printf("Too low! Try again.\n");
} else if (guess > secret) {
printf("Too high! Try again.\n");
}
}
printf("Congratulations! You guessed the number in %d attempts!\n", attempts);
return 0;
}
In this example, we don't know how many attempts the user will need, so a while loop is perfect. The loop continues as long as the guess doesn't match the secret number.
While Loop with break and continue
Sometimes, you might want to exit a loop early or skip to the next iteration. That's where break
and continue
come in handy.
break
The break
statement immediately exits the loop. Here's an example:
#include <stdio.h>
int main() {
int i = 1;
while (1) { // This creates an infinite loop
printf("%d ", i);
if (i == 5) {
break; // Exit the loop when i reaches 5
}
i++;
}
printf("\nLoop ended!\n");
return 0;
}
Output:
1 2 3 4 5
Loop ended!
continue
The continue
statement skips the rest of the current iteration and jumps to the next one. Let's see it in action:
#include <stdio.h>
int main() {
int i = 0;
while (i < 10) {
i++;
if (i % 2 == 0) {
continue; // Skip even numbers
}
printf("%d ", i);
}
printf("\nLoop ended!\n");
return 0;
}
Output:
1 3 5 7 9
Loop ended!
More Examples of C while Loop
Let's look at a few more examples to solidify our understanding:
Example 1: Sum of Numbers
#include <stdio.h>
int main() {
int num, sum = 0;
printf("Enter numbers to sum (enter 0 to finish):\n");
while (1) {
scanf("%d", &num);
if (num == 0) {
break;
}
sum += num;
}
printf("The sum is: %d\n", sum);
return 0;
}
This program keeps adding numbers until the user enters 0.
Example 2: Fibonacci Sequence
#include <stdio.h>
int main() {
int n, first = 0, second = 1, next;
printf("Enter the number of Fibonacci terms to generate: ");
scanf("%d", &n);
printf("Fibonacci Sequence:\n");
int i = 0;
while (i < n) {
if (i <= 1) {
next = i;
} else {
next = first + second;
first = second;
second = next;
}
printf("%d ", next);
i++;
}
printf("\n");
return 0;
}
This program generates the Fibonacci sequence up to n terms.
while Vs. do while Loops
Before we wrap up, let's quickly compare while loops with their cousin, the do-while loop:
Feature | while Loop | do-while Loop |
---|---|---|
Condition Check | At the beginning | At the end |
Minimum Executions | 0 (if condition is initially false) | 1 (always executes at least once) |
Syntax | while (condition) { ... } |
do { ... } while (condition); |
Best Use Case | When you're not sure if you need to execute the loop at all | When you know you need to execute the loop at least once |
The main difference is that a do-while loop always executes its code block at least once before checking the condition.
And there you have it, my coding apprentice! You've just unlocked the power of while loops in C. Remember, practice makes perfect, so don't be afraid to experiment with these concepts. Before you know it, you'll be looping like a pro! Happy coding! ??
Loop Pusingan: Catatan Pemrograman Berulang
Hai sana, bintang pemrograman masa depan! Siapakah untuk masuk ke dunia yang menakjubkan dari loop? Hari ini, kita akan jelajahi salah satu konsep paling dasar dalam pemrograman: loop while
dalam C. Percayalah, sekali Anda menguasai ini, Anda akan merasa seperti Anda telah membuka kekuatan super dalam pemrograman!
Apa Itu Loop while
?
Sebelum kita masuk ke hal yang berbelit-belit, mari kita mengerti apa itu loop while
. Bayangkan Anda sedang bermain permainan video tempat Anda harus mengalahkan 10 musuh untuk menyelesaikan level. Daripada menulis kode "serang" yang sama 10 kali, tidakkah Anda senang jika Anda bisa hanya mengatakan, "Terus serang selama masih ada musuh"? Itu tepatnya apa yang dilakukan loop while
dalam pemrograman!
Loop while
memungkinkan Anda untuk mengulangi blok kode selama suatu kondisi masih benar. Itu seperti memberi perintah kepada komputer Anda, "Hey, terus lakukan ini sampai saya memberitahu Anda untuk berhenti!"
Sintaks Loop while
dalam C
Mari kita lihat struktur dasar loop while
dalam C:
while (kondisi) {
// kode yang akan diulangi
}
Itu sangat sederhana! kondisi
dicek sebelum setiap iterasi loop. Jika kondisi
benar, kode di dalam kurung kurawal {}
dieksekusi. Proses ini terus berulang sampai kondisi
menjadi salah.
Diagram Alir Loop while
dalam C
Untuk mengvisualisasikan bagaimana loop while
bekerja, mari kita lihat diagram alir:
┌─────────────┐
│ Mulai │
└──────┬──────┘
│
▼
┌─────────────────┐
│ Cek kondisi │
└────────┬────────┘
│
▼
┌───────────┐ Tidak
┌───┤ Kondisi ├────────┐
│ │ benar? │ │
│ └───────────┘ │
│ │ Ya │
│ ▼ │
│ ┌──────────────┐ │
│ │ Eksekusi │ │
│ │ kode │ │
│ └──────┬───────┘ │
│ │ │
└─────────┘ │
▼
┌──────────┐
│ Akhir │
└──────────┘
Diagram ini menunjukkan bahwa kondisi dicek pertama kali. Jika itu benar, kode dieksekusi, dan kemudian kita kembali untuk mengecek kondisi lagi. siklus ini terus berlanjut sampai kondisi menjadi salah.
Bagaimana Loop while
Bekerja dalam C?
Mari kita uraikan proses ini:
- Program menemukan loop
while
. - Itu mengecek kondisi di dalam tanda kurung.
- Jika
kondisi
benar, itu mengeksekusi kode di dalam loop. - Setelah mengeksekusi kode, itu kembali ke langkah 2.
- Jika
kondisi
salah, itu melompat melewati loop dan melanjutkan ke bagian lain dari program.
Contoh Loop while
dalam C
Waktunya untuk contoh pertama! Mari kita buat program penghitung mundur sederhana:
#include <stdio.h>
int main() {
int countdown = 5;
while (countdown > 0) {
printf("%d...\n", countdown);
countdown--;
}
printf("Blast off!\n");
return 0;
}
Output:
5...
4...
3...
2...
1...
Blast off!
mari kitauraikan ini:
- Kita mulai dengan
countdown = 5
. - Loop
while
mengecek jikacountdown > 0
(yang benar). - Itu mencetak nilai
countdown
saat ini. - Kita mengurangi
countdown
dengan 1 menggunakancountdown--
. - Langkah 2-4 terus berulang sampai
countdown
menjadi 0. - Ketika
countdown
0,kondisi
menjadi salah, dan kita keluar dari loop. - Akhirnya, kita mencetak "Blast off!".
Menggunakan while
sebagai Loop Kondisional
Loop while
sempurna untuk situasi di mana Anda tidak yakin berapa kali Anda butuh mengulangi sesuatu. Mari kita lihat contoh di mana kita meminta pengguna untuk menebak angka:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main() {
srand(time(0)); // Benih untuk generasi angka acak
int secret = rand() % 100 + 1; // Angka acak antara 1 dan 100
int guess = 0;
int attempts = 0;
printf("Saya pikirkan angka antara 1 dan 100. Bisakah Anda menebaknya?\n");
while (guess != secret) {
printf("Masukkan tebakan Anda: ");
scanf("%d", &guess);
attempts++;
if (guess < secret) {
printf("Terlalu rendah! Cobalah lagi.\n");
} else if (guess > secret) {
printf("Terlalu tinggi! Cobalah lagi.\n");
}
}
printf("Congratulations! Anda menebak angka dalam %d percobaan!\n", attempts);
return 0;
}
Dalam contoh ini, kita tidak tahu berapa banyak percobaan pengguna butuh, jadi loop while
adalah yang tepat. Loop terus berlanjut sampai tebakan pengguna cocok dengan angka rahasia.
Loop while
dengan break
dan continue
kadang-kadang, Anda mungkin ingin keluar dari loop lebih awal atau melompat ke iterasi berikutnya. Itu saat break
dan continue
berguna.
break
Perintah break
secara langsung keluar dari loop. mari kita lihat contoh:
#include <stdio.h>
int main() {
int i = 1;
while (1) { // Ini membuat loop tak terbatas
printf("%d ", i);
if (i == 5) {
break; // Keluar dari loop saat i mencapai 5
}
i++;
}
printf("\nLoop berakhir!\n");
return 0;
}
Output:
1 2 3 4 5
Loop berakhir!
continue
Perintah continue
melewatkan sisanya iterasi saat ini dan melompat ke iterasi berikutnya. mari kita lihat contoh ini:
#include <stdio.h>
int main() {
int i = 0;
while (i < 10) {
i++;
if (i % 2 == 0) {
continue; // Lewati bilangan genap
}
printf("%d ", i);
}
printf("\nLoop berakhir!\n");
return 0;
}
Output:
1 3 5 7 9
Loop berakhir!
Contoh Lain Loop while
dalam C
Mari kita lihat beberapa contoh lain untuk memperkuat pemahaman kita:
Contoh 1: Penjumlahan Angka
#include <stdio.h>
int main() {
int num, sum = 0;
printf("Masukkan angka untuk dijumlahkan (masukkan 0 untuk selesai):\n");
while (1) {
scanf("%d", &num);
if (num == 0) {
break;
}
sum += num;
}
printf("Jumlahnya: %d\n", sum);
return 0;
}
Program ini terus menambahkan angka sampai pengguna memasukkan 0.
Contoh 2: Deret Fibonacci
#include <stdio.h>
int main() {
int n, first = 0, second = 1, next;
printf("Masukkan jumlah deret Fibonacci yang ingin dihasilkan: ");
scanf("%d", &n);
printf("Deret Fibonacci:\n");
int i = 0;
while (i < n) {
if (i <= 1) {
next = i;
} else {
next = first + second;
first = second;
second = next;
}
printf("%d ", next);
i++;
}
printf("\n");
return 0;
}
Program ini menghasilkan deret Fibonacci hingga n
Credits: Image by storyset