w3resource

C Exercises: Evaluate the equation y=xn when n is a non-negative integer


Evaluate y=xn

Write a C program to evaluate the equation y=xn when n is a non-negative integer.

Sample Solution:

C Code:

#include <stdio.h>
int main(){
    int count, n;
    float x,y;
    
    // Input the values of x and n
    printf("Input the values of x and n:\n");
    scanf("%f%d", &x,&n);
    
    y=1.0;
    count=1;
    
    // Calculate x to the power n
    while(count<=n)
    {
        y=y*x;
        count++;
    }
    
    // Print the result
    printf("x=%f; n=%d; \nx to power n=%f", x, n,y);
    
    return 0;
}

Sample Output:

Input the values of x and n: 256
x=256.000000; n=0; 
x to power n=1.000000

Flowchart:

C Programming Flowchart: Evaluate the equation y=xn when n is a non-negative integer


For more Practice: Solve these Related Problems:

  • Write a C program to compute x^n using a recursive function.
  • Write a C program to calculate x^n using exponentiation by squaring for efficient computation.
  • Write a C program to evaluate x^n and handle negative exponents by computing reciprocals.
  • Write a C program to calculate x^n for a series of (x, n) pairs read from a file.

Go to:


PREV :Generate 50 random numbers in [-0.5, 0.5] and save them to a file.
NEXT : Print powers of 2.

C programming Code Editor:



Have another way to solve this solution? Contribute your code (and comments) through Disqus.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.