C++ code for right triangle using WHILE loop
I need to print this triangle:
*
**
***
****
*****
******
*******
********
using a FOR and WHILE loop. I need help, I have already figured out the for loop 开发者_如何学Cversion I just have to convert it to while loop but everything I try is not giving me the correct output! Any help is appreciated!
My code so far:
#include <iostream>
using namespace std;
int main(int argc, char**argv) {
int i = 1;
int j = 1;
int N = 8;
while (i <= N)
{
i = i++;
while(j <= i)
{
cout<<"*";
j = j++;
}
cout<<endl;
}
}
I'll give you a hint (in the interest of making you do some figuring out yourself): You're forgetting to set j
back to 1
after the inner loop.
As it is now, when j
gets to be <= i
once, it stays that way and the inner loop is never entered again.
Also, while it's not directly related to your question, make sure never to do j = j++
or i = i++
; just do j++
and i++
(as Kshitij Mehta said in the comments). If you're interested in why, you can read this question and its answers.
What are the rules?
while (1)
{
cout << "*" << '\n';
cout << "**" << '\n';
cout << "***" << '\n';
cout << "****" << '\n';
cout << "*****" << '\n';
cout << "******" << '\n';
cout << "*******" << '\n';
cout << "********" << '\n';
break;
}
I'll give you a hint as well: i = i++;
doesn't do what you think it does.
I don't really know how to make it more succinct than this:
#include <iostream>
#include <sstream>
int main()
{
std::stringstream ss;
int i = 10;
while (i--)
std::cout << (ss<<'*', ss).str() << std::endl;
}
or as for loop, cutting down a line
for(int i=10; i--;)
std::cout << (ss<<'*', ss).str() << std::endl;
If you don't mind some less efficient code:
#include <iostream>
int main() { for(int i=1; i<10; std::cout << std::string(i++, '*') << std::endl); }
I can't see your triangle, but I think you need to set j to 1 before each loop on j:
while (i <= N)
{
i++;
j = 1;
while(j <= i)
{
cout<<"*";
j++;
}
cout<<endl;
}
#include <iostream>
using namespace std;
int main()
{
int i, j, N=7;
while(i <= N)
{
i++;
j = 1;
while(j <= i)
{
cout << "*";
j++;
}
cout << endl;
}
}
精彩评论