I'm trying to make a program in which you enter a number (n) and it prints (n-1) spaces followed by the "k" then on the next line, (n-2) spaces followed by "k" and so on until "k" has no spaces before it.
#include <iostream>
usingnamespace std;
int main ()
{
int len;
cout << "Enter a number: ";
cin >> len;
int i = 0;
int j = i + 1;
while (i < len)
{
while (j < len)
{
cout << " ";
j++;
}
i++;
cout << "#" << endl;
}
return 0;
}
so basically loop while there are more than 1 spaces and the initial space is n - 1.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
int n;
cout << "Enter n: ";
cin >> n;
--n;
while( n ) //loop while n is not 0
{
for( int i = 0; i < n; ++i ) //can you use for?
cout << ' ';
cout << 'K' << endl;
--n;
}
cout << 'K' << endl;
or instead of that while loop
1 2 3 4 5 6 7
while( n > -1 )
{
for( int i = 0; i < n; ++i )
cout << ' ';
cout << 'K' << endl;
--n;
}
Or you could just use 2 for loops.
[edit]Also int j = i + 1; is the same as int j = 1; in this case since i == 0.
actually you can ignore my code and just move line 12 inside of the first while loop :) You forgot to reset the value of j each time.
1 2 3 4 5 6 7 8 9 10 11 12
while (i < len)
{
int j = i + 1;
while (j < len)
{
cout << " ";
j++;
}
i++;
cout << "#" << endl;
}
#include <iostream>
usingnamespace std;
int main()
{
int len;
cout << "Enter a number: ";
cin >> len;
int i = 0;
do
{
int j = i + 1;
do
{
cout << " ";
j++;
} while( j < len );
cout << "#" << endl;
i++;
} while( i < len );
}
It seems to be almost correct but for some reason it is printing a " " even when j=len. This should not happen since the do while loop specifies j<len?