write a c function, check if an int array only contains 1 and 2

Solution for write a c function, check if an int array only contains 1 and 2
is Given Below:

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[]);
``````

Thanks!

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;
}
``````

``````#include <stdio.h>
int only12(const int nums[], int size){
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 size = 5;
int r = only12(nums, size);
printf("%d",r);
}
``````

In the code above, we find the size of the array and iterate over it using a for loop. In the for loop, we see if nums[i] is something other than 1 or 2 and we set `result` to 0 if that’s the case. At the end of the function, we return the `result`.
As pointed out in the comments, using `sizeof(nums)/sizeof(nums[0]);` won’t work, so I have passed `size` as a parameter.