C Programming

Solved Example

Practice Questions

Exercise Question

Program to calculate the power of a number

Objective

Enter two numbers n and p and write a program to calculate np.

Program / Solution

#include<stdio.h>
int main() {
	int i,n,p;
	long ans;
	
	printf("Enter the value of n and p: ");
	scanf("%d %d",&n,&p);
	
	ans = 1;
	for(i = 1; i <= p; i++) {
		ans = ans * n;
	}
	
	printf("%d to the power %d = %ld",n,p,ans);
}

Sample Output

Enter the value of n and p: 2 5
2 to the power 5 = 32