0

I used a for loop to generate a list of strings, and I've been trying to make them print horizontally instead of vertically.

Currently: the list is printed vertically, up to 10.

Goal: To have the list printed horizontally.

Code for reference:

#include <iostream>
using namespace std;

int main()
{
int x = 10;
int y, z = 0;
int result;

for (z = 1; z <= x; z++)
{
    cout << '\n';
    for (y = 1; y <= z; y++)
    {
        result = z * y;
        cout << z << " * " << y << " = " << result << '\n';
    }
cout << '\n';   
}

}
  • 2
    Argh, [images are evil (and kill kittens)](https://meta.stackoverflow.com/questions/285551/why-should-i-not-upload-images-of-code-data-errors-when-asking-a-question). Producing output like your image requires a little thinking similar to when you were asked to print various shapes made of asterisks. Look at the relationships between lines, spaces, and the values being computed. – Dúthomhas Sep 10 '22 at 06:26
  • @ArminMontigny - Since the question has been re-opened, fell free to convert your comment into an answer. – selbie Sep 10 '22 at 08:37
  • @ArminMontigny Thanks for your answer. So I print each row out, changing x * y into a "blank string" if row's value gets higher than col. Could you please add it to the answer so I can accept it? – Joshua Cha Sep 10 '22 at 14:58

1 Answers1

0

For the first block of number (1x1 .. 5x5), here's something similar to your expected output.

for (int x = 1; x <=5 ; x++)    {
    for (int y = 1; y <= 5; y++) {

        if (y < x) {
            cout << "                      ";
        }
        else {
            cout << setw(3) << y << " x " << setw(4) << x << " = " << setw(4) << x * y << "     ";
        }
    }
    cout << endl;
}

Prints out this:

  1 x    1 =    1       2 x    1 =    2       3 x    1 =    3       4 x    1 =    4       5 x    1 =    5
                        2 x    2 =    4       3 x    2 =    6       4 x    2 =    8       5 x    2 =   10
                                              3 x    3 =    9       4 x    3 =   12       5 x    3 =   15
                                                                    4 x    4 =   16       5 x    4 =   20
                                                                                          5 x    5 =   25

I'll leave it as an exercise for extending this to another set of rows for the 6 through 10 times tables.

selbie
  • 100,020
  • 15
  • 103
  • 173