# minor problem in a code

This is a discussion on minor problem in a code within the C Programming forums, part of the General Programming Boards category; hello guys im sorry for asking so much some codes in K&R are complicated Code: #include <stdio.h> /* test power ...

1. ## minor problem in a code

hello guys im sorry for asking so much some codes in K&R are complicated
Code:
```#include <stdio.h>
/* test power function */
int power(int m, int n);
/* power: raise base to n-th power; n >= 0 */
int power(int base, int n)
{
int i, p;
p = 1;
for (i = 1; i <= n; ++i)/*here i=0 i<=n i++
*like lets say we do 1 for int n it will run from 1 till num*/
p *= base;//p=p * base;
return p;
}
int main(void)
{
int i;
for (i = 0; i < 10; ++i)
printf("%d %d %d\n", i, power(2,i), power(-3,i));
getchar();
return 0;
}```
here we passed i then power(2,i) and power(-3,i));
in our orginal function power he set p=1 so if we passed base that means p=1 *2
shouldnt this alawys 1*num=num ? or what coz it gets diff results like first
set is 1 ,1 shoudlnt it be 2,-3 ??

2. The first value should be 0, 1, 1, then 1, 2, -3, then 2, 4, 9, etc.

--
Mats

3. but n is the 2nd parameter base is the first so it will be alawys 2 or -3 ?
and since he intilized the p to 1 it will alawys p=p*2; or p=p*-3; so
1=1*2; or 1=1*-3 since he didnt make * n right ?

4. Originally Posted by elwad
but n is the 2nd parameter base is the first so it will be alawys 2 or -3 ?
and since he intilized the p to 1 it will alawys p=p*2; or p=p*-3; so
1=1*2; or 1=1*-3 since he didnt make * n right ?
but look p is changing in the loop.for eg i=5, then base =2,n=5 so the loop in the power function will change p=p*base 5 times,i mean first p=1 then p=2,then p=4 and so on.and yes you're right base never changes,but p.i think u got me.

5. how p changes we didnt write any code to make it change ? we just wrote it to be =1 we didnt after that make in the for loop p=i ?so how does it = to i in this program ? its so confusing

6. Originally Posted by elwad
how p changes we didnt write any code to make it change ? we just wrote it to be =1 we didnt after that make in the for loop p=i ?so how does it = to i in this program ? its so confusing
just see as i told you let n=5,then in the for loop inside power function when i=1 then p=p*base makes p=1*2(for the case base=2),which is =2 so new value of p=2,then i increments to 2,then p=p*base makes p=2*2=4(new value of p),again i increments to 3,then p=p*base gives p=4*2=8(new value of p) and so on.this way p changes continuosly until i becomes 6.am i understood?

7. yah i understand now thanks

8. like each time it will get a new value from the loop lets say we made i=2 and and power by 2 it will run 2 times whish will get the value 4 lolz ........ stupid me

Popular pages Recent additions