Tuesday, June 28, 2011

IF statement in C program

0 comments

                    The if statement controls conditional branching.The body of an if statement is executed if the value of the expression is nonzero.The if statement allows you to control if a program enters a section of code or nor based on whether a given condition is true or false.One of the important function of the if statement is that it allows the program to select an action based upon the user's input.For example we can check user entered password by using if statement,and decide whether a user is allowed access to the program. 

Syntax is:

if(expression)
Execute this line of code


Example:


#include<stdio.h>
void main()
{
int number;
printf("Enter the number");
scanf("%d",&number);
if(number<5) /*if number less than five*/
{
printf("The number is less than five");
}
getch():
}


I recommended always putting braces following if statements.If you do this,you never have to remember to put them in when you want more than one statement to executed,and you make the body of the if statement more visually clear.

Else

 When the condition in an if statement evaluates to false,it would be nice to some code instead of the code executed when the statement evaluates to true. The else statement effectively says that whatever code after it is executed if the if statement is false.

Syntax is:

if(expression is TRUE)
 { 
 Execute this code 
 }
else 

Execute this code
 }

Example:

#include<stdio.h>
void main()
{
int num;
printf("Enter the number");
scanf("%d",&num);
if(num==5);
{
printf("The entered number is 5");
}
else
{
printf("The entered number is not 5");
}
getch():
}

Else if

When there are multiple conditional statements that may all evaluates to true,yet you want only if statements body to execute.You can use an else if statement following an if statement and it's body.If the first statement is true,the else if will be ignored,but if the if statement is false,it will then check condition for the else if statement.we can use numerous else if statements to ensure that only one block of code is executed.

Example:

#include<stdio.h>
void main()
{
int num;
printf("Enter the number 1 or 2 or 3");
scanf("%d",&num);
if(num==1)
{
printf("The entered number is one");
}
else if(num==2)
{
printf("The entered number is two");
}
else if(num==3)
{
printf("The entered number is three");
}
else
{
printf("number is invalid");
}
getch();
}


<<Prev Home Next>>



Leave a Reply