Geeks Talk

Prepare for your Next Interview




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

This is a discussion on An array of 100 elements consists of only 0's and 1's within the C and C++ forums, part of the Software Development category; 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 ...


Go Back   Geeks Talk > Software Development > C and C++

Register FAQ Members List Calendar Mark Forums Read
  #1 (permalink)  
Old 05-16-2007
Expert Member
 
Join Date: Feb 2007
Posts: 1,279
Thanks: 0
Thanked 164 Times in 138 Posts
Geek_Guest is on a distinguished roadGeek_Guest is on a distinguished road
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
Reply With Quote
Sponsored Links
  #2 (permalink)  
Old 06-26-2007
Junior Member
 
Join Date: Jun 2007
Location: Argentina
Posts: 9
Thanks: 0
Thanked 0 Times in 0 Posts
mdk69 is on a distinguished road
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
Reply With Quote
Reply

  Geeks Talk > Software Development > C and C++


Thread Tools
Display Modes


Similar Threads

Thread Thread Starter Forum Replies Last Post
convert one dimansional array to two dimansional array Geek_Guest C and C++ 6 12-22-2007 04:17 AM
Winrunner does not recognize all elements of the screen Geek_Guest WinRunner 0 04-12-2007 01:40 PM
Sorting elements JobHelper C and C++ 0 01-05-2007 06:45 AM
XML - Elements in Document Type Definitions (DTD) Lokesh M AJAX & XML 0 06-14-2006 11:51 AM
Learning Series - XML Elements, Attributes, Entities Lokesh M AJAX & XML 0 05-15-2006 11:11 AM


All times are GMT -4. The time now is 01:34 AM.


Powered by vBulletin® Version 3.6.8
Copyright ©2000 - 2008, Jelsoft Enterprises Ltd.
Search Engine Optimization by vBSEO 3.1.0
Copyright © 2008 GeekInterview.com. All Rights Reserved