answersLogoWhite

0

There are three ways to do repetitions in C as far as I know. The first is to use recursion (a function which calls itself) the second being a for loop and the third being a while loop, though both of these are basically the same thing. Here's a demonstration of using these three methods to compute the x raised to the power of y: (note this isn't the most efficient way of calculating the power of a number but it's good enough for an example)

//Recursion:

int pow(int base, int pwr){

if(pwr == 0){

return 1;

}else{

return base * pow(base, pwr - 1);

}

}

//For loop

int pow(int base, int pwr){

int i;

int result = 1;

//The for loop initialises i to the value of pwr, then

//runs the loop, subtracting 1 from i each time until

//i fails the test (i > 0) at which point the loop finishes

for(i = pwr; i > 0; i--){

result *= base

}

return result;

}

//While loop

int pow(int base, int pwr){

int result = 1;

while(pwr > 0){

result *= base;

pwr--;

}

return result;

}

User Avatar

Wiki User

14y ago

What else can I help you with?