C Programming: IF Statement

If statement is used in logical statements. Using If statement you can execute some block of code only when some condition is satisfied. For example you have to display “you are child” when your age is below 14, then you can use if statement to complete this task.
Genera Syntax

if(test expression)
code to be executed

Example

1: int age;
2: printf(“Enter your age: “);
3: scanf(“%d”,&age);
4: if(age <= 14)
5: printf(“You are child”);

If else Statement
Above code cannot decide what to do if user enter 25, it only works for age less than or equal to 14. To avoid this problem we use If else statement.
General Syntax

if(test expression){
true block of statement
}else{
false block of statement
}
Example

1: int age;
2: printf(“Enter your age: “);
3: scanf(“%d”,&age);
4: if(age <= 14){
5: printf(“You are child”);
6: }else{
7: printf(“You are not child”);
8: }

Else If Ladder
Above code only decide whether you are child or not child. What should I do if I have to display range of ages.e.g. “child” for 0-14, “young” for 14-25, “mature” for 25-50 and “old” for >50. I can use Else if Ladder.
General Syntax

if(condition 1)
statement-1
else if(condition-2)
statement-2
else if(conditoin-3)
statement-3
else
default statement
Example:

1: int age;
2: printf(“Enter your age: “);
3: scanf(“%d”,&age);
4: if(age<=14)
5: printf(“Child”);
6: else if(age>14 && age<=25)
7: printf(“Young”);
8: else if(age>25 && age<=50)
9: printf(“mature”);
10: else
11: printf(“Old”);

SHARE C Programming: IF Statement

You may also like...

Leave a Reply

Your email address will not be published.

Share