Friday, 6 July 2012

c program to find power of a number (pow(),while loop,for loop)

In this c program u need to input number and its power
For beginners
{I am going write the c program but before you need a c compiler(software).there are a lot of compilers(software). like Code::Blocks,dev c++  Download dev c++ its free and install it in your computer.open  dev c++ go to file-->new-->source file.} 

1.find power of number using while loop

#include<stdio.h>
#include<conio.h>
main()
{
      int c=1,n,y=1,x;
      printf("enter the number\n");
      scanf("%d",&x);
      printf("enter its power\n");
      scanf("%d",&n);
      while(c<=n)
      {
                 y=y*x;
                  c++;
                  }
                  printf("%d^%d=%d",x,n,y);
                  getch();
                  }


For beginners
{After typing this program go to execute-->compile & run-->a window will pop-up-->give file name:(anything u like)-->save as type: c source files-->click save.}

output

enter the number
2
enter its power
3
2^3=8

2
.find power of number using pow()

#include<math.h>

#include<stdio.h>
#include<conio.h>
main()
{
      int n1,n2,p;
      printf("enter the number\n");
      scanf("%d",&n1);
      printf("enter its power\n");
      scanf("%d",&n2);
      p=pow(n1,n2);
      printf("%d^%d=%d",n1,n2,p);
      getch();
      }



output


enter the number

2
enter its power
3
2^3=8


3.find power of number using for loop

#include<stdio.h>
#include<conio.h>
main()
{
      int c,n,y=1,x;
      printf("enter the number\n");
      scanf("%d",&x);
      printf("enter the power\n");
      scanf("%d",&n);
      for(c=1;c<=n;c++)
      {
           
                 y=y*x;
                  }
                  printf("%d^%d=%d",x,n,y);
                  getch();
                  }


output

enter the number

2

enter its power
3
2^3=8

6 comments:

  1. what is the use of y???
    plz explane it

    ReplyDelete
  2. Algorithm to find power of a number. To calculate base^exponent, it repetitively multiply base with result inside for loop. Finally, it prints the value of result on screen.

    ReplyDelete
  3. what is the meaning of y=y*x

    ReplyDelete
  4. Nice logic but it takes O(n) . Could be brought down to O(logn) when used divide and conquer recursively .

    ReplyDelete