Basic While loops

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#include <iostream>
using namespace 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;
   }
Last edited on
Thanks very much, on another note, I am trying to do the same thing but with do while loops.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#include <iostream>
using namespace 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?
A do-while loop will ALWAYS execute at least once. Of you don't want this to happen, just use the normal 'while' loops.
Thanks both giblit and NT3 for clearing those things up!
to make things easier you can use the setw function
http://www.cplusplus.com/reference/iomanip/setw/?kw=setw

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <iostream>
#include <iomanip>
using namespace std;

int main()
{
    int num = 0;

    //gets data from user
    cout << "Please enter an Integer: " << flush;
    cin >> num;

   //print
    while(num > 0)
    {
        cout << setw(num) << '#' << endl;
        num--;
    }

    cin.ignore();
    return 0;

}
Last edited on
Topic archived. No new replies allowed.