Simple question. I am trying to build a simple script that will ask you for a number. That integer will be the amount of numbers you will enter in total. Then your program finds the biggest number and the smallest. And I have build that. Easy.
int CHECK=100;
int a[50],size,i,max,min;
printf("\nEnter the size of the array: ");
scanf("%d",&size);
printf("\nEnter %d numbers: ", size);
for(i=0;i<size;i++)
scanf("%d",&a[i]);
}
max=a[0];
for(i=1;i<size;i++){
if(max<a[i])
max=a[i];
}
printf("\nLargest element: %d",max);
printf("\n");
min=a[0];
for(i=1;i<size;i++){
if(min>a[i])
min=a[i];
}
printf("Smallest element: %d",small);
printf("\n");
return 0;
}
My question is, how can I tell to check for conditions. For instance, the user can input only positive numbers and smaller than 100. So if you enter -4 or 201 an Error has to be displayed telling you to try again. Any ideas as of how we can do that in a simple way. Or even point me to the right direction.
I appreciate it. Thank you.
50) on how many numbers can be accepted. Designing programs to not have static limits is generally preferable.scanf()is terrible for inputting values, because if it can't match the input to the format string (e.g. if a letter like "A" was typed) then it will leave the remaining characters in the input buffer and they will screw up the next call toscanf().scanf()with something nicer, likefgets()followed bysscanf()(DO NOT usegets()because it can cause a buffer overflow!): What you need to do is check whether the result matched your expectations (e.g. the return value fromsscanf()should be 1, and the value should be in range), and if it's not then print an error message and do--i, so that the effect of the loop causesito remain unchanged on the next loop cycle.