0
I really don't understand this... Can anybody give me some help about what this means?
What is the output of this code? static int Vol(int x, int y=3, int z=1) { return x*y*z; } static void Main(string[] args) { Console.WriteLine(Vol(2, 4)); } Why does this output 8? And also, why do these output what they do? static int Pow(int x, int y=2) { int result = 1; for (int i = 0; i < y; i++) { result *= x; } return result; } static void Main(string[] args) { Console.WriteLine(Pow(6)); //Outputs 36 Console.WriteLine(Pow(3, 4)); //Outputs 81 }
7 Antworten
+ 5
The Pow funxzction multiplies the local variable result by the x parameter for a number of times defined by the parameter y.
Pow(6) means that x=6 and y, since is not specified assumes its default value y=2
the loop will run 2times (y=2)
in rhe loop
result=result*x. //1*6
in the first iteration
result becomes 6
in the second iteration
result=result*x. //6*6
result assumes rhe value of 36
the loops ends after the second iteration (y=2) unless you specify a different number for y as the second argument of the Pow Function.
This is what happens in the second pow example in your program: Pow(3,4)
The loop will iterate 4 times
1*3=3
3*3=9
9*3=27
27*3 hence 81
+ 4
vol(in x, int y=3, int z=1)
means that the second and third parameters have default values of 3 and 1 in case you don't specify them with arguments;
calling vol(2,4) you are makin x=2, you are specifying that y=4 and you won't use the default value. you are not specifying the value of z that will be the default value z=1.
return x*y*z is equivalent to return 2*4*1, hence return 8
+ 3
Wow such a huge explanation
Hats off
+ 3
@Visnu ks the value of missing argumen is the default value specified by the parameter.
If you "set it to zero" it won't work
Pow(3) woud work erraticaly if the unspecified argument y would be equal to 0.
+ 3
@seamiki
It's vishnu n not visnu
K coming back, if the default value is not specified then it will be set to zero.
+ 2
The basic concept here is that when the number of parameters you pass while calling the function doesn't match with the number of parameters specified in the function definition, the value of the missing parameters by default are set to zero
0
At first I was like how does it go through 4 iterations. Think I was reminded that 'i' in the for loop "for(int i = 0; i < y; i++)" started at 0 and not 1.