beginner at loops

Ok so i'm trying to write a program that writes out first 20 lowercase letters and them sort them into a number of columns between 1-5 that the user types in...
i know how to get the letters out but i'm having trouble on how to put them into the columns, can someone please help me and tell me what my next step should be? i was able to write it with switches but we weren't supposed to do that...

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

int main()
{
	char ch;
	int columns;

	cout<<"enter number of columns(1-5): ";
	cin>>columns;

	for (ch= 'a'; ch<= 't'; ch++)
	{
		cout<<setw(5)<<ch;
	}
	return 0;
}
Last edited on
You mean like this?

1
2
3
4
5
6
columns = 5

abcde
fghij
klmno
pqrst



You won't be able to do that with setw() or any other built-in iomanip thing. You'll have to do it yourself.

It's actually pretty simple. Just count the characters as you output them. Then aftre every X characters are printed, print a new line.
1
2
3
4
5
6
7
8
9
10
char ch;
int columns;

cout<<"enter number of columns(1-5): ";
cin>>columns;
int counter = 0;
for (ch= 'a'; ch<= 't'; ch++,counter++)
  (!(counter%columns) && counter) ? cout << "\n" << ch : cout << ch;

cout << "\n";
Last edited on
Don't post full solutions, sahguanh. That doesn't help him learn, and it makes people think this site is a homework service.
Topic archived. No new replies allowed.