Saturday, 13 July 2013

[C Programming #2] Calculate power of a number without using pow() pre-defined function

Calculate power of a number without using pow() pre-defined function
This question is also asked in interviews frequently.

Please check below program:

  1. #include<stdio.h>

  2. int main()
  3. {
  4.   int n, power;
  5.   int i, j;
  6.   int total = 0, sum;
  7.  
  8. printf("Please enter Value and its power\n");
  9. scanf("%d%d", &n, &power);
  10.  
  11. printf("Calculate: %d^%d:\n", n, power);
  12.  
  13. total = n;
  14. for (i=1; i<power; i++) {
  15. sum = total;
  16. for (j=1; j<n; j++) {
  17. total += sum;
  18. }
  19. }
  20. printf("Result: %d\n", total);


  21. return 0;
  22. }
Output:
Please enter Value and its power
10
3
Calculate: 10^3:
Result: 1000

No comments:

Post a Comment

You might also like

Related Posts Plugin for WordPress, Blogger...