0

This program takes in 10 integer values and stores them in a 2D array. Say if I enter numbers 1 through 10 I expect an output of 1 2 3 4 5 6 7 8 9 10. I don't want it in a matrix format. How can I accomplish this?

#include <stdio.h>

int main() {
    /* 2D array declaration*/
    int disp[2][3];
    /* Counter variables for the loop */
    int i, j;
    for (i = 0; i < 2; i++) {
        for (j = 0; j < 3; j++) {
            printf("Enter value for disp[%d][%d]:", i, j);
            scanf("%d", &disp[i][j]);
        }
    }
    // Displaying array elements
    printf("Two Dimensional array elements:\n");
    for (i = 0; i < 2; i++) {
        for (j = 0; j < 3; j++) {
            printf("%d ", disp[i][j]);
            if (j == 2) {
                printf("\n");
            }
        }
    }
    return 0;
}
chqrlie
  • 131,814
  • 10
  • 121
  • 189

3 Answers3

0

If you don't want it in a matrix format, simply don't print the line breaks. This means you should omit these lines:

if(j==2){
    printf("\n");
}

Without line breaks, your output will all be in one line.

Revise your code for displaying the array elements to something like this:

//Displaying array elements
       printf("Two Dimensional array elements:\n");
       for(i=0; i<2; i++) {
          for(j=0;j<3;j++) {
             printf("%d ", disp[i][j]);
          }
       }
Ryan Zhang
  • 1,856
  • 9
  • 19
  • How can I add the elements from the matrix into a variable? –  Jun 12 '22 at 16:27
  • I'm guessing you'd want to put them into an array. Declare an array and add `disp[i][j]` to the back of the array. – Ryan Zhang Jun 12 '22 at 16:28
  • I want to store numbers say in a variable called 'numbers' and print them from there. –  Jun 12 '22 at 16:35
  • Okay. You're going to need an array - in C you can't store them in an array. Define `int numbers[6]`. You could then, instead of `printf("%d ", disp[i][j])`, do `numbers[i*3+j] = disp[i][j]`. You can print out these numbers with `for(int i = 0; i < 6; ++i) printf("%d ", numbers[i]);` – Ryan Zhang Jun 12 '22 at 16:37
0

This part

            if (j == 2) {
                printf("\n");
            }

is adding the newline. The \n means ENTER. Remove the above and everything will be displayed in a single line as a result.

Lajos Arpad
  • 64,414
  • 37
  • 100
  • 175
0

We can clear find that "printf("\n");" is among the loop. This means that it will be run once every time the loop is looped. That is why your line is broken.

obsai
  • 11