C program to find power of a number using for loop

Previous Program Next Program

Write a C program to find power of any number using for loop. How to find power of any number without using built in library functions in C programming. Logic to find power of any number without using pow() function in C program.

Example

Input

Input base: 2
Input exponent: 5

Output

2 ^ 5 = 32

Required knowledge

Basic C programming, For loop, Base and exponents

Logic to find power of any number

I have explained in one of my previous post how easily you can find power. Using the help of inbuilt pow() library function. In this exercise you will learn to find power of any number without using library function.

Power of a number can be defined as base multiplied to itself n times (where n is exponent). Below is the step by step descriptive logic.

  1. Read base and exponents from user. Store it in two variables say base and expo.
  2. Initialize a power variable with 1. Which is power = 1.
  3. Run a loop from 1 to expo, increment loop counter by 1 in each iteration. The loop structure must look similar to for(i=1; i<=expo; i++).
  4. Multiply power with num i.e. power = power * num.
  5. Finally after loop you are left with power.

Program to find power of any number

/**
 * C program to find power of any number using for loop
 */

#include <stdio.h>

int main()
{
    int base, exponent;
    long long power = 1;
    int i;

    /* Read base and exponent from user */
    printf("Enter base: ");
    scanf("%d", &base);
    printf("Enter exponent: ");
    scanf("%d", &exponent);

    /* Multiply base, exponent times*/
    for(i=1; i<=exponent; i++)
    {
        power = power * base;
    }

    printf("%d ^ %d = %lld", base, exponent, power);

    return 0;
}

Note: Some compilers do not support long long data type hence if your compiler reports any errors in the program just change the data type from long long with long type also replace the format specifier %lld to %ld.


Output
Enter base: 2
Enter exponent: 5
2 ^ 5 = 32

Happy coding ;)

Recommended posts

Previous Program Next Program
Any doubt or suggestion write here. I will try my best to help. Before posting your code you must escape it to view. To format your source code and use format highlighting, post your source code inside
< pre>< code >----Your Source Code---- < / code > < / pre > (Remove spaces from pre and code tags)

2 comments:

  1. I like your theme of choice for web journal however need to recommend you for sharing some more data with respect to your subject so we can comprehend your idea all the more unmistakably. Buzz Apps

    ReplyDelete
    Replies
    1. Thanks noman, and yes I am working over it. To ensure the readers can get all from this single site.

      Delete