C – If, If-else and Nested If-else Statements

0
5
digitalample eye

If Statement

For Decision making, C uses the keyword if. The general form of the if statement is

if(text_expression)
statement1;
The test expression should always be enclosed in parentheses. If the test_expression is nonzero(true) then the statement statement1 is executed; Otherwise statement1 is skipped and control passes to the next statement. The statement1 can be a single statement or compound statement. The statement1 part of the if statement is the body of the if statement. This construct is shown in following flowchart. 
If Statement
If Statement

C Code

#include<stdio.h>
int main(void){
     int marks;
        printf("Enter Marks :");
        scanf("%d",&marks);
             if(marks>=40)
                 printf("Passed");
      return 0;
}

C Output

Enter Marks: 50
Passed

If -Else Statement

The if – else statement is also used for decision making purpose, C uses the keyword if-else. The general form of the if-else statement is,

if(test_expression)
statement1;
else 
statement2;
The if statement executes a single statement or a compound statement, when the test expression is true or nonzero. It does nothing when the test expression is not true.

C - If - else Statement
IF-ELSE STATEMENT

When the test expression is true or nonzero, then the body of if is executed and control passes to the next statement immediately following the if-else construct. But if the expression is not true or zero then the body of else is executed.

C Code

#include<stdio.h>
int main(void)
{
int g;
printf("Enter Your Marksn");
scanf("%d",&g);
if (g>=60)
printf("you passedn");
else
printf("you failedn");
}

C – Output

Condition1;

Enter Your Marks


45


you failed



Condition 2;


Enter Your Marks


61


you passed 

Nested If-Else Statement

The meaning of nesting is to have same construct within itself. Nesting means statement inside statement. Previously we learn about if-else statement, we identified a set of statements as the if block ans another set as the else block. The statement within the if-else statements could be another if or if-else statement. So this type of statement is called a nested conditional statement. This inner conditional expression is said to be nested within the outer one.

C Code

if(expression 1)
if(expresssion2)
statement1;
else
statement2;
else
if(expresssion2)
statement3;
else
statement4;

The statements can be surrounded by compound statement, if there exist more than one statement or other statement.

C Code

#include<stdio>
int main(void){
int n,v;
printf("Enter 2 Numbers:");
scanf("%d%d",&n,&v);
if(n>v)
printf("first is larger");
else
if(n<v)
printf("second is largern");
else
printf("both numbers are equaln");
return 0;
}

LEAVE A REPLY

Please enter your comment!
Please enter your name here