Help! To develop a program (For-loop)

help
i need to create a prgramme that does ..
·
Demonstrates
a ‘for’ loop that produces the
output: 3, 5, 9, 17, 33, 65. (Hint: the loop variable value is first doubled,
then reduced by 1)

Demonstrates a ‘do’
– ‘while’ loop that does exactly the same, just the other way round (Hint:
first add 1 to the loop variable, then divide by 2). However, the 17 must not
be printed out, i.e. the output is: 65, 33, 9, 5, 3

1)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
//series.cpp
//##

#include <iostream>
using std::cout;
using std::endl;


int main(){

        for(int i=3;i<=66;i*=2){
                //if i is equal to 3 just print i; else print i-1
                cout<<(i==3?i:i-1)<<' ';
                if(i!=3)--i; //if i is not equal to 3 i-1 (decreases i by 1);
        }//end for
        cout<<endl;


return 0; //indicates success
}//end of main
./series 
3 5 9 17 33 65 
Why not simply put:
 
for(int i = 3; i < 66; i = i * 2 - 1)


Then you can ignore the ternary operator and if statement.

The assignment is pretty straight forward could you show some code prash?


[edit] just noticed I put + 1 instead of -1

Last edited on
You could accomplish it even faster by using
1
2
for(unsigned int i = 3; i <= 65; (i *= 2) -= 1)
        cout << i << " ";

Removing the need for an if statement.

As for the 2nd task, something like this should work
1
2
3
4
5
6
7
8
unsigned int i = 65;
    
do
{
    if(i != 17) cout << i << " ";
    i = (i + 1) / 2;
}
while(i >= 3);
I think that keeps (easy to understand) simple
the implementation.
But you are clever
people dudes ;D
Thanks guys that was really helpful!! :)
Topic archived. No new replies allowed.