How can we print odd numbers up to 99 using nested for loops in C++?

Join the discussion
Registration is free. Ask a follow-up in this thread, or start your own.
7 replies · 2K views
ineedhelpnow
Messages
649
Reaction score
0
I have my final exam for C++ tomorrow. I was studying a previous exam and I came across a certain problem that I would like to know how to do.

Suppose that we want to print out the following on the screen, please complete the code segment below by filling in the blanks
1
1 3
1 3 5
...
...
1 3 5 7... 99
Code:
for(int n=1; ---1---;++n){
       for(int i=1; ---2---; ---3---)
       cout<<---4---;
     ---5---;
}

1 is n<=99
I don't know what 2,3,4 are. I think 2 is i<=99 but I'm not sure.
And 5 is cout<<endl;
 
Physics news on Phys.org
This is how I would code it:

Code:
for(int n = 1; n < 51; ++n){
    for(int i = 1; i < 2*n; i += 2)
        cout << i << ' ';
    cout << endl;
}
 
Thank You! It was the condition i<n that I couldn't seem to remember. :o
 
I edited the code I posted to include a space after each number on a line.

Just to be clear, we want [m]i < 2*n[/m]. :D
 
Code:
for(int n=1; n<=99 ;++n){
       for(int i=1; i<n ; ++i)
       cout<<i<<" ";
     cout<<endl;
}

Will ^ work as well?
 
ineedhelpnow said:
Code:
for(int n=1; n<=99 ;++n){
       for(int i=1; i<n ; ++i)
       cout<<i<<" ";
     cout<<endl;
}

Will ^ work as well?

No...you will wind up printing even numbers too. Also, you will never print the number 99.
 
Code:
for(int n=1; n<=99 ;++n){
       for(int i=1; i<n ; i+=2)
       cout<<i<<" ";
     cout<<endl;
}

How about ^? :D (Just want to see if it can be done in different ways also)

Why won't 99 ever be printed?
 
ineedhelpnow said:
Code:
for(int n=1; n<=99 ;++n){
       for(int i=1; i<n ; i+=2)
       cout<<i<<" ";
     cout<<endl;
}

How about ^? :D (Just want to see if it can be done in different ways also)

Why won't 99 ever be printed?

The outer loop determines how many lines you want to print...and this is 50:

$$N=\frac{99-1}{2}+1=50$$

The way you have it coded, there will be 99 lines printed. To see why 99 would never be printed, look at what happens the last time your outer loop is iterated...n is 99, but your condition statement on the inner loop is [m]i < n[/m]. :D