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.
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";
}
}
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 accountSign in
Already have an account? Sign in here.
Sign In Now