the program asks to calculate the power of a number, for eg. if 2 is entered as the base and 3 is th power it should display 8.

Recommended Answers

All 12 Replies

HI
Step to follow

> Declare a variable (say ans) as int or long
> Initialize ans as 1 (ans = 1)
> Start a for loop with variable (say i) for 1 to the given number (say power, in your example 3)
> multiply base (ur example 2) with ans in the for loop
> After finishing the loop u get the result in "ans"

the program asks to calculate the power of a number, for eg. if 2 is entered as the base and 3 is th power it should display 8.

I assume your question has to do more with the power than

#include <math.h>
#include <stdio.h>

int main ()
{
double base = 2, power = 3;
printf ("answer = %f\n", pow(base,power);
return 0;
}

for the input try using scanf to get the values from the command line. (google it)

i'll bet that, as part of the homework requirements, he's not allowed to use the <math.h> library

Kernighan and Richie's "The C programming language" has a a useful function for calculating powers. Although I suspect it's very similar to the one on math.h :P

In any case, just multiply a number by itself (power) times

i'll bet that, as part of the homework requirements, he's not allowed to use the <math.h> library

you're probably right.

it'll be fun to deal with 3^-1 :)

hopefully the scope of the assignment is for integer values of >= 0

if (pow<0)
ans = 1.0/ans;


fractional powers would be more fun.

:P

wait let me do it and put the code in here

here is the Code

#include<stdio.h>

main()
{
int x,y,ans=1;


printf("Enter Your Number:");
scanf("%d",&x);


printf("Enter the Power Number:");
scanf("%d",&y);

for(int i=0;i<y;i++)
{
ans=ans*x;
}
printf("The power of %d is %d",x,ans);


}

lich, if youre going to help,

(1) learn to indent your code properly
(2) learn to use tags

and for the record, your code is horribly fragile and will break if someone looks crosseyed at it.

.[code=c] tags

and for the record, your code is horribly fragile and will break if someone looks crosseyed at it.


.

HI
Step to follow

> Declare a variable (say ans) as int or long
> Initialize ans as 1 (ans = 1)
> Start a for loop with variable (say i) for 1 to the given number (say power, in your example 3)
> multiply base (ur example 2) with ans in the for loop
> After finishing the loop u get the result in "ans"

thanx,that really helped me. It compiled successfully.

Thanx, the code was fantastic. It compiled successfully

im so sorry about it. i just copied and paste it. im still a noob

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.