Thursday, July 14, 2011

IF-ELSE STATEMENT

IF-ELSE STATEMENT

If Statements

The if statement is used to conditionally execute a block of code based on whether a test condition is true. If the condition is true the block of code is executed, otherwise it is skipped.
Syntax:
if(condition)
    {
          statement1;
          statement1;
          ...........................1;
    }
Example:
#include <stdio.h>

main()
{
    int number = 5;
    int guess;

    printf("I am thinking of a number between 1 and 10\n");
    printf("Enter your guess, please \n");
    scanf("%d",&guess);

    if (guess == number)
    {
        printf("Incredible, you are correct\n");
    }
}

if-else Statement

The else statement provides a way to execute one block of code if a condition is true, another if it is false.
Syntax:
if(condition)
    {
          statement1;
          statement1;
          ...........................1;
    }
else
    {
          statement1;
          statement1;
          ...........................1;
    }
Program: WAP a program to find out the entered number is even or odd.
#include<stdio.h>
#include<conio.h>
 
main()
{
    int x;
 
    printf("Enter any number");
    scanf("%d", &x);
   
    if(x%2==0
          printf("Even No.";
    else
          printf("Odd No.");
    getch();
}

Nested if-else Statement

The else statement provides a way to execute one block of code if a condition is true, another if it is false.
Syntax:
if(condition)
    {
          statement1;
          statement1;
          ...........................1;
    }
else if(condition)
    {
          statement1;
          statement1;
          ...........................1;
    }
Example : finding out the greatest number among three numbers

#include<stdio.h>
#include<conio.h>
 
void main()
{
    int A,B,C;
 
    printf("Enter Three No.:");
    scanf("%d %d %d",&A,&B,&C);
 
    if(A>B)
    {
          if(A>C)
                printf("A is the Greatest");
          else
                printf("C is the Greatest");
    }
    else
    {
          if(B>C)
                printf("B is the Greatest");
          else
                printf("C is the Greatest");
    }
    getch();
}

0 comments:

Post a Comment