Write C++ Nested Loop Program to Print 0-userNum

  • C/C++
  • Thread starter ineedhelpnow
  • Start date
  • Tags
    C++ Loops
In summary, someone is struggling to solve a problem that was given to them with no hints. They are asking for help, but also state that they don't need any help.
  • #1
ineedhelpnow
651
0
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​

Sample program:

Code:
#include <iostream>
using namespace std;

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

   <STUDENT CODE>

   return 0;
}

someone help me! i don't know how to do this!
the indents at the top arent supposed to be that big. just one extra space for each but i had to use the indent thing so it made a HUGE space.
 
Technology news on Phys.org
  • #2
Use a nested loop. The idea is that for each number $j$ the inner loop will make the spaces because it will run for $j$ number of times.
 
Last edited:
  • #3
(Giggle) yes the instructions say to use a nested loop but i don't know how. i actually did this problem a while ago but i can't remember how i did it.
 
  • #4
Hint:

Code:
0
    1
        2
            3

If you rewrite it in words, it looks like this:

Code:
0
SPACE 1
SPACE SPACE 2
SPACE SPACE SPACE 3

Notice a pattern? Looks like for all numbers N from 0 to 3, it prints out N spaces, and then that number. So you can use two loops here: the outer loop runs N from 0 to the user input, and the inner one takes care of printing as many spaces as required each time (equivalently, you can write a "print_n_spaces" function to help you, probably using a loop).

Remember, programming is predominantly about problem solving. It's okay to ask for help if you're really stuck, but you really, really, really should dig in before giving up and saying you can't do it. For instance, a problem solving trick could be to try and replicate the output for, say, N = 3. Then see how you can modify it to handle N = 4, and then try to generalize. Another technique is to work through what's going on on paper for a little while, and then extract the basic concept and code it up. Yet another technique (probably the most useful one) is to break up a problem into its constituent parts until they are easy to understand separately, code them up, and then put them back together into a solution to your problem - the print_n_spaces function I mentioned is an example of this.
 
  • Like
Likes hmmm27
  • #5
Couldn't somebody answer the question... I don't need hints.
 
  • #6
jgaudiojr said:
Couldn't somebody answer the question... I don't need hints.

I cleaned up your post to make it more civil. Please don't post using censored words.

Here at MHB, we don't just do people's work for them...we try to actually help. What have you tried so far in this assignment?
 
  • #7
Did you ever figure this one out? I am struggling on this one too, I am able to make it work except it throws in extra spaces at the end.
 
  • #8
LearnCode said:
Did you ever figure this one out? I am struggling on this one too, I am able to make it work except it throws in extra spaces at the end.

If you post your code, perhaps we can figure out why you are getting extra spaces at the end. :)
 
  • #9
it is giving me 4 spaces on a line after the last digit, I need the last digit to be the last line.
#include <iostream>
using namespace std;

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

/* Your solution goes here */
for(i=0; i<=userNum; i++) {
cout << i << endl;
for(j=0; j<=i; j++) {
cout << " ";
}
}
return 0;
}
 
  • #10
Your code prints the integer followed by output of spaces; the problem says "print" spaces and then the integer. So move "cout<<i<<endl;" after the inner "for j loop". Also your for j loop "prints" i+1 spaces; the problem says print i spaces. So you need to modify the for j loop slightly.
In future, wrap code tags around your code so that it's more readable.
 
  • #11
I am still not fully understanding what to do, this stuff is due tomorrow and I have been strugging throug it for 3 days. If someone could help me see exactly what I am doing wrong I would appreciate it. I tried another variation based on what I am being told but still not getting it.

Code:
int main() {
    
    int userNum = 3;
    int i = 0;
    int j = 0;
    
	while (i<=0) {
	    while(j<=userNum) {
	        cout << j << endl;
	        cout << " ";
	        j++;
	    }
	 
	    i++;
	}
	return 0;
}
 
  • #12
First, it looks to me like you want the outer loop to run from 0 to [m]userNum[/m], and then have the inner loop run from 0 to 1 less than the index of the outer loop. And only have the spaces printed by the inner loop, as follows:

Code:
int main() {
    
	int userNum = 3;
	int i = 0;
	int j = 0;
    
	while (i <= userNum) {
		while(j < i) {
			cout << " ";
			j++;
		}
	        cout << i << endl;	 
		i++;
		j = 0;
	}
	return 0;
}
 
  • #13
Thanks that was it, although I would like to understand how you came to it. I was about to start trying some crazy if/else statements
 
  • #14
The best I can tell you about how I came up with it is to mentally step through the code line by line, iterating the loops, to see what's happening and how it works. :)
 
  • #15
Another method is:

for (i = 0; i <= userNum; ++i){

for (j = 0; j < i; ++j){
cout << " ";}

cout << i << endl;
}
 
  • #16
holmesr2007 said:
Another method is:

for (i = 0; i <= userNum; ++i){

for (j = 0; j < i; ++j){
cout << " ";}

cout << i << endl;
}

I love that this just saved me in October 2020. I can't thank you enough for this! I was *so close* ... but close only counts in horseshoes and hand grenades, so I was still stuck. I feel like I could *almost* grasp the shape of the thing, but nooooot quite. Seeing this (combined with the thread advice in general) made a H U G E difference. TY again!
 
  • #17
Thank you so much for the explanation! I have the same question and was lost with the spaces. :0)
Nono713 said:
Hint:

Code:
0
    1
        2
            3

If you rewrite it in words, it looks like this:

Code:
0
SPACE 1
SPACE SPACE 2
SPACE SPACE SPACE 3

Notice a pattern? Looks like for all numbers N from 0 to 3, it prints out N spaces, and then that number. So you can use two loops here: the outer loop runs N from 0 to the user input, and the inner one takes care of printing as many spaces as required each time (equivalently, you can write a "print_n_spaces" function to help you, probably using a loop).

Remember, programming is predominantly about problem solving. It's okay to ask for help if you're really stuck, but you really, really, really should dig in before giving up and saying you can't do it. For instance, a problem solving trick could be to try and replicate the output for, say, N = 3. Then see how you can modify it to handle N = 4, and then try to generalize. Another technique is to work through what's going on on paper for a little while, and then extract the basic concept and code it up. Yet another technique (probably the most useful one) is to break up a problem into its constituent parts until they are easy to understand separately, code them up, and then put them back together into a solution to your problem - the print_n_spaces function I mentioned is an example of this.
 
  • #18
CrunchyAstrologer said:
Thank you so much for the explanation! I have the same question and was lost with the spaces. :0)
If you read through this thread you should see that it has already been solved.
 
  • #19
Mark44 said:
If you read through this thread you should see that it has already been solved.
Maybe, but it was the "hint" that let somebody solve it on their own'ish. Me too, for that matter : I couldn't figure out why anybody'd bother with a nested loop, until I realized they were printing one character at a time.
 
  • #20
hmmm27 said:
I couldn't figure out why anybody'd bother with a nested loop, until I realized they were printing one character at a time.
The outer loop prints the numbers 0, 1, 2, and so on, in each loop iteration, but you need an inner loop to print the appropriate number of spaces, one at a time, before printing the numbers.
 
  • #21
Mark44 said:
The outer loop prints the numbers 0, 1, 2, and so on, in each loop iteration, but you need an inner loop to print the appropriate number of spaces, one at a time, before printing the numbers.
My go-to thought was to the effect of using only one printing statement per line ; something like 'PRINT (n(spaces),n,newline)' ; thus my confusion.
 
  • #22
hmmm27 said:
My go-to thought was to the effect of using only one printing statement per line ; something like 'PRINT (n(spaces),n,newline)' ; thus my confusion.
Actually, you can do something like this.

C:
#include <stdio.h>

int main()
{    
    int n = 10;
    for (int i = 1; i <= n; i++)
    printf("%*d\n", i + 1, i);    
}

Output:
Code:
1
  2
   3
    4
     5
      6
       7
        8
         9
         10

The '*' width specifier in the printf() call will print a variable number of spaces, corresponding to the first parameter after the format list. See https://cplusplus.com/reference/cstdio/printf/ for more details.
 
  • Like
  • Informative
Likes hmmm27 and jim mcnamara
  • #23
Do I count nine spaces in front of the ##\tt 10## ? 😜
 
  • Like
Likes FactChecker
  • #24
BvU said:
Do I count nine spaces in front of the ##\tt 10## ? 😜
This is a perfect example why clever code should be reserved for clever code contests. Production code should almost always be boring.

BoB
 
  • #25
rbelli1 said:
This is a perfect example why clever code should be reserved for clever code contests. Production code should almost always be boring.

BoB
It's not really a good example of that. "%*d" will right-align your number in a field with a width of the second parameter. That is what you will be using mostly in boring production code.

Also I don't really know which code sample is more boring.
 
  • #26
How about:
C:
printf("%*d\n", i + 1, i + floor(log10(i + 1)));
😁
 
  • #27
willem2 said:
It's not really a good example of that.
The "clever" part is that justifying a number at n+1 characters produces a line with n spaces and one character. This is fine with the original example of zero through three that accidentally does what is needed. Once you get to 10 now justifying to n+1 characters does exactly what it is supposed to do which is not printing n spaces and a number.

The harder you assume that the code will only need to work with 0-9 the harder someone else (often future you) will use it outside of those limits.

BoB
 
  • #28
Alternative memory-intensive approach:
C++:
#include <iostream>
#include <new>

using namespace std;

// ...

char * spaces = new char[userNum+1];

cout << '0' << '\n';

for(int i = 1; i <= userNum; i++)
{
   spaces[i - 1] = ' '; spaces[i] = '\0';
   cout << spaces << i << '\n';
}

delete[] spaces;
 
Last edited:
  • Like
Likes Greg Bernhardt
  • #29
If you prefer pointer arithmetic, here's an alternative to the @pasmith 's "Alternative memory-intensive approach":
C++:
#include <iostream>
#include <new>
using namespace std;

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

   // "Student Code"
   char * spaces = new char[userNum+2];
   char * tail = spaces+userNum+1;
   *tail = 0;
   for(i = 0; i <= userNum; i++)
   {
      cout << tail << i << '\n';
      *(--tail)=' ';
   }
   delete[] spaces;
   return 0;
}
 

1. How do I start writing a C++ nested loop program?

To start writing a C++ nested loop program, you will need to open a text editor or an integrated development environment (IDE) such as Visual Studio or Code::Blocks. Then, create a new C++ file and include the necessary header files, such as #include . You can then begin writing your program by defining the main() function.

2. What is a nested loop in C++?

A nested loop in C++ is a loop inside another loop. This means that one loop is contained within the body of another loop. The inner loop will be executed repeatedly for each iteration of the outer loop. This allows for more complex and precise control over the flow of the program.

3. How do I print numbers in a nested loop in C++?

To print numbers in a nested loop in C++, you will need to use two for loops, one nested inside the other. The outer loop will control the number of rows and the inner loop will control the number of columns. Inside the inner loop, you can use the cout statement to print the desired numbers.

4. How do I use user input in a C++ nested loop program?

To use user input in a C++ nested loop program, you can use the cin statement to read in a value from the user. You can then use this value as the upper limit for your nested loop. This will allow the user to control the number of rows and columns to be printed in the program.

5. Can a nested loop in C++ be used for other purposes besides printing numbers?

Yes, a nested loop in C++ can be used for various purposes besides printing numbers. It can be used for tasks such as searching, sorting, and manipulating data in multidimensional arrays. Nested loops can also be used for repetitive tasks that require multiple levels of iteration.

Similar threads

  • Programming and Computer Science
Replies
1
Views
6K
  • Programming and Computer Science
Replies
2
Views
8K
  • Programming and Computer Science
Replies
2
Views
12K
  • Programming and Computer Science
Replies
4
Views
4K
  • Programming and Computer Science
Replies
12
Views
1K
  • Programming and Computer Science
Replies
4
Views
10K
  • Programming and Computer Science
Replies
15
Views
2K
  • Programming and Computer Science
Replies
25
Views
2K
  • Programming and Computer Science
Replies
2
Views
12K
  • Programming and Computer Science
Replies
3
Views
10K
Back
Top