In: Computer Science
Q1) Write programs with iterators that computes:
• The sum of all even numbers between 2 and 100 (inclusive).
• The sum of all squares between 1 and 100 (inclusive).
• The product of all powers of 2 from 20 up to 220 .
• The product of all odd numbers between a and b (inclusive), where a and b are inputs. sum would be 3 + 7 + 7 = 17.)
Q2) Recall the Fibonacci sequence: 1, 1, 2, 3, 5, 8, 13, . . .
In general we can generate Fibonacci-like sequences by making linear combinations of the formula that gives us the nth term of the sequence.
Consider the following general case for generating Fibonacci-like sequences:
F1 = 1
F2 = 1
Fn = aFn−1 + bFn−2
where a, b are integers. Write a function that given values a, b and n will print a Fibonacci-like sequece up to the nth term of the squence.
(eg, if a = 1 and b = 2 the resulting sequence is 1, 1, 3, 5, 11, 21, 43 . . .)
*note: Since no particular language is mentioned, I have written code in C++
Ans 1: a.
#include<iostream>
using namespace std;
int main(){
int total=0;
for(int i=2;i<=100;i++){
if(i%2==0){
total=total+i;
}
}
cout<<"Sum of even number between 2 and 100 is
:"<<total;
return 0;
}
Ans 1. b.
#include<iostream>
using namespace std;
int main(){
int total=0;
for(int i=1;i<=10;i++){
total=total+(i*i);
}
cout<<"sum of all squares between 1 and 100 is
:"<<total;
return 0;
}
Ans 1. c.
#include<bits/stdc++.h>
using namespace std;
int main(){
int j=4,prod=1,i=1;
while(pow(2,j)<=220){
i=pow(2,j);
if(i>20){
cout<<i<<endl;
prod=prod*i;
}
j++;
}
cout<<"product of all powers of 2 from 20 up to 220
:"<<prod;
return 0;
}
Ans 1. d.
#include<bits/stdc++.h>
using namespace std;
int main(){
int a,b,prod=1;
cout<<"Enter value of a and b :";
cin>>a>>b;
for(int i=a;i<=b;i++){
if(i%2==1){
prod=prod*i;
}
}
cout<<"The product of all odd numbers between a and b
:"<<prod;
return 0;
}
Ans 2.
#include <iostream>
using namespace std;
int fib(int n,int a,int b) {
if((n==1)||(n==0)) {
return(n);
}else {
return((a*fib(n-1,a,b))+(b*fib(n-2,a,b)));
}
}
int main() {
int n,i=1,a,b;
cout<<"Enter the value of a and b :";
cin>>a>>b;
cout<<"Enter the length for series: ";
cin>>n;
cout<<endl<<"Series :";
while(i<=n) {
cout<<" "<<fib(i,a,b);
i++;
}
return 0;
}