Important C++ Practical Programs with Q&A
Question: Write a C++ program to add two numbers.
Answer:
This program demonstrates basic input and output operations in C++. Two numbers are taken as
input from the user, and their sum is displayed as output.
Code:
#include <iostream>
using namespace std;
int main() {
int a, b, sum;
cout << "Enter two numbers: ";
cin >> a >> b;
sum = a + b;
cout << "Sum: " << sum << endl;
return 0;
Sample Output:
Input:
Enter two numbers: 5 10
Output:
Sum: 15
Question: Write a C++ program to calculate the factorial of a number.
Answer:
This program calculates the factorial of a number using a for loop. Factorial is calculated as the
product of all integers from 1 to the given number.
Code:
#include <iostream>
using namespace std;
int main() {
int n, factorial = 1;
cout << "Enter a number: ";
cin >> n;
for (int i = 1; i <= n; i++) {
factorial *= i;
cout << "Factorial: " << factorial << endl;
return 0;
Sample Output:
Input:
Enter a number: 5
Output:
Factorial: 120
Question: Write a C++ program to display the Fibonacci series up to n terms.
Answer:
This program generates the Fibonacci series, where each term is the sum of the two preceding
terms. The user inputs the number of terms to display.
Code:
#include <iostream>
using namespace std;
int main() {
int n, t1 = 0, t2 = 1, nextTerm;
cout << "Enter the number of terms: ";
cin >> n;
for (int i = 1; i <= n; i++) {
cout << t1 << " ";
nextTerm = t1 + t2;
t1 = t2;
t2 = nextTerm;
return 0;
Sample Output:
Input:
Enter the number of terms: 5
Output:
01123
Question: Write a C++ program to check if a number is prime.
Answer:
This program checks if a number is prime by verifying whether it has any divisors other than 1 and
itself. A loop is used to test divisibility up to n/2.
Code:
#include <iostream>
using namespace std;
int main() {
int n, i;
bool isPrime = true;
cout << "Enter a positive integer: ";
cin >> n;
if (n <= 1) {
isPrime = false;
} else {
for (i = 2; i <= n / 2; i++) {
if (n % i == 0) {
isPrime = false;
break;
}
if (isPrime)
cout << n << " is a prime number.";
else
cout << n << " is not a prime number.";
return 0;
Sample Output:
Input:
Enter a positive integer: 7
Output:
7 is a prime number.