C & C++ fundamentals / 06
Conditional statements
Control which statements run with if, nested conditions, else if, and else.
On this page
An if statement runs the code inside its braces when the condition in parentheses is true. If the condition is false, it skips that block.
For example, after declaring a variable a, you can write if (a > 0) {}. The block runs only when a is greater than zero. Let's combine this with input:
#include <stdio.h>
int main()
{
int a = 0;
int b = 0;
int c = 0;
scanf("%d",&a);
if(a>0)
{
a = b + c;
}
return 0;
}
If a > 0 is true, the code assigns b + c to a. Notice that a, b, and c are initialized to zero. An uninitialized local variable can have an indeterminate value, so initializing variables before using them is an important habit.
Nested conditions
You can place a conditional statement inside another one. Here is an example that combines input with two conditions:
#include <stdio.h>
int main()
{
int a = 0;
int b = 0;
int c = 0;
scanf("%d%d",&a,&b);
if(a>0)
{
if(b<0)
{
a = b + c;
}
}
return 0;
}
The inner assignment is reached only when a > 0 and b < 0.
else if and else
An else if introduces another condition after an if. An else handles the remaining case. The usual order is if, followed by any else if branches, followed by an optional else.
#include <stdio.h>
int main()
{
int a = 0;
scanf("%d",&a);
if(a>0)
{
a = 5;
}
else if(a<0)
{
a = 6;
}
else
{
a = 7;
}
return 0;
}
This program first reads a:
- If
a > 0, it assigns5toa. - If
a < 0, it assigns6. - If neither condition is true—meaning
ais zero—it assigns7.
Review the examples and try following each possible path through the code.
Editorial note: the original text said every conditional must end with
else. Anelsebranch is optional. The nested example also declares three variables, despite the original introduction referring to four.
Moved here from Tistory
I migrated this post from my Korean Tistory blog, I am Jason Lee, to this website and translated it into English. My writing and projects now live together in one place.
The original publication date, code examples, and screenshots are preserved. Editorial notes clarify known issues in the original material.
Original post on Tistory English edition · Aug 30, 2026