0% found this document useful (0 votes)
11 views20 pages

SAMPLE C++ Programs

The document contains multiple C++ program examples demonstrating various programming concepts such as classes, functions, loops, and memory management. Each example includes code snippets that illustrate how to implement specific functionalities, such as calculating averages, swapping values, and handling user input. The programs cover a wide range of topics suitable for learning and practicing C++ programming.
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)
11 views20 pages

SAMPLE C++ Programs

The document contains multiple C++ program examples demonstrating various programming concepts such as classes, functions, loops, and memory management. Each example includes code snippets that illustrate how to implement specific functionalities, such as calculating averages, swapping values, and handling user input. The programs cover a wide range of topics suitable for learning and practicing C++ programming.
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/ 20

MORE SAMPLE C++ PROGRAMS

1. Write a C++ program to demonstrate the use of class in program.

#include <iostream>
#include <string>
using namespace std;

// Define a class called Person


class Person {
private:
string name;
int age;

public:
// Constructor to initialize the name and age
Person(string n, int a) {
name = n;
age = a;
}

// Function to set the name of the person


void setName(string n) {
name = n;
}

// Function to set the age of the person


void setAge(int a) {
age = a;
}

// Function to get the name of the person


string getName() {
return name;
}

// Function to get the age of the person


int getAge() {
return age;
}

// Function to display the details of the person


void display() {
cout << "Name: " << name << endl;
cout << "Age: " << age << endl;
}
};

int main() {
// Create an object of the Person class
Person person1("John", 25);
// Display the initial details
cout << "Initial Details:" << endl;
person1.display();

// Modify the details


person1.setName("Jane");
person1.setAge(30);

// Display the modified details


cout << "\nModified 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;

// Displaying the output using a single cout statement with formatting


cout << "Maths= " << maths << "\nPhysics= " << physics << "\nChemistry= " << chemistry << endl;

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;

// Prompt the user to enter a character


cout << "Enter a character: ";
cin >> inputChar;

// Display the ASCII value of the entered character


cout << "ASCII value of '" << inputChar << "' is: " << static_cast<int>(inputChar) << endl;

return 0;
}
In this program:

• We declare a variable inputChar of type char to store the user's input.


• We prompt the user to enter a character.
• The cin statement reads the input character from the keyboard and stores it in inputChar.
• We then use static_cast<int>(inputChar) to convert the char variable to its corresponding
ASCII value.
• Finally, we display the ASCII value of the entered character using cout.

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;

// Prompt the user to enter temperature in Fahrenheit


cout << "Enter temperature in Fahrenheit: ";
cin >> fahrenheit;

// Convert Fahrenheit to Celsius and display the result


double celsius = Temp::convertToFahrenheit(fahrenheit);
cout << "Temperature in Celsius: " << celsius << endl;

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;

// Function to swap two integers using reference variables


void swapIntegers(int &a, int &b) {
int temp = a;
a = b;
b = temp;
}

int main() {
int num1, num2;
// Input two integers from the user
cout << "Enter two integers separated by space: ";
cin >> num1 >> num2;

// Display the original values


cout << "Before swapping: " << endl;
cout << "num1 = " << num1 << ", num2 = " << num2 << endl;

// Call the swap function


swapIntegers(num1, num2);

// Display the values after swapping


cout << "\nAfter swapping: " << endl;
cout << "num1 = " << num1 << ", num2 = " << num2 << endl;

return 0;
}

6. Write a program to print the following output using for loops.


1
22
333
4444
55555

#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>

#include <iomanip> // For std::setprecision

using namespace std;

// Structure to represent a player

struct Player {

string name;

int runs;

int innings;

int not_out;

double average;

};

// Function to calculate batting average

double calculateAverage(int runs, int innings, int not_out) {

if (innings - not_out == 0)

return 0.0; // To avoid division by zero

return static_cast<double>(runs) / (innings - not_out);

// Function to read player details

void readPlayer(Player &player) {

cout << "Enter player's name: ";

cin >> player.name;

cout << "Enter runs scored by " << player.name << ": ";

cin >> player.runs;

cout << "Enter innings played by " << player.name << ": ";

cin >> player.innings;

cout << "Enter times not out for " << player.name << ": ";
cin >> player.not_out;

// Function to display player details

void displayPlayer(const Player &player) {

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() {

Player sachin, saurav, rahul;

// Read player details

cout << "Enter batting figures for Sachin:\n";

readPlayer(sachin);

sachin.average = calculateAverage(sachin.runs, sachin.innings, sachin.not_out);

cout << "Enter batting figures for Saurav:\n";

readPlayer(saurav);

saurav.average = calculateAverage(saurav.runs, saurav.innings, saurav.not_out);

cout << "Enter batting figures for Rahul:\n";

readPlayer(rahul);

rahul.average = calculateAverage(rahul.runs, rahul.innings, rahul.not_out);

// Display the table

cout << "\nBatting figures for the cricket team:\n";

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;

// Check if the ballot is valid (1 to 5)


if (ballot >= 1 && ballot <= 5) {
count[ballot - 1]++; // Increment the count for the corresponding candidate
} else if (ballot == -1) {
break; // Stop taking input if -1 is entered
} else {
spoilt_ballots++; // Increment the count of spoilt ballots
}
}

// Display the results


cout << "\nResults:\n";
for (int i = 0; i < num_candidates; ++i) {
cout << "Candidate " << i + 1 << ": " << count[i] << " votes\n";
}
cout << "Spoilt ballots: " << spoilt_ballots << endl;

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;

// Function to modify the global variable


void modifyGlobalVar() {
globalVar = 20;
}

int main() {
// Display the initial value of the global variable
cout << "Initial value of globalVar: " << globalVar << endl;

// Call a function to modify the global variable


modifyGlobalVar();

// Display the modified value of the global variable


cout << "Modified 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;

// Check if memory allocation was successful


if (ptr == nullptr) {
cerr << "Memory allocation failed!" << endl;
return 1;
}
// Assign a value to the dynamically allocated memory
*ptr = 42;

// Display the value


cout << "Value stored in dynamically allocated memory: " << *ptr << endl;

// Deallocate the memory


delete ptr;

// After deleting, accessing the memory can lead to undefined behavior


// So, it's a good practice to set the pointer to nullptr
ptr = nullptr;

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);

cout << "Program exited." << endl;


return 0;
}
12. Write a program to find the maximum and minimum of a set of real numbers, to be entered in one line of
the console.
#include <iostream>
#include <sstream> // For stringstream
#include <limits> // For numeric_limits

using namespace std;

int main() {
// Input the numbers in one line
cout << "Enter real numbers separated by spaces: ";
string input;
getline(cin, input);

// Create a stringstream to parse the input


stringstream ss(input);

// Initialize variables for max and min


double max = numeric_limits<double>::lowest();
double min = numeric_limits<double>::max();
double num;

// Iterate through the numbers in the stringstream


while (ss >> num) {
// Update max and min
if (num > max) max = num;
if (num < min) min = num;
}

// Check if any numbers were entered


if (max == numeric_limits<double>::lowest() && min == numeric_limits<double>::max()) {
cout << "No numbers entered." << endl;
} else {
// Output the maximum and minimum
cout << "Maximum: " << max << endl;
cout << "Minimum: " << min << endl;
}

return 0;
}

Explanation:

1. **Including Necessary Libraries**:


- `#include <iostream>`: This header file is included to provide functionality for input and output operations.
- `#include <sstream>`: This header file is included to use `std::stringstream` for parsing input strings.
- `#include <limits>`: This header file is included to use `std::numeric_limits` for getting the maximum and
minimum values of a data type.

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.

4. **Inputting Real Numbers**:


- `cout << "Enter real numbers separated by spaces: ";`: This line outputs a prompt asking the user to enter
real numbers separated by spaces.
- `string input;`: This declares a string variable named `input` to store the input.
- `getline(cin, input);`: This line reads a line of input from the standard input (`cin`) and stores it in the `input`
variable.

5. **Parsing Input String**:


- `stringstream ss(input);`: This creates a stringstream object `ss` and initializes it with the content of the
`input` string. This allows us to treat the input string as if it were a stream of input data.
- `double max = numeric_limits<double>::lowest();`: This initializes a variable `max` to the lowest possible
value for a `double`.
- `double min = numeric_limits<double>::max();`: This initializes a variable `min` to the highest possible value
for a `double`.

6. **Finding Maximum and Minimum**:


- `double num;`: This declares a variable `num` to store each real number as it is read from the stringstream.
- `while (ss >> num) { ... }`: This loop reads each real number from the stringstream `ss`. The loop continues
until no more numbers can be read from `ss`.
- `if (num > max) max = num;`: This checks if the current number `num` is greater than the current maximum
`max`. If so, it updates `max` to `num`.
- `if (num < min) min = num;`: This checks if the current number `num` is less than the current minimum
`min`. If so, it updates `min` to `num`.

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.

8. **Returning from Main**:


- `return 0;`: This statement indicates that the program executed successfully and returns an exit code of 0.

13. Write a c++ program to print fibonacci series without using recursion and using recursion.

#include <iostream>

using namespace std;

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 << " ";

for (int i = 3; i <= n; ++i) {


c = a + b;
cout << c << " ";
a = b;
b = c;
}

cout << endl;

return 0;
}

#include <iostream>

using namespace std;

// Function to calculate the Fibonacci series term using recursion


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

int main() {
int n;
cout << "Enter the number of terms in Fibonacci series: ";
cin >> n;

cout << "Fibonacci Series using recursion: ";

for (int i = 0; i < n; ++i) {


cout << fibonacci(i) << " ";
}

cout << endl;

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.

Mathematically, the Fibonacci sequence can be defined by the recurrence relation:

\[ F(n) = F(n-1) + F(n-2) \]

where:
- \( F(n) \) is the \( n \)-th Fibonacci number,
- \( F(0) = 0 \) and \( F(1) = 1 \).

Here's the beginning of the Fibonacci sequence:

- \( 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;

cout << "Enter a positive integer: ";


cin >> n;

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;
}

15. Write a c++ program to print sum of digits.


#include <iostream>
using namespace std;
int main() {
int num, sum = 0;

cout << "Enter a positive integer: ";


cin >> num;

while (num != 0) {
sum += num % 10;
num /= 10;
}

cout << "Sum of digits: " << sum << endl;

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;

cout << "Enter a positive integer: ";


cin >> num;

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 << "Enter two numbers separated by space: ";


cin >> 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};

cout << "Matrix 1:" << endl;


for (int i = 0; i < 3; ++i) {
for (int j = 0; j < 3; ++j)
cout << m1[i][j] << " ";
cout << endl;
}

cout << "\nMatrix 2:" << endl;


for (int i = 0; i < 3; ++i) {
for (int j = 0; j < 3; ++j)
cout << m2[i][j] << " ";
cout << endl;
}

cout << "\nResultant Matrix:" << endl;


for (int i = 0; i < 3; ++i) {
for (int j = 0; j < 3; ++j) {
for (int k = 0; k < 3; ++k) {
result[i][j] += m1[i][k] * m2[k][j];
}
cout << result[i][j] << " ";
}
cout << endl;
}

return 0;
}

19. Write a c++ program to convert decimal number to binary


#include <iostream>
using namespace std;
int main() {
int decimalNum;
cout << "Enter a decimal number: ";
cin >> decimalNum;

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

// Convert decimal to binary


while (decimalNum > 0) {
binary[index] = decimalNum % 2;
decimalNum /= 2;
index++;
}

// Print binary equivalent


cout << "Binary equivalent: ";
for (int i = index - 1; i >= 0; i--) {
cout << binary[i];
}
cout << endl;

return 0;
}

20. Write a c++ program to print alphabet triangle


#include <iostream>
using namespace std;
int main() {
int rows;
char ch = 'A';

cout << "Enter the number of rows: ";


cin >> rows;

for (int i = 1; i <= rows; ++i) {


for (int j = 1; j <= i; ++j) {
cout << ch << " ";
++ch;
}
cout << endl;
}

return 0;
}

21. Write a c++ program to print number triangle.


#include <iostream>
using namespace std;
int main() {
int rows, num = 1;

cout << "Enter the number of rows: ";


cin >> rows;

for (int i = 1; i <= rows; ++i) {


for (int j = 1; j <= i; ++j) {
cout << num << " ";
++num;
}
cout << endl;
}

return 0;
}

22. Write a c++ program to generate fibonacci triangle


#include <iostream>
using namespace std;
int main() {
int rows, a = 0, b = 1, c;

cout << "Enter the number of rows: ";


cin >> rows;

for (int i = 1; i <= rows; ++i) {


for (int j = 1; j <= i; ++j) {
cout << a << " ";
c = a + b;
a = b;
b = c;
}
cout << endl;
}

return 0;
}

23. Write a c++ program to convert number in characters.


#include <iostream>
using namespace std;
int main() {
int num;

cout << "Enter a number (1-9): ";


cin >> num;

if (num >= 1 && num <= 9) {


char ch = 'A' + num - 1;
cout << "Character equivalent: " << ch << endl;
} else {
cout << "Invalid input!" << endl;
}

return 0;
}
24. Write C++ Program to print Quadratic Equations
#include <iostream>
#include <cmath>

using namespace std;

int main() {
double a, b, c, discriminant, root1, root2;

cout << "Enter coefficients a, b, and c: ";


cin >> a >> b >> c;

// Calculate discriminant
discriminant = b * b - 4 * a * c;

// Condition for real and different roots


if (discriminant > 0) {
root1 = (-b + sqrt(discriminant)) / (2 * a);
root2 = (-b - sqrt(discriminant)) / (2 * a);
cout << "Roots are real and different." << endl;
cout << "Root 1 = " << root1 << endl;
cout << "Root 2 = " << root2 << endl;
}
// Condition for real and equal roots
else if (discriminant == 0) {
root1 = -b / (2 * a);
cout << "Roots are real and equal." << endl;
cout << "Root 1 = Root 2 = " << root1 << endl;
}
// Condition for complex roots
else {
double realPart = -b / (2 * a);
double imaginaryPart = sqrt(-discriminant) / (2 * a);
cout << "Roots are complex and different." << endl;
cout << "Root 1 = " << realPart << " + " << imaginaryPart << "i" << endl;
cout << "Root 2 = " << realPart << " - " << imaginaryPart << "i" << endl;
}

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:

1. If the discriminant is positive, the roots are real and different.


2. If the discriminant is zero, the roots are real and equal.
3. If the discriminant is negative, the roots are complex conjugates.
Output:

You might also like