audiedoggie
audiedoggie

Reputation: 80

Infinite "true" while loop

I know I am probably just doing something dumb wrong, but I need to take a number from the user, create an infinite loop (by making my while statement true) of multiples of 2. I got the math to multiply the number from the user times itself, but I can't get it to loop. This is the last part of my homework for the week and my brain is fried, so I can't figure out where I went wrong!

Any help would be amazing! Here is what I have:

#include <iostream>

using namespace std;

int main (int argc, const char * argv[])
{
    int d;
    int e;
    cin >> d;
    while (true)
    {
        e = d * d;
    }
        cout << e << ", ";
}

Upvotes: 3

Views: 628

Answers (3)

Ajay
Ajay

Reputation: 18429

One of the the possible solutions:

int main (int argc, const char * argv[])
{
    int d;
    int e = 2;
    cin >> d;
    while (d>0)
    {
       cout << e << ", ";

       e = e * 2;
       d--;
    }
}

Upvotes: 0

Z&#233;ychin
Z&#233;ychin

Reputation: 4205

There is unreachable code at: cout << e << ", "; Perhaps this was meant to go in the while loop?

You are assigning e the value of d*d over and over. Because d*d does not change, the value of e never changes. Perhaps you should initialize e to the number you want outside of the loop, and then set e = e * 2 inside of the loop, then print e. This will print multiples of your number by successive powers of 2, which is what I think you want.

Upvotes: 4

Jon7
Jon7

Reputation: 7225

As written, your code will loop forever and, as a result, it will never get to that cout statement. Maybe you want to put the cout statement inside of the loop body so that the variable gets printed?

Upvotes: 4

Related Questions