简体   繁体   中英

How do I print all array items on one line?

I have the following code which uses an array. When I run the program it shows the result 9 times on 9 different lines, but I want to show the result just once:

#include <stdio.h>

int main(void) {

    int sin_num[9];
    int num1;

    for (num1 = 0; num1 < 9; num1++) {
        printf("Enter your SIN number one by one:");
        scanf("%d", &sin_num);
    }

    for (num1 = 0; num1 < 9; num1++) {
        printf("%d \n", &sin_num[num1]);
    }
}

3 issue in your program:

  1. Read the scanf() manual page

    scanf("%d", &sin_num);` ^^^^^^^ here, sin_num is array of int, so scan should take it into its element and not to its base address.

    replace it with index as shown below, scanf("%d", &sin_num[i]);

     for (num1 = 0; num1 < 9; num1++) { printf("Enter your SIN number one by one:"); scanf("%d", &sin_num[i]); }
  2. Read the printf(3) manual page.

     printf("%d \\n", &sin_num[num1]); /* ^, here no need of & as you are looping over array. */ /* Correction => printf("%d \\n", sin_num[num1]); */ for (num1 = 0; num1 < 9; num1++) { printf("%d \\n", sin_num[num1]); }
  3. To avoid multiple lines

     printf("%d \\n", sin_num[num1]); /* ^^ as per your requirement, you don't need every element on new line so it should be removed. */ for (num1 = 0; num1 < 9; num1++) { printf("%d \\n", sin_num[num1]); }

Get rid of the "\\n" in your second for loop.

for(num1=0; num1<9; num1++) {
    printf("%d ", sin_num[num1]);
}
print("\n");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM