Home > other >  A Program that accepts looping limit and will serve as multiplier of itself(per column) using C
A Program that accepts looping limit and will serve as multiplier of itself(per column) using C

Time:01-20

I have a Activity that accepts looping limit and will serve as multiplier of itself(per column) this is the example output

3   9   27
9  27   81
27 81  243

but this is my output

Enter number of rows: 3
3 9 27 
81 243 729 
2187 6561 19683 

This is the code

#include <iostream>
using namespace std;
 
int main()
{
    int rows;
    cout << "Enter number of rows: ";
    cin >> rows;
 
    int i, j;
    int num = 1;
    int plc = 1;
    for(i = 1; i <= rows; i  )
    {
        for(j = 1 ; j<=rows ; j  )
        {
            
            plc = plc * rows;
           cout << plc << " ";
        }
        
      
        
        cout << endl;
    }
 
    return 0;
}

Where I did wrong?

CodePudding user response:

You are only multiplying the previous value by rows(3) each time and not taking into account the row and columns, the code below will solve your problem:

int main()
{

    cout << "Enter number of rows: ";
    cin >> rows;

    int i, j;
    int num = 1;
    int plc = 1;
    int count = 0;
    for (i = 1; i <= rows; i  )
    {
        for (j = 1; j <= rows; j  )
        {
            plc = 1;

            for (int mult=0;mult< ((i - 1)   j);mult  )
            {
                plc *= 3;
            }

            cout << plc << " ";
        }

        cout << endl;
    }

    return 0;
}

Gives the expected outout:

3   9   27
9  27   81
27 81  243

CodePudding user response:

Perhaps you forgot to use the num variable?

#include <iostream>

int main( int argc, char* argv[] )
{
    int rows = ::atoi(argv[1]);
    int num = 1;
    for(int i = 1; i <= rows; i  )
    {        
        int plc = num;
        num *= rows;
        for(int j = 1 ; j<=rows ; j  )
        {            
            plc = plc * rows;
            std::cout << plc << " ";
        }
        std::cout << std::endl;
    }
    return 0;
}

Produces:

Program stdout
3 9 27 
9 27 81 
27 81 243 

Godbolt: https://godbolt.org/z/sfn119vTs

  •  Tags:  
  • c
  • Related