SAMPLE C++ Programs
SAMPLE C++ Programs
#include <iostream>
#include <string>
using namespace std;
public:
// Constructor to initialize the name and age
Person(string n, int a) {
name = n;
age = a;
}
int main() {
// Create an object of the Person class
Person person1("John", 25);
// Display the initial details
cout << "Initial Details:" << endl;
person1.display();
return 0;
}
2. Write a program to display the following output using single cout statement
Maths= 90
Physics= 77
Chemistry= 69
#include <iostream>
using namespace std;
int main() {
int maths = 90;
int physics = 77;
int chemistry = 69;
return 0;
}
3. Write a program that a character from keyboard and display its corresponding ASCII value on the screen.
#include <iostream>
Using namespace std;
int main() {
char inputChar;
return 0;
}
In this program:
4. Write a C++ program that will ask for temperature in Fahrenheit and display it in Celsius. Write above
program using a class called temp and member functions.
#include <iostream>
using namespace std;
class Temp {
public:
// Function to convert Fahrenheit to Celsius
static double convertToFahrenheit(double fahrenheit) {
return (fahrenheit - 32.0) * 5.0 / 9.0;
}
};
int main() {
double fahrenheit;
return 0;
}
5. Write a c++ program with a function using reference variable as argument to swap the values
of a pair of integers.
#include <iostream>
using namespace std;
int main() {
int num1, num2;
// Input two integers from the user
cout << "Enter two integers separated by space: ";
cin >> num1 >> num2;
return 0;
}
#include <iostream>
using namespace std;
int main() {
// Outer loop controls the number of rows
for (int i = 1; i <= 5; ++i) {
// Inner loop prints the numbers in each row
for (int j = 1; j <= i; ++j) {
cout << i;
}
// Move to the next line after each row
cout << endl;
}
return 0;
}
7.
#include <iostream>
struct Player {
string name;
int runs;
int innings;
int not_out;
double average;
};
if (innings - not_out == 0)
cout << "Enter runs scored by " << player.name << ": ";
cout << "Enter innings played by " << player.name << ": ";
cout << "Enter times not out for " << player.name << ": ";
cin >> player.not_out;
cout << setw(10) << player.name << setw(10) << player.runs << setw(10) << player.innings << setw(10) <<
player.not_out << setw(10) << fixed << setprecision(2) << player.average << endl;
int main() {
readPlayer(sachin);
readPlayer(saurav);
readPlayer(rahul);
cout << setw(10) << "Name" << setw(10) << "Runs" << setw(10) << "Innings" << setw(10) << "Not Out" <<
setw(10) << "Average" << endl;
displayPlayer(sachin);
displayPlayer(saurav);
displayPlayer(rahul);
return 0;
}
8. An election is contested by five candidates. The candidates are numbered 1 to 5 and the voting is done by
making the candidate number on ballot paper. Write a program to read the ballot and count the votes cate
for each candidate using an array variable count. In case, a number read is outside the range 1 to 5, the
ballot should be considered as a ‘spoilt ballot’, and the program should also count the number of spoilt
ballots.
#include <iostream>
Using namespace std;
int main() {
const int num_candidates = 5;
int count[num_candidates] = {0}; // Array to store the count of votes for each candidate
int spoilt_ballots = 0;
cout << "Enter the ballot numbers (1 to 5) separated by spaces (enter -1 to stop):\n";
int ballot;
while (true) {
cin >> ballot;
return 0;
}
In this program:
• We use an array count to store the count of votes for each candidate.
• We use a loop to continuously read the ballot numbers until -1 is entered to stop.
• Inside the loop, we check if the entered ballot number is between 1 and 5. If it is, we increment
the count for the corresponding candidate.
• If the entered number is outside this range, we consider it as a spoilt ballot and increment the
spoilt_ballots count.
• After the loop, we display the count of votes for each candidate and the number of spoilt
ballots.
9. Write a C++ program to demonstrate the use of global version of a variable.
#include <iostream>
Using namespace std;
// Declare a global variable
int globalVar = 10;
int main() {
// Display the initial value of the global variable
cout << "Initial value of globalVar: " << globalVar << endl;
return 0;
}
In this program:
• We declare a global variable globalVar outside of any function. This variable can be accessed
and modified by any function in the program.
• Inside the modifyGlobalVar() function, we modify the value of globalVar.
• In the main() function, we display the initial value of globalVar, call the modifyGlobalVar()
function to modify it, and then display the modified value.
• The global variable globalVar is accessible and modifiable by both modifyGlobalVar() and
main().
10. Write a program to demonstrate the use of new and delete operator for dynamic allocation of memory.
#include <iostream>
using namespace std;
int main() {
// Dynamically allocate memory for an integer
int *ptr = new int;
return 0;
}
Explanation:
• We use the new operator to dynamically allocate memory for an integer. This line int *ptr =
new int; allocates memory for an integer and returns a pointer to that memory.
• We check if the allocation was successful by checking if the pointer is nullptr. If allocation
failed, we print an error message and return from the program.
• We assign a value to the memory location pointed to by ptr using the dereference operator *.
• We then display the value stored in dynamically allocated memory.
• Finally, we use the delete operator to release the memory allocated dynamically. It deallocates
the memory pointed to by ptr.
• It's a good practice to set the pointer to nullptr after deallocating the memory to avoid
accessing the memory that has been released.
11. Write a C++ program that reads the radius of a circle, calculates the area and then writes the calculated
result. The calculation continues until a value 0 is entered for the radius.
#include <iostream>
#include <cmath> // For M_PI constant
using namespace std;
int main() {
double radius;
do {
cout << "Enter the radius of the circle (0 to exit): ";
cin >> radius;
if (radius != 0) {
double area = M_PI * radius * radius;
cout << "Area of the circle with radius " << radius << " is: " << area << endl;
}
} while (radius != 0);
int main() {
// Input the numbers in one line
cout << "Enter real numbers separated by spaces: ";
string input;
getline(cin, input);
return 0;
}
Explanation:
2. **Namespace Declaration**:
- `using namespace std;`: This statement tells the compiler to consider all names from the `std` namespace
as if they were directly declared in the global namespace. This avoids the need to prefix standard library names
with `std::`.
3. **Main Function**:
- `int main()`: This is the entry point of the program. The execution of the program starts from here.
7. **Outputting Results**:
- `if (max == numeric_limits<double>::lowest() && min == numeric_limits<double>::max()) { ... }`: This
condition checks if no numbers were entered. If so, it outputs a message indicating that no numbers were
entered.
- `else { ... }`: If numbers were entered, it outputs the maximum and minimum values found.
- `cout << "Maximum: " << max << endl;`: This line outputs the maximum value.
- `cout << "Minimum: " << min << endl;`: This line outputs the minimum value.
13. Write a c++ program to print fibonacci series without using recursion and using recursion.
#include <iostream>
int main() {
int n;
cout << "Enter the number of terms in Fibonacci series: ";
cin >> n;
int a = 0, b = 1, c;
cout << "Fibonacci Series without recursion: ";
if (n >= 1)
cout << a << " ";
if (n >= 2)
cout << b << " ";
return 0;
}
#include <iostream>
int main() {
int n;
cout << "Enter the number of terms in Fibonacci series: ";
cin >> n;
return 0;
}
Explanation:
• For the non-recursive version, a loop calculates and prints each term of the series iteratively.
• For the recursive version, a recursive function calculates each term of the series.
Fibonacci is a sequence of numbers where each number is the sum of the two preceding ones, usually starting
with 0 and 1. So, the sequence goes: 0, 1, 1, 2, 3, 5, 8, 13, 21, and so on.
where:
- \( F(n) \) is the \( n \)-th Fibonacci number,
- \( F(0) = 0 \) and \( F(1) = 1 \).
- \( F(0) = 0 \)
- \( F(1) = 1 \)
- \( F(2) = F(1) + F(0) = 1 + 0 = 1 \)
- \( F(3) = F(2) + F(1) = 1 + 1 = 2 \)
- \( F(4) = F(3) + F(2) = 2 + 1 = 3 \)
- \( F(5) = F(4) + F(3) = 3 + 2 = 5 \)
- \( F(6) = F(5) + F(4) = 5 + 3 = 8 \)
- \( F(7) = F(6) + F(5) = 8 + 5 = 13 \)
- \( F(8) = F(7) + F(6) = 13 + 8 = 21 \)
- And so on...
The Fibonacci sequence has many interesting properties and applications in mathematics, computer science,
nature, and art. It appears in many different contexts, such as the arrangement of leaves on a stem, the
branching of trees, the spiral shells of snails, and the patterns in pinecones and sunflowers.
14. Write a c++ program to check prime number.
#include <iostream>
using namespace std;
int main() {
int n;
bool isPrime = true;
if (n <= 1) {
isPrime = false;
} else {
for (int i = 2; i <= n / 2; ++i) {
if (n % i == 0) {
isPrime = false;
break;
}
}
}
if (isPrime)
cout << n << " is a prime number." << endl;
else
cout << n << " is not a prime number." << endl;
return 0;
}
while (num != 0) {
sum += num % 10;
num /= 10;
}
return 0;
}
16. Write a c++ program to check armstrong number.
#include <iostream>
#include <cmath>
using namespace std;
int main() {
int num, originalNum, remainder, n = 0, result = 0;
originalNum = num;
while (originalNum != 0) {
originalNum /= 10;
++n;
}
originalNum = num;
while (originalNum != 0) {
remainder = originalNum % 10;
result += pow(remainder, n);
originalNum /= 10;
}
if (result == num)
cout << num << " is an Armstrong number." << endl;
else
cout << num << " is not an Armstrong number." << endl;
return 0;
}
17. Write a c++ program to swap two numbers without using third variable.
#include <iostream>
using namespace std;
int main() {
int a, b;
cout << "Before swapping: a = " << a << ", b = " << b << endl;
a = a + b;
b = a - b;
a = a - b;
cout << "After swapping: a = " << a << ", b = " << b << endl;
return 0;
}
18. Write a c++ program to print multiplication of 2 matrices
#include <iostream>
using namespace std;
int main() {
int m1[3][3] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
int m2[3][3] = {{9, 8, 7}, {6, 5, 4}, {3, 2, 1}};
int result[3][3] = {0};
return 0;
}
if (decimalNum < 0) {
cout << "Negative numbers are not supported." << endl;
return 1;
}
if (decimalNum == 0) {
cout << "Binary equivalent: 0" << endl;
return 0;
}
int binary[32]; // Array to store binary digits
int index = 0; // Index to store binary digits in the array
return 0;
}
return 0;
}
return 0;
}
return 0;
}
return 0;
}
24. Write C++ Program to print Quadratic Equations
#include <iostream>
#include <cmath>
int main() {
double a, b, c, discriminant, root1, root2;
// Calculate discriminant
discriminant = b * b - 4 * a * c;
return 0;
}
This program takes the coefficients of a quadratic equation (a, b, and c) as input and calculates its
roots. It considers three cases: