Author Topic: Help with C++  (Read 304 times)

Offline Kalkalash

  • Jr. Member
  • **
  • Posts: 644
  • aka Niko1992
    • View Profile
Help with C++
« on: 22-01-2013, 17:01:51 »
I currently have a small assignment on a programming course. I need to create a program in which the user can specify a number, let's call it n. The program then puts numbers from 1 to n on the first row as well as the first column and between them all the multiplications of the digits on the 1st row and column. I have the code working fine but I'm having trouble with the formatting. It should look like a nice clean table but it doesn't. Here's how it looks:


I tried to look info on tables on Google but couldn't really find anything useful.
Here's how the code looks like:
Quote
#include <iostream>

using namespace std;

int main () {
    int multiplier = 2;
    int input_number;
    int row = 1;
   
    cout << "Input number to multiply" << endl;
    cin >> input_number;
    cout << endl;
   
    while ( row <= input_number ) {
          cout << row;
               while ( multiplier <=  input_number ) {
                     cout << " " << row * multiplier << " ";
                     ++multiplier;
                     }
          multiplier = 2;
          ++row;
          cout << endl;
          }   
    system ("PAUSE");
}

Anyone here with any tips?
“Think of how stupid the average person is, and realize half of them are stupider than that.” - George Carlin

Offline gavrant

  • (Almost) retired dev
  • Developer
  • ******
  • Posts: 598
    • View Profile
Re: Help with C++
« Reply #1 on: 22-01-2013, 17:01:46 »
My knowledge of C++ is quite rusty by now, but maybe try setw for padding numbers with spaces?
I found this tutorial for setw: http://arachnoid.com/cpptutor/student3.html, see "1. Field Width" section there.

BTW, I think your code would look more elegant, so to speak, with for instead of while. For example, I'd replace:
Code: [Select]
int row = 1;
...
while ( row <= input_number ) {
    ...
    ++row;
}   
with:
Code: [Select]
for(int row = 1; row <= input_number; row++) {
    ...
}   

Offline Kalkalash

  • Jr. Member
  • **
  • Posts: 644
  • aka Niko1992
    • View Profile
Re: Help with C++
« Reply #2 on: 28-01-2013, 15:01:43 »
Oops, forgot to reply to this. Yeah, setw did the trick. Thanks for the help.
“Think of how stupid the average person is, and realize half of them are stupider than that.” - George Carlin