0% found this document useful (0 votes)
4 views

C++_Programming_Questions_Solutions

The document contains C++ programming solutions for generating the Fibonacci series both iteratively and recursively. It also includes a function to check if a number is prime. Each section provides code examples and prompts for user input.

Uploaded by

Gabriel Mturi
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

C++_Programming_Questions_Solutions

The document contains C++ programming solutions for generating the Fibonacci series both iteratively and recursively. It also includes a function to check if a number is prime. Each section provides code examples and prompts for user input.

Uploaded by

Gabriel Mturi
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 3

C++ Programming Questions & Solutions

Q1: Fibonacci Series (Without Recursion)

#include <iostream>
using namespace std;

void fibonacci(int n) {
int t1 = 0, t2 = 1, nextTerm;
for (int i = 1; i <= n; i++) {
cout << t1 << " ";
nextTerm = t1 + t2;
t1 = t2;
t2 = nextTerm;
}
}

int main() {
int n;
cout << "Enter number of terms: ";
cin >> n;
fibonacci(n);
return 0;
}

Q1: Fibonacci Series (With Recursion)

#include <iostream>
using namespace std;

int fibonacci(int n) {
if (n <= 1)
return n;
return fibonacci(n - 1) + fibonacci(n - 2);
}

int main() {
int n;
cout << "Enter number of terms: ";
cin >> n;
for (int i = 0; i < n; i++) {
cout << fibonacci(i) << " ";
}
return 0;
}

Q2: Prime Number Check

#include <iostream>
using namespace std;

bool isPrime(int n) {
if (n < 2)
return false;
for (int i = 2; i * i <= n; i++) {
if (n % i == 0)
return false;
}
return true;
}

int main() {
int num;
cout << "Enter a number: ";
cin >> num;
if (isPrime(num))
cout << num << " is a prime number.";
else
cout << num << " is not a prime number.";
return 0;
}

You might also like