if else Statement in C/C++


If Else Statement

if else statement in C/C++ is used to make decisions.

For instance, see an example

#include<stdio.h>

#include<conio.h>

void main()

{

int  i, n=10;

clrscr();

for (i=1; i<=n ; i++){

if ( i % 2 == 0)

{

printf( “This is an even number =%d”, i)

} else {

printf( “This is an odd number =%d”, i)

}

}

getch();

}

The out of the program will be.

This is an even number =2

This is an odd number=3

This is an even number =4

This is an odd number=5

. ……………………………….

………………………………..

…………………………………

if else Program description-

In the program, for loop executes from the i=1 to i=10. Further, if statement checks whether or not i is divisible by 2. If yes this is an even number else (otherwise) odd.

Another example-

To make a program for the grading system.

For example, if you want to make a grading system program.

In which

90-99- Grade A

80-89- Grade B

70-79- Grade C

60-69- Grade D

50-59- Grade E

Less than 50-  Fail

#include<stdio.h>

#include<conio.h>

void main()

{

int marks, grade;

printf(“Enter the marks”, &marks);

scanf(“%d”,&marks);

if( marks>90 || marks< 100)

{

printf(“Grade A”);

}

if( marks>80 || marks< 90)

{

printf(“Grade B”);

}

if( marks>70 || marks< 79)

{

printf(“Grade C”);

}

if( marks>60 || marks< 69)

{

printf(“Grade D”);

}

if( marks>50 || marks< 59)

{

printf(“Grade E”);

}

getch();

}

Output-

Check yourself

Description of the program

There are two variables a declared marks, grade. scanf(“format string “, address of the variable);  function takes input from the user as marks. If statement checks the expression if it is true then control enters in if block. Otherwise, it checks another statement. Finally, it reaches at getch(); function that holds output on the screen.

References

[1] C if…else Statement, Web URL, “https://www.programiz.com/c-programming/c-if-else-statement“.

[2]  C – if…else statement, Web URL,   “https://www.tutorialspoint.com/cprogramming/if_else_statement_in_c.htm

Have any Question or Comment?

One comment on “if else Statement in C/C++

[…] Like if-else, switch case is also a decision-making structure. Furthermore, it can help to make decision-making programs. […]

Leave a Reply

Subscribe to Our Newsletter