The 'if' Statement
The 'if' statement is the simplest form of selection structure. It is a decision making statement. It is used to execute or to ignore a statement or a set of statements after testing a condition.
The ' if ' statement evaluates the condition. If the given condition is true, the statement or a set of statements following the ' if ' statement is ignored and control transfers to the statement that comes after the 'if' structure.
The syntax of 'if' statement for a single statement is as follows:
if ( condition )
statement - 1 ;
statement - 2 ;
In the above syntax:
condition It indicates the test condition. It can be a relational expression or logical expression.
statement-1 It is a single statement which will be executed if the condition is true. If the condition is false, statement-1 is ignored.
statement-2 This statement comes after the 'if' structure.
A set of statements following the 'if' statement can be given. In this case, these statements are written within curly braces { }. The set of statements surrounded by curly braces { } is called compound statement.
The syntax of 'if' statement for compound statement is as follows:
if ( condition )
{
statement - 1 ;
statement - 2 ;
- - - - - - - - - -
statement - m ;
}
statement - n ;
In the above syntax, the set of statements (from statement-1 to statement-m ) represent the compound statement. The statement-n represents the statement that comes after the 'if' structure.
Flowchart of Simple ' if ' Structure
The flowchart of 'if' statement is as follows:
Example in C
#include < stdio.h >
#include < conio.h >
void main ( )
{
int n ;
printf ( " Enter a Number " ) ;
scanf ( " %d " , &n ) ;
if ( n >= 100 )
printf ( " Number is greater than 100\n" ) ;
getch ( ) ;
}
cout << " Enter a Number " ;
cin >> n ;
if ( n >= 100 )
cout << " Number is greater than 100 " ;
return 0;
}
Flowchart Of ' if ' Statement |
Write a program that inputs a number and displays a message if the number is greater than 100.
Example in C
#include < stdio.h >
#include < conio.h >
void main ( )
{
int n ;
printf ( " Enter a Number " ) ;
scanf ( " %d " , &n ) ;
if ( n >= 100 )
printf ( " Number is greater than 100\n" ) ;
getch ( ) ;
}
Example in C
#include < iostream >
using namespace std ;
int main ( )
{
int n ;cout << " Enter a Number " ;
cin >> n ;
if ( n >= 100 )
cout << " Number is greater than 100 " ;
return 0;
}
No comments:
Post a Comment
Thanks For Visiting Here...!! I will Reply you as soon as possible.