The program must be coded in C. Please restrict to only using #INCLUDE<STDIO.H>
ID: 3726543 • Letter: T
Question
The program must be coded in C. Please restrict to only using #INCLUDE<STDIO.H> and no FOR statements as well.
(1) Write a program that will generate the first 15 numbers in the Fibonacci sequence and stores them into an array.
(2) Print out the contents of the array created in (1) in reverse
(3) Ask the user for which index would they like the "odd cumulative sum" taken (0 through 14). The odd cumulative sum is the sum of al odd numbers preceding and including the requested index.
This is the code I have so far:
#include <stdio.h>
int main()
{
int fib[15];
fib[0] =0;
fib[1]=1;
int i;
int n;
n= 15;
i =2;
while(fib[i] < n)
{
fib[i] = fib[i-1] + fib[i-1];
printf("Fibonacci Sequence is: %i ", fib[i]);
i = i+1;
}
}
Explanation / Answer
#include <stdio.h>
int main()
{
int fib[15];
fib[0] =0;
fib[1]=1;
printf("Fibonacci Sequence is: ");
printf(" %d %d ",fib[0],fib[1]);
int i;
int n;
n= 15;
i =2;
int index;
int sum=0;
while(i< n)
{
fib[i] = fib[i-1] + fib[i-2]; //sum of previous 2 numbers
printf(" %d", fib[i]);
i = i+1;
}
printf("Fibonacci Sequence in reverse order ");
i=n-1;//for reverse order
while(i>=0)
{
printf(" %d", fib[i]);
i = i-1;
}
printf(" ");
printf(" for which index would you like the odd cumulative sum taken ");
scanf("%d",&index);
i=0;
while(i<=index)
{
if(fib[i]%2==1)
sum=sum+fib[i];
i++;
}
printf("Odd cumulative sum is %d",sum);
}
EXPLANATION
preeding is subjected here as before
fib[i] = fib[i-1] + fib[i-2]; means sum of previous two numbers
example fib[2]=fib[1]+fib[0];
fib[3]=fib[2]+fib[1] and so on.....
print in reverse order means from 15 to 0
ODD number can be checked if any number is divided by 2 and gives remainder 1.
i.e any number 5 is odd as it gives 1 as remainder when divided by 2.
so condition should be checked as
if (num%2==1)
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.