I don't understand this Method and Output | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 2

I don't understand this Method and Output

static int Pow(int x, int y = 2) { int result = 1; for (int i = 0; i < y; i++) /* this is the for loop that I don't understand. I know that it would express itself as i = 0 and i = 1 and then stop, but I'm not sure how the variable i affects the x and y in this case. */ { result *=x; /* I know this means x*x so if x were 3 it would be 9 */ } return result; } static void Main(string[] args) { Console.WriteLine(Pow(6)); /* so the output here is 36, were x = 6 and y as a default y = 2, but I don't see how we

22nd Jan 2017, 5:14 PM
Steven Bennett
Steven Bennett - avatar
2 Answers
+ 3
The way it works is that the for loop continues until i < y is false. In your code y = 2 an i = 0 at the start so that means that the loop can do 2 iterations(repeats) before it is 2 and not smaller than y. result *= x; means result = result * x. So if you fill in the values of the variables, the first iteration it is result = 1 * 6 and the second it is: result = 6 * 6 which is ofcourse 36.
22nd Jan 2017, 5:34 PM
Niels Koomen
Niels Koomen - avatar
0
Thank you very much
27th Jul 2017, 6:38 PM
niccoob _
niccoob _ - avatar