Reputation: 3
I have found the solution in particular size of array. However, how can I get the largest and smallest numbers without asking to input the size of the array? thanks
e.g. It will only return 65 and -1 when I input numbers like 1, 0, -1, 5, 43, 65. I want to ignore the step for entering the size of the array which is 6 for this case.
#include<stdio.h>
int main(){
int a[50],size,i,big,small;
printf("\nEnter the size of the array: ");
scanf("%d",&size);
printf("\nEnter %d elements in to the array: ", size);
for(i=0;i<size;i++)
scanf("%d",&a[i]);
big=a[0];
for(i=1;i<size;i++){
if(big<a[i])
big=a[i];
}
printf("Largest element: %d",big);
small=a[0];
for(i=1;i<size;i++){
if(small>a[i])
small=a[i];
}
printf("Smallest element: %d",small);
return 0;
}
Upvotes: 0
Views: 2067
Reputation: 66194
I'll go you one further. You don't need an array for this in the first place, thereby making the size-input-avoidance trivial (there is no need for it, because there is no array):
#include <stdio.h>
int main()
{
int val;
printf("Enter number: ");
fflush(stdout);
if (scanf("%d", &val) == 1)
{
int big = val, small = val;
do
{
if (big < val)
big = val;
if (val < small)
small = val;
printf("Enter number: ");
fflush(stdout);
} while (scanf("%d", &val) == 1);
printf("Largest element: %d\n",big);
printf("Smallest element: %d\n",small);
}
return 0;
}
Upvotes: 3
Reputation: 1104
could define a macro which lets you calculate the number of entries in an array
#define ArrayLength(arr) (sizeof(arr)/sizeof(arr[0]))
...
int x;
for(x=0;x<ArraLength(myArray);x++){...}
Upvotes: 0