开发者

How to find the largest and smallest number in an array in c

I have to find a way to display the Maximum and Minium number in an array, the size of the array is 100 and will not exceed that and there is not need for input validation. The program will keep asking for input until 0 is encountered and it too will get added to the array.

I have everything figured out except how to keep track which is the largest and smallest value. I'd appreciate it if someone can fix my code or show me.Another problem I'm having is getting the loop to terminate and do max/min calculation within the while loop when the input is equal to 0.

/*
 ============================================================================
 Name        : test.c
 Author      :
 Version     :
 Copyright   : Your copyright notice
 Description : Hello World in C, Ansi-style
 ============================================================================
 */

#include <stdio.h>
#include <stdlib.h>
#define n  100
int main(void){


 int numbers[n];
 int i = 1;
 int j;
        int input;
 int maxvalue;
 int minvalue;

   printf("Enter the next array element>");

input = scanf("%d", &numbers[100]);



while (input != 0){

  numbers[i] = input;
  i++;
  printf("Enter the next array element, while loop>");
  input = scanf("%d", &numbers[n]);
  if (input == 0){
printf("Enter the next array element, if loop");
   numbers[i] = 0;

   for (j =2;j <= i; j++){
    minvalue = numbers[1];

    j++;
    if (numbers[j] > minvalue){
     maxvalue = numbers[j] ;
    }
    else{
     minvalue = numbers[j] ;
    }

   }


  }
 }


printf("%f\t", maxvalue);

printf("%f\n", minvalue); 
 }

EDIT: I took all off your suggestions and edited my code. This is my code below. However, it's output isnt what I'm expecting.

#include <stdio.h>
#include <stdlib.h>
#define N  100
int main(void){


    int numbers[N];
    int i = 0;
    int j;
        int input;
    int maxvalue;
    int minvalue;

            printf("Enter the next array element>");

scanf("%d", &input);



while (input != 0){

        numbers[i] = input;
        i++;

        if (input == 0){
                   i++;
            numbers[i] = 0;
                        minvalue = numbers[0];
                        maxvalue = numbers[0];
                        for (j=0;j<=i-1;j++){

                            if (minvalue >= numbers[j]){
                                minvalue = numbers[j];
                            }else if (maxvalue <= numbers[j]){
                                maxvalue = numbers[j];
                            }


                        }

/* min = value of first array element
max = value of first array element

begin loop for each array element, index = 0 to (n-1)

--- if array element value is less than min, set min to this value
--- if array element value is more than max, set max to this value

increment index and repeat loop til last index is completed

average = sum / number of elements (n).
max and min will hold their correct values.*/




        }
                printf("Enter the next array element, while loop>");
    scanf("%d", &input);
    }


printf("%d\t", maxvalue);
printf("%d", minvalue);
    }

This is the output, I'm getting! Can someone solve this for me.

Enter the next array element>1
Enter the next array element, while loop>2
Enter the next array element, while loop>3
Enter the next array element, while loop>0
12190144 l6Press [Enter] to close the terminal

FINAL EDIT: I SOLVED THIS ON MY OWN. I put the min/max checking outside the master WHILE loop, this allowed the input of 0 to be entered in the array.

#include <stdio.h>
#include <stdlib.h>
#define开发者_高级运维 N  100
int main(void){


    int numbers[N];
    int i = 0;
    int j;
        int input;
    int maxvalue =1;
    int minvalue = 1;
            printf("Enter the next array element>");

scanf("%d", &input);
minvalue = input;
maxvalue = input;



while (input != 0){
    numbers[i] = input;

    ++i;
                printf("Enter the next array element>");
    scanf("%d", &input);

if (input == 0){
numbers[i] = 0;
  ++i;

  }

}
for (j =0;j<i;j++){
 if (numbers[j] >= maxvalue){
                                maxvalue = numbers[j];
                            }
                            if(numbers[j] < minvalue){
                                minvalue = numbers[j];
                            }

}

printf("%d\t", maxvalue);
printf("%d\n", minvalue);

    }


First of all, you're assigning input to the return value of scanf(). This is the number of items assigned by the call, and since you say the input will always be correct, this value will always be 1.

Secondly, you're writing past the end of the numbers[] array with the line:

input = scanf("%d", &numbers[100]);

(you should do scanf("%d, &input) instead, and assign numbers[i] to input in your loop.

Finally, you don't need to recalculate maxvalue and minvalue by iterating through numbers[] every iteration of your loop. Instead, just compare them to input and assign them accordingly.

Hopefully this puts you on the right track.


It looks like your central problem is that you compare each number only against minvalue. That's fine for deciding whether to replace the current minvalue, but obviously it doesn't tell you anything about the relationship of each element to maxvalue.

Another problem: it makes sense to initialize minvalue from the first element, but not if you do it in the loop. That just invalidates all your prior work.

You need to do the same initialization with maxvalue as well. You should initialize that number to the first value.

You should also make a decision about calculating the min and max as you accumulate the data or in a pass through the data when done. What you don't want to do, however, is loop through past elements with every new one. That gives your program quadratic time complexity for no benefit.

Finally, don't tolerate crummy formatting. Debugging always involves studying the code and you will want it to always be perfectly formatted both to be professional about things and also to facilitate reading your own work.


You are asking two questions, about the strategy for the min / max computation and for the loop. Don't do that (to yourself) but solve one problem at a time. So first put something like

signed int input[] = { 8, -5 , /* some more values */ };
size_t const n = sizeof input/ sizeof input[0];

at the start and forget about your scanf problems.

Then wrap your min/max detection in the appropriate loop instruction.

Then compile your code with warnings on: e.g -Wall for gcc, but this might vary for your compiler.

Mine the tells me something:

test-numbers.c:21: warning: 'maxvalue' may be used uninitialized in this function test-numbers.c:22: warning: 'minvalue' may be used uninitialized in this function

This tells you that you are doing something very wrong in not considering the starting point of your algorithm well.


I've reindented your code and replaced lots of it with `/* ...PLACEHOLDER... */

#include <stdio.h>
#include <stdlib.h>
#define N  100
int main(void) {
    int numbers[N];
    int i = 0;
    int input;
    int maxvalue;
    int minvalue;

    printf("Enter the next array element>");
    scanf("%d", &input);

    while (input != 0) {
        numbers[i] = input;
        i++;

        if (input == 0) {
            /* ...PLACEHOLDER... */
        }
        printf("Enter the next array element, while loop>");
        scanf("%d", &input);
    }
    printf("%d\t", maxvalue);
    printf("%d", minvalue);
}

Hopefully you can see what happens when you enter 1, or 2, or 3 and when you enetr 0.

Hint: maxvalue and minvalue values are never changed.

Another hint: how many times does the while() line execute?


Edit with example run

For this example run, code is on the left side, what happens is on the left side

        printf("Enter the next array element>"); |
        scanf("%d", &input);                     | Enter 42
                                                 |
        while (input != 0) {                     | input is 42, so you do the loop
            numbers[i] = input;                  | numbers[0] = 42
            i++;                                 | i = 1
                                                 |
            if (input == 0) {                    | input != 0; skip placeholder
                /* ...PLACEHOLDER... */          |
            }                                    |
            printf("Enter the next ...>");       |
            scanf("%d", &input);                 | enter 3
        }                                        | 
        while (input != 0) {                     | input is 3
            numbers[i] = input;                  | numbers[1] = 3
            i++;                                 | i = 2
                                                 |
            if (input == 0) {                    | input != 0; skip placeholder
                /* ...PLACEHOLDER... */          |
            }                                    |
            printf("Enter the next ...>");       |
            scanf("%d", &input);                 | enter 0
        }                                        | 
        while (input != 0) {                     | input is 0, skip while body
            /* ...PLACEHOLDER... */              |
        }                                        |
        printf("%d\t", maxvalue);                | maxvalue hasn't been initialized
        printf("%d", minvalue);                  | minvalue hasn't been changed


int cmp(const void *a,const void *b)
{
  return *(const int*)a-*(const int*)b;
}
...
qsort( numbers, 100, sizeof(numbers[0]), cmp );
printf("\nmin: %d\nmax: %d",numbers[0],numbers[99]);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜