Nested Loops homework problem.

Can anyone help me with this nested loops homework problem? I'm stuck on it and I'll be beyond grateful for anyone's help.

2. Request an integer value n.
Output a n x n grid from 1 to n inclusive where the following is true:
For each factor f of n:
If the current row number is equivalent to f, output f X’s.
Otherwise output blank spaces or lines (for non-factor rows).

Example Output (input in bold italics)
Enter an integer: 6
X
X X
X X X
(blank)
(blank)
X X X X X X

Last edited on
So what are you stuck on?

- reading an integer?

- determining if one number is a factor of another?

- printing some given number of X on a line.

In other words, code what you know then ask about where you're actually stuck.
Let me re-frame the question.

-> Request an integer value n.
-> Loop through 1 to n (let the counter variable be named 'i').
-> If the counter variable 'i' divides n evenly, print 'i' number of Xs.
-> Print a new line after every iteration.

So you're gonna require a for-loop to iterate 1 through n and another for-loop inside this for-loop to print Xs.
One for() loop only:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
// Example program
#include <iostream>
#include <string>
using namespace std;

int main()
{
    unsigned n;
    string str;
    
    cout << "Enter a positive integer pls: ";
    cin >> n;
    
    for (uint i=1; i <= n; ++i)
    {
        str = '\0';
        if (n % i == 0)
            cout << str.append(i, 'X');
        cout << "\n";
    }
    cout << "Done";
}
Topic archived. No new replies allowed.