0
int main(){
    
    char answer; 
    int numbers[100];
    int i = 0;
    int size;
    int max = -9999;

    do{

        printf("Please enter an number: ");
        scanf("%d", &numbers[i]);
        printf("Would you like to keep adding numbers:(Y/N)");
        scanf("%c", &answer);
        scanf("%c");
        i++;

    }while(answer == 'Y');


    size = sizeof(numbers)/sizeof(numbers[0]);
    for(int j = 0; j<size; j++){
        if(numbers[j]>= max){
            max = numbers[j];
        }
    }

    printf("The max number is: %d", max);


return 0;

}

Hello beginner in C, here in my code i am trying to take an arbitrary amount of (the user enters Y if he/she wishes to enter another number.) input as integers and add them to an array and find the maximum of the input using a for loop, however i am not getting the correct output. What could be the error in my code?

mch
  • 9,424
  • 2
  • 28
  • 42
  • 1
    First off, don't **ever** use `scanf()` without checking the return value. Your `numbers[i]` might be uninitialized. – DevSolar Feb 08 '23 at 11:52
  • The FAQ: Please see [scanf() leaves the newline char in the buffer](https://stackoverflow.com/questions/5240789/scanf-leaves-the-new-line-char-in-the-buffer). This is the moment to get used to debugging - had you examined what `scanf("%c", &answer);` input (numerically) you'd find out something. – Weather Vane Feb 08 '23 at 11:53
  • When the user enters `17Y23...` the `` or `'\n'` is left in the buffer after the `scanf("%d", &numbers[i]);` reads the number. So, the `scanf("%c", &answer);` will read a `'\n'`, not the `'Y'`. You have to use `scanf(" %c", &answer);`, note the space before the `%c` to discard whitespaces. – mch Feb 08 '23 at 11:53
  • 1
    You also need to check the compiler warnings, such as for `scanf("%c");` which is very likelt to crash the program. – Weather Vane Feb 08 '23 at 11:56
  • 1
    You check the whole array, instead of just the values entered: `for(int j = 0; j < i; j++)` – Weather Vane Feb 08 '23 at 11:58
  • @Mert Erdem, "take an arbitrary amount " --> Code has `int numbers[100];` limiting to 100. Is that OK? If not, what limit?, 1000, million, billion, until all memory is used? – chux - Reinstate Monica Feb 08 '23 at 12:02
  • @Reinstate Monica Yes i know that it actually isn't arbitrary lets assume that the user wont enter past 100 numbers, the problem i have with my code is actually is related to the max output, here is a sample output: Please enter an number: 5 Would you like to keep adding numbers:(Y/N)Y Please enter an number: 9 Would you like to keep adding numbers:(Y/N)Y Please enter an number: 14 Would you like to keep adding numbers:(Y/N)Y Please enter an number: 26 Would you like to keep adding numbers:(Y/N)N The max of all numbers entered is: 1980104705% why is the max so large? and not 26 – Mert Erdem Feb 08 '23 at 12:06
  • Please read the comments carefully: they are explaining. Here is a repeat: You check the whole array, instead of just the values entered: `for(int j = 0; j < i; j++)`. The other elements you checked (from index `i` to `size-1`) were not initialised and have no values entered. They are indeterminate. – Weather Vane Feb 08 '23 at 12:11
  • This little program will be much easier — both for you and the user — if you change it slightly. One of the main problems you're having is reading the "would you like to keep adding?" answer, because `%c` is basically broken. (Not your fault.) But having to type Y or N is a nuisance for the user, too. So tell the user, "Type as many numbers as you want, and the word "done" (or control-D, or control-Z, or anything non-numeric) when you're done." Then just use `if(scanf("%d", &numbers[i]) != 1) break;` to exit the loop. (One way or another you always want to check scanf's return value.) – Steve Summit Feb 08 '23 at 12:26
  • The title of the question could be edited to "How do I use scanf() in a sane manner?", and the answer is "you don't". As a beginner, you should avoid `scanf` completely. When you are more comfortable with the language, your reasons for avoiding `scanf` will be slightly different, but you should continue avoiding it. – William Pursell Feb 08 '23 at 12:47

1 Answers1

2

Problems include:

Reading a '\n' when a letter is expected

scanf("%c", &answer); reads the character after the prior input of a number (example:9), which is likely the prior entry's '\n' Enter.

Use a space to consume leading white-space like '\n', space, tab, ...

// scanf("%c", &answer);
scanf(" %c", &answer);

Enable all warnings

Invalid/unnecessary code scanf("%c"); will raise a compiler warning with a well enabled compiler.

  • Best advice in this answer: enable all compiler warnings to save time.

Start at INT_MIN

The maximum input may be less than -9999.
INT_MIN in <limits.h>

// int max = -9999;
int max = INT_MIN;

Iterate to i

Rather than iterate to 100, only need to iterate to i, the count of values entered.

// for(int j = 0; j<size; j++){
for(int j = 0; j<i; j++){

Check return values

scanf() returns a value indicated the number of successful conversions. Use it to validated input successfully happened.

// scanf("%d", &numbers[i]);
if (scanf("%d", &numbers[i]) != 1) {
  ; // Report error with TBD code.
}

Do not loop too often

// } while(answer == 'Y');
} while(answer == 'Y' && i < 100); 

There is no reason to save an array of values

The maximum could be calculated as data is entered.

int max = INT_MIN;
do {
  int num;
  printf("Please enter an number: ");
  if (scanf("%d", number) != 1) {
    break;
  }
  if (num > max) {
    max = num;
  }
  printf("Would you like to keep adding numbers:(Y/N)");
  if (scanf(" %c", &answer) != 1) {
    break;
  }
} while (answer == 'Y' || answer == 'y');
printf("The max number is: %d", max);

Future Improvements

  • Handle values outside int range. Research intmax_t.

  • Detect case of no valid input entered. Research fgets()

  • Detect non-valid Y/N input. Research fgets()

  • Recover, rather than quit loop with invalid input.

chux - Reinstate Monica
  • 143,097
  • 13
  • 135
  • 256