0% found this document useful (0 votes)
19 views12 pages

1, Write A progr-WPS Office

The document contains multiple C++ programming examples demonstrating various concepts. These include using function pointers for arithmetic operations, calculating the height of a binary tree, managing dynamic memory for a Movie structure, finding the oldest person in an array of Person structures, and appending student data to a file. Each example includes code snippets and explanations for clarity.

Uploaded by

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

1, Write A progr-WPS Office

The document contains multiple C++ programming examples demonstrating various concepts. These include using function pointers for arithmetic operations, calculating the height of a binary tree, managing dynamic memory for a Movie structure, finding the oldest person in an array of Person structures, and appending student data to a file. Each example includes code snippets and explanations for clarity.

Uploaded by

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

1,Write a program that demonstrates the use of a function pointer.

The program should

take two integers and perform different arithmetic operations (addition, subtraction)

based on the user’s choice using a function pointer.

#include <iostream>

// Function prototypes for arithmetic operations

int add(int a, int b);

int subtract(int a, int b);

int main() {

// Function pointer declaration

int (*operation)(int, int);

int num1, num2;

int choice;

// User input

std::cout << "Enter two integers: ";

std::cin >> num1 >> num2;

std::cout << "Choose an operation:\n";

std::cout << "1. Addition\n";

std::cout << "2. Subtraction\n";


std::cout << "Enter your choice (1 or 2): ";

std::cin >> choice;

// Assign the function pointer based on user choice

if (choice == 1) {

operation = add; // Point to the add function

} else if (choice == 2) {

operation = subtract; // Point to the subtract function

} else {

std::cout << "Invalid choice!" << std::endl;

return 1; // Exit with an error code

// Call the selected operation using the function pointer

int result = operation(num1, num2);

// Display the result

std::cout << "Result: " << result << std::endl;

return 0;

// Function definitions

int add(int a, int b) {

return a + b;
}

int subtract(int a, int b) {

return a - b;

2 Define a structure Node for a binary tree and write a recursive function to calculate the

height of the tree.

#include <iostream>

// Define the structure for a Node in the binary tree

struct Node {

int data; // Data stored in the node

Node* left; // Pointer to the left child

Node* right; // Pointer to the right child

// Constructor to initialize a new node

Node(int value) : data(value), left(nullptr), right(nullptr) {}

};

// Function to calculate the height of the binary tree

int height(Node* root) {

// Base case: if the tree is empty, height is -1


if (root == nullptr) {

return -1;

// Recursively calculate the height of the left and right subtrees

int leftHeight = height(root->left);

int rightHeight = height(root->right);

// The height of the tree is the maximum height of its subtrees plus one for the root

return std::max(leftHeight, rightHeight) + 1;

// Helper function to insert nodes into the binary tree (for testing)

Node* insert(Node* root, int value) {

if (root == nullptr) {

return new Node(value);

if (value < root->data) {

root->left = insert(root->left, value);

} else {

root->right = insert(root->right, value);

return root;
}

// Main function to demonstrate the height calculation

int main() {

Node* root = nullptr;

// Inserting nodes into the binary tree

root = insert(root, 10);

insert(root, 5);

insert(root, 15);

insert(root, 3);

insert(root, 7);

insert(root, 12);

insert(root, 18);

// Calculate and display the height of the binary tree

int treeHeight = height(root);

std::cout << "The height of the binary tree is: " << treeHeight << std::endl;

return 0;

3 Define a structure Movie with title, director, and year as members. Allocate memory

dynamically for each movie’s title and director. Implement functions to add new movies
and display all movie details.
#include <iostream>

#include <cstring> // For using strcpy and strlen

#include <vector> // For using vector

// Define the structure for a Movie

struct Movie {

char* title; // Dynamically allocated title

char* director; // Dynamically allocated director

int year; // Year of release

// Constructor to initialize a Movie

Movie(const char* t, const char* d, int y) {

title = new char[strlen(t) + 1]; // Allocate memory for title

strcpy(title, t); // Copy title into allocated memory

director = new char[strlen(d) + 1]; // Allocate memory for director

strcpy(director, d); // Copy director into allocated memory

year = y; // Set the year

// Destructor to free allocated memory

~Movie() {

delete[] title; // Free memory for title

delete[] director; // Free memory for director

};
// Function to add a new movie

void addMovie(std::vector<Movie>& movies) {

char title[100];

char director[100];

int year;

std::cout << "Enter movie title: ";

std::cin.ignore(); // Clear the input buffer

std::cin.getline(title, 100); // Read title

std::cout << "Enter director name: ";

std::cin.getline(director, 100); // Read director

std::cout << "Enter release year: ";

std::cin >> year; // Read year

movies.emplace_back(title, director, year); // Add new movie to the vector

// Function to display all movie details

void displayMovies(const std::vector<Movie>& movies) {

std::cout << "\nList of Movies:\n";

for (const auto& movie : movies) {

std::cout << "Title: " << movie.title


<< ", Director: " << movie.director

<< ", Year: " << movie.year << std::endl;

int main() {

std::vector<Movie> movies; // Vector to hold movies

int choice;

do {

std::cout << "\nMenu:\n";

std::cout << "1. Add Movie\n";

std::cout << "2. Display Movies\n";

std::cout << "3. Exit\n";

std::cout << "Enter your choice: ";

std::cin >> choice;

switch (choice) {

case 1:

addMovie(movies); // Add a new movie

break;

case 2:

displayMovies(movies); // Display all movies

break;

case 3:
std::cout << "Exiting program.\n";

break;

default:

std::cout << "Invalid choice. Please try again.\n";

} while (choice != 3);

return 0;

4 Create an array of Person structures and implement a function to find the oldest person

from the array

#include <iostream>

#include <cstring> // For using strlen and strcpy

// Define the structure for a Person

struct Person {

char name[100]; // Name of the person

int age; // Age of the person

};

// Function to find the oldest person in the array

Person findOldestPerson(const Person* people, int size) {

Person oldest = people[0]; // Assume the first person is the oldest initially
for (int i = 1; i < size; ++i) {

if (people[i].age > oldest.age) {

oldest = people[i]; // Update if current person is older

return oldest; // Return the oldest person found

int main() {

const int SIZE = 5; // Number of persons

Person people[SIZE]; // Array of Person structures

// Input details for each person

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

std::cout << "Enter name of person " << (i + 1) << ": ";

std::cin.ignore(); // Clear the input buffer

std::cin.getline(people[i].name, 100); // Read name

std::cout << "Enter age of person " << (i + 1) << ": ";

std::cin >> people[i].age; // Read age

// Find the oldest person

Person oldest = findOldestPerson(people, SIZE);


// Display the oldest person's details

std::cout << "\nThe oldest person is:\n";

std::cout << "Name: " << oldest.name << ", Age: " << oldest.age << std::endl;

return 0;

5 Write a program that appends new student data (name and grade) to an existing file

without overwriting the current content.

#include <iostream>

#include <fstream>

#include <string>

int main() {

std::string filename = "students.txt"; // Name of the file to append data to

std::ofstream outFile; // Output file stream

// Open the file in append mode

outFile.open(filename, std::ios::app);

// Check if the file opened successfully

if (!outFile) {

std::cerr << "Error opening file for writing." << std::endl;

return 1; // Exit with an error code

}
std::string name;

float grade;

// Input student data

std::cout << "Enter student name: ";

std::getline(std::cin, name); // Use getline to allow spaces in names

std::cout << "Enter student grade: ";

std::cin >> grade;

// Append the new student data to the file

outFile << name << "," << grade << std::endl;

// Close the file

outFile.close();

std::cout << "Student data appended successfully!" << std::endl;

return 0; // Exit with success code

You might also like