0
/** calculate the value of 'a' raised to 'b'.**/
#include <stdio.h>

int main (){

int a,b,calc,calculation;

printf("Enter value of a and b\n");
scanf("%d %d",&a,&b);

calculation=1;
for(calc=1;calc<=b;calc++)
{

calculation=calculation*a;
}

printf("%d raised to %d is %d",a,b,calculation);
return 0;

}

My problem is I don't understand how this part " calculation=calculation*a; "
Let's say a=2, b=3; in for loop it will loop for 3 times rite?, but after that i don't know how it calculates to get the result. Just want to get some explanation because there is no explanation in the book about how it works.Thanks.

2
Contributors
2
Replies
3
Views
8 Years
Discussion Span
Last Post by J-son
0

> Let's say a=2, b=3; in for loop it will loop for 3 times rite?
Right. If you know how many times the loop will loop, you can take the loop away and simplify the world:

a = 2;
b = 3;
calculation = 1;

for(calc = 1; calc <= b; calc++)
{
  calculation=calculation * a;
}

Becomes:

a = 2;
calculation = 1;
calculation = calculation * a;
calculation = calculation * a;
calculation = calculation * a;

The value of a doesn't change, so you can remove that and make it a constant:

calculation = 1;
calculation = calculation * 2;
calculation = calculation * 2;
calculation = calculation * 2;

calculation = calculation * 2 is multiplying calculation by 2 and replacing the original value with the new one. You can remove even that complexity and hard code it:

calculation = 1;
calculation = 2; // 1 * 2 = 2
calculation = 4; // 2 * 2 = 4
calculation = 8; // 4 * 2 = 8

A lot of complicated code can be unrolled like that to figure out how it works. :)

0

Thank you very much. You explanation really helpful. :)

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.