Once you can calculate and compare values (Part 4), it is time to steer the program based on those results. In C, conditionals decide “what happens in this situation,” and loops decide “how many times should this happen.” This post focuses on if, else, for, and while so you can control execution paths.
New Terms In This Post
- Condition expression: an expression like
score > 80that evaluates to true or false - Branch: the alternate path created by an
ifstatement - Loop: syntax that repeats a block of code
- Infinite loop: a loop without a terminating condition
Core Ideas
Study Notes
- Time required: 45–60 minutes
- Prerequisites: variables, comparison operators, and comfort with
printf- Goal: write branching and repetition patterns with conditionals and loops
Conditionals look at the current values and decide which block runs. Loops repeat work until a condition changes. Together they form the backbone of most programs—for example, “if the score is 80 or higher, print pass; otherwise encourage more study.”
We will cover five skills:
- Build branches with
if,else if, andelse - Combine comparison and logical operators in condition expressions
- Repeat a known number of times with
for - Repeat while a condition is true with
while - Adjust loop flow with
breakandcontinue
Follow Along in Code
Split Paths with if
An if statement runs its block only when the condition is true.
#include <stdio.h>
int main(void) {
int score = 88;
if (score >= 80) {
printf("Within the pass range.\n");
}
return 0;
}
score >= 80 is the condition. If it is true, the block runs; otherwise it is skipped. In a boolean context, any non-zero value is treated as true and 0 is treated as false. For now, keep using explicit comparisons like score > 80; later you will see code that uses the value directly.
Chain if, else if, else
Use chained conditionals when you have multiple cases.
#include <stdio.h>
int main(void) {
int score = 72;
if (score >= 90) {
printf("Grade A.\n");
} else if (score >= 80) {
printf("Grade B.\n");
} else if (score >= 70) {
printf("Grade C.\n");
} else {
printf("More study required.\n");
}
return 0;
}
Conditions run from top to bottom. The first true block executes, and the rest are skipped, so order matters.
Comparison and Logical Operators
Build richer conditions using comparison and logical operators:
==,!=,>,<,>=,<=&&(and),||(or),!(not)
#include <stdio.h>
int main(void) {
int age = 17;
int has_id = 1;
if (age >= 17 && has_id == 1) {
printf("Entry granted.\n");
} else {
printf("Entry denied.\n");
}
return 0;
}
In many beginner examples, 1 represents true and 0 represents false, because conditions in C really are integers under the hood. Just remember that in a boolean context, any non-zero value counts as true.
Do Not Mix Up = and ==
This is the classic beginner mistake:
=assigns a value.==compares two values.
int score = 80; // assignment
if (score == 80) {
// comparison
}
Using = in a condition assigns a value first, then evaluates that value as a condition—which is almost always a bug.
int score = 50;
if (score = 80) {
printf("This might run unexpectedly.\n");
}
Here score becomes 80, which is non-zero, so the block runs. Watch compiler warnings to catch this early.
Repeat with for
Use a for loop when you know the iteration count. If you need to do the same thing 100 times, a loop is what keeps you from writing the same line 100 times.
#include <stdio.h>
int main(void) {
int i;
for (i = 1; i <= 5; i++) {
printf("Print #%d\n", i);
}
return 0;
}
Read the structure as for (start; condition; update). The flow is set i = 1 -> check i <= 5 -> run body -> i++ -> check again. i++ is shorthand for i = i + 1.
Repeat with while
When the number of iterations is unknown and depends on the data, use while.
#include <stdio.h>
int main(void) {
int countdown = 3;
while (countdown > 0) {
printf("%d\n", countdown);
countdown--;
}
printf("Start!\n");
return 0;
}
Always ensure something inside the loop makes the condition false eventually; otherwise you get an infinite loop.
break vs. continue
Inside loops you can fine-tune the flow:
break: exit the loop immediately.continue: skip the rest of this iteration and move to the next.
#include <stdio.h>
int main(void) {
int i;
for (i = 1; i <= 5; i++) {
if (i == 3) {
continue;
}
if (i == 5) {
break;
}
printf("i = %d\n", i);
}
return 0;
}
Here the loop skips printing when i == 3, and the entire loop stops when i == 5. If you later nest loops, remember that break exits only the innermost loop.
Practical Example: Count Warning Scores
#include <stdio.h>
int main(void) {
int scores[5] = {95, 61, 48, 82, 55};
int i;
int warning_count = 0;
for (i = 0; i < 5; i++) {
if (scores[i] < 60) {
warning_count++;
printf("Warning score: %d\n", scores[i]);
}
}
printf("Total warnings: %d\n", warning_count);
return 0;
}
Even before diving deep into arrays, you can think of scores[i] as "the score at index i," where the first score is at index 0. The focus here is that we loop through multiple values and apply a condition to each one.
Why This Matters
Conditionals and loops give shape to your program. Without them, variables just hold values with no decision-making. Keep these five points:
- Conditionals run different code based on value states.
- Loops repeat work, either a set number of times or while a condition holds.
- Use
forwhen the count is clear,whilewhen the condition is the priority. breakandcontinuefine-tune loop execution.- Never confuse
=(assignment) with==(comparison).
With this control-flow intuition, you are ready to package decisions and repetitions into reusable functions in the next installment.
Practice in CodeSandbox
The sandbox below uses CodeSandbox's Universal starter. For C, the key learning loop is still compile and run in the terminal, so recreate the lesson code as a source file and repeat that cycle directly.
💬 댓글
이 글에 대한 의견을 남겨주세요