Lecture 8 – Decisions (if)
Decisions (if)
if structure
Syntax
There
are situations when we need to take a decision. For example you are going to
your home and there’s a traffic jam, you opt for alternate route. Similarly in
C programming there are situations where we need to change the course of our
program flow based upon a condition.
There
are some decision constructs in C which help us to achieve that functionality.
if structure
It is
used when you need to take a decision. Its general syntax is
Syntax
if
(condition)
{
//
Statements to be executed when the condition is true
}
Let’s
understand it using an example
// This program demonstrates the use of if
|
Output
Please enter your marks: 75
Congratulations! You’ve passed
|
# include <stdio.h>
# include <conio.h>
|
Output
Please enter your marks: 25
|
void main()
{
|
Output
Please enter your marks: 50
|
int marks;
clrscr();
|
In last two examples there was no output because, those
conditions were not handled in this code
|
printf(“\nPlease enter your
marks: ”);
scanf(“%d”, &marks);
if(marks>50)
{
printf(“\nCongratulations! You’ve passed”);
}
getch();
}
Example 15 – Use of if and a relational
operator
|
Output
Please enter your marks: 75
Congratulations! You’ve passed
|
// This program demonstrates
the use of multiple if’s
# include
<stdio.h>
# include
<conio.h>
void main()
|
Output
Please enter your marks: 25
Sorry! You didn’t make it :(
|
{
int marks;
clrscr();
|
Output
Please enter your marks: 50
Sorry! You didn’t make it :(
|
printf(“\nPlease enter your
marks: ”);
scanf(“%d”,
&marks);
if(marks>50)
|
In last example the output is not what is expected.
This is called a logical error. This condition is not handled in this code.
|
{
printf(“\nCongratulations!
You’ve passed”);
}
If(marks < 50)
{
printf(“\nSorry!
You didn’t make it :(”);
}
getch();
}
Example 16 – Use of multiple if's and two relational operators
// This program
demonstrates the use of multiple if’s
# include
<stdio.h>
# include
<conio.h>
|
Output
Please enter your marks: 75
Congratulations! You’ve passed
|
|
Output
Please enter your marks: 25
Sorry! You didn’t make it :(
|
|
Output
Please enter your marks: 50
Congratulations! You’ve passed
|
void main()
{
int marks;
clrscr();
printf(“\nPlease
enter your marks: ”);
scanf(“%d”,
&marks);
if(marks>=50)
{
printf(“\nCongratulations!
You’ve passed”);
}
If(marks < 50)
{
printf(“\nSorry! You
didn’t make it :(”);
}
getch();
}
Example 17 – Use of multiple if's and different relational operators
Comments
Post a Comment