Results 1 to 2 of 2

Thread: An array of 100 elements consists of only 0's and 1's

  1. #1
    Geek_Guest
    Guest

    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


  2. #2
    Junior Member
    Join Date
    Jun 2007
    Answers
    9

    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
  •  
About us
Applying for a job can be a stressful and frustrating experience, especially for someone who has never done it before. Considering that you are competing for the position with a at least a dozen other applicants, it is imperative that you thoroughly prepare for the job interview, in order to stand a good chance of getting hired. That's where GeekInterview can help.
Interact