Frage

I need something in my program to determine the max of array: printarr[]

The function of the code is to print *'s for the amount of numbers that are entered by the user. Then the *'s have to be scaled by a factor of 30, so the number that has been entered most is represented by 30 *'s.

This is the code i have so far:

Can someone pls help me by finding a solution to determine the max of printarr[]

:)

#include <stdio.h>;

int main() {
int numbers[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };          
int i, j, n, x;
int one = 0, two = 0, three = 0, four = 0, five = 0, six = 0, seven = 0, eight = 0, nine = 0, ten = 0;

printf("Enter integers from 1 - 10\n");
printf("\nEnter -1 to finish input.\n\n");

for (i = 0; i <= 100; i++) {
    scanf("%d", &x);
    if (x == -1) {                                      
        break;
    }

    if (x == numbers[0]) {
        one++;
    }
    if (x == numbers[1]) {
        two++;
    }
    if (x == numbers[2]) {
        three++;
    }
    if (x == numbers[3]) {
        four++;
    }
    if (x == numbers[4]) {
        five++;
    }
    if (x == numbers[5]) {
        six++;
    }
    if (x == numbers[6]) {
        seven++;
    }
    if (x == numbers[7]) {
        eight++;
    }
    if (x == numbers[8]) {
        nine++;
    }
    if (x == numbers[9]) {
        ten++;
    }
}

int printarr[] = { one, two, three, four, five, six, seven, eight, nine, ten };

for (n = 0; n <= 9; n++){
    printf("\n%d: ", n);
    for (j = 1; j <= /* 30/max * */ printarr[n]; j++)
        printf("*");
}

printf("\n\nPress enter to close program!");
fflush(stdin);
getchar();
return 0;
}
War es hilfreich?

Lösung 2

To find the max of an array v of size size you can use something like this:

int find_max(int* v, size_t size) {
  int max=v[0];
  size_t i;
  for (i=0; i<size; ++i) {
    if (v[i] > max) max = v[i];
  }
  return max;
}

The precondition to this function is to have at least one element on the array. That's it, if the v array does not have any elements this function returns garbage.

Andere Tipps

I won't provide you a full solution, but I'll guide you through it.

In order to get the largest value, you should first pick the first element and pretend that it's the largest one. You save it in a variable called max for example.

Then you iterate on the array, when you find larger one, you assign it to max. After you iterate on the array, you'll get the largest number in max.

Example:

myArr = {3,1,6,2}

max is 3, then we iterate. Is 1 larger than 3? No.. Is 6 larger? Yes, we assign 6 to max. Is 2 larger than 6? No, we leave max. Final result: max = 6.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top