Home > Mobile >  Printing out elements in an array
Printing out elements in an array

Time:10-04

Currently the code I have working is close but I'm having issues with printing the saved inputs. My output should look include the input elements above and then the elements reversed. Currently my code will only output the reversed array.

    #include <stdio.h>
    
    int main(void) {
       const int NUM_VALS = 4;
       int courseGrades[NUM_VALS];
       int i;
    
       for (i = 0; i < NUM_VALS;   i) {
          scanf("%d", &(courseGrades[i]));
       }
       //above cannot be modified. Adding print statment below is 
       //close but only prints 4

       printf("%d \n", courseGrades[i];
       for (i = NUM_VALS - 1; i > 0; i--) {
           printf("%d ", courseGrades[i]);
        }
        printf("%d \n", courseGrades[i]);
       return 0;
    }

CodePudding user response:

Just add code for printing array

for (i = 0; i < NUM_VALS;   i) {
      printf("%d ", courseGrades[i]);
   }
printf("\n");

CodePudding user response:

In the first for loop, the variable i is incremented to NUM_VALS which is 4. After that the line has printf(without closing brace)

printf("%d \n", courseGrades[i];

tries to prints coursesGrade[4] because of the reason I've mentioned. But there is no value at 4th index so it causes an undefined behaviour. So you need to remove that line, first.

In addition, as mentioned in comments above, you have an unneccessary line which is

printf("%d \n", courseGrades[i]);

If you insist on using it, then make it

printf("%d \n", courseGrades[0]);

OR

for (i = NUM_VALS - 1; i >= 0; i--) { // i>0 ==> i>=0
    printf("%d ", courseGrades[i]);
 }
  • Related