Close
Close

for loop (a raised to the power b program)

   UTHAPPA

#include <stdio.h>
int main()
{
    int a,b,power,i ;
    power = 1;

    printf("To find a raised to the power b.\n give value of a");
    scanf("%d",&a);

    printf("Give value of b\n");
    scanf("%d",&b);

    for ( i = 1 ; i <= b ; i ++ )
    {
        power = power*a;
    }

    printf("Power of a'%d' raised to b'%d' is %d\n",a,b,power);
    return 0;
}
  1. Please give a detailed explaination of this program
  1. why is the variable “i” used?
  2. why is the power assigned the value 1 in the beginning?
  3. why is i<=b written?


Answers

  •   

    To calculate ab, we multiply a*a*a*a*a…...*a b times. So to achieve this, let’s have a variable which will store the value of the calculated result and name it power. Let’s give this power the value of a.

    Now, if we multiply power with a and assign this value to power then:

    power = power*a = i.e. a2

    let’s multiply again,

    power = power*a i.e. a3 (as power was a2 with previous multiplication).

    Similarly we can calculate an.

    Now let’s come to your third question first.

    We want to to store the value of calculated result in the variable power and for this we have to first assign the value of a to the power as done in the explaination above. We will do this inside for loop by multiplying power to a (i.e. power = power*a) and since the any value multiplied by 1 is the value itself, so power will take the value of as the initial value of power is 1. (Wait till the explaintion of loop, there you will get this more clearly).

     for ( i = 1 ; i <= b ; i ++ )
     {
            power = power*a;
     }
    

    Let’s first iterate the loop.

    In the first turn, power = power*a (i.e. power = 1*a) will make the value of power equal to that of a and this is equivalent to a1. And here we can understand why we have given the value of power 1 initially. This was just because anything multiplied by 1 is the value itself. So, a multiplied with power(with value 1) is the same value of a and hence making the value of power equal to a and calculating a1.

    In the second iteration,

    power = power*a (i.e. power = a*a) and making the value of power equal to aand this is equivalent of calculating a2.

    In third iteration, power = a2*a will be calculated (since power is a2 from second iteration) and this is equivalent to calculating a3.

    Similarly in the bth iteration,

    power = power*a will calculate ab.

    The use of is just to run the loop.

    i<=b is used to run the loop b times. As i will go from 1 to b and this will make the loop run b times.


    • Thankyou Amit
      - UTHAPPA

  •    seoexpertim

    This is the first time i am visiting the site and it is very good. I got most of important content from https://www.airslate.com/bots/activecampaign for my paper. I will definitely visit the site again.



Ask Yours
Post Yours
Write your answer