Thursday, 15 September 2011

How to find largest and smallest number in c -



How to find largest and smallest number in c -

i have found solution in particular size of array. however, how can largest , smallest numbers without asking input size of array? thanks

e.g. homecoming 65 , -1 when input numbers 1, 0, -1, 5, 43, 65. want ignore step entering size of array 6 case.

#include<stdio.h> int main(){ int a[50],size,i,big,small; printf("\nenter size of array: "); scanf("%d",&size); printf("\nenter %d elements in 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); homecoming 0; }

i'll go 1 further. don't need array in first place, thereby making size-input-avoidance trivial (there no need it, because there no array):

#include <stdio.h> int main() { int val; printf("enter number: "); fflush(stdout); if (scanf("%d", &val) == 1) { int big = val, little = val; { if (big < val) big = val; if (val < small) little = val; printf("enter number: "); fflush(stdout); } while (scanf("%d", &val) == 1); printf("largest element: %d\n",big); printf("smallest element: %d\n",small); } homecoming 0; }

c

No comments:

Post a Comment