By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
446,260 Members | 1,338 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 446,260 IT Pros & Developers. It's quick & easy.

Urgent Help Required in 'C' Language

P: 1
Freinds, I want some of you to help me write a program in 'C' to count the Total no. of +ves, total no of -ves and total no of zeros using ternary (Conditional Operaators). I am enclosing the Code fragment htat I have written. But it is giving a "Expression Syntax" Error.

#include <stdio.h>
#include <conio.h>

main()
{
int p, n, z, num, term, i, res ;
p = n = z = 0;
printf("Enter how many numbers you require? ");
scanf("%d",&term);
for (i = 1; i <=term; i++)
{
printf("Enter the number to check");
scanf("%d", &num);
if (num > 0 ? p = p + 1 : If (num < 0 ? n = n + 1 : z = z + 1));
}
printf("Positive numbers = %d\n", p);
printf("Negative numbers = %d\n", n);
printf("zero numbers = %d\n", z);
getch();
}


An Solution to this will be highly appreciated
Oct 3 '06 #1
Share this Question
Share on Google+
1 Reply


100+
P: 293
D_C
Expand|Select|Wrap|Line Numbers
  1. if (num > 0 ? p = p + 1 : If (num < 0 ? n = n + 1 : z = z + 1));
This is probably where it goes wrong. Typically, if else statements are used instead of question mark and colons. The two following code fragments (should) generate the same code.
Expand|Select|Wrap|Line Numbers
  1. if(expr)
  2.   DoTrue();
  3. else
  4.   DoFalse();
Expand|Select|Wrap|Line Numbers
  1. (expr? DoTrue():DoFalse());
Therefore, either
Expand|Select|Wrap|Line Numbers
  1. if(num > 0)
  2.  p++;
  3. else if (num < 0)
  4.        n++;
  5.      else
  6.        z++;
or
Expand|Select|Wrap|Line Numbers
  1. num>0?p++:num<0?n++:z++;
I'll confess I haven't used the ? : syntax in a long time, and usually it isn't used. I haven't tested the code, but I think it's correct. I know the if else code is.
Oct 3 '06 #2

Post your reply

Sign in to post your reply or Sign up for a free account.