-
An array of 100 elements consists of only 0's and 1's
An array of 100 elements consists of only 0's and 1's. One should count the number of 1's or 0's with a very few lines of C program. One method is to sum all the elements to get the number of 1's. But there should be a built-in command to get the answer in a single line of program, I suppose. Please notify me if anyone knows the answer.
Question asked by visitor Vanitha
-
Junior Member
Re: An array of 100 elements consists of only 0's and 1's
in C you can do it in one line
for(i = 0; i < ARR_SIZ ; i++) (num[i] == 1) ? ones++: zeros++;
a sample program could be...
------------------
#include <stdio.h>
#define ARR_SIZ 100
int main()
{
int num[ARR_SIZ],
i,
ones,
zeros;
ones = 0;
zeros = 0;
/* array fill */
for (i = 0; i < ARR_SIZ; i++)
num[i] = (i % 2) == 0 ? 1: 0;
/* array processing */
for(i = 0; i < ARR_SIZ ; i++)
(num[i] == 1) ? ones++: zeros++;
printf("\nones: %d\tzeros: %d\n",
ones,
zeros);
return 0;
}
------------
hth
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules