Home > Blockchain >  Creating a Power Table - C
Creating a Power Table - C

Time:03-25

I'm attempting to create a power table in c using forloops, exponents, etc, but I'm new to c and haven't gotten particularly far on my own.

The code I've gotten to far is

#include <iostream>
#include <math.h>
#include <iomanip>
using namespace std;
int main() {

 char again='y';
  while (again == 'y'){
   int power, rc, thing;
  
  cout << "Please enter the power you wish to compute by. ";
  cin >> power;

  cout << "Please enter the maximum amount of rows and columns you would like to have. ";
  cin >> rc;

int i=0;
  while(i<=rc){
   cout << setw(5) << i << " ";
    i  ;
  }
    
  for(int i=0; i<=rc; i  ){
    cout << setw(5) << i << " ";
        thing = 1;
    thing = pow(power, i);
    cout  << setw(5) << thing << endl;
    }
    
    cout << endl;
    cout << "Enter 'y' to repeat action." << endl;
    cin >> again;
    }
}

Using 5 as both the power and number of rows and columns, the output so far is this. Which is where I now need help proceeding.

  • How do I make it become a grid, going both horizontally and vertically until it's a full table?
  • If it's just formatting, endl, and loops, how do I properly format it?
  • How do I get rid of that annoying 0 1 on the top right of the table?

Any and all help would be appreciated at this point.

I'm trying to get the end result to look something like this: To the power of 4 and with 6 rows/columns,

     1      2      3      4      5      6

 1 |      1      16      81     256     625     1296  

 2 |     16     256     1296     4096    10000    20736  

 3 |     81     1296     6561    20736    50625    104976  

 4 |     256     4096    20736    65536    160000    331776  

 5 |     625    10000    50625    160000    390625    810000  

 6 |    1296    20736    104976    331776    810000 1.67962e 06  

CodePudding user response:

You get rid of the 0 by replacing this:

int i=0;
  while(i<=rc){
   cout << setw(5) << i << " ";
    i  ;
  }

with something that starts the counter at 1:

  cout << "      ";
  for( int i = 1; i <= rc; i   )
  {
    cout << setw(5) << i << " ";
  }
  cout << "\n";

You probably want to start the row counter at 1 as well, to get rid of the "0 1" line.

CodePudding user response:

To get rid of the 0 and 1 on the top you have to insert an endl

while(i<=rc){
    cout << setw(5) << i << " ";
    i  ;
}
cout <<endl;
...

here is another resource for formatting How can I easily format my data table in C ?

  • Related