C prints only integer sign

I was wondering if (and how) it is possible to print only the sign of an array entry. For example, I would have something like

{1, -1, -1, 1} 

and I would like the result to look like

 + - - + 

I am new to C, and the only solution I can come up with is a kind of if (... < 0) contdition, the result of which is either + or - char. But it seems rather uncomfortable.

It is simply intended to create large β€œpatterns” that I draw with +1 and -1 . I would really be happy if someone could help.

+5
source share
4 answers

You are on the right track. This is the approach I would use. Although bitwise operations will also work, something needs to be said for readability.

 #include <stdio.h> int main(int argc, char **argv) { int numbers[4] = {1, -1, -1, -1}; for (int i = 0; i < (sizeof(numbers) / sizeof(numbers[0])); i++) { printf("%s ", (numbers[i] < 0 ? "-" : "+")); } printf("\n"); return 0; } 

Or you can build a line with sprintf() / snprintf() ; Not sure if you want to get it out or use it elsewhere.

+1
source

The way you mentioned is effective for this purpose. If you want to do the same in a different way, you can use the ternary operator as:

 a[i] < 0 ? printf("-"): printf("+"); 
+4
source

Take a look at this .

The + flag causes the output to show the sign of a number

0
source

You can do it like this:

 #include <stdio.h> int main (void) { int num [4] = {1, -1, -1, 1); int i; for (i = 0; i < 4; i ++) { if (num [i] < 0) { printf ("-"); } else printf ("+"); } return 0; } 
0
source

Source: https://habr.com/ru/post/1240908/


All Articles