0% found this document useful (0 votes)
8 views19 pages

Assignment PBA (FINAL) - 1

The document contains multiple C++ programming assignments that cover various topics such as basic arithmetic operations, input/output handling, escape sequences, and geometric calculations. Each program demonstrates different programming concepts, including the use of functions, conditionals, and loops. The assignments also include programs for solving quadratic equations, calculating GCD and LCM, and sorting lists of numbers or strings.

Uploaded by

hashirmehmood56
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)
8 views19 pages

Assignment PBA (FINAL) - 1

The document contains multiple C++ programming assignments that cover various topics such as basic arithmetic operations, input/output handling, escape sequences, and geometric calculations. Each program demonstrates different programming concepts, including the use of functions, conditionals, and loops. The assignments also include programs for solving quadratic equations, calculating GCD and LCM, and sorting lists of numbers or strings.

Uploaded by

hashirmehmood56
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/ 19

PBA ASSIGNMENT (SOLUTION )

STUDENT – 1

1
Program # 1 ( Write a program using Cin )
#include <iostream>
using namespace std;
int main()
{
int a,b,sum;
cout<<"Enter the first number:";
cin >>a;
cout<<"Enter the second number:";
cin >> b;
sum=a+b;
cout<<"The sum of first and second number is "<<sum<<endl;
return 0;
}
Program # 2 ( Write a program using Cout )
#include <iostream>
using namespace std;
int main()
{
int a=5 , b=7;
cout<<" The sum of "<< a <<" and "<< b <<" is <<(a+b)<<endl;
return 0;
}
Program # 3 (Write a program using Escape Sequence)
#include <iostream>
using namespace std;
int main()
{
cout << "Hello, World!\n";
cout << "Welcome to C++ Programming.\n\n";
cout << "Name\t:\tJohn Doe\n";
cout << "Age\t\t:\t25\n";
cout << "Country\t:\tUSA\n\n";
return 0;
}
Program # 4 ( Write a program using Setw )
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
cout << setw(10) << "Name"<< setw(10) << "Class"<< setw(10) << "Section"
<< setw(10) << "Campus" << endl;
cout << setw(10) << "Ali"<< setw(10) << “XII”<< setw(10) << “CA50”<< setw(10) << “APC” << endl;
return 0;
}

2
Program # 5 ( Write a program for solving arithmetic problems to calculate interest, percentage, average,
ratio, grades )

Method 1: By separate programs Method 2: By using functions::


o Interest #include <iostream>
#include <iomanip>
#include <iostream> using namespace std;
int main() void calculateInterest()
{ {
float p, r, i; double principal, rate, time, interest;
cout << "Enter principal and rate: "; cout << "\nEnter Principal Amount: ";
cin >> p >> r; cin >> principal;
i = (p * r) / 100; cout << "Enter Interest Rate (in %): ";
cout << "Interest: " << i << endl; cin >> rate;
return 0; cout << "Enter Time (in years): ";
} cin >> time;
interest = (principal * rate * time) / 100;
o Ratio cout << "Simple Interest: " << fixed << setprecision(2) <<
interest << endl;
#include <iostream> }
int main() void calculatePercentage()
{ {
int a, b; double obtainedMarks, totalMarks, percentage;
cout << "Enter two numbers: "; cout << "\nEnter Obtained Marks: ";
cin >> a >> b; cin >> obtainedMarks;
cout << "Ratio: " << a/b << endl; cout << "Enter Total Marks: ";
return 0; cin >> totalMarks;
} if (totalMarks == 0)
{
o Percentage/Grade cout << "Total Marks cannot be zero." << endl;
return;
#include <iostream> }
int main() percentage = (obtainedMarks / totalMarks) * 100;
{ cout << "Percentage: " << fixed << setprecision(2) <<
int total_m,obt_m; percentage<< "%" << endl;
floate p; }
cout << "Enter total marks: ";
cin >> total_m; void calculateAverage()
cout<< ‘’Enter obtained marks: ‘’; {
p=(obt_m*100)/total_m; int n;
cout << "Percentage: "<<p; cout << "\nEnter the number of values: ";
if(p>=80) cout << "Grade: A"; cin >> n;
else if(p>=70) cout << "Grade: B"; if (n <= 0)
else if(p>=60) cout << "Grade: C"; {
else if(p>=50) cout<< ‘’Grade:D”; cout << "Invalid number of values." << endl;
else if(p>=40) cout<< ‘’Grade:E’’; return;
else cout << "Grade: F"; }
return 0; double sum = 0, value;
} for (int i = 1; i <= n; i++)
{
cout << "Enter value " << i << ": ";
cin >> value;
sum += value;
}
cout << "Average: " << fixed << (sum / n) <<endl;
}
void calculateRatio()

3
{
double a, b;
cout << "\nEnter first number: ";
cin >> a;
cout << "Enter second number: ";
cin >> b;
if (b == 0)
{
cout << "The second number cannot be zero." << endl;
return;
}
double ratio = a / b;
cout << "The ratio of " << a << " to " << b << " is " <<
fixed << ratio << " : 1" << endl;
}
void calculateGrades()
{
double marks; char grade;
cout << "\nEnter Marks (0 - 100): ";
cin >> marks;
if (marks < 0 || marks > 100)
{
cout << "Invalid marks entered. enter between 0 and 100." << endl;
return;
}
if (marks >= 90)
grade = 'A';
else if (marks >= 80)
grade = 'B';
else if (marks >= 70)
grade = 'C';
else if (marks >= 60)
grade = 'D';
else if (marks >= 50)
grade = 'E';
else
grade = 'F';
cout << "Grade: " << grade << endl;
}

int main()
{
int choice;
do
{
cout << "\n=== Arithmetic Problem Solver ===\n";
cout << "1. Calculate Interest\n";
cout << "2. Calculate Percentage\n";
cout << "3. Calculate Average\n";
cout << "4. Calculate Ratio\n";
cout << "5. Calculate Grade\n";
cout << "6. Exit\n";
cout << "Choose an option (1-6): ";
cin >> choice;
switch (choice)
{
case 1:

4
calculateInterest();
break;
case 2:
calculatePercentage();
break;
case 3:
calculateAverage();
break;
case 4:
calculateRatio();
break;
case 5:
calculateGrades();
break;
case 6:
cout << "Exiting the program. Goodbye!" << endl;
break;
default:
cout << "Invalid choice! Please select a valid option." << endl;
}
}
while (choice != 6);
return 0;
}

Program # 6 ( Write a program for calculating area, volume


and perimeter of some basic geometrical shapes )

o Square o Rectangle

#include <iostream> #include <iostream>


int main() int main() {
{ int l,w,h;
int s; cout << "Enter Length: ";
cout << "Enter side: "; cin >> l;
cin >> s; cout<<"Enter Height: ";
cout << "Area: " << s*s << endl; cin>>h;
cout << "Perimeter: " << 4*s << endl; cout<<"Enter Width: ";
cout << "Volume (cube): " << s*s*s << endl; cin>>w;
return 0; cout << "Area: " << l*w << endl;
} cout << "Perimeter: " << 2(l+w) << endl;
cout << "Volume (cube): " << l*w*h << endl;
return 0; }

o Triangle

#include <iostream>
int main()
{
int s1,s2,s3;
cout << "Enter side1: ";
cin >> s1;
cout << "Enter side2: ";
cin >> s2;
cout << "Enter side3: ";
cin >> s3;
cout << "Area: " << 1/2(s1*s2) << endl;

5
cout << "Perimeter: " << s1+s2+s3 << endl;
return 0;
}

Program # 7 ( Write a program for comparing numbers/strings )

compares strings (without functions) compares strings (Using functions)


#include <iostream>
#include <string.h> #include <iostream>
int main() #include <string>
{ using namespace std;
char str1[20], str2[20]; void compareNumbers()
cout << "Enter first string: "; {
cin.get(str1, 20) double num1, num2;
cout << "Enter second string: "; cout << "\nEnter the first number: ";
cin.get(str2, 20) cin >> num1;
x=strcmp(str1, str2); cout << "Enter the second number: ";
cin >> num2;
if(x==0) if (num1 > num2)
cout<<”Stings are equal”; {
else if(x>0) cout << num1 << " is greater than " << num2 << endl;
cout<<”Sring1 is less than String2”; }
else else if (num1 < num2)
cout<<”String1 is > than String2”; {
cout << num1 << " is less than " << num2 << endl;
return 0; }
} else
{
cout << num1 << " is equal to " << num2 << endl;
}
}
void compareStrings()
{
string str1, str2;
cout << "\nEnter the first string: ";
cin >> str1;
cout << "Enter the second string: ";
cin >> str2;
if (str1 > str2)
{
cout << str1 << "is greater than " <<str2 << endl;
}
else if (str1 < str2)
{
cout << str1 << " is less than " <<str2 << endl;
}
else
{
cout << str1 << " is equal to " << str2 << endl;
}
}
int main()
{
int choice;

6
do
{
cout << "\n=== Compare Numbers or Strings ===\n";
cout << "1. Compare Numbers\n";
cout << "2. Compare Strings\n";
cout << "3. Exit\n";
cout << "Choose an option (1-3): ";
cin >> choice;
switch (choice)
{
case 1:
compareNumbers();
break;
case 2:
compareStrings();
break;
case 3:
cout << "Exiting the program. Goodbye!" << endl;
break;
default:
cout << "Invalid choice! Please select a valid option." <<
endl;
}
}
while (choice != 3);
return 0;
}

Program # 8 ( Write a program for solving Quadratic equation


#include<iostream>
#include<cmath>
using namespace std;
int main ()
{
int a, b, c;
int x1=0, x2=0;
cout<<"Enter coefficient of a,b and c";
cin>>a>>b>>c;

if((b*b-4*a*c)<0)
{
cout<<"No real solutions<< endl;
}
else if((b*b-4*a*c) ==0)
{
x1-b/(4*a*c) ;
cout<<"x1 is"<<x1<<endl;
}
else
{
x1=(-b+sqrt(b*b-4*a*c)))/(2*a);
x2=(-b-sqrt(b*b-4*a*c)))/(2*a);
cout<<"x1 is"<<x1<<endl;
cout<<"x2 is"<<x2<< endl;
}
return 0; }

7
Program # 9 ( Write a program for finding out the GCD and LCM )

Without using functions By using functions


GCD #include <iostream>
using namespace std;
#include <iostream> // Function to calculate GCD (using Euclidean algorithm)
int main()
{ int gcd(int a, int b)
int num1, num2, gcd = 1; {
cout << "Enter two numbers: "; while (b != 0)
cin >> num1 >> num2; {
for (int i = 1; i <= num1 && i <= num2; i++) int temp = b;
{ b = a % b;
if (num1 % i == 0 && num2 % i == 0) a = temp;
gcd = i; }
} return a;
cout << "GCD: " << gcd; }
return 0;
} // Function to calculate LCM (using the formula LCM(a, b) = |
a * b| /GCD(a, b))
LCM
int lcm(int a, int b)
#include <iostream>
{
int main()
return (a * b) / gcd(a, b); }
{
int main()
int num1, num2;
{
cout << "Enter two numbers: ";
int num1, num2, choice;
cin >> num1 >> num2;
do
{
int lcm = (num1 * num2) / ( gcd(num1,
cout << "\n=== GCD and LCM Calculator ===\n";
num2));
cout << "1. Calculate GCD\n";
cout << "LCM: " << lcm;
cout << "2. Calculate LCM\n";
return 0;
cout << "3. Calculate both GCD and LCM\n";
}
cout << "4. Exit\n";
cout << "Choose an option (1-4): ";
cin >> choice;
if (choice != 4)
{
cout << "Enter the first number: ";
cin >> num1;
cout << "Enter the second number: ";
cin >> num2;
switch (choice)
{ case 1:
cout << "GCD of " << num1 << " and " << num2 << " is " <<
gcd(num1, num2) << endl;
break;
case 2:
cout << "LCM of " << num1 << " and " << num2 << " is " <<
lcm(num1, num2) << endl;
break;
case 3:
cout << "GCD of " << num1 << " and " << num2 << " is " <<
gcd(num1, num2) << endl;
cout << "LCM of " << num1 << " and " << num2 << " is " <<
lcm(num1, num2) << endl;
break;

8
default:
cout << "Invalid choice!" << endl;
} }
else
{ cout << "Exiting the program. Goodbye!" << endl;
}
}
while (choice != 4);
return 0;
}

Program # 10 ( Write a program that reads a


number and find out whether it is a prime or composite )

#include <iostream>
Method 1 Method 2

int prime(int num)


#include<iostream>

{
using namespace std;
Bool isPrime(int num) ;

if (num <= 1) return false;


int main()

for (int i = 2; i <= num / 2; i++)


{

{
int num;
Bool flag;
if (num % i == 0) return false;
cout<<"Enter any number:";

return true;
cin>>num;

}
flag=isPrime(num)

int main()
if(flag==true)
cout<<num<<"is a prime number ";

{
else

int num;
cout<<num<<" is a composite number ";

cout << "Enter a number: ";


return 0;

cin >> num;


}
Bool isPrime(int num)

if (prime(num))
{

cout << num << " is Prime";


Bool flag=true;

else
for(int i=2;i<=num/2;i++)

cout << num << " is Composite";


{
if(num%i==0)

return 0;
{

}
flag=false;
break;
}
}
return flag;
}

Program # 11 ( Write a program for sorting a list of numeric/string )


Sorting numbers (without functions) With functions
include <iostream> #include <iostream>
using namespace std; #include <vector>
#include <string>
int main() #include <algorithm>
{ using namespace std;
int n; void sortNumbers()
{
cout<<"Enter the size of array: "; cin>>n; int n;

9
cout << "\nEnter the number of elements: ";
int a[n]; cin >> n;
vector<int> numbers(n);
cout<<"\nEnter the elements: "; cout << "Enter " << n << " numbers:\n";
for(int i=0; i<n; i++) cin>>a[i]; for (int i = 0; i < n; i++)
{
cin >> numbers[i];
for(int i=0; i<n; i++) }
{ sort(numbers.begin(), numbers.end());
for(int j=i+1; j<n; j++) { if(a[i]>a[j]) cout << "Sorted numbers: ";
{ for (int num : numbers)
int temp = a[i]; {
a[i] = a[j]; cout << num << " ";
a[j] = temp; }
} cout << endl;
} }
} void sortStrings()
{
cout<<"\nArray after swapping: "; int n;
cout << "\nEnter the number of strings: ";
for(int i=0; i<n; i++) cin >> n;
cout<<a[i]<<" "; vector<string> strings(n);
cout << "Enter " << n << " strings:\n";
return 0; cin.ignore(); // To ignore any leftover newline
} character
for (int i = 0; i < n; i++)
{
getline(cin, strings[i]);
}
sort(strings.begin(), strings.end());
cout << "Sorted strings:\n";
for (const string& str : strings)
{
cout << str << endl;
}
}
int main()
{
int choice;
do
{
cout << "\n=== List Sorting ===\n";
cout << "1. Sort Numbers\n";
cout << "2. Sort Strings\n";
cout << "3. Exit\n";
cout << "Choose an option (1-3): ";
cin >> choice;
switch (choice)
{
case 1:
sortNumbers();
break;
case 2:
sortStrings();
break;
case 3:
cout << "Exiting the program. Goodbye!" << endl;

10
break;
default:
cout << "Invalid choice! Please select a valid
option." <<
endl;
}
}
while (choice != 3);
return 0;
}

Program # 12 ( Write a C++ program for searching an item out of a list of items numeric/string )
Searching a number Linear search
#include<iostream> #include <iostream>
using namespace std; #include <conio.h>
//Program to find a number in an array. using namespace std;
int main() int main()
{ {
int a[100],n,i,x; // define an array
cout<<"\nEnter The Limit: "; int num[]= {12,9,37,86,2,17,5};
cin>>n; int i,x,f;
for(i=0;i<n;i++) cout<<"Array: ";
{ for(i=0; i<7; i++)
cout<<"\nEnter The Value : "; {
cin>>a[i]; cout<<num[i]<<" ";
} }
cout<<"\nEnter The Value to Search :";
cin>>x; // store the number in variable x to search in the array
cout<<"\n\nEnter number to search ";
for(i=0;i<n;i++)//1 2 3 4 5 cin>>x;
{
if(a[i]==x) // set the value of variable f=0
{ f=0;
cout<<"Value Found @"<<i;
return 0; // run loop i from 0 to N-1 to read number from the array
} for(i=0; i<7; i++)
} {
cout<<"Value Not Found"; // check if value of x is equal to the num[i] then print
return 0; // message "Number found at index" and the value of i and
} set f=1 and break the loop
if(x==num[i])
{
cout<<"Number found at index "<<i;
f=1;
break;
}
}

// check if value of f is 0 then print number not found


if(f==0)
{
cout<<"Number not found";
}
return 0;
}

11
Binary search Searching strings and numbers using functions
#include <iostream> #include <iostream>
#include <conio.h> #include <vector>
#include <string>
using namespace std; using namespace std;
template <typename T>
int main() int searchItem(const vector<T>& list, T item)
{ {
// define an array that contain numbers for (int i = 0; i < list.size(); i++)
in ascending order { if (list[i] == item)
int num[]= {2,5,9,12,17,37,86}; {
int i,x,f,S,E,M; return i; // Item found, return the index
}
cout<<"Array: "; }
for(i=0; i<7; i++) return -1; // Item not found
{ }
cout<<num[i]<<" "; int main()
} {
// Example with numeric list
// store the number in variable x to vector<int> numList = {10, 20, 30, 40, 50};
search in the array int numItem = 30;
cout<<"\n\nEnter number to search "; int numResult = searchItem(numList, numItem);
cin>>x; if (numResult != -1)
{
// set the value of variable f=0 cout << "Item " << numItem << " found at index " <<
f=0; numResult
<< endl;
// set the start index S, end index E }
with the start and end index of the array else
S=0; {
E=6; cout << "Item " << numItem << " not found!" << endl;
}
// run a while loop till S is less than or // Example with string list
equal to E vector<string> strList = {"apple", "banana", "cherry", "date"};
while(S<=E) string strItem = "banana";
{ int strResult = searchItem(strList, strItem);
// find the middle index M by if (strResult != -1)
dividing the sum of S and E by 2 {
// and consider only the integer part cout << "Item \"" << strItem << "\" found at index " << strResult
of the result. << endl;
M=(S+E)/2; }
else
// check if value of x is equal to the {
value of num[M] then print message cout << "Item \"" << strItem << "\" not found!" << endl;
// 'Number found at index' along }
with the value of M and set f=1 and then return 0; }
break the loop
if(x==num[M])
{
cout<<"Number found at index
"<<M;
f=1;
break;
}
else if(x>num[M]) // check if value
of x is greater than the value at num[M]

12
then set the start index S=M+1
{
S=M+1;
}
else if(x<num[M]) // check if value
of x is smaller than the value at num[M]
then set the end index E=M-1
{
E=M-1;
}
}

// check if value of f is 0 then print


number not found
if(f==0)
{
cout<<"Number not found";
}
return 0;
}

Program # 13 ( Write a C++ program for generating random number for a dice using function )
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
int rollDice()
{
return rand() % 6 + 1;
}
int main()
{
srand(time(0));
int result = rollDice();
cout << "You rolled a " << result << "!" << endl;
return 0;
}

Program # 14 ( Write a program for finding addition and multiplication of matrices 3 x 3 )


#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
int rows, cols;
cout << "Enter the number of rows: ";
cin >> rows;
cout << "Enter the number of columns: ";
cin >> cols;
int matrix1[rows][cols], matrix2[rows][cols], result[rows][cols];
cout << "Enter elements for first matrix: " << endl;
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
cin >> matrix1[i][j];

13
}
}
cout << "Enter elements for second matrix: " << endl;
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
cin >> matrix2[i][j];
}
}
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
result[i][j] = matrix1[i][j] + matrix2[i][j];
}
}
cout << "\nResultant Matrix (After Addition): " << endl;
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
cout << setw(5) << result[i][j];
}
cout << endl;
}
return 0;
}

Program # 15 ( Write a C++ program for finding transpose of a matrix (3*3) )


#include <iostream>
using namespace std;
int main()
{
int matrix[3][3], transpose[3][3];
cout << "Enter elements of 3x3 matrix:\n";
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 3; j++)
{
cout << "Element [" << i + 1 << "][" << j + 1 << "]: ";
cin >> matrix[i][j];
}
}
cout << "\nOriginal Matrix:\n";
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 3; j++)
{
cout << matrix[i][j] << " ";
}
cout << endl;
}
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 3; j++)
{
transpose[j][i] = matrix[i][j];
}
}
cout << "\nTranspose of the Matrix:\n";
for (int i = 0; i < 3; i++)
{

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

Program # 16 ( Write a program for generating and summing simple series )

Write a program in C++ to display the sum of the series Sum of natural numbers (1 + 2 + 3 + ... + n)
[ 9 + 99 + 999 + 9999 ...].
#include <iostream> #include <iostream>
using namespace std; using namespace std;

int main() int main() {


{ int n, sum = 0;
long int n, i, t = 9;
int sum = 0; cout << "Enter a positive integer: ";
cout << "\n\n Display the sum of the series [ 9 + 99 + cin >> n;
999 + 9999 ...]\n";
cout << "------------------------------------------------------\n"; for (int i = 1; i <= n; ++i) {
cout << " Input number of terms: "; sum += i;
cin >> n; }
for (i = 1; i <= n; i++)
{ cout << "Sum = " << sum;
sum += t; return 0;
cout << t << " "; }
t = t * 10 + 9;
}
cout << "\n The sum of the series = " << sum << endl;
}
Using function
#include <iostream>
using namespace std;
int sumSeries(int N)
{
int sum = 0;
for (int i = 1; i <= N; i++)
{
sum += i;
}
return sum;
}

int main()
{
int N;
cout << "Enter the number of terms (N): ";
cin >> N;
int result = sumSeries(N);
cout << "The sum of the first " << N << " natural
numbers is: " << result << endl;
return 0; }
Program # 17 (Write a program for reversing a given number or string)

15
Number String
#include <iostream> #include <iostream>
Void reverseNumber(int num) #include <string>
{ Void reverseString(char str[ ])
Int reversedNum = 0; {
While (num != 0) String reversedStr = “ “;
{ For (int i = str.length() – 1; i ≥ 0; i--)
Int digit = num % 10; {
reversedNum = reversedNum * 10 + digit; reversedStr += str[i];

Cout ≪ “Reversed String: “ ≪ reversedStr ≪


num /= 10; }

Cout ≪ “Reversed Number: “ ≪ reversedNum ≪


}
endl;
endl; }
} Int main()
Int main() {

Cout ≪ “Enter a string: “;


{ String str;

Cout ≪ “Enter a number: “; Cin ≫ str;


Int num;

Cin ≫ num; reverseString(str);


reverseNumber(num); return 0;
return 0; }
}

PART-II

Program # 1 ( Write a program for finding out a specific day of a week for a given data using function )
#include <iostream>
using namespace std;
string getDayOfWeek(int day, int month, int year)
{ if (month < 3) {
month += 12;
year -= 1; }
int K = year % 100; // Year of the century
int J = year / 100; // Zero-based century
// Zeller's Congruence formula
int h = (day + 13 * (month + 1) / 5 + K + K / 4 + J / 4 + 5 * J) % 7;
// Mapping Zeller's output to days of the week
string daysOfWeek[] = {"Saturday", "Sunday", "Monday",
"Tuesday", "Wednesday", "Thursday", "Friday"};
return daysOfWeek[h];
}
int main()
{
int day, month, year;
cout << "Enter the date (DD MM YYYY): ";
cin >> day >> month >> year;
string dayOfWeek = getDayOfWeek(day, month, year);
cout << "The day of the week is: " << dayOfWeek << endl;
return 0;
}
Program # 2 ( Write a program to sum two and three numbers of different data types )
#include <iostream>

16
using namespace std;
int main()
{
int intNum1, intNum2; // Variables for two-number sum
float floatNum1, floatNum2;
double doubleNum1, doubleNum2; // Input for summing two numbers of different data types
cout << "Enter an integer and a float to sum: ";
cin >> intNum1 >> floatNum1;
cout << "Enter a float and a double to sum: ";
cin >> floatNum2 >> doubleNum1;
float sum1 = intNum1 + floatNum1; // int + float // Summing two numbers of different data types
double sum2 = floatNum2 + doubleNum1; // float + double
cout << "\nSum of integer and float: " << sum1 << endl; // Displaying the sums of two numbers
cout << "Sum of float and double: " << sum2 << endl;
cout << "\nEnter an integer, a float, double to sum: ";
cin >> intNum2 >> floatNum1 >> doubleNum2;
double sum3 = intNum2 + floatNum1 + doubleNum2; // int + float + double
cout << "Sum of integer, float, and double: " << sum3 << endl;
return 0;
}

Program # 3 ( Write a program to display the address and of a variable using pointers )
#include <iostream>
using namespace std;
int main()
{
int num; // Declare an integer variable
int *ptr; // Declare a pointer to an integer
cout << "Enter an integer value: ";
cin >> num;
ptr = &num; // Store the address of 'num' in the pointer 'ptr'
cout << "\nValue of num: " << num << endl; // Direct access
cout << "Value of num using pointer: " << *ptr << endl; // Access
using pointer (dereferencing)
cout << "\nAddress of num: " << &num << endl; // Address of 'num'
directly
cout << "Address of num using pointer: " << ptr << endl; // Address using the pointer
return 0;
}

Program # 4 ( Write a program to create and display student object with data members as name age and
class )
#include <iostream>

17
#include <string>
using namespace std;
class Student
{
public:
string name;
int age;
int grade;
void inputDetails()
{
cout << "Enter Student Name: ";
getline(cin, name); // To read full name including spaces
cout << "Enter Age: ";
cin >> age;
cout << "Enter Class (Grade): ";
cin >> grade;
cin.ignore(); // To clear the newline character left in the input
buffer
}
// Member function to display student details
void displayDetails()
{
cout << "\n--- Student Details ---" << endl;
cout << "Name : " << name << endl;
cout << "Age : " << age << endl;
cout << "Class: " << grade << endl;
}
};
int main()
{
Student student1;
student1.inputDetails();
student1.displayDetails();
'return 0;
}

Program # 5 ( Write a program to create and read a data file )


#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
// Writing to a file
ofstream outFile("studentData.txt");
if (!outFile) { // Check if the file was created successfully
cerr << "Error creating the file!" << endl;
return 1;
}
// Writing data to the file
outFile << "Name: John Doe\n";
outFile << "Age: 20\n";
outFile << "Grade: A\n";
outFile << "Major: Computer Science\n";
// Closing the file after writing

18
outFile.close();
// Reading from the file
ifstream inFile("studentData.txt"); // Open the file for reading
if (!inFile) { // Check if the file exists and can be opened
cerr << "Error opening the file!" << endl;
return 1;
}
string line;
// Reading and displaying the content of the file
cout << "\nReading data from file:\n";
while (getline(inFile, line)) { // Read the file line by line
cout << line << endl;
}
// Closing the file after reading
inFile.close();
return 0;
}

19

You might also like