package hlo;
public class While {
public static void main(String[]args) {
int no=7;
int count=1; // 7=7+3=10 10=10-2=8
while(count<=3) {
no=no+3;
System.out.print(no+ " " );
no=no-2;
System.out.print(no+ " " );
count=count+1;
}
}
}
//Explanation:
//This is a simple alternating addition and subtraction series. In the first pattern, 3 is added; in the second, 2 is subtracted.
//Look at this series: 7, 10, 8, 11, 9, 12, ... What number should come next?
Output:
10 8 11 9 12 10
why use count?
You're wondering if the count variable, that is incremented as count = count + 1, can be changed to increase by 2 (count = count + 2), or if we could use subtraction, multiplication, or division within the while loop.
Answer:
Yes, you may change count in any way you want.
If you set count = count + 2, the loop will execute half as often because count is incremented by 2 rather than by 1.
If you use count = count - 1, the loop may never end (infinite loop) if you do not establish proper conditions.
If you use multiplication (count = count * 2), the loop will expand exponentially and terminate long before.
If you use division (count = count / 2), the value will reduce, and based on the condition, it may never meet the stopping criteria or stop prematurely.
The idea is to reduce count cautiously in relation to the number of times you wish to repeat the loop.
Top comments (0)