简体   繁体   中英

How to find largest and smallest number in c

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

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

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

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++){...}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM