C++Basics BEC358C ICEAS
[Link] in C++ to find sum of n natural numbers
#include <iostream>
using namespace std;
nt main()
{
int n, sum = 0;
cout<< "Enter the value of n: ";
cin >> n;
for (int i = 1; i <= n; i++)
{ sum = sum + i;
}
cout << "Sum of first " << n << " natural numbers = " << sum << endl;
return 0;
}
[Link] inC++ to find sum of n different numbers
#include <iostream>
using namespace std;
int main(){
int n;
float num, sum = 0;
cout << "Enter number of elements: ";
cin >> n;
cout << "Enter " << n << " different numbers:" << endl;
for (int i = 1; i <= n; i++) {
cin >> num;
sum = sum + num;
}
cout << "Sum of given numbers = " << sum << endl;
return 0;
}
Enter number of elements: 4
Enter 4 different numbers: 5 10 3 2
Sum of given numbers = 20
1
C++Basics BEC358C ICEAS
Explanation
n→ number of values
Loop runs n times
Each entered number is added to sum
Works for integers or decimal numbers
[Link] to Generate Fibonacci Sequence Up to a Certain Number n
#include <iostream>
#include<conio.h>
using namespace std;
int main() {
int t1 = 0, t2 = 1, nextTerm = 0, n;
cout << "Enter a positive number: ";
cin >> n;
// displays the first two terms which is always 0 and 1
cout << "Fibonacci Series: " << t1 << ", " << t2 << ", ";
nextTerm = t1 + t2;
while(nextTerm <= n) {
cout << nextTerm << ", ";
t1 = t2;
t2 = nextTerm;
nextTerm = t1 + t2;
}
Getche();
return 0;
}
Run Code
Output
Enter a positive integer: 100
Fibonacci Series: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89,
3. Write a C++ program for finding factorial of a number
#include <iostream>
using namespace std;
2
C++Basics BEC358C ICEAS
int main() {
int n;
long factorial = 1.0;
cout << "Enter a positive integer: ";
cin >> n;
if (n < 0)
cout << "Error! Factorial of a negative number doesn't exist.";
else {
for(int i = 1; i <= n; ++i) {
factorial *= i;
}
cout << "Factorial of " << n << " = " << factorial;
}
return 0;
}
Run Code
Output
Enter a positive integer: 4
Factorial of 4 = 24
[Link] a C++ program to find largest, smallest & second largest of three numbers using
inline functions MAX & Min.
#include <iostream>
using namespace std;
// Inline function to find the maximum of two numbers
inline int MAX(int a, int b) {
return (a > b) ? a : b;
}
// Inline function to find the minimum of two numbers
inline int MIN(int a, int b) {
return (a < b) ? a : b;
}
int main() {
int num1, num2, num3;
// Input three numbers
3
C++Basics BEC358C ICEAS
cout << "Enter three numbers: ";
cin >> num1 >> num2 >> num3;
// Find the largest and smallest numbers using inline functions
int largest = MAX(MAX(num1, num2), num3);
int smallest = MIN(MIN(num1, num2), num3);
// Determine the second largest number
int second_largest;
second_largest=(((num1+num2+num2)- largest)-smallest)
// Output the results
cout << "Largest number: " << largest << endl;
cout << "Smallest number: " << smallest << endl;
cout << "Second largest number: " << second_largest << endl;
return 0;
}
output
Enter three numbers: 34
56
78
Largest number: 78
Smallest number: 34
Second largest number: 56
6. Write a c++ program to create a 3x3 matrix and display the matrix
#include <iostream>
#include<conio.h>
using namespace std;
int main()
{
// Declaring 2D array
int array1[3][3];
// Initialize 2D array using loop
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
cout<<”enter the elements of the matrix”;
cin>>array1[i][j] ;
}
}
// Printing the element of 2D array
4
C++Basics BEC358C ICEAS
for (int i = 0; i < 3; i++) {
for (int j = 0; j <3; j++) {
cout << array1[i][j] << " ";
}
cout << endl;
}
getch();
return 0;
}
7. Write a C++ program to calculate the volume of different geometric shapes like cube,
cylinder and sphere using function overloading concept.
#include <iostream>
#include <cmath> // For M_PI constant
using namespace std;
// Function to calculate the volume of a cube
double volume(double side) {
return pow(side, 3);
}
// Function to calculate the volume of a cylinder
double volume(double radius, double height) {
return M_PI * pow(radius, 2) * height;
}
// Function to calculate the volume of a sphere
double volume(double radius, bool isSphere) {
return (4.0 / 3.0) * M_PI * pow(radius, 3);
}
int main() {
double side, radius, height;
// Volume of a cube
cout << "Enter the side length of the cube: ";
cin >> side;
cout << "Volume of the cube: " << volume(side) << endl;
// Volume of a cylinder
cout << "Enter the radius and height of the cylinder: ";
cin >> radius >> height;
cout << "Volume of the cylinder: " << volume(radius, height) << endl;
// Volume of a sphere
cout << "Enter the radius of the sphere: ";
cin >> radius;
cout << "Volume of the sphere: " << volume(radius, true) << endl;
return 0;
5
C++Basics BEC358C ICEAS
}
Output
Enter the side length of the cube: 4
Volume of the cube: 64
Enter the radius and height of the cylinder: 2
5
Volume of the cylinder: 62.8319
Enter the radius of the sphere: 5
Volume of the sphere: 523.599
8. Define a STUDENT class with USN, Name & Marks in 3 tests of a subject. Declare an
array of 3 STUDENT objects. Using appropriate functions, find the average of the two
better marks for each student. Print the USN, Name & the average marks of all the
students.
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
class STUDENT {
private:
string USN;
string Name;
int Marks[3];
public:
void input() {
cout << "Enter USN: ";
cin >> USN;
cout << "Enter Name: ";
cin >> Name;
cout << "Enter marks for 3 tests: ";
for (int i = 0; i < 3; i++) {
cin >> Marks[i];
}
}
void display() const {
cout << "USN: " << USN << ", Name: " << Name << ", Average of two best marks: " <<
calculateAverage() << endl;
}
double calculateAverage() const {
int minMark = *min_element(Marks, Marks + 3);
int sum = Marks[0] + Marks[1] + Marks[2];
6
C++Basics BEC358C ICEAS
double average = (sum - minMark) / 2.0;
return average;
}
};
int main() {
const int numberOfStudents = 3;
STUDENT students[numberOfStudents];
// Input details for each student
for (int i = 0; i < numberOfStudents; i++) {
cout << "Enter details for student " << i + 1 << ":" << endl;
students[i].input();
}
// Display details for each student
cout << "\nDetails of students with average of two best marks:" << endl;
for (int i = 0; i < numberOfStudents; i++) {
students[i].display();
}
return 0;
}
Enter details for student 1:
Enter USN: 1
Enter Name: aa
Enter marks for 3 tests: 34
35
45
Enter details for student 2:
Enter USN: 2
Enter Name: bb
Enter marks for 3 tests: 35
36
46
Enter details for student 3:
Enter USN: 3
Enter Name: cc
Enter marks for 3 tests: 23
45
34
Details of students with average of two best marks:
USN: 1, Name: aa, Average of two best marks: 40
7
C++Basics BEC358C ICEAS
USN: 2, Name: bb, Average of two best marks: 41
USN: 3, Name: cc, Average of two best marks: 39.5
[Link] simple inheritance concept by creating a base class FATHER with data
members:First Name, Surname, DOB & bank Balance and creating a derived class SON,
which inherits:Surname & Bank Balance feature from base class but provides its own
feature: First Name & [Link] & initialize F1 & S1 objects with appropriate
constructors & display the FATHER & SONdetails.
#include <iostream>
#include <string>
using namespace std;
class FATHER {
protected:
string FirstName;
string Surname;
string DOB;
double BankBalance;
public:
// Constructor to initialize FATHER's data members
FATHER(string firstName, string surname, string dob, double bankBalance)
: FirstName(firstName), Surname(surname), DOB(dob), BankBalance(bankBalance) {}
// Function to display FATHER's details
void display() const {
cout << "Father's Name: " << FirstName << " " << Surname << endl;
cout << "DOB: " << DOB << endl;
cout << "Bank Balance: $" << BankBalance << endl;
}
};
class SON : public FATHER {
private:
string SonFirstName;
string SonDOB;
public:
// Constructor to initialize SON's data members and inherit Surname & BankBalance from
FATHER
SON(string fatherFirstName, string surname, string fatherDOB, double bankBalance,
string sonFirstName, string sonDOB)
: FATHER(fatherFirstName, surname, fatherDOB, bankBalance),
SonFirstName(sonFirstName), SonDOB(sonDOB) {}
// Function to display SON's details
void display() const {
8
C++Basics BEC358C ICEAS
cout << "Son's Name: " << SonFirstName << " " << Surname << endl;
cout << "DOB: " << SonDOB << endl;
cout << "Inherited Bank Balance: $" << BankBalance << endl;
}
};
int main() {
// Create and initialize FATHER object
FATHER F1("John", "Doe", "01-01-1970", 50000.00);
// Create and initialize SON object
SON S1("John", "Doe", "01-01-1970", 50000.00, "Mike", "01-01-2000");
// Display FATHER's details
cout << "Father's Details:" << endl;
[Link]();
cout << endl;
// Display SON's details
cout << "Son's Details:" << endl;
[Link]();
return 0;
}
Father's Details:
Father's Name: John Doe
DOB: 01-01-1970
Bank Balance: $50000
Son's Details:
Son's Name: Mike Doe
DOB: 01-01-2000
Inherited Bank Balance: $50000
[Link] a C++ program to define class name FATHER & SON that holds the income
[Link] & display total income of a family using Friend function.
#include <iostream>
using namespace std;
class SON; // Forward declaration
class FATHER {
private:
double income;
public:
9
C++Basics BEC358C ICEAS
// Constructor to initialize income
FATHER(double inc) : income(inc) {}
// Friend function declaration
friend double calculateTotalIncome(const FATHER& f, const SON& s);
// Function to display father's income
void displayIncome() const {
cout << "Father's Income: $" << income << endl;
}
};
class SON {
private:
double income;
public:
// Constructor to initialize income
SON(double inc) : income(inc) {}
// Friend function declaration
friend double calculateTotalIncome(const FATHER& f, const SON& s);
// Function to display son's income
void displayIncome() const {
cout << "Son's Income: $" << income << endl;
}
};
// Friend function to calculate total income
double calculateTotalIncome(const FATHER& f, const SON& s) {
return [Link] + [Link];
}
int main() {
// Create and initialize FATHER and SON objects
FATHER father(50000.00);
SON son(20000.00);
// Display individual incomes
[Link]();
[Link]();
// Calculate and display total family income
double totalIncome = calculateTotalIncome(father, son);
cout << "Total Family Income: $" << totalIncome << endl;
10
C++Basics BEC358C ICEAS
return 0;
}
Output
Father's Income: $50000
Son's Income: $20000
Total Family Income: $70000
11. Write a C++ program to accept the student detail such as name & 3 different marks by
get_data() method & display the name & average of marks using display() method. Define
a friend function for calculating the average marks using the method mark_avg()
#include <iostream>
#include <string>
using namespace std;
class Student {
private:
string name;
float marks[3];
public:
void get_data() {
cout << "Enter student's name: ";
getline(cin, name);
for (int i = 0; i < 3; ++i) {
cout << "Enter mark " << i + 1 << ": ";
cin >> marks[i];
}
}
void display() const {
cout << "Name: " << name << endl;
// Declare the friend function
friend float mark_avg(const Student& student);
};
// Define the friend function
float mark_avg(const Student& student) {
float total = 0;
for (int i = 0; i < 3; ++i) {
total += [Link][i];
}
11
C++Basics BEC358C ICEAS
return total / 3;
}
int main() {
Student student;
student.get_data();
[Link]();
cout << "Average Marks: " << mark_avg(student) << endl;
return 0;
}
output
Enter student's name: aaa
Enter mark 1: 50
Enter mark 2: 48
Enter mark 3: 45
Name: aaa
Average Marks: 47.6667
[Link], develop and execute a program in C++ based on the following requirements: An
EMPLOYEE class containing data members & members functions: i) Data members:
employeenumber (an integer), Employee_ Name (a string of characters), Basic_ Salary (in
integer), All_Allowances (an integer), Net_Salary (an integer). (ii) Member functions: To
read the data of an employee, to calculate Net_Salary & to print the values of all the data
members. (All_Allowances= 123% of Basic, Income Tax (IT) =30% of gross salary (=basic_
Salary_All_Allowances_IT).
#include <iostream>
#include <string>
using namespace std;
class EMPLOYEE {
private:
int employee_number;
string employee_name;
int basic_salary;
int all_allowances;
int net_salary;
public:
// Function to read employee data
void read_data() {
cout << "Enter employee number: ";
cin >> employee_number;
[Link](); // To ignore the newline character after reading employee number
cout << "Enter employee name: ";
getline(cin, employee_name);
12
C++Basics BEC358C ICEAS
cout << "Enter basic salary: ";
cin >> basic_salary;
}
// Function to calculate net salary
void calculate_net_salary() {
all_allowances = static_cast<int>(basic_salary * 1.23); // 123% of basic salary
int gross_salary = basic_salary + all_allowances;
int income_tax = static_cast<int>(gross_salary * 0.30); // 30% of gross salary
net_salary = gross_salary - income_tax;
}
// Function to print employee details
void print_data() const {
cout << "Employee Number: " << employee_number << endl;
cout << "Employee Name: " << employee_name << endl;
cout << "Basic Salary: " << basic_salary << endl;
cout << "All Allowances: " << all_allowances << endl;
cout << "Net Salary: " << net_salary << endl;
}
};
int main() {
EMPLOYEE emp;
// Read employee data
emp.read_data();
// Calculate net salary
emp.calculate_net_salary();
// Print employee data
emp.print_data();
return 0;
}
output
Enter employee number: 1
Enter employee name: aaa
Enter basic salary: 1000
Employee Number: 1
Employee Name: aaa
Basic Salary: 1000
All Allowances: 1230
Net Salary: 1561
13
C++Basics BEC358C ICEAS
[Link] a C++ program to create three objects for a class named count object with data
members such as roll_no & Name. Create a members function set_data ( ) for setting the
data values & display ( ) member function to display which object has invoked it using
“this‟ pointer.
#include <iostream>
#include <string>
using namespace std;
class count_object
{
private:
int roll_no;
string name;
public:
// Function to set data
void set_data(int roll, string n)
{
this->roll_no = roll;
this->name = n;
}
// Function to display data and object address
void display()
{
cout << "Object invoked at address: " << this << endl;
cout << "Roll No : " << roll_no << endl;
cout << "Name : " << name << endl;
cout << "------------------------" << endl;
}
};
int main()
{
// Creating three objects
count_object obj1, obj2, obj3;
// Setting data
obj1.set_data(101, "Alice");
obj2.set_data(102, "Bob");
obj3.set_data(103, "Charlie");
// Displaying data
[Link]();
[Link]();
[Link]();
return 0;
}
14
C++Basics BEC358C ICEAS
[Link] a C++ program to illustrate multiple inheritance
#include <iostream>
using namespace std;
class M
{
protected:
int m;
public:
void get_m(int x)
{
m=x;
}
};
class N
{
protected:
int n;
public:
void get_n(int y)
{
n=y;
}
};
class P:public M,public N
{
public:
void display(void)
{
cout<<"m="<<m<<endl;
cout<<"n="<<n<<endl;
cout<<"m*n="<<m*n<<endl;
}
};
int main()
{
P p1;
p1.get_m(10);
p1.get_n(20);
[Link]();
return 0;
}
15
C++Basics BEC358C ICEAS
output
m=10
n=20
m*n=200
16