### Thread: Array Question

1. No Profile Picture
Registered User
Devshed Newbie (0 - 499 posts)

Join Date
Feb 2013
Posts
8
Rep Power
0

#### Array Question

Lets say i make an array with 5 variables.
1, 1, 2, 3, 1
how do i check the array and display their are 3 ones ?
2. take one loop and compare all element with 1 and take one count variable and increment it on success.
3. No Profile Picture
Registered User
Devshed Newbie (0 - 499 posts)

Join Date
Mar 2013
Posts
101
Rep Power
0
Lets say i make an array with 5 variables.
1, 1, 2, 3, 1
how do i check the array and display their are 3 ones ?

Easy.

Code:
```#include<stdio.h>

int main()
{
int numbers[5] = {2,1,3,1,1};
short ones = 0,i = 0;
for(i;i <= 4;i++)
{
if(numbers[i] == 1)
{
ones++;
}
}
printf("%d",ones);
getchar();
return 0;
}```
try that out

#### Comments on this post

• ptr2void disagrees : Don't just hand people answers to their homework!
• eramit2010 disagrees : dont give ready made code just give some logic.
4. No Profile Picture
Registered User
Devshed Newbie (0 - 499 posts)

Join Date
Feb 2013
Posts
8
Rep Power
0
Thank you , i got it all figured out :cheers:
5. New homework assignment,
rewrite the given program without the if statement. No reserved words are permitted in the for loop block.
6. Originally Posted by b49P23TIvg
New homework assignment,
rewrite the given program without the if statement. No reserved words are permitted in the for loop block.
it can be possible by conditional operator :D
or that is also not allowed :confused:
7. Good point, no ternary operator allowed!
(But OK, I didn't think of that. You win.)

?: /* NO! */
8. Originally Posted by b49P23TIvg
Good point, no ternary operator allowed!
(But OK, I didn't think of that. You win.)

?: /* NO! */

Code:
`ones=ones+!(numbers[i]^1);`

#### Comments on this post

• b49P23TIvg agrees : ones += numbers[i] == 1; /* may be simpler, I like ! and !! to convert to Boolean */