fb popup

/* remove if it's exist in your template */

IF-ELSE

The basic thing to learn before going to if-else:-That is about Ternary operator.

 syntax:- (condition)? statement1:statement2;

The above statement indicates that to execute and give output of statement1 if the condition is true otherwise execute the statement 2.

The above syntax can be modified as :-
if(condition)

{

statement1;

}

else

{

statement2;

}
Ex:-To know whether given number is even or odd:-
#include<stdio.h>

main()

{

int i;

printf("Enter a number\n");

scanf("%d",&i);

if(i%2==0)

{

printf("given number is even\n");

}

else

{

printf("given number is odd\n");

}
output:-
case 1:-

Enter a number

5

given number is odd
case 2:-

Enter a number

524

given number is even
 
The logic of the above program is if the remainder of the given number is 0 when it is divided by 2 then it is even otherwise it is odd.

If and else if:-
 
if(condition1)

{

statement1;

}

else if(condition2)

{

statement2;

}

else if(condition3)

{

statement3;

}

else

{

statement 4;

}
Here in the above syntax indicates that if the condition 1 is true the statement belonging to that "if" part i.e statement 1 is executed and ends the program.If condition 1 is false then it checks condition 2 and if it is true then statement 2 is executed and ends the program.otherwise checks condition3 and so on until the checking of all conditions are over.If all the conditions are false then the "else" part which has no "if" i.e statement 4 is executed.

 EX:- To print a color of your interest.
#include<stdio.h>

main()

{

char d;

printf("Enter a letter V-violet,I-Indigo,B-blue,G-green,Y-yellow,O-orange,R-red\n");

scanf("%c",d);

if(d==V||d==v)

printf("Violet");

else if(d==I||d==i)

printf("Indigo");

else if(d==G||d==g)

printf("Green");

else if(d==Y||d==y)

printf("Yellow");

else if(d==O||d==o)

printf("Orange");

else if(d==R||d==r)

printf("Red");

else

printf("Invalid Choice");

}
In the above I didn't use {} for printf because there is only one statement under if else so there is no need of braces and if it is more than one then we must keep them. OUTPUT:-
case I:-Enter a letter V-violet,I-Indigo,B-blue,G-green,Y-yellow,O-orange,R-red

V

Violet.

case II:-Enter a letter V-violet,I-Indigo,B-blue,G-green,Y-yellow,O-orange,R-red

v

Violet

case III:-Enter a letter V-violet,I-Indigo,B-blue,G-green,Y-yellow,O-orange,R-red

F

Invalid Choice


Nested If:-
if(condition1)

{

if(condition2)

{

statement1;

}

}

else

{

if(condition3)

{

statement2;

}

}

Ex:-To know the highest of the 3 numbers.
#include<stdio.h>

main()

{

int a,b,c;

printf("Enter 3 numbers\n");

scanf("%d%d%d",&a,&b,&c);

if(a>b)

{

if(a>c)

printf("%d is greater\n",a);

else

printf("%d is greater\n",c);

}

else

{

if(b>c)

printf("%d is greater\n",b);

else

printf("%d is greater\n",c);

}

}

Output:-
Enter 3 numbers

12

2

59

59 is greater

No comments:

Post a Comment