Given an array of ints, return 1 if every element is a 1 or a 2, otherwise return 0;
only12([1,2,2]) -> 1
only12([1,4,2,4]) -> 0
only12([2,1]) -> 1
only12([1,2,12]) -> 0
only12([]) -> 1
only12(NULL) -> 0
prototype:
int only12(const int nums[]);
Any advice? Thanks!
updated answer from HiEd : The result is 1 even the array includes 3.
// answered by HiEd
#include <stdio.h>
int only12(const int nums[])
{
int size = sizeof(nums)/sizeof(nums[0]);
int i;
int result = 1;
for(i = 0; i < size; i++)
{
if(nums[i] != 1 && nums[i]!=2 )
{
result = 0;
}
}
//printf("%d",result);
return result;
}
int main()
{
const int nums[5]= {1,2,3,1,1};
int r = only12(nums);
printf("%d",r);
}
After reading Gerhardh's comment, I decided to give value for size in the function, then the program runs. but still did not get this part:
only12([]) -> 1
this is the code updated:
#include <stdio.h>
#include <stdlib.h>
int only12(const int nums[]);
int only12(const int nums[])
{
size_t i, size = 5;
int result = 1;
for(i = 0; i < size; i++)
{
if(nums[i] != 1 && nums[i] != 2 )
{
result = 0;
}
}
return result;
}
int main()
{
const int nums[5]= {1,2,2,1,3};
printf("%d", only12(nums));
return 0;
}