Ahmed Sh Ahmed Sh - 2 months ago 13
C++ Question

C++ Code Adjustment

I wrote some code to display the result as attached picture.
enter image description here

My code which I wrote as below :

#include <iostream>
#include <iomanip>

using namespace std;

int main()

{

int col , lig;

const int i = 10;

cout<<"tab x!";

for (col = 1 ; col <= i ; col = col + 1)
{
cout<< col<< setw(6) ;
}
cout<<endl;

cout<<"_________________________________________________________________"<<endl;

for (lig=1;lig<=i;lig=lig+1) {

{

cout<<setw(5)<<endl;


for (col=2;col<=i+1;col=col+1)
{ for (lig=2;lig<=i+1;lig=lig+1)
cout<<(col-1) * (lig-1) <<setw(6);
cout<<setw(1);
cout<<setw(5)<<endl;}}



return 0;
}}


but the result currently display as below by running the code above :

tab x!1 2 3 4 5 6 7 8 9 10
_________________________________________________________________

1 2 3 4 5 6 7 8 9 10
2 4 6 8 10 12 14 16 18 20
3 6 9 12 15 18 21 24 27 30
4 8 12 16 20 24 28 32 36 40
5 10 15 20 25 30 35 40 45 50
6 12 18 24 30 36 42 48 54 60
7 14 21 28 35 42 49 56 63 70
8 16 24 32 40 48 56 64 72 80
9 18 27 36 45 54 63 72 81 90
10 20 30 40 50 60 70 80 90 100


question:

I need to display the result as attached picture up and I cant find where is my problem ... please help me to achive the result same as picture up.

Answer

without touching much of your code logic

int main() {
    int col, lig;
    const int i = 10;
    cout << "tab x|";
    for (col = 1; col <= i; col = col + 1) {
        cout << setw(4) << col;
    }
    cout << endl;
    cout << "______________________________________________" << endl;
    cout << endl;

    for (lig = 1; lig <= i; lig = lig + 1) {
        for (col = 2; col <= i + 1; col = col + 1) {
            cout << setw(4) << (col - 1) << " |";
            for (lig = 2; lig <= i + 1; lig = lig + 1)
                cout << setw(4) << (col - 1) * (lig - 1);
            cout << endl;
        }
    }
    return 0;
}

Same result can be obtain with only two for loops though.