Skip to main content

Posts

Showing posts from March, 2023

Write a program using the algorithm count() to count how many elements in a container have a specified value.

 Here's an example program using the count() algorithm to count the number of occurrences of a specific value in a vector container: #include <iostream> #include <vector> #include <algorithm> using namespace std; int main() {     vector<int> numbers = { 2, 5, 3, 7, 8, 5, 1, 5, 4 };          // count the number of occurrences of the value 5 in the vector     int count = count(numbers.begin(), numbers.end(), 5);          cout << "The number of occurrences of 5 in the vector is: " << count << endl;          return 0; } Output: The number of occurrences of 5 in the vector is: 3 Explanation: The program starts by creating a vector named numbers that contains several integer values. The count() algorithm is used to count the number of occurrences of the value 5 in the numbers vector. The function takes three arguments: the beginning and end iterators of...

Write a program in C++ using the find() algorithm to locate the position of a specified value in a sequence container.

  here's an example program using the find() algorithm to locate the position of a specified value in a vector: #include <iostream> #include <vector> #include <algorithm> using namespace std; int main() {     // Create a vector of integers     vector<int> vec = { 5, 2, 7, 9, 1, 8 };     // Find the position of the value 7 in the vector     auto it = find(vec.begin(), vec.end(), 7);     // Check if the value was found and print the position     if (it != vec.end()) {         cout << "The position of the value 7 is: " << distance(vec.begin(), it) << endl;     } else {         cout << "The value 7 was not found in the vector." << endl;     }     return 0; } Output: The position of the value 7 is: 2 In this program, we first create a vector of integers with some random values. We then use the find() algor...

Write a main program that calls a deeply nested function containing an exception. Incorporate necessary exception handling mechanism.

 Here's an example program that demonstrates a deeply nested function containing an exception, and incorporates exception handling: #include <iostream> using namespace std; void functionC() {     // A divide-by-zero exception will be thrown here     int x = 10, y = 0, z = x/y; } void functionB() {     functionC(); } void functionA() {     functionB(); } int main() {     try     {         functionA();     }     catch(const exception& e)     {         cerr << "Exception caught: " << e.what() << '\n';     }     return 0; } In this program, functionC() performs a divide-by-zero operation, which throws an exception. functionC() is called by functionB(), which is called by functionA(), which is called from main(). The try block in main() calls functionA(), which may throw an exception. If an exception is thrown, ...

Write a program to demonstrate the concept of rethrowing an exception.

 In C++, an exception can be rethrown to be caught by another catch block. This allows for more fine-grained handling of exceptions in a program. Here is an example program that demonstrates rethrowing an exception: #include <iostream> using namespace std; void divide(int a, int b) {     try {         if (b == 0) {             throw "Division by zero error";         }         else {             cout << "a/b = " << a/b << endl;         }     }     catch (const char* e) {         cout << "Exception caught in divide(): " << e << endl;         throw;  // rethrowing the same exception     } } int main() {     int x = 10, y = 0;     try {         divide(x, y);     }   ...

Write a program that demonstrates how certain exception types are not allowed to be thrown.

 In C++, there are certain types of exceptions that are not allowed to be thrown. These include void, function type, reference type, and array of non-zero bound with elements of these types. Let's see an example program that demonstrates this: #include <iostream> using namespace std; int main() {    try {       // Attempt to throw an exception of type void       throw void();    }    catch (...) {       cout << "Caught an exception of type void!" << endl;    }    try {       // Attempt to throw an exception of type function type       throw int(int);    }    catch (...) {       cout << "Caught an exception of type function type!" << endl;    }    try {       // Attempt to throw an exception of type reference type       int a = 10;     ...

Write a program that illustrates the application of multiple catch statements.

 Here's an example program that uses multiple catch statements to handle different types of exceptions: #include <iostream> #include <string> using namespace std; int main() {     try {         int num1, num2, result;         cout << "Enter two numbers to divide: ";         cin >> num1 >> num2;         if (num2 == 0) {             throw string("Cannot divide by zero!");         }         result = num1 / num2;         cout << "Result: " << result << endl;     } catch (string errorMessage) {         cout << "Error: " << errorMessage << endl;     } catch (...) {         cout << "Unknown error occurred." << endl;     }     return 0; } In this program, we...

Write a program containing a possible exception. Use a try block to throw it and a catch block to handle it properly.

 Here is an example program that demonstrates the use of try and catch block to handle an exception: #include <iostream> #include <string> using namespace std; void divide(int a, int b) {     if (b == 0) {         throw "Divide by zero exception";     }     cout << "a/b = " << a/b << endl; } int main() {     int a, b;     cout << "Enter two numbers: ";     cin >> a >> b;     try {         divide(a, b);     }     catch (const char* msg) {         cerr << "Exception caught: " << msg << endl;     }     return 0; } In this program, we define a function divide that takes two integers as arguments and throws an exception if the second argument is zero. The main function reads two integers from the user and calls the divide function within a try block. If a...

Write a function template to perform linear search in an array in C++ program.

  here's an example program in C++ that uses a function template to perform linear search on an array: #include <iostream> using namespace std; template <typename T> int linearSearch(T arr[], int size, T key) {     for (int i = 0; i < size; i++) {         if (arr[i] == key) {             return i; // Return the index where key was found         }     }     return -1; // Key not found in array } int main() {     int intArr[] = { 1, 2, 3, 4, 5 };     int intSize = sizeof(intArr) / sizeof(intArr[0]);     int intKey = 3;     cout << "Index of " << intKey << " in intArr: " << linearSearch(intArr, intSize, intKey) << endl;     double doubleArr[] = { 1.2, 2.3, 3.4, 4.5, 5.6 };     int doubleSize = sizeof(doubleArr) / sizeof(doubleArr[0]);     double doubleKey = 4.5;   ...

Write a function template for finding the minimum value contained in an array in C++ program.

 here's an example of a function template for finding the minimum value contained in an array in C++: #include <iostream> using namespace std; template<typename T> T findMin(T arr[], int size) {     T minVal = arr[0];     for(int i = 1; i < size; i++) {         if(arr[i] < minVal) {             minVal = arr[i];         }     }     return minVal; } int main() {     int intArr[] = {4, 8, 2, 10, 5};     double doubleArr[] = {2.5, 6.7, 1.2, 4.5};          cout << "Minimum value in intArr: " << findMin(intArr, 5) << endl;     cout << "Minimum value in doubleArr: " << findMin(doubleArr, 4) << endl;     return 0; } In this example, we define a function template findMin that takes an array of any type (T) and its size as parameters. The function iterates through th...

Write a program that reads a text file and creates another file that is identical except that every sequence of consecutive blank spaces is replaced by a single space.

 To solve this problem, we can follow these steps: Open the input file for reading and the output file for writing. Read the input file line by line. For each line, replace every sequence of consecutive blank spaces with a single space using the std::regex_replace function from the regex library. Write the modified line to the output file. Here is the code: #include <iostream> #include <fstream> #include <regex> using namespace std; int main() {     // Open the input file for reading and the output file for writing     ifstream infile("input.txt");     ofstream outfile("output.txt");     if (!infile) {         cerr << "Error: Could not open input file.\n";         return 1;     }     if (!outfile) {         cerr << "Error: Could not open output file.\n";         return 1;     }     string lin...

Write a program which reads a text from the keyboard and displays the following information on the screen: a) Number of lines b) Number of words c) Number of characters Strings should be left-justified and numbers should be right-justified in suitable field width.

 To solve this problem, we can read the text input from the keyboard using the getline function and then process the text to count the number of lines, words, and characters. We can use the istringstream class to separate the text into words. Here's the program: #include <iostream> #include <sstream> #include <string> using namespace std; int main() {     string text;     int num_lines = 0, num_words = 0, num_chars = 0;     // Read text from keyboard     cout << "Enter text: " << endl;     getline(cin, text);     // Process text     istringstream iss(text);     string word;     while (iss >> word) {         num_words++;         num_chars += word.length();     }     // Count lines     for (char c : text) {         if (c == '\n') {           ...

Write a program to find the value of e in the following series: e=1+1/1!+1/2!+......... upto acc = 0.0001

 To find the value of e in the given series, we need to sum up the terms until the accuracy reaches 0.0001. We can use a loop to add the terms and check for the accuracy. Here's the program to find the value of e: #include <iostream> #include <cmath> using namespace std; int main() {     double e = 1.0, term = 1.0;     int i = 1;     const double acc = 0.0001; // desired accuracy     while (fabs(term) > acc) {         term /= i; // i! = i * (i-1)!, so divide by i to get (i-1)!         e += term;         i++;     }     cout << "The value of e is: " << e << endl;     return 0; } In this program, we initialize the value of e and term to 1.0 and i to 1. We also set the desired accuracy acc to 0.0001. The loop continues until the absolute value of term is less than or equal to acc . In each iteration, we divide term b...

Write a program to read a list containing item name, item code, and cost interactively and produce a three column output. Note that the name and code are left-justified with a precision of two digits.

 Here's a program to read a list containing item name, item code, and cost interactively and produce a three column output: #include <iostream> #include <iomanip> #include <string> using namespace std; int main() {     string name, code;     double cost;     cout << "Enter item name, code, and cost: " << endl;     cin >> name >> code >> cost;     cout << setw(20) << left << "Item Name" << setw(10) << left << "Item Code" << setw(10) << left << "Cost" << endl;     cout << setw(20) << left << name << setw(10) << left << code << setprecision(2) << fixed << cost << endl;     return 0; } Example output: Enter item name, code, and cost: Shirt SH-01 25.99 Item Name           Item Code Cost Shirt        ...

Write a program to compute the area of a triangle and a circle by overloading the area() function.

 Here's an example program that overloads the area() function to calculate the area of a triangle and a circle: #include <iostream> using namespace std; // Function to calculate area of triangle float area(float base, float height) {     return 0.5 * base * height; } // Function to calculate area of circle float area(float radius) {     return 3.14 * radius * radius; } int main() {     float base, height, radius;     // Read input for triangle     cout << "Enter base and height of the triangle: ";     cin >> base >> height;     // Calculate and display area of triangle     float tri_area = area(base, height);     cout << "Area of triangle: " << tri_area << endl;     // Read input for circle     cout << "Enter radius of the circle: ";     cin >> radius;     // Calculate and display area of circle ...

Write a program to read a matrix of size m x n from the keyboard and display the same on the screen using functions.

  here's a program that reads a matrix of size m x n from the keyboard and displays it on the screen using functions: #include <iostream> using namespace std; // Function to read matrix of size m x n from the keyboard void read_matrix(int m, int n, int matrix[][]) {     cout << "Enter the elements of the matrix:" << endl;     for (int i = 0; i < m; i++) {         for (int j = 0; j < n; j++) {             cin >> matrix[i][j];         }     } } // Function to display matrix of size m x n on the screen void display_matrix(int m, int n, int matrix[][]) {     cout << "The matrix is:" << endl;     for (int i = 0; i < m; i++) {         for (int j = 0; j < n; j++) {             cout << matrix[i][j] << "\t";         }        ...

Write a function to read a matrix of size m x n from the keyboard.

Write a function to read a matrix of size m x n from the keyboard. here's an example program to read a matrix of size m x n from the keyboard: #include <iostream> using namespace std; int main() {     int m, n;     cout << "Enter the size of matrix (m x n): ";     cin >> m >> n;     int matrix[m][n];     cout << "Enter the elements of matrix:" << endl;     for (int i = 0; i < m; i++) {         for (int j = 0; j < n; j++) {             cin >> matrix[i][j];         }     }     cout << "The matrix is:" << endl;     for (int i = 0; i < m; i++) {         for (int j = 0; j < n; j++) {             cout << matrix[i][j] << " ";         }         cout << endl; ...

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 the ballot paper. Write a program to read the ballots and count the votes cast 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.

 Here is a C++ program that reads the ballots and counts the votes cast for each candidate and the number of spoilt ballots: #include <iostream> using namespace std; int main() {    int count[5] = {0}; // initialize count array with 0s    int spoilt_ballots = 0;    int candidate;    // read ballots until -1 is entered    cout << "Enter the candidate number (1-5) on the ballot paper (-1 to stop):\n";    cin >> candidate;    while (candidate != -1) {       if (candidate >= 1 && candidate <= 5) {          count[candidate-1]++;       } else {          spoilt_ballots++;       }       cin >> candidate;    }    // display the results    for (int i = 0; i < 5; i++) {       cout << "Candidate " << i+1 << " recei...

Print format using C++ program

 Write a program to print the following output using for loops. 1 22 333 4444 55555 Here's a program in C++ to print the pattern using nested for loops: #include <iostream> using namespace std; int main() {     int rows;     cout << "Enter the number of rows: ";     cin >> rows;     for(int i = 1; i <= rows; i++) {         for(int j = 1; j <= i; j++) {             cout << i;         }         cout << endl;     }     return 0; } Output for the pattern with 5 rows: 1 22 333 4444 55555 Explanation: We first prompt the user to enter the number of rows they want to print for the pattern. We use nested for loops to iterate through each row and column of the pattern. The outer for loop runs from 1 to the number of rows input by the user. The inner for loop runs from 1 to the current row number. For each in...

Write a function that creates a vector of user-given size M using new operator in a program

  here's an example program that creates a vector of user-given size M using the new operator: #include <iostream> #include <vector> using namespace std; // Function to create a vector of given size using new operator vector<int>* createVector(int size) {     return new vector<int>(size); } int main() {     int M;     cout << "Enter the size of vector: ";     cin >> M;     // Create vector using new operator     vector<int>* myVector = createVector(M);     // Display vector size     cout << "Vector size: " << myVector->size() << endl;     // Deallocate memory used by vector     delete myVector;     return 0; } In this program, we define a function called createVector that takes an integer argument size and returns a pointer to a new std::vector<int> object created using the new operator with the specified ...

Write a function using reference variables as arguments to swap the values of a pair of integers in a program

 here's an example program that swaps the values of two integers using a function with reference variables: #include <iostream> using namespace std; // function to swap two integers using reference variables void swap(int& x, int& y) {     int temp = x;     x = y;     y = temp; } int main() {     int num1 = 10, num2 = 20;          // before swapping     cout << "Before swapping: " << endl;     cout << "num1 = " << num1 << ", num2 = " << num2 << endl;          // swap the values of num1 and num2     swap(num1, num2);          // after swapping     cout << "After swapping: " << endl;     cout << "num1 = " << num1 << ", num2 = " << num2 << endl;          return 0; } Output: Before swapping: num1 = 10, ...

Write a C++ program that will ask for a temperature in Fahrenheit and display it in Celsius using class named temp and member functions

 here's an example program that converts temperature from Fahrenheit to Celsius using a class named Temp and member functions: #include <iostream> using namespace std; class Temp { private:     float fahrenheit; public:     void getTemp() {         cout << "Enter temperature in Fahrenheit: ";         cin >> fahrenheit;     }     void convertToFahrenheit() {         cout << fahrenheit << " degrees Fahrenheit is " << (fahrenheit - 32) * 5/9 << " degrees Celsius." << endl;     } }; int main() {     Temp temp;     temp.getTemp();     temp.convertToFahrenheit();     return 0; } Explanation: We define a class named Temp with a private data member fahrenheit and two member functions: getTemp() and convertToFahrenheit(). The getTemp() function prompts the user to enter the temperature in Fahrenh...

Write a C++ program that will ask for a temperature in Fahrenheit and display it in Celsius.

 here's an example program that asks the user for a temperature in Fahrenheit and displays it in Celsius: #include <iostream> using namespace std; int main() {     double fahrenheit, celsius;          // get temperature in Fahrenheit from user     cout << "Enter temperature in Fahrenheit: ";     cin >> fahrenheit;          // convert Fahrenheit to Celsius     celsius = (fahrenheit - 32) * 5 / 9;          // display temperature in Celsius     cout << "Temperature in Celsius: " << celsius << endl;          return 0; } Example output: Enter temperature in Fahrenheit: 68 Temperature in Celsius: 20 In this program, we first declare two variables fahrenheit and celsius of type double to store the temperature in Fahrenheit and Celsius, respectively. We then prompt the user to enter the temperature in Fahre...

Write a program to read the values of a, b and c and display the value of x, where x= a/b-c Test your program for the following values: a) a=250, b=85, c=25 b) a=300, b=70, c=70

 Here's the program to read the values of a, b, and c and display the value of x, where x = a/b - c: #include <iostream> using namespace std; int main() {     int a, b, c;     float x;     // first test case     a = 250;     b = 85;     c = 25;     x = a / b - c;     cout << "For values a = " << a << ", b = " << b << ", and c = " << c << endl;     cout << "The value of x is: " << x << endl << endl;     // second test case     a = 300;     b = 70;     c = 70;     x = a / b - c;     cout << "For values a = " << a << ", b = " << b << ", and c = " << c << endl;     cout << "The value of x is: " << x << endl;     return 0; } Output: For values a = 250, b = 85, and c = 25 The value of x is: ...

Write a program that inputs a character from keyboard and displays its corresponding ASCII value on the screen.

 here's a C++ program that does that: #include <iostream> using namespace std; int main() {     char c;     cout << "Enter a character: ";     cin >> c;     cout << "The ASCII value of " << c << " is " << int(c) << endl;     return 0; } Output: Enter a character: A The ASCII value of A is 65 Explanation: We start by including the necessary headers and using the std namespace. In the main function, we declare a variable c of type char, which will store the character input by the user. We prompt the user to enter a character by printing the message "Enter a character: " on the console using the cout object. We read the character entered by the user using the cin object and store it in the variable c. We use the int() function to convert the char value of c to its corresponding ASCII value, and then we print it on the console using the cout object. We return 0 to indicate that the program...

Write a program to read two numbers from the keyboard and display the larger value on the screen.

 Here's the program to read two numbers from the keyboard and display the larger value on the screen: c++ Copy code #include <iostream> using namespace std; int main() {    int num1, num2;    cout << "Enter first number: ";    cin >> num1;    cout << "Enter second number: ";    cin >> num2;    if (num1 > num2) {       cout << "Larger number is: " << num1 << endl;    }    else {       cout << "Larger number is: " << num2 << endl;    }    return 0; } Sample output: Enter first number: 23  Enter second number: 45 Larger number is: 45 Explanation: The program starts by including the necessary header file iostream which contains the standard input/output library in C++. using namespace std; statement is used to avoid typing std:: before standard library objects. Two integer variab...

Write a program to display the following output using a single cout statement. Math = 90 Physics =70 Chemistry = 69

 Here's a program in C++ that displays the required output using a single cout statement: #include <iostream> using namespace std; int main() {     cout << "Math = 90\nPhysics = 70\nChemistry = 69\n";     return 0; } Output: Math = 90 Physics = 70 Chemistry = 69 Explanation: The program uses the cout statement to display the output on the screen. The \n characters in the statement represent new lines, which separate each subject and its score. Here's a program in C++ that displays the required output using a multiple cout statement: #include <iostream> using namespace std; int main() {     cout << "Math = 90\n";     cout << " Physics = 70\n";     cout << " Chemistry = 69\n";     return 0; } Output: Math = 90 Physics = 70 Chemistry = 69 Here's a program in C++ that displays the required output using a multiple cout statement and endl: #include <iostream> using namespace std; int mai...

Write a program with class calculate that ask user to enter two numbers and any of the operators: +, -, *, / and % and perform the task accordingly. For example if an user enters numbers 2 & 5 and operator '+', a program should add 2 to 5 and display 7 as result. Use switch statement to make a selection among operators. Assume appropriate data members and member functions. With output and explanation.

 here's an example program with a class named Calculate that performs arithmetic operations based on user input: #include <iostream> using namespace std; class Calculate {     private:         double num1, num2;     public:         void getNumbers() {             cout << "Enter two numbers: ";             cin >> num1 >> num2;         }         void add() {             cout << "The sum is: " << num1 + num2 << endl;         }         void subtract() {             cout << "The difference is: " << num1 - num2 << endl;         }         void multiply() {             cout << "The product is: " <...

Create a class named Student with six data members (name, roll, and marks in Math, English and Programming, total_marks). Write a program with member functions: one that initializes necessary data members, another one that calculate total marks and another one that displays student's detail. In main(), create two objects of class Student, for each object, invoke the functions defined above in the class.

 Here's the program that creates a class named Student and its member functions to initialize data members, calculate total marks and display student's details: #include <iostream> #include <string> using namespace std; class Student {     private:         string name;         int roll, math_marks, english_marks, programming_marks, total_marks;          public:         void set_data() {             cout << "Enter student's name: ";             cin >> name;             cout << "Enter student's roll number: ";             cin >> roll;             cout << "Enter marks in Math: ";             cin >> math_marks;             cout << "E...

Create a class named Date with four data members ( year, month, day, day_of_week). Write a program with member functions: one that initializes necessary data members and another that displays today's date in standard format.

 To create a class named Date with four data members (year, month, day, day_of_week) and member functions to initialize data members and display today's date in standard format, we can follow these steps: Define a class named Date with the four data members - year, month, day, and day_of_week. Define a constructor function that initializes the year, month, day, and day_of_week data members to the current date. Define a member function named displayDate() that displays the current date in standard format - "YYYY/MM/DD (Day of Week)". Here's the C++ code for the above program: #include <iostream> #include <ctime> using namespace std; class Date {     private:         int year, month, day, day_of_week;     public:         Date() {             // Get current date and time             time_t now = time(0);             tm *ltm =...

Write a program to create a structure named student that has name, roll, mark and remark as members. A program should read and display data entered by the user, except for remark which is set to 'P' if student has secured 40% or more marks in exam, otherwise it is set to 'F'. Assume appropriate data types.

Here is a program that creates a student structure with name, roll, mark, and remark members. The program reads in data from the user, calculates the remark based on the student's marks, and displays all the information back to the user. #include <iostream> #include <string> using namespace std; struct student {     string name;     int roll;     double mark;     char remark; }; int main() {     student s;     // Read in student data     cout << "Enter student name: ";     getline(cin, s.name);     cout << "Enter student roll number: ";     cin >> s.roll;     cout << "Enter student marks: ";     cin >> s.mark;     // Calculate student remark     if (s.mark >= 40) {         s.remark = 'P';     } else {         s.remark = 'F';     }     /...

Write a program with function printf() that takes string as argument and print that string on screen. Note that printf() is a user-defined function (not one defined under stdio.h header file of C library), so you have to write its definition yourself.

 Here is the code for the printf() function: #include <iostream> void printf(const char* str) {     for(int i = 0; str[i] != '\0'; i++) {         putchar(str[i]);     } } int main() {     printf("Hello, world!\n");     printf("This is my custom printf function.\n");     return 0; } In this program, we first define the printf() function, which takes a const char* argument named str. We then use a for loop to iterate over each character in the string pointed to by str, printing each character to the console using the putchar() function. In the main() function, we call the printf() function twice with different strings as arguments. The output of this program will be: Hello, world! This is my custom printf function. Note that while this function is similar to the printf() function in the standard library, it does not support formatting options, such as %d or %s, and should not be used as a replacement for the ...

Write a program with an overloaded function calcArea() that calculate and return area of circle, rectangle and triangle. Assume appropriate number and type of arguments and return type.

 Here's a C++ program that defines an overloaded function called calcArea() that calculates and returns the area of a circle, rectangle, or triangle based on the parameters passed to it: #include <iostream> #include <cmath> const double PI = 3.14159; double calcArea(double radius) {     return PI * pow(radius, 2); } double calcArea(double width, double height) {     return width * height; } double calcArea(double base, double height, bool isTriangle) {     if (isTriangle) {         return 0.5 * base * height;     } else {         return -1; // Invalid input for rectangle     } } int main() {     double radius = 5.0;     double width = 10.0;     double height = 8.0;     double base = 6.0;     cout << "Area of circle with radius " << radius << " = " << calcArea(radius) << endl;     cout <<...

Write a function that takes floating point number as argument and return integer and fractional part. Use Reference argument.

 Here's a C++ program that defines a function called splitFloat() that takes a floating-point number as an argument and returns its integer and fractional parts through reference arguments: #include <iostream> using namespace std; void splitFloat(float num, int& intPart, float& fracPart) {     intPart = static_cast<int>(num);     fracPart = num - intPart; } int main() {     float num;     int intPart;     float fracPart;     cout << "Enter a floating-point number: ";     cin >> num;     splitFloat(num, intPart, fracPart);     cout << "Integer part = " << intPart << std::endl;     cout << "Fractional part = " << fracPart << std::endl;     return 0; } Output: Enter a floating-point number: 3.14159 Integer part = 3 Fractional part = 0.14159 Explanation: The program defines a function called splitFloat() that t...

Write a program to generate Fibonacci series up to n terms using recursive function.

 Here's a C++ program to generate the Fibonacci series up to n terms using a recursive function: #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 the number of terms: ";     cin >> n;     cout << "Fibonacci Series: ";     for (int i = 0; i < n; i++) {         cout << fibonacci(i) << " ";     }     return 0; } Output: Enter the number of terms: 7 Fibonacci Series: 0 1 1 2 3 5 8 Explanation: The program defines a function fibonacci() that takes an integer argument n and returns the n-th term in the Fibonacci series. The function uses recursion to calculate the Fibonacci number. If n is 0 or 1, the function returns n itself. Otherwise, it returns the sum of the p...

Define a struct named Currency that has rupees and paisa as variables. Write a function called addCurrnecy() that takes two struct Currency variables as arguments, add those and display sum.

 Here's a C++ program that defines a Currency struct and includes the addCurrency() function: #include <iostream> using namespace std; struct Currency {     int rupees;     int paisa; }; void addCurrency(Currency c1, Currency c2) {     Currency sum;     sum.paisa = c1.paisa + c2.paisa;     sum.rupees = c1.rupees + c2.rupees;     if (sum.paisa >= 100) {         sum.paisa -= 100;         sum.rupees++;     }     cout << "Sum: " << sum.rupees << " rupees, " << sum.paisa << " paisa." << endl; } int main() {     Currency c1 = { 50, 30 };     Currency c2 = { 20, 75 };     addCurrency(c1, c2);     return 0; } Output: Sum: 71 rupees, 5 paisa. Explanation: The program defines a Currency struct that has two integer variables - rupees and paisa. The program includes the addCurrency() function...

Write a function called totalSeconds() that takes three int values - for hours, minutes and seconds - as arguments, and returns the equivalent time in seconds (type long). Create a program that does above task repeatedly until user hits 'N' or 'n' from keyboard.

 Here's a C++ program that includes the totalSeconds() function and a loop to repeatedly ask the user for input until they enter 'N' or 'n': #include <iostream> using namespace std; long totalSeconds(int hours, int minutes, int seconds) {     return hours * 3600 + minutes * 60 + seconds; } int main() {     char repeat = 'Y';     while (repeat == 'Y' || repeat == 'y') {         int hours, minutes, seconds;         cout << "Enter time in hours, minutes, and seconds: ";         cin >> hours >> minutes >> seconds;         long totalSecs = totalSeconds(hours, minutes, seconds);         cout << "Total seconds: " << totalSecs << endl;         cout << "Do you want to calculate again? (Y/N): ";         cin >> repeat;     }     return 0; } Output...

Write a program that ask user to enter two numbers, calculate and display their sum, difference and product. Calculate each of above using different user defined functions.

 Here's a program in C++ that asks the user to enter two numbers, calculates their sum, difference, and product using user-defined functions, and then displays the results: #include <iostream> using namespace std; int sum(int a, int b) {     return a + b; } int difference(int a, int b) {     return a - b; } int product(int a, int b) {     return a * b; } int main() {     int num1, num2;     cout << "Enter the first number: ";     cin >> num1;     cout << "Enter the second number: ";     cin >> num2;     int result_sum = sum(num1, num2);     int result_diff = difference(num1, num2);     int result_prod = product(num1, num2);     cout << "The sum of the numbers is: " << result_sum << endl;     cout << "The difference of the numbers is: " << result_diff << endl;     cout << "T...

C++ program to print lines of text using function

  Write a program to print following lines of text in an exact format using functions, ***************************************** ** Welcone to C++ programming language ** ***************************************** The first and third line of the text should be printed using one function and the second line using another one. Here's a program in C++ that prints the following lines of text in an exact format using functions: #include <iostream> #include <string> using namespace std; void printLine(int length, char character) { for (int i = 0; i < length; i++) { cout << character; } cout << endl; } void printText(string text, int length, char character) { int textLength = text.length(); int spaces = length - textLength - 2; cout << character << " "; cout << text; for (int i = 0; i < spaces; i++) { cout << " "; } cout << " " << chara...