+ 1

when we write the following code. Output comes 3 why not 9

when we write the following code. Output comes 3 why not 9 { class Program { static void Sqr(int x) { x = x * x; } static void Main(string[] args) { int a = 3; Sqr(a); Console.WriteLine(a); } } }

23rd Sep 2018, 1:26 AM
kp kalia
kp kalia - avatar
2 odpowiedzi
+ 4
the output is 3 because x is only changed within the function. if you wish for it to be changed outside it do: static void Sqr(ref int x) and Sqr(ref a) then you'll see the output being 9
23rd Sep 2018, 8:52 AM
hinanawi
hinanawi - avatar
+ 1
kp kalia do like this to get answer as 9: a = Sqr(a); and in method , do return x changing function return type as int from void..
23rd Sep 2018, 4:26 AM
Ketan Lalcheta
Ketan Lalcheta - avatar