Branching Statement (if ,If-else) in C-language
Concept of Branching -if
If statement is very frequently used in decision making and allowing the flow of program execution. The condition part should not end with a semicolon, since the condition and statement should be put together as a dingle statement.
Syntax
if(condition)
{ Statement;}
Example-Write a code using if statement show input number is positive or negative
program-
#include<stdio.h>
void main()
{
int number;
printf("Type a number ");
scanf("%d",&number);
if(number>0)
printf("Enter number is positive ");
if (number<0)
printf("Enter number is negative ");
}
output-
Type a number 10
Enter number is positive
--------------------------------
//for negative number
Type a number -5
Enter number is negative
--------------------------------
Q.N. which of the following are incorrect statements ? if int a=10.
1) if(a==10) printf("Include Help");
2) if(10==a) printf("Include Help");
3) if(a=10) printf("Include Help");
4) if(10=a) printf("Include Help");
Answer- 4) if(10=a) printf("Include Help");
Branching : If-else statement-
The else if statement in C is like another if condition, it's used in program when id statement having multiple decisions.
syntax
if(boolean_expression){
/*Statement(s) will execute if the boolean expression is true */
}
else {
/* statements(s) will execute if the boolean expression is false */
Example-Write a code using if-else statement show input number is positive or negative
program-
#include<stdio.h>
void main()
{
int number;
printf("Type a number ");
scanf("%d",&number);
if(number>0)
printf("Enter number is positive ");
else
printf("Enter number is negative ");
}
output-
Type a number 10
Enter number is positive
--------------------------------
//for negative number
Type a number -5
Enter number is negative
--------------------------------
Branching: multiway Decision statement
Nesting of if.......else statement
When more than one if...else are used know as nesting of if......else statement
Syntax
if(test condition)
{
if(test condition)
{
statement 1;
}
else
{
statement 2;
}
}
else
{
statement 3;
}
}
Example- write a program to find the grade of five subject marks. using nested if else statement
Program-
#include<stdio.h>
void main()
{
int per,m1,m2,m3,m4,m5;
printf("Enter the marks in five subject:");
scanf("%d %d %d %d %d",&m1,&m2,&m3,&m4,&m5);
per=(m1+m2+m3+m4+m5)/5;
if(per>=60)
printf("Frist division ");
else
{
if(per>=50)
printf("Second division ");
else
{
if(per>=40)
printf("Thrid division ");
else
printf("Fail");
}
}
}
Output-
Enter the marks in five subject:65
85
92
64
68
Frist division
--------------------------------
Comments
Post a Comment