-6

my confusion is that how in the program the number of positive and negative numbers are calculated by writing that piece of code shown. explain these code please!

int num[5], i, neg = 0, pos = 0;

printf("enter any 5 numbers");
for (i = 0; i <= 4; i++)
    scanf("%d", &num[i]);
for (i = 0; i <= 4; i++) {
    num[i] < 0 ? neg++ : (pos++);
}
printf("\nnegative elements=%d", neg);
printf("\npositive elements=%d", pos);
getch();
chqrlie
  • 131,814
  • 10
  • 121
  • 189

4 Answers4

1
 num[i]<0?neg++:(pos++);

Here, If number less then zero then condition become true and count the negative numbers and If number not less then zero then condition become false and count positive numbers.

msc
  • 33,420
  • 29
  • 119
  • 214
1

The line

num[i]<0?neg++:(pos++);

means- compare num[i] to 0, if it is lower, increase the variable neg. Otherwise (num[i] >= 0), increase the variable pos.

hope this helps

Inbaral
  • 59
  • 10
0

Since, most answers have explained the ternary operator, I need not do it again. The neg++ post-increments the previous value of neg variable. And the same goes for pos++. Here's a link on post/pre increments.

WhiteSword
  • 101
  • 9
0

The ternary operator used as an expression statement evaluates like an if statement:

num[i] < 0 ? neg++ : (pos++);

is equivalent to

if (num[i] < 0)
    neg++;
else
    pos++;

This kind of coding is not considered good style, and there are other issues in the code fragment posted:

  • the return value of scanf() should be checked to avoid undefined behavior if the input cannot be converted to an int.

  • the loop index should be compared to the array size with i < 5 instead of using the <= operator and a close but different constant.

  • output lines should be terminated with newline, not initiated with one.

  • getch() is a non standard function. Its purpose is to force a pause before the program exits. Fixing shortcomings of the environment inside the program is a sad workaround. Opening a terminal window to execute programs is a better alternative: it allows the programmer to observe all program output including any extra runtime messages occurring upon program termination.

chqrlie
  • 131,814
  • 10
  • 121
  • 189
  • Thanks for these valuable tips, i'm little confused about how to check the scanf() return value and last one how to open a terminal window to execute program. – Muktesh Jul 06 '17 at 05:27
  • `scanf()` returns the number of successful conversions. In your case it should return `1` if an integer number was stored into `num[i]`. To open a terminal window, in Windows use the start menu, run, `cmd.exe`. – chqrlie Jul 06 '17 at 07:06