“Array Elements Equality Check Using First Element in C”
C
Medium
13 views
Problem Description
There are some numbers in an array and you need to find out whether all the numbers are same or different - how do you design comparison logic from the first element?
Official Solution
#include <stdio.h>
int main() {
int arr[] = {5, 5, 5, 5, 5};
int size = sizeof(arr) / sizeof(arr[0]);
int i;
int same = 1; // assume all are same initially
for (i = 1; i < size; i++) {
if (arr[i] != arr[0]) {
same = 0; // found a different element
break;
}
}
if (same)
printf("All numbers are SAMEn");
else
printf("Numbers are DIFFERENTn");
return 0;
}
Solutions (0)
No solutions submitted yet. Be the first!
No comments yet. Start the discussion!