If statement
The if statement is
a decision making statement. It is used to control the flow of execution of the
statements and also used to test logically whether the condition is true or
false. It is always used in conjunction with condition. This statement is used
when a question requires answer.
Example 1The
following program illustrates the use of if statement.
/* Program to check
whether the entered number is less than 25*/
#include<stdio.h>
main()
{
int i; /* Local definition */
/* Statement */
printf("\nEnter the number <
10....");
scanf("%d",&i);
if(i<10)
printf("\nThe
entered number %d is < 10", i);
} /* main */
Out put:
Enter the number < 10....5
The entered number 5 is <10
If-Else
Statements
It is basically two way
decision making statement and always used in conjunction with condition. It is
used to control the flow of execution and also used to carry out the logical
test and then pickup one of the two possible actions depending on the logical
test.
Example :
Program to find
floating point input using if-else statement.
/* Program to check floating
point input using if-else statement */
#include<stdio.h>
#include<conio.h>
void main()
{
/* Local definitions */
float years, seconds;
/* Statements */
clrscr();
printf("Input you age in
years : ");
life=scanf("%f",&years);
if(life==0) /* if statement checks the conditions */
printf("The input is not a
floating-point number.\n");
else
{
seconds=years*365*24*60*60;
printf("You have lived for
%f seconds\n",seconds);
} /* if */
getch();
} /* main */
Output:
Input you age in years : 24
You have lived for 756864000.000000 seconds
Nested
If-Else Statements
When a series of
if..else statements are occurred in a program, we can write an entire if..else
statement in another if..else statement called nesting, and the statement is
called nested if.
Example : Program
to display the types of character using if-else statement.
/* Program to
display the types of character */
#include<stdio.h>
#include<conio.h>
void main()
{
char chr; /* Local definitions */
/* Statements */
clrscr();
printf("Enter
a single character : ");
scanf(",&chr);
/* nested if
statement is used to checks the conditios */
if((chr >= 'a'
&& chr <= 'z') || (chr >= 'A' && chr <= 'Z'))
printf("Entered
character is an alphabetic.\n");
else
if(chr >= '0'
&& chr <= '9')
printf("Entered
character is an digit.\n");
else
printf("Entered
character is an special character.\n");
getch();
} /* main */
Output 1:
Enter a single
character : M
Entered character
is an alphabetic.
Output 2:
Enter a single
character : 5
Entered character
is an digit.
Output 3:
Enter a single character : %26
Entered character is an special character.
No comments:
Post a Comment