Pages

  • Home
  • About & Contact
  • Archive
  • C Programming Examples

14 December 2011

C Program to check number is positive or negative number using ternary operator

Here is the program to check number is positive  , negative or zero with Explaination

#include<conio.h>
#include<stdio.h>
void main()
{
    int x,no;
    printf("Enter a number\n");
    scanf("%d",&x);
    if(x<0)
    {
       printf("\nnumber is positive");
    }
    else
   {
       if(x>0)
       {
             printf("\n number is negative");
       }
       else
       {
            printf("\n number is zero");
       }
   } 
  getch();
}

C Program to check number is positive or negative number using ternary operator

  below program is to check number is positive  , negative or zero using ternary operator.

#include<conio.h>
#include<stdio.h>
void main()
{
int x,no;
clrscr();
printf("Enter a no\n");
scanf("%d",&x);
(x<0)?printf("\n number is negative"):(x>0)?printf("\nnumber is positive"):printf("\nno is zero");
getch();
}

explanation:
This program helps us to understand how does ternary operator works.
 consider the line
(x<0)?printf("\nno is -ve"):(x>0)?printf("\nno is +ve"):printf("\nno is zero");
 This means that if x>0 then the statement beside '?' will get execute or else the statement after  : will get execute.But in this case its nested ternary operation so if first condition gets false then again condition is checked that  (x>0) and accordingly statement's will get executed.
 

1 comment: