CONTROL STATEMENT IN C (if-else STATEMENT)

Dev Frank
3 min readJan 3, 2024

--

The if-else statement is a fundamental control flow structure in C. If-else is another conditional or decision making statement. The if-else is similar to the if statement, the only difference is the else attached to it. It allows you to make decisions in your program based on the evaluation of a condition.

Consider this scenario: Your mom tasks you with fetching mangoes from the supermarket. She says if there are mangoes in the supermarket get them, otherwise come back home.

This is applicable to programming. You tell the control to print some statements, expression, etc. only if the condition is true, otherwise display something else.

The if statement starts with a condition enclosed in parentheses. This condition is a boolean expression that evaluates to either true or false. If the condition is true, the code within the if statement will be executed, If the condition is false, the code within the else block is executed. The program executes either the code block under if or the one under else, but not both.

EXPLANATION OF if-else STATEMENT USING FLOWCHART

Dev Frank

SYNTAX OF IF-ELSE CONDITION

if(condition) 
// executes this block of code if condition is true
else
// execute this block of code if statement is false.

Example

#include <stdio.h>
#include <conio.h>

int main(void)
{
int x = 5;

if(x < 10)
printf("%d is less than 10\n",x);
else
printf("%d is greater than 10\n",x);

getch();
return (0);
}

OUTPUT

5 is less than 10

Here the statement “5 is less than 10” will be printed, because x was declared and initialized to 5. And 5 is less than 10. Because this statement is true, the if block statement be evaluated.

Supposing you want two or more statements to be evaluated if only the condition is true, you make use of the curly braces { }.

#include <stdio.h>
#include <conio.h>

int main(void)
{
int x = 5;

if (x < 10)
{
printf("Value of x is 5\n",);
printf("%d is less than 10\n",);
}else
printf("%d is greater than 10\n",x);

getch();

return(0);
}

OUTPUT


Value of x is 5
5 is less than 10

It’s important to note that the else part is optional. If you only want to execute code when the condition is true and do nothing otherwise, you can omit the else block:

TRY THIS !!!

#include <stdio.h>

int main() {
int number = 7;

if (number % 2 == 0) {
printf("The number is even.\n");
} else {
printf("The number is odd.\n");
}

return 0;
}

Feel free to drop your answers or questions at the comment section.

--

--

Dev Frank

Passionate tech enthusiast, diving deep into the world of software engineering. Thrilled to share insights with the world. A Software engineering student.