In this lesson, you will learn about Conditional Statements in C, particularly the if statement, and its usage, along with examples to better understand the topic.
A conditional statement is a code block that determines a program’s execution route based on the set condition’s value. Code implementation can be divided into categories as shown below:
Like most programming languages, C enables you to write code based on the outcomes of a logical or comparative test condition at runtime that executes distinct activities. This implies that in the form of phrases that evaluate either true or false, you can generate test circumstances, and, based on these outcomes, you can execute specific activities.
This lesson will focus on the if conditional statement and its usage.
The if statement executes a code block based on a condition. The condition must be true. Otherwise, the compiler will not execute the code inside the statement.
if(condition is true or false){ // Code to be processed here based on condition }
#include <stdio.h> int main() { int var; printf("Enter an integer: "); scanf("%d", &var); // takes the input // true if input is divisible by 2 if ((var % 2) == 0) { printf("The number you entered if dividable by 2 %d.\n", var); } return 0; }
Output
Enter an integer: 8 Come in this block if you are divisible by 8
The program above takes the user input and checks if that input is dividable by 2. If the statement (var % 2) == 0
, which is the modulus of var, is true, then the condition is met, and the code inside the if statement will be executed. Else, the program skips the code inside the if statement and reaches the end by executing the return 0
.
In the next lesson, you will learn about another conditional statement in C, the if-else statement.