Jump to content
Search In
  • More options...
Find results that contain...
Find results in...
duckypath

C++ nested for loop help

4 minutes ago, kberes said:

#include <iostream>

#include <iomanip>

using namespace std;

int main() 
{
        for(int i=1; i<=9; i++)
    
        {
    
            for(int j=1; j<=3; j++)
            
            cout << j << " x " << i << " = " << i * j << "  ";
            cout << endl;
        
        }
        
    cout << endl;
        
        for(int i=1; i<=9; i++)
    
        {
    
            for(int j=4; j<=6; j++)
            
            cout << j << " x " << i << " = " << i * j << "  ";
            cout << endl;
        
        }
        
    cout << endl;
    
    for(int i=1; i<=9; i++)
    
        {
    
            for(int j=7; j<=9; j++)
            
            cout << j << " x " << i << " = " << i * j << "  ";
            cout << endl;
        
        }
        
}

I ended up getting it here, but I don't like the repeated as I feel there is a better way to do this with nested loops. Maybe as I learn more I will revisit.

 

cpp.sh/73wuo

 

image.png.1339d1d0ba854bb6192762eb075aea90.png

This is an example of minor edits to your original code doing it correctly:

 

#include <iostream>
#include <iomanip>

int main ()

{
    
    for (int i = 1; i <= 9; i += 3)
    {
        for (int j = 1; j <= 9; j++)
        {
            for (int k = j; k <= j; k++) 
            {
                std::cout << i << " x" << std::setw(2) << j << " =" << std::setw(2) << i * j << "   ";
                std::cout << i+1 << " x " << j << " =  " << (i+1)*j << " ";
                std::cout << i+2 << " x " << j << " = " << (i+2)*j << " ";
                std::cout << "\n";
            }
        }
        
        std::cout << "\n";
        
    }

}

Recommended Posts

Posted · Original PosterOP

Hey,

 

A little stuck on completing the formatting of this 9x9 multiplication table. I have the code done so that the numbers are looped correctly, but I am unsure how to format it to look like the supplied image.

 

Here is what I have so far: 

 

#include <iostream>
#include <iomanip>

int main ()

{
    
    for (int i = 1; i <= 9; i++)
    {
        for (int j = 1; j <= 9; j++)
        {
            for (int k = j; k <= j; k++) 
            {
                std::cout << i << " x" << std::setw(2) << j << " =" << std::setw(2) << i * j << "   ";
                std::cout << "\n";
            }
        }
        
        std::cout << "\n";
        
    }

}

 

image.png.4b747663f938f2430d174d0129a144cc.png

Link to post
Share on other sites

So just a very quick look at it. You could use an if else statement that only sends out the endl or “\n” for every third one printed out. So you could cout each time it shoots out and at 2/3 depending on if you’d start counting at 0 or 1 either reset the count, or sent it up to do it only when the count is divisible by 3. I’m hoping that’s what you were asking for.

Link to post
Share on other sites

This looks like homework so I'll only try to point you in the right direction:

 

for each line you'll have to print the result of multiplying three sequential numbers by one number; this can be done in its own loop. Then you'll need a higher level loop to make that one number go from one to nine. Then you'll need yet another loop on top of that to increase the baseline of the sequential numbers.


...is there a question here? 🤔

sudo chmod -R 000 /*

What is scaling and how does it work? Asus PB287Q unboxing! Console alternatives :D Watch Netflix with Kodi on Arch Linux Sharing folders over the internet using SSH Beginner's Guide To LTT (by iamdarkyoshi)

Sauron'stm Product Scores:

Spoiler

Just a list of my personal scores for some products, in no particular order, with brief comments. I just got the idea to do them so they aren't many for now :)

Don't take these as complete reviews or final truths - they are just my personal impressions on products I may or may not have used, summed up in a couple of sentences and a rough score. All scores take into account the unit's price and time of release, heavily so, therefore don't expect absolute performance to be reflected here.

 

-Lenovo Thinkpad X220 - [8/10]

Spoiler

A durable and reliable machine that is relatively lightweight, has all the hardware it needs to never feel sluggish and has a great IPS matte screen. Downsides are mostly due to its age, most notably the screen resolution of 1366x768 and usb 2.0 ports.

 

-Apple Macbook (2015) - [Garbage -/10]

Spoiler

From my perspective, this product has no redeeming factors given its price and the competition. It is underpowered, overpriced, impractical due to its single port and is made redundant even by Apple's own iPad pro line.

 

-OnePlus X - [7/10]

Spoiler

A good phone for the price. It does everything I (and most people) need without being sluggish and has no particularly bad flaws. The lack of recent software updates and relatively barebones feature kit (most notably the lack of 5GHz wifi, biometric sensors and backlight for the capacitive buttons) prevent it from being exceptional.

 

-Microsoft Surface Book 2 - [Garbage - -/10]

Spoiler

Overpriced and rushed, offers nothing notable compared to the competition, doesn't come with an adequate charger despite the premium price. Worse than the Macbook for not even offering the small plus sides of having macOS. Buy a Razer Blade if you want high performance in a (relatively) light package.

 

-Intel Core i7 2600/k - [9/10]

Spoiler

Quite possibly Intel's best product launch ever. It had all the bleeding edge features of the time, it came with a very significant performance improvement over its predecessor and it had a soldered heatspreader, allowing for efficient cooling and great overclocking. Even the "locked" version could be overclocked through the multiplier within (quite reasonable) limits.

 

-Apple iPad Pro - [5/10]

Spoiler

A pretty good product, sunk by its price (plus the extra cost of the physical keyboard and the pencil). Buy it if you don't mind the Apple tax and are looking for a very light office machine with an excellent digitizer. Particularly good for rich students. Bad for cheap tinkerers like myself.

 

 

Link to post
Share on other sites
Posted · Original PosterOP
24 minutes ago, Sauron said:

This looks like homework so I'll only try to point you in the right direction:

 

for each line you'll have to print the result of multiplying three sequential numbers by one number; this can be done in its own loop. Then you'll need a higher level loop to make that one number go from one to nine. Then you'll need yet another loop on top of that to increase the baseline of the sequential numbers.

So what I have basically gives me i for the first number, j for the second, and the answer being i * j. What I am having an issue with is formatting it, so that the for loops add a new line when each row has 3 columns. IDK if you could provide further clarification/

 

#include <iostream>
#include <iomanip>

int main ()

{
    for (int i = 1; i <= 3; i++)
    {
        for (int j = 1; j <= 9; j++)
        {
            std::cout << i << " x " << j << " = " << i * j << " ";
            for (int k = 1; k <= 1; k++)
            {
            std::cout << "\n";
            }
        } 
    }
}

Link to post
Share on other sites
5 minutes ago, kberes said:

So what I have basically gives me i for the first number, j for the second, and the answer being i * j. What I am having an issue with is formatting it, so that the for loops add a new line when each row has 3 columns. IDK if you could provide further clarification/

You're thinking about it the wrong way - you need to consider how it's going to be printed first because in the terminal you can't go back and print on a previous line (at least not without special libraries).

 

So for the first line you need to cycle from 1 to 3 and multiply them by 1. On the second line you need to do the same thing except this time you multiply them by 2... and so on. When you get to 9 you'll need to start printing the same thing but this time for numbers from 4 to 6 and you need to do this 3 times in total.

 

Suppose then that i represents the series you're on (this must go from 0 to 2 and tells you whether you're doing multiplications with numbers 1-3, 4-6 or 7-9), j represents the line within that series (1-9) and k represents which multiplication you're printing within that line (0-2). One member of one line will then be (in pseudocode):

print "(i*3 + k) * j = ..."

and every three times this is done (i.e. when k is larger than 2) you can put in a newline and increase the value of j. When j reaches 9 you can increase the value of i.


...is there a question here? 🤔

sudo chmod -R 000 /*

What is scaling and how does it work? Asus PB287Q unboxing! Console alternatives :D Watch Netflix with Kodi on Arch Linux Sharing folders over the internet using SSH Beginner's Guide To LTT (by iamdarkyoshi)

Sauron'stm Product Scores:

Spoiler

Just a list of my personal scores for some products, in no particular order, with brief comments. I just got the idea to do them so they aren't many for now :)

Don't take these as complete reviews or final truths - they are just my personal impressions on products I may or may not have used, summed up in a couple of sentences and a rough score. All scores take into account the unit's price and time of release, heavily so, therefore don't expect absolute performance to be reflected here.

 

-Lenovo Thinkpad X220 - [8/10]

Spoiler

A durable and reliable machine that is relatively lightweight, has all the hardware it needs to never feel sluggish and has a great IPS matte screen. Downsides are mostly due to its age, most notably the screen resolution of 1366x768 and usb 2.0 ports.

 

-Apple Macbook (2015) - [Garbage -/10]

Spoiler

From my perspective, this product has no redeeming factors given its price and the competition. It is underpowered, overpriced, impractical due to its single port and is made redundant even by Apple's own iPad pro line.

 

-OnePlus X - [7/10]

Spoiler

A good phone for the price. It does everything I (and most people) need without being sluggish and has no particularly bad flaws. The lack of recent software updates and relatively barebones feature kit (most notably the lack of 5GHz wifi, biometric sensors and backlight for the capacitive buttons) prevent it from being exceptional.

 

-Microsoft Surface Book 2 - [Garbage - -/10]

Spoiler

Overpriced and rushed, offers nothing notable compared to the competition, doesn't come with an adequate charger despite the premium price. Worse than the Macbook for not even offering the small plus sides of having macOS. Buy a Razer Blade if you want high performance in a (relatively) light package.

 

-Intel Core i7 2600/k - [9/10]

Spoiler

Quite possibly Intel's best product launch ever. It had all the bleeding edge features of the time, it came with a very significant performance improvement over its predecessor and it had a soldered heatspreader, allowing for efficient cooling and great overclocking. Even the "locked" version could be overclocked through the multiplier within (quite reasonable) limits.

 

-Apple iPad Pro - [5/10]

Spoiler

A pretty good product, sunk by its price (plus the extra cost of the physical keyboard and the pencil). Buy it if you don't mind the Apple tax and are looking for a very light office machine with an excellent digitizer. Particularly good for rich students. Bad for cheap tinkerers like myself.

 

 

Link to post
Share on other sites
Posted · Original PosterOP
45 minutes ago, Sauron said:

You're thinking about it the wrong way - you need to consider how it's going to be printed first because in the terminal you can't go back and print on a previous line (at least not without special libraries).

 

So for the first line you need to cycle from 1 to 3 and multiply them by 1. On the second line you need to do the same thing except this time you multiply them by 2... and so on. When you get to 9 you'll need to start printing the same thing but this time for numbers from 4 to 6 and you need to do this 3 times in total.

 

Suppose then that i represents the series you're on (this must go from 0 to 2 and tells you whether you're doing multiplications with numbers 1-3, 4-6 or 7-9), j represents the line within that series (1-9) and k represents which multiplication you're printing within that line (0-2). One member of one line will then be (in pseudocode):


print "(i*3 + k) * j = ..."

and every three times this is done (i.e. when k is larger than 2) you can put in a newline and increase the value of j. When j reaches 9 you can increase the value of i.

I appreciate the help, but something is not clicking. This is my 3rd day with C++ so kinda lost of how the logic of for loops are constructed. After trying a bunch of things I am able to get the attached picture. But that is still not correct. I see what you are saying with having i increment by 1 for a total of 3 times, than after it hits the third loop to change j. But again, I am very unfamiliar with this language.

 

image.png.d2dfd2c84d5263a6e367f970cd06526b.png

Link to post
Share on other sites

Hey so I looked back over your code and there is some minor logic errors with what you're attempting to do. If you want them to be printed out like in the photos where 1 2 and 3's multiplication is all store in the same "table" then you need to account for that in your programming.

So you first loop needs to increment i by 3. Then you need to also account for the changes to i in the print out where you increase i by 2 and 3 as well when couting out. I editted your example to show a possible way of doing this.

 so for instance you need to change what happens inside your final for loop a bit.

thinking something along the lines of adding this to your code:

 

std::cout << i+1 << " x " << j << " =  " << (i+1)*j << " ";

It's more than just this since you want 3 answers attached. But it should hopefully be straight forward on how to get the 3rd number if you input this into your code.

 

I put the changes into your code and tested it on my end getting the result you were asking for. 1 is grouped with 2 and 3, 4 with 5 and 6 etc.

 

Sorry that I missed understood what you were asking for initially I quickly read through it.

Link to post
Share on other sites
31 minutes ago, kberes said:

I appreciate the help, but something is not clicking. This is my 3rd day with C++ so kinda lost of how the logic of for loops are constructed. After trying a bunch of things I am able to get the attached picture. But that is still not correct. I see what you are saying with having i increment by 1 for a total of 3 times, than after it hits the third loop to change j. But again, I am very unfamiliar with this language.

 

image.png.d2dfd2c84d5263a6e367f970cd06526b.png

You almost got it, just invert the first and the second number in the cout command.


...is there a question here? 🤔

sudo chmod -R 000 /*

What is scaling and how does it work? Asus PB287Q unboxing! Console alternatives :D Watch Netflix with Kodi on Arch Linux Sharing folders over the internet using SSH Beginner's Guide To LTT (by iamdarkyoshi)

Sauron'stm Product Scores:

Spoiler

Just a list of my personal scores for some products, in no particular order, with brief comments. I just got the idea to do them so they aren't many for now :)

Don't take these as complete reviews or final truths - they are just my personal impressions on products I may or may not have used, summed up in a couple of sentences and a rough score. All scores take into account the unit's price and time of release, heavily so, therefore don't expect absolute performance to be reflected here.

 

-Lenovo Thinkpad X220 - [8/10]

Spoiler

A durable and reliable machine that is relatively lightweight, has all the hardware it needs to never feel sluggish and has a great IPS matte screen. Downsides are mostly due to its age, most notably the screen resolution of 1366x768 and usb 2.0 ports.

 

-Apple Macbook (2015) - [Garbage -/10]

Spoiler

From my perspective, this product has no redeeming factors given its price and the competition. It is underpowered, overpriced, impractical due to its single port and is made redundant even by Apple's own iPad pro line.

 

-OnePlus X - [7/10]

Spoiler

A good phone for the price. It does everything I (and most people) need without being sluggish and has no particularly bad flaws. The lack of recent software updates and relatively barebones feature kit (most notably the lack of 5GHz wifi, biometric sensors and backlight for the capacitive buttons) prevent it from being exceptional.

 

-Microsoft Surface Book 2 - [Garbage - -/10]

Spoiler

Overpriced and rushed, offers nothing notable compared to the competition, doesn't come with an adequate charger despite the premium price. Worse than the Macbook for not even offering the small plus sides of having macOS. Buy a Razer Blade if you want high performance in a (relatively) light package.

 

-Intel Core i7 2600/k - [9/10]

Spoiler

Quite possibly Intel's best product launch ever. It had all the bleeding edge features of the time, it came with a very significant performance improvement over its predecessor and it had a soldered heatspreader, allowing for efficient cooling and great overclocking. Even the "locked" version could be overclocked through the multiplier within (quite reasonable) limits.

 

-Apple iPad Pro - [5/10]

Spoiler

A pretty good product, sunk by its price (plus the extra cost of the physical keyboard and the pencil). Buy it if you don't mind the Apple tax and are looking for a very light office machine with an excellent digitizer. Particularly good for rich students. Bad for cheap tinkerers like myself.

 

 

Link to post
Share on other sites
Posted · Original PosterOP
23 minutes ago, Sauron said:

You almost got it, just invert the first and the second number in the cout command.

Ok, perfect that part works. Now I am unsure how to further this so that I can extend i to 1-9, not just 1-3. As the example I am trying to match is 3 separate blocks. SO far I have the first one. **Thank you a lot! btw**

Link to post
Share on other sites
Posted · Original PosterOP
#include <iostream>

#include <iomanip>

using namespace std;

int main() 
{
        for(int i = 1; i <= 9; i++)
    
        {
    
            for(int j = 1; j <= 3; j++)
            
            cout << j << " x " << i << " = " << i * j << "     ";
            cout << endl;
        
        }
        
}

image.png.ef5aa733bd5fba072301937303a4e6f2.png

Link to post
Share on other sites
Posted · Original PosterOP
#include <iostream>

#include <iomanip>

using namespace std;

int main() 
{
        for(int i = 1; i <= 9; i++)
    
        {
    
            for(int j = 1; j <= 9; j++)
            
            cout << j << " x " << i << " = " << i * j << "     ";
            cout << endl;
        }
        
}

This is perfect, but I need to figure out how to endl; every third section.

 

image.thumb.png.3038ee0e4799020bf994a20b8bf8a9f8.png

Link to post
Share on other sites
Posted · Original PosterOP
#include <iostream>

#include <iomanip>

using namespace std;

int main() 
{
        for(int i=1; i<=9; i++)
    
        {
    
            for(int j=1; j<=3; j++)
            
            cout << j << " x " << i << " = " << i * j << "  ";
            cout << endl;
        
        }
        
    cout << endl;
        
        for(int i=1; i<=9; i++)
    
        {
    
            for(int j=4; j<=6; j++)
            
            cout << j << " x " << i << " = " << i * j << "  ";
            cout << endl;
        
        }
        
    cout << endl;
    
    for(int i=1; i<=9; i++)
    
        {
    
            for(int j=7; j<=9; j++)
            
            cout << j << " x " << i << " = " << i * j << "  ";
            cout << endl;
        
        }
        
}

I ended up getting it here, but I don't like the repeated as I feel there is a better way to do this with nested loops. Maybe as I learn more I will revisit.

 

cpp.sh/73wuo

 

image.png.1339d1d0ba854bb6192762eb075aea90.png

Link to post
Share on other sites
Posted · Best Answer
4 minutes ago, kberes said:

#include <iostream>

#include <iomanip>

using namespace std;

int main() 
{
        for(int i=1; i<=9; i++)
    
        {
    
            for(int j=1; j<=3; j++)
            
            cout << j << " x " << i << " = " << i * j << "  ";
            cout << endl;
        
        }
        
    cout << endl;
        
        for(int i=1; i<=9; i++)
    
        {
    
            for(int j=4; j<=6; j++)
            
            cout << j << " x " << i << " = " << i * j << "  ";
            cout << endl;
        
        }
        
    cout << endl;
    
    for(int i=1; i<=9; i++)
    
        {
    
            for(int j=7; j<=9; j++)
            
            cout << j << " x " << i << " = " << i * j << "  ";
            cout << endl;
        
        }
        
}

I ended up getting it here, but I don't like the repeated as I feel there is a better way to do this with nested loops. Maybe as I learn more I will revisit.

 

cpp.sh/73wuo

 

image.png.1339d1d0ba854bb6192762eb075aea90.png

This is an example of minor edits to your original code doing it correctly:

 

#include <iostream>
#include <iomanip>

int main ()

{
    
    for (int i = 1; i <= 9; i += 3)
    {
        for (int j = 1; j <= 9; j++)
        {
            for (int k = j; k <= j; k++) 
            {
                std::cout << i << " x" << std::setw(2) << j << " =" << std::setw(2) << i * j << "   ";
                std::cout << i+1 << " x " << j << " =  " << (i+1)*j << " ";
                std::cout << i+2 << " x " << j << " = " << (i+2)*j << " ";
                std::cout << "\n";
            }
        }
        
        std::cout << "\n";
        
    }

}

Link to post
Share on other sites
Posted · Original PosterOP
5 minutes ago, NeosIII said:

This is an example of minor edits to your original code doing it correctly:

 

#include <iostream>
#include <iomanip>

int main ()

{
    
    for (int i = 1; i <= 9; i += 3)
    {
        for (int j = 1; j <= 9; j++)
        {
            for (int k = j; k <= j; k++) 
            {
                std::cout << i << " x" << std::setw(2) << j << " =" << std::setw(2) << i * j << "   ";
                std::cout << i+1 << " x " << j << " =  " << (i+1)*j << " ";
                std::cout << i+2 << " x " << j << " = " << (i+2)*j << " ";
                std::cout << "\n";
            }
        }
        
        std::cout << "\n";
        
    }

}

Thank you!! Since I am very new to c++ this flew over my head at first when you mentioned it. Makes sense now! I know that ill be reading loop chapters for the nest couple weeks.

 

@Sauron I really appreciate you assistance as well!

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Newegg

×