A Fibonacci sequence consists of the numbers: 1, 1, 2, 3, 5, 8. 13, 21 ... The s
ID: 642958 • Letter: A
Question
A Fibonacci sequence consists of the numbers: 1, 1, 2, 3, 5, 8. 13, 21 ... The sequence starts with numbers 1 and 1. All of the following numbers are calculated by adding the previous two numbers in the sequence. For example, the 3rd number is obtained by adding 1+1 = 2, the 4th number is: 1+2 = 3, the 5th number is: 2+3 = 5, and so on. Calculate the separated average of all odd and even numbers of a Fibonacci sequence up to a number ''n''. Write a C++ program that: - Asks the user for a positive natural number ''n'' (the upper bound in the Fibonacci sequence) - Has a function that calculates the Fibonacci numbers - Has a function that tests whether a number is odd/oven - Uses both functions efficiently Notes: The program that you turn in must be your original and individual work. While you are allowed to discuss the program assignments in general terms with others, you are not allowed to share details of the actual solution(s) or program code with anybody except the instructor. Turning in a copy of someone else's program, even a copy with extensive changes made to it, or receiving any unauthorized assistance is a very serious offense in this course. An automated plagiarism checker may scan programs at any time during the semester. Only submit your source code (.cpp). This must be done on or before the due date through Blackboard. No late submissions. Blackboard will automatically close the submission page right after the deadline. Your program must include comments explaining your steps and must be properly formatted (see Program_Style_Guidelines.pdf in Blackboard). * ELET 2300 * Programming Assignment #4 * Compiler type (if other then Visual C++)Explanation / Answer
#include <iostream>
using namespace std;
double avg[2];
int iseven(int i) //Checks for prime
{
if(i%2==0)
return 1;
else
return 0;
}
void fibonacci(int n, double *avg) //Generates fibonacci and checks prime
{
int a=1,b=1,c=2,cntodd=2,cnteven=0,sumodd=2,sumeven=0;
if(n==1)
{
avg[0]=1;
avg[1]=0;
return;
}
while(c<=n)
{
if(iseven(c))
{
++cnteven;
sumeven = sumeven + c;
}
else
{
++cntodd;
sumodd = sumodd + c;
}
a=b;
b=c;
c=a+b;
}
avg[1] = (double)sumeven/cnteven;
avg[0] = (double)sumodd/cntodd;
}
int main() {
int n;
cout<< "Enter n: ";
cin>>n;
fibonacci(n,avg);
cout<<"Average of odd fibonacci nos upto n= "<< avg[0] <<" ";
cout<<"Average of even fibonacci nos upto n= "<< avg[1] <<" ";
return 0;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.