Build a pyramid with numbers between 1 and the inserted integer
i'm trying to build a pyramid with numbers between 1 and the inserted number. For example, if i insert 6 to the integer, that the piramid will be as there:
12345654321
234565432
3456543
45开发者_StackOverflow中文版654
565
6
I tried using a for loop but i get in any line one or ++ numbers to 6. This is the code:
#include<stdio.h>
#include <iostream>
#include <conio.h>
int main()
{
int i,j,d;
std::cin >> d;
for(i=1;i<=d;i++)
{
for(j=1;j<=i;j++)
printf("%d",j);
printf("\n");
}
getch();
return 0;
}
How can i solve this problem building a pyramid like the shown.
Since this is homework, I won't paste an algorithm, but here's a few hints:
This
12345654321
can be printed by counting from one to six and then back to one.This
__3456543__
means that for numbers smaller than n, you have to output a_
instead, where n depends on the level you are printing.Define your loop variables within the loop:
for(int i=1;i<=d;i++) ...
They are only interesting within the loop, and access outside the loop is usually an error, which is then flagged by the compiler.There's no need to for the
getch();
at the end. When you're in the debugger, you can put a breakpoint on the last line. If you aren't you don't want to have to press a key just to end your program.If you use
std::cout << j
andstd::cout << '\n'
for outputting, you don't needprintf()
either. (Once you want formatting, many will tell you thatprintf
format strings are easier. I don't believe that, but would accept it, if it weren't that you can crash any application with an ill-formedprintf
format string, while it's much harder to come up with a way to crash your app using streams.)
There you go:
for(j=i;j<=d;j++)
Also you forgot about formatting and the right side of the pyramid, but I think that's out of scope for this question and you can figure the code yourself :)
- Try to have the first line working the way you want.
- Repeat it d times, where d is the number entered by the user.
- Notice that on line l, numbers < l are replaced by spaces.
Consider this: you have D
rows, 1..D
. Six rows means your rows are numbered 1 to 6. Now, for each row d
:
- print
d-1
space characters. First row has no spaces, second has one and so on. - print the numbers
d..D
. So on the first line you print 1..6, on the second you print 2..6. - print the numbers
D-1..d
. So on the first line you print 5..1, on the second you print 5..2 - print a new line
精彩评论