Search code examples
c++nested-loops

Write a C++ program using nested loops to output the following numbers to the screen?


I wrote a C++ program, but the output I got was unexpected (as shown below).

enter image description here

#include<stdio.h>
#include<iostream>
#include<iomanip>
using namespace std;
main()
{
int a,b;
for(a=3;a<=21;a+=2)
    {
    printf("\n");
    for(b=1;b<a;b+=2)
        {
        cout<<setw(2)<<a+b-1<<" ";
        }
    }
cout<<"\n";
}

Can someone help me tweak it, so it runs like this:

enter image description here


Solution

  • Is this what you want to achieve?

    #include<stdio.h>
    #include<iostream>
    #include<iomanip>
    using namespace std;
    main()
    {
    int a,b;
    for(a = 1 ;a <= 10; a++)
    {
        for(b = 2 * a + 1;b <= 3 * a; b++)
        {
            cout<<setw(2)<<b<<" ";
        }
        printf("\n");
    }
    cout<<"\n";
    }