Reputation: 133
I was writing a practice program in Java for one number raised to the other. Unknowingly I made a peculiar mistake which I caught. However the answer still came out correct no matter the input I give. Below is the piece of code.
public static void main(String args[])
{
int count;
int num1, num2, result = count =1;
try(Scanner n1 = new Scanner(System.in))
{
System.out.println("Enter the 1st number");
num1 = n1.nextInt();
System.out.println("Enter the 2nd number");
num2 = n1.nextInt();
}
while(count<=num2)
{
if(num2!=0)
{
result = num1*result;
count++;
}
else
{
System.out.println(num1+" to the power "+num2+" is "+num1);
}
}
System.out.println(num1+" to the power "+num2+" is "+result);
}
I'm going crazy as to what exactly happened. how come the statement "System.out.println(num1+" to the power "+num2+" is "+num1)" didn't print value of num1.
Following is the output:
{
Enter the 1st number
100
Enter the 2nd number
0
100 to the power 0 is 1
}
I use ECLIPSE LUNA to code java.
Upvotes: 1
Views: 1279
Reputation: 394026
Well, assuming that you initialize count
and result
to 1 (which, after your edit, I see was a correct assumption), if num2
is 0, the loop is not entered at all, and all you see is the output printed by the last line (after the loop).
Therefore it doesn't matter what you have inside the loop in this case - System.out.println(num1+" to the power "+num2+" is "+num1);
will never be executed when num2
is 0.
Upvotes: 6