Make the computer repeat a job: build a current table with for, follow a battery discharge with while, validate input with do-while and reduce noise by averaging ADC samples.
An ADC often "jitters" a little on a single reading: for the same voltage you read 510 one moment and 514 the next. The simplest way to reduce that noise is to take several samples and compute their average. Instead of writing eight readings one by one, you want to tell the computer "do this eight times". That's what loops are for. C has three loops: for, while and do-while.
for: a loop with a known number of turns
Let's print a table of the current that flows when different resistors are connected to a 5 V supply:
#include <stdio.h>
int main(void) {
printf("R (ohm) | I (mA)\n");
for (int r = 100; r <= 500; r += 100) {
printf("%7d | %6.1f\n", r, 5000.0 / r);
}
return 0;
}
R (ohm) | I (mA)
100 | 50.0
200 | 25.0
300 | 16.7
400 | 12.5
500 | 10.0
The for parentheses contain three parts separated by semicolons:
- Initialisation:
int r = 100runs only once, at the very start. - Condition:
r <= 500is checked before every turn; when it becomes false, the loop ends. - Step:
r += 100runs at the end of every turn.
To get the current directly in milliamps instead of amps, we wrote 5 V as 5000 mV: I (mA) = 5000 / R. Writing 5000.0 also makes the division floating point.
while: loop as long as the condition holds
When you don't know in advance how many turns are needed, use while. Let's find how many hours it takes a battery that drops about 350 mV per hour to reach its 11 V cut-off voltage (we keep the voltage as an integer in millivolts):
#include <stdio.h>
int main(void) {
int aku_mv = 12600;
int saat = 0;
while (aku_mv > 11000) {
aku_mv -= 350;
saat++;
printf("%d. saat: %d mV\n", saat, aku_mv);
}
printf("Kesme gerilimine %d saatte ulasildi.\n", saat);
return 0;
}
1. saat: 12250 mV
2. saat: 11900 mV
3. saat: 11550 mV
4. saat: 11200 mV
5. saat: 10850 mV
Kesme gerilimine 5 saatte ulasildi.
The loop body must contain something that will make the condition false one day. If you delete the line aku_mv -= 350;, the condition stays true forever and the program never stops. You can get out of an endless loop with Ctrl+C.
do-while: run at least once
In do-while the condition is checked at the end, so the body runs at least once. It is ideal for asking the user again and again until a valid value arrives:
#include <stdio.h>
int main(void) {
int adc;
do {
printf("ADC (0-1023): ");
if (scanf("%d", &adc) != 1) {
return 1; // sayi degil: cik
}
} while (adc < 0 || adc > 1023);
printf("Gerilim: %.3f V\n", adc * 5.0 / 1023);
return 0;
}
ADC (0-1023): 1500
ADC (0-1023): -3
ADC (0-1023): 300
Gerilim: 1.466 V
If we didn't check scanf's return value, a typed letter would stay in the buffer, scanf would get stuck on the same letter every turn and the loop would never end.
Averaging ADC samples: skip bad data with continue
Now back to our main job. We keep eight ADC samples in an array (we'll cover arrays in detail in lesson 8; for now think of "numbered boxes", numbered from 0). A value of 1023 means the ADC is saturated, which most likely indicates a sensor fault; we skip that sample with continue:
#include <stdio.h>
int main(void) {
int adc[8] = {510, 514, 509, 1023, 515, 512, 511, 513};
long toplam = 0;
int gecerli = 0;
for (int i = 0; i < 8; i++) {
if (adc[i] >= 1023) { // doyum: sensor hatasi olabilir
continue;
}
toplam += adc[i];
gecerli++;
}
double ort = (double)toplam / gecerli;
printf("Gecerli ornek: %d\n", gecerli);
printf("Ortalama ADC : %.1f\n", ort);
printf("Gerilim : %.3f V\n", ort * 5.0 / 1023);
return 0;
}
Gecerli ornek: 7
Ortalama ADC : 512.0
Gerilim : 2.502 V
continue skips the rest of the current turn and moves on to the next one. break, on the other hand, ends the loop completely. Had we included the faulty sample in the average, the result would rise to 575.9 and the voltage would show about 2.81 V: a single bad reading would shift the measurement by more than 12 percent.
Common mistakes
Going one turn too far: in an array of 8 elements the valid indices are 0-7. If you write i <= 8, you read memory outside the array. C doesn't check this; the program quietly carries on with a garbage value.
- Putting a semicolon at the end of the for line:
for (i = 0; i < 8; i++);is an empty loop; the block below runs only once. - Forgetting to update the counter: if nothing in a while loop changes the condition, the loop never ends.
Exercise
A temperature sensor gave these 10 samples: 41.5, 43.0, 47.2, 52.8, 58.1, 61.4, 63.0, 59.9, 55.2, 50.0. Find the highest and lowest values. Then use break to print which sample first exceeded 60 °C.
Hint: give the maximum and minimum the first element of the array as their starting value, then compare in the loop. Since people count from 1, print i + 1.
Solution
#include <stdio.h>
int main(void) {
double t[10] = {41.5, 43.0, 47.2, 52.8, 58.1, 61.4, 63.0, 59.9, 55.2, 50.0};
double enb = t[0], enk = t[0];
for (int i = 1; i < 10; i++) {
if (t[i] > enb) enb = t[i];
if (t[i] < enk) enk = t[i];
}
printf("En yuksek: %.1f C\n", enb);
printf("En dusuk : %.1f C\n", enk);
for (int i = 0; i < 10; i++) {
if (t[i] > 60.0) {
printf("60 C ilk kez %d. ornekte asildi.\n", i + 1);
break;
}
}
return 0;
}
En yuksek: 63.0 C
En dusuk : 41.5 C
60 C ilk kez 6. ornekte asildi.
With loops you've reduced repetitive work to a few lines and cleaned up a noisy measurement with an average. In the next lesson we'll split code into functions to make it tidy and reusable.
// Spot the bug +10 XP
Exactly one line below is wrong. Click the faulty line.
Because the condition on line 7 is i <= 8, the loop runs 9 times and also reads adc[8], which is outside the array. In an array of 8 elements the valid indices are 0-7; correct version: for (int i = 0; i < 8; i++)
// Mini quiz
Click an option; you will see right away, with the reason, whether it is correct or not.
Mark it when you finish: your progress is saved and you earn +20 XP.
Tip: ← → keys let you move between lessons.


