Saturday, 29 March 2014

The If Statement in C

C Programming

Decisions in C

Computer languages must be able to perform different sets of actions depending on the circumstances. C has three major decision-making structures: the If statement, the If-Else statement, the Else-If statements and Switch statement.


The If Statement

C uses the keyword If to introduce the basic decision making statement, here is an example:

Program 
void main ( )
{
char ch;
ch=getche( );
if (ch = = 'a')
printf("\n you typed a.");
}

Output
a
you typed a

If you type 'a' the program will print "you typed a". If you type some other character then the program does nothing.

Multiple Statements with If

The body of the If Statement my consist of either a single statement or by a number of statements enclosed in braces. Here is an example:
void main ( )
{
     char ch;
     ch = getche ( );
     if ( ch = = 'a' )
         {
         printf("\n you typed a.");
         printf("\n not some other letter.");
         }
}

Output
a
you typed a.
not some other letter.

Nested If Statements

If statement can be nested like loops. Here is an example:

void main ( )
{
     if (getche ( ) = = 'n' )
          if ( getche ( ) = = 'o')
               printf("\n you typed no.");
}
In the above example, the inner if statement will not be reached unless the outer one is true, and the printf( ) statement will not be executed unless both if statements are true.








No comments:

Post a Comment