question on a simple for loop

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • gdarian216
    New Member
    • Oct 2006
    • 57

    question on a simple for loop

    I am tring to write a loop that will do exponents without using the cmath class.

    Code:
    // Output:  1 2 4 ... 2^(num - 1)
        // First num powers of 2, ^ denotes exponentiation/power
        // There is no operator to do exponentiation in C++.
        cout << "\n 6. ";
        int a = 1;
        cout << a;
        for (int i = 0; i <= num; i++)
        {
            int b = 2;
            int c = 0;
            int d = 1;
            while (d < num)
            {
            c *=b;
            }
            cout << c;
        }
    this is what I have so far but im getting a infinite loop, i think im over thinking this can anyone help?
  • Ganon11
    Recognized Expert Specialist
    • Oct 2006
    • 3651

    #2
    Originally posted by gdarian216
    I am tring to write a loop that will do exponents without using the cmath class.

    Code:
    // Output:  1 2 4 ... 2^(num - 1)
        // First num powers of 2, ^ denotes exponentiation/power
        // There is no operator to do exponentiation in C++.
        cout << "\n 6. ";
        int a = 1;
        cout << a;
        for (int i = 0; i <= num; i++)
        {
            int b = 2;
            int c = 0;
            int d = 1;
            while (d < num)
            {
            c *=b;
            }
            cout << c;
        }
    this is what I have so far but im getting a infinite loop, i think im over thinking this can anyone help?
    Two issues:

    1) Your while loop is being controlled by d - but you aren't changing d's value inside the loop. This is where your infinite loop comes from.

    2) Inside this while loop, you multiply c by b to obtain a new c value. But c's initial value is 0. 0 times anything is 0, so your c value will always be 0.

    You can probably do this with 2 nested for...loops and not bother with this while loop...

    Comment

    Working...