C has three major control statements:-
- if statement,
- if – else statement, and
- Switch statement.
if Statement:-
The statement inside if body executes only when the condition defined by if statement is true. If the condition is false then the compiler skips the statement enclosed in if’s body.
We can have any number of statement s inside if’s body.
Syntax:
if(expression/condition)
{
statements;
}
Example:
#include<stdio.h>
#include<conio.h>
using namespace std;
int main () {
int num;
if(num%2==0){
printf("EVEN");
}
}
return 0;
}
if – else statement:-
In an if-else Statement, we have two blocks of statements. If the condition inside the if block results true then the if block gets executed, otherwise the statement inside the else block gets executed.
Else can’t exit without if statement.
Syntax:
if(expression/condition)
{
statements;
}
else
{
statements;
}
Example:
Nested if – else
When we write an entire if -else construct within either the body of if statement or in the body of else statement is called nested if.
Syntax:
// Program to check whether a number is even or odd
#include<stdio.h>
#include<conio.h>
using namespace std;
int main() {
int num;
printf("enter the num");
if(n%2==0) {
printf("even");
}
else{
printf("odd");
}
return 0;
}
if(expression)
{
if(expression)
{
statements;
}
else
{
statements;
}
}
else
{
statements;
}
Example:
// Program to print series of numbers 1 to 10 using for loop.
#include<stdio.h>
#include<conio .h>
int main ()
{
int i;
for (i=1; n c=10; n++) // for loop to print 1-10 number
{
printf("n10"); // to print the number
}
return 0;
}
if – else – if ladder Statement:-
In if – else – if ladder if statement are executed from top to down. As soon as one of the condition of if is true , the Statement associated to it executed and the rest of the else -if ladder is by passed. And if none of two condition is true then the final else statement.
Syntax:
if(expression)
{
statement-1;
}
else
if(expression)
{
statement-2;
}
else
if(expression)
{
statement-3;
}
else
{
statement-4;
}
Example:
// Program to print series of numbers 1 to 10 using for loop.
#include<stdio.h>
#include<conio .h>
int main ()
{
int i;
for (i=1; n c=10; n++) // for loop to print 1-10 number
{
printf("n10"); // to print the number
}
return 0;
}