if, for and while in C
Builds on lessons 1 to 3. Start at lesson 1
Learn
Conditions are numbers
Programs get interesting when they can choose and repeat.
Choosing uses if, else if and else. The condition goes in parentheses:
if (score >= 90) {
printf("A\n");
} else if (score >= 50) {
printf("pass\n");
} else {
printf("try again\n");
}Early C had no boolean type, and a condition is still just a number. 0 means false, anything else means true. Comparisons like x > 3 produce the int 1 or 0. (<stdbool.h> gives you bool, true and false as friendlier names.)
That is why this classic bug compiles happily:
if (level = 5) // stores 5 in level; 5 is nonzero, so always trueYou wanted ==. Some compilers warn about this one; this one does not, so learn to spot it by eye.
Learn
Loops and remainders
Repeating uses loops. A for loop packs start, condition and step into one line:
for (int i = 1; i <= 5; i++) {
printf("%d\n", i);
}A while loop keeps going while its condition is true, which suits "I do not know how many times yet" situations. break leaves a loop early, continue skips to the next round.
In memory, i is one int: 4 bytes. Each round writes the new value into the same 4 bytes, and the old value is gone. A loop never keeps a list of past values unless you store them yourself.
The % operator gives the remainder of a division: 10 % 3 is 1. If n % 2 == 0, n is even. You will use this constantly.
Some programs here read numbers that are typed in. scanf("%d", &n); reads one whole number into the int called n; call it again for the next number. Write it exactly like that for now, with the &: the pointers lesson explains what the & does.
Try
Run it: a running total
The example is already in the editor. Run it, change one thing, and run it again.
#include <stdio.h>
int main(void) {
int total = 0;
int n = 1;
while (total < 20) {
total = total + n;
printf("added %d, total is %d\n", n, total);
n++;
}
if (total % 2 == 0) {
printf("%d is even\n", total);
} else {
printf("%d is odd\n", total);
}
return 0;
}
Practice
FizzBuzz to fifteen
For each number from 1 to 15, print Fizz if it divides by 3, Buzz if it divides by 5, FizzBuzz if it divides by both, and otherwise the number itself. One per line.
#include <stdio.h>
int main(void) {
for (int i = 1; i <= 15; i++) {
printf("%d\n", i);
}
return 0;
}
Practice
Count down from input
The program reads a number n with scanf. Print a countdown from n to 1, one number per line, then print Liftoff!. With the input below, the output is:
54321Liftoff!
Your program reads the Input box under the editor.
#include <stdio.h>
int main(void) {
int n;
scanf("%d", &n);
// count down here
return 0;
}
Break/fixFix the bug
Everyone gets gold
The program reads three race scores and should only give gold for a perfect 100. Everyone gets gold, and the scores print wrong too. Fix it. With the input below it should print:
70: keep going100: gold85: keep going
Your program reads the Input box under the editor.
#include <stdio.h>
int main(void) {
int s;
for (int i = 0; i < 3; i++) {
scanf("%d", &s);
if (s = 100) {
printf("%d: gold\n", s);
} else {
printf("%d: keep going\n", s);
}
}
return 0;
}
Your turn
Longest practice streak
A practice app logs the minutes you played guitar each day. The input is a count n, then n daily totals. A day counts towards a streak if it has at least 30 minutes. Print the longest run of counting days in a row as longest streak N days.
Milestones
- Streak in the middle
- Every session under target
- Streak at the end
On your own. Hints open after your first check.
Your program reads the Input box under the editor. Check also tries 2 other inputs.
#include <stdio.h>
Passed
You can now