Outputting a line N amount of times

Hi, so I am writing a program for one of my classes. I have to output the message "Happy-Birthday" N amount of times given the user's input. I have this titled as "userrows." If the user types 6, the code should output "Happy-Birthday" 6 times and in 6 rows, and if the first row starts with "Happy" the second row needs to start with "Birthday". I can get it in 6 rows, but am struggling to get it to print across the row 6 times and in the right order. If you guys could help me understand, I would greatly appreciate it!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
#include <iostream>
#include <iomanip>
#include <string>
using namespace std;

int main ()
{
  //variable delcaration//
  int userrows;
  int useranswer = 2;
  string first = "Happy";
  string second = "Birthday";

  //program logic//
  for (int a = 2; (a = useranswer);)
  {
   if((useranswer == 1))
   {
       return 0;
   }
   else if ((useranswer == 2))
   {
    cout << "Enter the number of rows." << endl;
    cin >> userrows;
    if ((userrows <=0))
    {
        cout << "Error! Please enter a positive integer." << endl;
        cin >> userrows;
    }

    for (int i = 0; i < userrows; i++)
    {
      if (userrows % 2 == 0)
      {
        cout << first + "-" + second << endl;
      }
      else
      {
          cout << second + "-" + first << endl;
      }
    }
    cout << "Run again? 2 for yes, 1 for no" << endl;
    cin >> useranswer;
    }
    if((useranswer == 1))
    {
        return 0;
    }
  }
}

You got the swapping idea right, though if you swap on even numbers, then you pring twice the same line (swap on even, line start with "Happy", don't swap on odd, line start with "Happy" again ).
The outer loop handles the "per row" order of the word, so the only thing you're missing is to repeat said word N times in that rows, which ammounts to simply another loop.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
	vector<string> words = { "Happy", "Birthday" };
	int rows;

	cout << "Input: ";
	cin >> rows;

	auto word1 = words.begin(), word2 = words.begin() + 1;
	for (size_t i = 0; i < rows; i++)
	{
		for (size_t j = 0; j < rows; j++)
		{
			cout << *word1 << " " << *word2 << " ";
		}
		swap(word1, word2);
		cout << endl;
	}
Last edited on
awesome! Thanks!
Topic archived. No new replies allowed.