Skip to content

Instantly share code, notes, and snippets.

@mmstick
Last active August 29, 2015 14:03
Show Gist options
  • Save mmstick/30cb8716eb4c05ef6cbe to your computer and use it in GitHub Desktop.
Save mmstick/30cb8716eb4c05ef6cbe to your computer and use it in GitHub Desktop.
An example of how to print in columns from top to bottom in C++.
#include <iostream>
#include <string>
using namespace std;
int main() {
// Initial variables for the list
int listSize = 26;
int numOfColumns = 6;
string list[] = {"A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L",
"M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"};
int lastRowCount = listSize % numOfColumns;
// Determine number of rows to print to.
int numOfRows;
if (lastRowCount != 0) {
numOfRows = listSize / numOfColumns + 1;
} else {
numOfRows = listSize / numOfColumns;
}
// Initial variables for the printer state.
int currentRow = 1;
int currentIndex = 0;
bool printing = true;
// Print the list from top to bottom until the printer is turned off.
while (printing) {
if (currentRow < numOfRows || lastRowCount == 0) {
for (int column = 1; column < numOfColumns; column++) {
cout << list[currentIndex] << " ";
if (column >= lastRowCount + 1 && lastRowCount != 0) {
currentIndex += numOfRows - 1;
} else {
currentIndex += numOfRows;
}
}
cout << list[currentIndex] << endl;
currentRow++;
currentIndex = currentRow - 1;
} else {
for (int index = 1; index <= lastRowCount; index++) {
cout << list[currentIndex] << " ";
currentIndex += numOfRows;
}
printing = false;
cout << endl; // Extra newline at the end to cleanly exit the program.
}
}
return 0;
}
/* Output Example:
* A F K O S W
* B G L P T X
* C H M Q U Y
* D I N R V Z
* E J
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment