I am trying to print a Fibonacci sequence using a do-while
loop in java and can't understand this. Needs to be between 0 and 100.
I have the following code:
int prevPrevVal = 0;
int prevVal = 1;
int currVal;
System.out.println(prevPrevVal);
System.out.println(prevVal);
do
{
currVal = prevVal + prevPrevVal;
System.out.println(currVal);
prevPrevVal = prevVal;
prevVal = currVal;
} while (prevVal <= 100);
This is a simplified program to find out the Fibonacci series by providing the conditional limit in the while loop. Hope you guys get an idea over with this....!!
int a=0;
int b=0;
int temp=1;
do {
a=b;
b=temp;
temp=a+b;
System.out.println(temp);
}while(temp<100);
Managed to do it with two variables and without printing a number out of range. Sorry if it's crappy, it's my first day of programming :)
int x = 0;
int y = 1;
do
{
System.out.println(x);
y = x + y;
if (y < 100)
{
System.out.println(y);
}
x = x + y;
} while (x < 100);
This should be your solution
public static void main(String[] args) {
int prevVal = 1;
int prevPrevVal = 0;
int n = 0;
do{
int currVal = prevVal + prevPrevVal;
prevPrevVal = prevVal;
prevVal = currVal;
System.out.print(currVal+" ");
n++;
}while(n<5);//n is the number of terms
}
Here you go :
int prevVal = 1;
int prevPrevVal = 0;
do{
int currVal = prevVal + prevPrevVal;
//currVal is your Fibonacc seq.
prevPrevVal = prevVal;
prevVal = currVal;
}
while(yourCondition);
Using the basic structure of a do-while
loop from the documentation :
do {
statement(s)
} while (expression);
What you want in the "statement(s)" section is to increment (and possibly output) your result through each iteration. A basic Fibonacci sequence using a do-while
loop would look like the following:
int prevVal = 1;
int prevPrevVal = 0;
int currVal;
do {
// Add the two numbers
currVal = prevVal + prevPrevVal;
// "Bump" up prevPrevVal to prevVal, and prevVal to currVal
prevPrevVal = prevVal;
prevVal = currVal;
// Output to the screen
System.out.println(currval + "\n");
} while(expression);
Since you want the terms of Fibonacci up to 100,just change while (prevVal <= 100);
to while (prevVal+prevPrevVal <= 100);
This will print up to 89.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.