[Solved] Print numbers in columns c++


I want to print a string array containing numbers organized in
columns. The array contains {"2","1","3","16","8","3","4","1","2"}

I want to print them in this form

2       16        4
1       8         1
3       3         2

For the the given code of yours, you can do following changes to achieve the result.

  • Find the array length using sizeof(arr)/sizeof(*arr);.
  • Make a loop according to the size of your matrix. This is to iterate through the rows.
  • Using a second loop, until it gets to the maximum array length, print each array elements. The index increments according to the matrix size.
  • Make a line break after each time inner-loop has done printing.

PS: Using std::string array is a bad idea. You can use instead of that, simple arrays, std::array or std::vector, as it look like you want an integer array/ matrix.

See output HERE

#include <iostream>
#include <iomanip>
#include <string>

int main()
{
   std::string arr[]={"2","1","3","16","8","3","4","1","2"};
   const int arrlength = sizeof(arr)/sizeof(*arr);
   const int matrixSize = 3;

   for(int row = 0; row < matrixSize; ++row)
   {
      for (int index = row; index < arrlength ; index += matrixSize)
         std::cout << arr[index] << std::setw(5);
      std::cout << "\n";
   }

  return 0;
}

Output:

2   16    4    
1    8    1    
3    3    2 

0

solved Print numbers in columns c++