Why does my program accept one integer too many and input one too few?

前端 未结 3 545
甜味超标
甜味超标 2021-01-25 15:12

I\'d like to understand why the program allows me to input 3 integers when I have defined SIZE as 2. And when it returns the array it only returns two numbers NOT the three I ha

3条回答
  •  不思量自难忘°
    2021-01-25 16:09

    why the program allows me to input 3 integers

    This loop runs exactly 2 times:

    for (count=1;count<=SIZE;count++){
            scanf("%d\n",&myArray[count]);
        }
    

    But as you used \n in the scanf(), this scanf() waits until you give any whitespace.

    Proper Input code:

    for (count=0;count

    And when it returns the array it only returns two numbers

    Your original output code prints first number correctly, But your second number is garbage value.

    Proper Output Code:

    for (count=0;count

    So Full Code goes like this:

    //C How to Program Exercises 2.23
    #include 
    #include 
    #define SIZE 2
    
    int main (void){
    
        int myArray[SIZE];
        int count;
        printf("Please enter 5 integers\n");
        for (count=0;count

提交回复
热议问题