0% found this document useful (0 votes)
15 views3 pages

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)
15 views3 pages

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

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy