how to write a program for raising a number to a power(integer only)
(e.g 2^2=4 ; 3^3=27 etc)
without using a precompiled C function(ie pow()). but only used addition, substraction, while loops,if statement and/or for loop.

#include <stdio.h>
int main(void)
{
int base, power, index;
long answer;

base = 0;
power = 0;
answer = 1.00;

printf("Enter a base number: ");
scanf("%d", &base);
printf("Enter a power to raise the base to: ");
scanf("%d", &power);

for(index = 1; index <= power; index++)
answer = answer * base;


printf("%d raised to the power of %d is %ld.", base, power, answer);
getchar();
getchar();
return 0;
}


This is just something I threw together in about a minute.

I still haven't quite figured out the indention method on this forum, and the getchar() at the end are for the Dev-C++ compiler so that the DOS-Prompt doesn't close automatically.

Why, in any circumstance, would resurrecting a four year old thread to ask a vague question using bad grammar (forget english grammar, I mean C grammar. C doesn't have "commands") be a good idea? Hmmm...

#include<stdio.h>
#include<conio.h>
#include<math.h>
void main()
{
int base,power,answer;
clrscr();
printf("Enter the base no\n");
scanf("%d",&base);
prinf("Enter the power\n");
scanf("%d",&power);
answer=pow(base,power);
printf("The result is %d",answer);
getch();
}

>BimanD

Did you even read what the question posed was...? And what others have replied to it...?

how to write a program for raising a number to a power(integer only)
(e.g 2^2=4 ; 3^3=27 etc)
without using a precompiled C function(ie pow()). but only used addition, substraction, while loops,if statement and/or for loop.

You intend to do it without inbuilt library functions like pow() right ? Do it with recursive call of a function as:

int power( int b , int p)
{
if( p > 1 )
               return b * power( b , p-1 );
else
               return b;
}

where b and p would take the format in library function pow as pow(b,p).Just call the above shown function in main passing the two numbers as arguments.Your work is done.
There are many other ways of doing this.But its just left to your interest.If you really want to learn programming in C then try in ow many ways can you write the same program(using different logic) and to what extent you can simplify.

Do not resurrect an old thread to ask a question. You should only post help to an existing thread.

Now go start your own thread and reword your question giving us all the detail necessary for understanding exactly what you want.

This article has been dead for over six months. Start a new discussion instead.