Computer Applications
How many times will the following loop execute? Write the output of the code:
int a = 5;
while (a > 0) {
System.out.println(a-- + 2);
if (a % 3 == 0)
break;
}
Java Iterative Stmts
2 Likes
Answer
Loop executes two times.
Output
7
6
Reason — Let's go through the Java program step by step to understand how it works:
Initial Value:
a = 5
Iteration 1:
System.out.println(a-- + 2);
a--
: Post-decrement is used, so the current value ofa
(5
) is used first, then decremented.- Output:
5 + 2 = 7
a
becomes4
if (a % 3 == 0)
:4 % 3 = 1
→ Condition is false, so the loop continues.
Iteration 2:
System.out.println(a-- + 2);
a--
: Current value ofa
(4
) is used, then decremented.- Output:
4 + 2 = 6
a
becomes3
.
if (a % 3 == 0)
:3 % 3 = 0
→ Condition is true, so thebreak
statement exits the loop.
Therefore, the loop executes 2 times and the output is:
7
6
Answered By
2 Likes
Related Questions
Give the output of following code and mention how many times the loop will execute?
int i; for( i=5; i>=1; i--) { if(i%2 == 1) continue; System.out.print(i+" "); }
Define a class to accept a number from user and check if it is an EvenPal number or not.
(The number is said to be EvenPal number when number is palindrome number (a number is palindrome if it is equal to its reverse) and sum of its digits is an even number.)
Example: 121 – is a palindrome number
Sum of the digits – 1+2+1 = 4 which is an even numberDefine a class to accept a number and check whether it is a SUPERSPY number or not. A number is called SUPERSPY if the sum of the digits equals the number of the digits.
Example1:
Input: 1021 output: SUPERSPY number [SUM OF THE DIGITS = 1+0+2+1 = 4, NUMBER OF DIGITS = 4 ]
Example2:
Input: 125 output: Not an SUPERSPY number [1+2+5 is not equal to 3]
A tech number has even number of digits. If the number is split in two equal halves, then the square of sum of these halves is equal to the number itself. Write a program to generate and print all four digits tech numbers.
Example:
Consider the number 3025
Square of sum of the halves of 3025 = (30 + 25)2
= (55)2
= 3025 is a tech number.