RobT
RobT

Reputation: 31

How do I print the rest of these numbers?

My assignment is as follows:

Print numbers 0, 1, 2, ..., userNum as shown, with each number indented by that number of spaces. For each printed line, print the leading spaces, then the number, and then a newline. Hint: Use i and j as loop variables (initialize i and j explicitly). Note: Avoid any other spaces like spaces after the printed number. Ex: userNum = 3 prints:

0
 1
  2
   3

So far I have:

#include <iostream>
using namespace std;

int main() {
  int userNum  = 0;
  int i = 0;
  int j = 0;


  for (i; i <= userNum; i++)
  {
    for (j; j <= userNum; j++)
    {
      cout << userNum << endl;
    }   
  }   

  return 0;
}

I'm still new to this. How do I loop in the rest of the numbers and spaces?

Upvotes: 3

Views: 9920

Answers (1)

Your loops are nested syntactically, but not semantically, since j is only initialised outside the loops. Also, you're printing userNum which is most definitely not what you should be printing.

Think about why two nested loops are required: one to count up from 0 to userNum, and another one (the inner one) to count the spaces before each of these numbers. The second has to be a loop as well, because the number of spaces depends on how far the first loop has gotten so far.

Try modifying your loops so that the loop over i takes care of the numbers, and the loop over j takes care of the spaces.

Hint: you can (and should) declare loop variables inside the first part of the for construct:

for (int i = 0; i <= userNum; ++i) {
  for (int j = 0; j <= /*something*/; ++j) {

Since this is obviously a learning exercise, I am intentionally not giving out a full answer.

Upvotes: 4

Related Questions