Thursday, February 17, 2011

Decision Making and Branching

Write a program that will read the value of x and evaluate the following function
y = 1, for x < 0
y = 0, for x = 0
y = -1, for x < 0
using
(a) nested if statements,
(b) else if statements, and
(c) conditional operator ?:

#include <stdio.h>
void main()
{
int x,y,z;
clrscr();
printf("a) Enter the value of x:");
scanf("%d",&x);
if(x>0)
printf("y=1");
if(x==0)
printf("y=0");
if(x<0)
printf("y=-1");
printf("\nb) Enter the value of x:");
scanf("%d",&x);
if(x>0)
printf("y=1");
else if(x==0)
printf("y==0");
else if(x<0)
printf("y=-1");
printf("\nc) Enter the value of x:");
scanf("%d",&y);
z=(y>0?1:(x<0)?1:0);
printf("y=%d",z);
getch();
}

No comments:

Post a Comment