#include <stdio.h> int main(void) { int userinput; int fib3, fib1 = 1, fib2 = 1;
ID: 3651189 • Letter: #
Question
#include <stdio.h>int main(void)
{
int userinput;
int fib3, fib1 = 1, fib2 = 1;
printf(" Enter a limit on the largest number to be displayed: ");
scanf("%d", &userinput);
printf("%d ", fib1);
do
{
printf("%d ", fib2);
fib3 = fib1 + fib2;
fib1 = fib2;
fib2 = fib3;
} while(fib3 <= userinput);
int j;
int max = 0;
int temp = fib1;
int final = 2;
for(j = 1; temp % j == 0 && j <= temp; j *= 2)
{
max = j;
}
printf(" The last number %d is disible by %d ", temp, max);
return 0;
}
Here is what the user will see when the program is executed:
This program prints the Fibonacci sequence
Enter a limit on the largest number to be displayed: 50
1 1 2 3 5 8 13 21 34
The last number 34 is divisible by 2.
Do you want to print a different sequence (Y/N): y
Enter a limit on the largest number to be displayed: 200
1 1 2 3 5 8 13 21 34 55 89 144
The last number 144 is divisible by 16.
Do you want to print a different sequence (Y/N): n
Explanation / Answer
you are using two while loops at the end, which is not required and also you have this line
" }while(choice != 'n'); ". There is a closed brace( } ) before while. that means you are supposed to use 2 do,while loops in your code. I have made some changes to your code and here it is
#include <stdio.h>
int main(void)
{
int userinput;
int fib3; //fib1 = 1, fib2 = 1; every time the user enters yes, these values should be intialised to 1. so I have initialised inside the do, while loop.
char choice;
do // this is the first do, while loop you should use in your program
{
int fib1 = 1, fib2 = 1; // every time initialise these values
printf(" Enter a limit on the largest number to be displayed: ");
scanf("%d", &userinput);
printf("%d ", fib1);
do
{
printf("%d ", fib2);
fib3 = fib1 + fib2;
fib1 = fib2;
fib2 = fib3;
} while(fib3 <= userinput);
int j;
int max = 0;
int temp = fib1;
int final = 2;
for(j = 1; temp % j == 0 && j <= temp; j *= 2)
{
max = j;
}
printf(" The last number %d is disible by %d ", temp, max);
printf(" Do you want to print a different sequence (y/n):");
scanf(" %c",&choice);
}//while((choice = getchar()) != 'n'); //continue; we are just checking to see if the user enters 'y' or 'n' so, just one scanf and the choice!='n' in the next line is sufficient.
while(choice != 'n');
system("pause");
return 0;
}
hope it helps
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.