Calculate Power using C Language

Calculate Power using C Language

Write a C program that accepts two numbers x and y from input device. Calculate x power y.

For Loop
--------
#include <stdio.h>
#include <conio.h>
void main() {
    int x, y;
    long long result = 1; // Use long long to handle larger results

    // Accepting the base (x) and exponent (y) from the user
    printf("Enter the base (x): ");
    scanf("%d", &x);
    printf("Enter the exponent (y): ");
    scanf("%d", &y);

    // Calculating x^y using a for loop
    for (int i = 1; i <= y; i++) {
        result *= x; // Multiply result by x, y times
    }

    // Displaying the result
    printf("%d raised to the power of %d is: %lld\n", x, y, result);

    getch();
}

Do While
---------
#include <stdio.h>
#include <conio.h>
void main() {
    int x, y;
    long long result = 1; // Use long long to handle larger results

    // Accepting the base (x) and power (y) from the user
    printf("Enter the base (x): ");
    scanf("%d", &x);
    printf("Enter the power (y): ");
    scanf("%d", &y);

    // Calculating x^y using a do-while loop
    if (y >= 0) {
        int i = 1;
        do {
            result *= x; // Multiply result by x, y times
            i++;
        } while (i <= y);
    } else {
        printf("power (y) must be a non-negative integer.\n");
        return 1; // Exit the program with an error code
    }

    // Displaying the result
    printf("%d raised to the power of %d is: %lld\n", x, y, result);

    getch();
}