If Statement
Part of the Fundamentals section of Coddy's C journey — lesson 25 of 63.
The if statement is a fundamental control flow structure in C that allows your program to make decisions.
An if statement executes a block of code only if a specified condition is true.
Basic syntax of an if statement:
if (condition) {
// Code to execute if condition is true
}Let's look at a simple example:
int age = 20;
if (age >= 18) {
printf("You are an adult.\n");
}In this example:
- We check if the value in
ageis greater than or equal to 18
- If this condition is true, the message "You are an adult." is printed
- If the condition is false, the program skips the code block and continues with the next statement
Challenge
EasyYou are writing a simple program to check the weather condition based on a preset temperature value.
Here’s the task:
- Create an
intvariable calledtemperatureand set it to any value you like (for example, 35). - Use
ifstatements to print messages based on the value oftemperature:- If the temperature is above 30, print
"It's a hot day!" - If the temperature is between 20 and 30 (inclusive), print
"The weather is nice." - If the temperature is below 20, print
"It's a bit cold today."
- If the temperature is above 30, print
Cheat sheet
The if statement executes code only if a specified condition is true:
if (condition) {
// Code to execute if condition is true
}Example:
int age = 20;
if (age >= 18) {
printf("You are an adult.\n");
}If the condition is false, the program skips the code block and continues with the next statement.
Try it yourself
#include <stdio.h>
int main() {
int temperature;
scanf("%d", &temperature);
// Don't change above this line
// Write your if statements below
return 0;
}This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Fundamentals
4Control Flow
If StatementIf - ElseElse-IfSwitch CaseTernary Conditional OperatorRecap ChallengeNested If - Else3Operators
Arithmetic OperatorsModulo OperatorIncrement/DecrementAssignment OperatorsRelational OperatorsLogical Operators Part 1Logical Operators Part 2Logical Operators Part 3Recap Challenge