Home > Software engineering >  program for calculating x raised to the power of y using while loop
program for calculating x raised to the power of y using while loop

Time:07-07

int main()
{ unsigned int x, y;

    printf_s("Enter value for x: ");
    scanf_s("%u", &x);

    printf_s("Enter value for y: ");
    scanf_s("%u", &y);

    unsigned int count = 1;
    while (count < y);
    {
        x *= x;
        count  ;
    }

    printf_s("x raised to the power of y is: %u", x);
}

Hi, I'm not sure where I went wrong. When I run it, I enter two values as prompted and then nothing else happens. It just stops after I enter they value for y.

Enter value for x: 3 Enter value for y: 2

Like this. Could someone point me in the right direction? I understand that this way will not work if y <= 1. But shouldn't it work for when y > 1?

I've searched for it. There is another question using for loop. I can see that it could be done with for loop but I think while loop is more appropriate since it gives more freedom. Please and thank you!

CodePudding user response:

  1. Use functions
  2. you have ; past the while and your code in braces is not executed in the loop
  3. use a larger integer type as the result as a "normal" unsigned int will wraparound quickly.
  4. x *= x is definitely wrong.
unsigned long long mypow(unsigned x, unsigned y)
{
    unsigned long long result = 1;
    while(y--) result *= x;
    return result;
}


int main(void)
{
    unsigned x, y;

    scanf("%u,%u", &x, &y);

    printf("%u ^ %u = %llu\n", x, y, mypow(x, y));
}

https://godbolt.org/z/xzx8Mo5aW

CodePudding user response:

#include <iostream>

int main()
{

    unsigned int long x; // assign x
    printf_s("Enter value for x: "); // prompt
    scanf_s("%u", &x); // read input

    unsigned int y; // assign y
    printf_s("Enter value for y: "); // prompt
    scanf_s("%u", &y); // read input

    unsigned int count = 0; // initialize count
    unsigned int power = 1; // initialize power
    while (count < y) // loop while y is less than count
    {
        power *= x; // multiply power by x
        count  ; // increment count

    } // loop ends

    printf_s("x raised to the power of y is: %u", power); // display result
}

I've deleted ;. I've added long to unsigned int. I've set up a new variable, power, in order to contain the value of x raised to a power of y. I've checked if this works when y = 0 or 1 and it does. Thank you everyone for your help!

P.S. Textbook answer has pritnf( "%s", "Enter first integer: "); for prompting for the first integer, x. I'm not sure why they add %s as it works perfectly fine without it. Does anyone know why one would add %s?

  • Related