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

∙ 15y ago

What else can I help you with?

Related Questions

What is the trigonometric function for cotA plus B plus C?

cot(A+B+C) is, itself, a trigonometric function, so the question does not really make any sense!


When will you make a function inline in c plus plus?

yes,we can make function inline


Is 2x plus y equals 5 a function?

Yep. No values of X will ever repeat themselves.


How do you make internationaql calls?

Dial [1] plus the area code, and the number itself


How do you make plus or minus sign with MS keyboard?

press function (Fn) + P


What is the polynomial for x2 plus 11x plus 30?

The actual equation itself is the polynomial. There is no polynomial for it, and your question doesn't really make sense.


Is y plus x2 plus 1 a function?

That is not a function, although it does involve the function of addition. A function is something that is done to numbers.


A c plus plus statement that invokes a function is known as?

...a function call.


What are the building function in c plus plus?

There is no such term as "building function" in C++.


In C plus plus when a function is executing what happens when the end of the function is reached?

Control is returning to the caller of the function.


Can reading plus repeat the story 3 times?

yes it can


Which C plus plus keyword allows a function outside of a class to access private class members?

The keyword is friend. The external function must be declared a friend of the class (from within the class itself) in order to become a member of the class and thus gain access to the private (and protected) members of the class.