Computer Applications
Give output of the following method definition and also write the mathematical operation they carry out:
void test2(int a, int b)
{
while( a != b)
{
if ( a > b)
a = a — b;
else
a = b — a;
}
System.out.println(a);
}
if 4 and 17 are passed to the function.
Answer
Infinite Loop
Working
Initial value of a
is 4 and b
is 17 as given in the question. As a
and b
are not equal, condition of while loop is true, first iteration starts. a
is less than b
so if condition is false, a = b - a
is executed and a
becomes 17 - 4 = 13
. Condition of while loop is true so second iteration starts. Again, if condition is false. This time a
becomes 17 - 13 = 4
. Like this, the value of a
keeps oscillating between 13 and 4 resulting in an infinite loop.
Related Questions
Give output of the following method definition and also write the mathematical operation they carry out:
void test1(int n) { for(int x=1; x<=< span>n; x++) if(n%x == 0) System. out.println(x); } =<>
if 12 is passed to n.
Give output of the following method definition and also write the mathematical operation they carry out:
void test4(String x, String y) { if(x.compareTo(y) > 0) System.out.println(x); else System.out.println(y); }
if "AMIT" and "AMAN" are passed to the method.
Give output of the following method definition and also write the mathematical operation they carry out:
void test3(char c) { System.out.println( (int) c); }
if 'm' is passed to c.