asdfg1234 - 1 year ago 115
C Question

# find greatest and smallest number in n

so I am confused to the meaning of the code. Why is

`greatestnumber = smallestnumber = n`
? And what is this comparison ?
`if(greatestNumber < i`
If for example I enter 3 numbers: 10,8,2 the output is

The largest number 2460 The smallest number 2 Average of 6

Why is it doing that?

``````#include <stdio.h>

int main()
{
int n,i;
int smallestNumber, greatestNumber, average;
int total = 0;
greatestNumber = smallestNumber = n;

printf("How many integer: ");
scanf("%d",&n);

for(int k=0; k<n; k++) {

scanf("%d",&i);
if(greatestNumber < i) {
greatestNumber = i;
}
else if (smallestNumber > i) {
smallestNumber = i;
}

total+=i;
}
printf("The largest number %d\n",greatestNumber);
printf("The smallest number %d\n",smallestNumber);
printf("Average of %d\n",total/n);
return(0);
}
``````

Answer Source

In your code `int n` is not initialized. This means that when you do this:

``````greatestNumber = smallestNumber = n;
``````

The value of `n` (which is a garbage) will be the same value inside `greatestNumber` and `smallestNumber`.

You need to initialize `N` first.

Check the following:

``````#include <stdio.h>

int main(void){
int a, b, c ,d, e,n=0;

a = b = c = d = e = n;

printf("A = %d\n", a);
printf("B = %d\n", b);
printf("C = %d\n", c);
printf("D = %d\n", d);
printf("E = %d\n", e);
printf("N = %d\n", n);

}
``````

Output:

``````A = 0
B = 0
C = 0
D = 0
E = 0
N = 0
``````

More over you should check the return of `scanf()` before you try to use it:

``````if ( scanf("%d",&n) != 1){
printf("Erorr, scanf.");
exit(1);
}
``````

and this line:

``````greatestNumber = smallestNumber = n;
``````

Move it after the `scanf`

Your program should look now like this:

``````#include <stdio.h>
#include <stdlib.h>

int main(void)
{
int n=0,i;
int smallestNumber, greatestNumber;
int total = 0;

printf("How many integer: ");
if ( scanf("%d",&n) != 1){
printf("Erorr, scanf 1.");
exit(1);
}

greatestNumber = smallestNumber = n;

for(int k=0; k<n; k++) {

if ( scanf("%d",&i) != 1){
printf("Error, scanf 2.");
exit(2);
}
if(greatestNumber < i) {
greatestNumber = i;
}
else if (smallestNumber > i) {
smallestNumber = i;
}

total+=i;
}
printf("The largest number %d\n",greatestNumber);
printf("The smallest number %d\n",smallestNumber);
printf("Average of %d\n",total/n);
return 0;
}
``````

Another important thing, do not treat the `return` statement like a function.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download