Cutting the pattern number
public class numPattern {
public static void main(String[] args) {
int digit1 = 2;
int digit2 = 7;
int tal = 0;
System.out.print(digit1 + " ");
System.out.print(digit2 + " ");
while (tal < 550) {
tal = digit1 + digit2;
System.out.print(tal + " ");
digit1 = digit2;
digit2 = tal;
}
}
}
This outputs 2, 7, 9, 16, 25, 41, 66......453 and 733
The problem is, it has to stop at 453, because 733 is over 550.
Which command will make sure the program ends in 453 to match the 550 or greater I'm trying to look for?
source to share
Simple change:
while (tal < 550){
tal = digit1 + digit2;
System.out.print(tal + " ");
digit1 = digit2;
digit2 = tal;
}
in
while (tal < 550) {
System.out.print(tal + " ");
digit1 = digit2;
digit2 = tal;
tal = digit1 + digit2;
}
and initialization tal
:
from int tal = 0
, toint tal = digit1 + digit2;
source to share
Just skip the printout digit2
, initialize tal
to the same value, and reorder the statements in your loop:
int digit1 = 2;
System.out.print(digit1 + " ");
int digit2 = 7;
int tal = digit2;
while (tal < 550) {
System.out.print(tal + " ");
tal = digit1 + digit2;
digit1 = digit2;
digit2 = tal;
}
source to share
int digit1 = 2;
System.out.print(digit1 + " "); //it will print digit1
do not print digit2
int digit2 = 7;
int tal = digit2;
while (tal < 550) {
System.out.print(tal + " ");
tal = digit1 + digit2;
digit1 = digit2;
digit2 = tal;
}
Because in your loop, it first increments the value and then prints it before the condition says false, it already prints out the value when tal = 443, then it enters the while loop and it prints it, then go to check the value
After it is changed, it will first print the value, then execute the sum and check if it is less or not, and hence it will not act after 443
source to share