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

21HCS4160

Uploaded by

Neha Das
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 views67 pages

21HCS4160

Uploaded by

Neha Das
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/ 67

B.Sc.

(HONS) COMPUTER SCIENCE SEMESTER-1

COMPUTER SCIENCE LAB (C-I): Programming


Fundamentals using C++ Lab

NAME : NEHA DAS


ROLL NO : 21HCS4160

1. WAP to print the sum and product of digits of an integer.

// WAP to print the sum and product of digits of an


integer.

#include<iostream>
using namespace std;

int main(){
int a , b;
cout<<"Enter 1st digit :"<<endl;
cin>>a;
cout<<"Enter 2nd digit :"<<endl;
cin>>b;
cout<<"The sum is :"<<a+b<<endl;
cout<<"The product is :"<<a*b<<endl;

return 0 ;
}

OUTPUT
2. WAP to reverse a number.

// WAP to reverse a number.

#include<iostream>
using namespace std;

int main(){
int n , reverse=0 , rem;
cout<<"Enter a number :"<<endl;
cin>>n;
while(n!=0)
{
rem=n%10;
reverse=reverse*10+rem;
n=n/10;
}
cout<<"Reversed Number :"<<reverse<<endl;

return 0 ;
}

OUTPUT

3. WAP to compute the sum of the first n terms of the following series
S = 1+1/2+1/3+1/4+……

#include<iostream>
using namespace std;
class cl
{
int n; double s;
public:
cl()
{
n=0;
s=0.0;
}
cl(int p)
{
n=p;
}
void sum()
{
for(int i=1; i<=n; i++)
s=s+1/(double)i;
cout<<"Sum of series = "<<s<<endl;
}

};

int main(){
int i;
cout<<" enter no of terms :"<<endl;
cin>>i;
cl ob(i);
ob.sum();

return 0 ;
}
OUTPUT

4. WAP to compute the sum of the first n terms of the following series
S =1-2+3-4+5…………….

#include<iostream>
using namespace std;

int main(){
int i,sum,n,sign;
cout<<"Enter value of n: "<<endl;
cin>>n;
sum=0;
sign=1;
for(i=1; i<=n; i++)
{
sum=sum+i*sign;
sign=sign*(-1);

cout<<"result="<<sum;

return 0 ;
}

OUTPUT
5. Write a function that checks whether a given string is Palindrome or not. Use
this
function to find whether the string entered by user is Palindrome or not.

#include <iostream>
using namespace std;

string isPalindrome(string S)
{
for (int i = 0; i < S.length() / 2; i++)
{
if (S[i] != S[S.length() - i - 1])
{
return "No, The string is not a
Palindrome";
}
}
return "yes, The string is a Palindrome";
}

int main()
{
string S;
cout<<"Enter the string :"<<endl;
cin>>S;
cout<< isPalindrome(S);

return 0;
}

OUTPUT
6. Write a function to find whether a given no. is prime or not. Use the same to
generate
the prime numbers less than 100.

#include<iostream>
using namespace std;

// Function to check whether a number is prime or not.

bool checkPrimeNumber(int n){


bool isPrime=true;

// 0 and 1 are not prime numbers


if(n==0||n==1){
bool isPrime=false;

}
else{
for(int i=2; i<=n/2; ++i){
if(n%i==0){
isPrime=false;
break;
}
}
}
return isPrime;
}

// Function to print prime numbers.

void printPrime(int n)
{
for(int i=2; i<=100; i++){
if(checkPrimeNumber(i))

cout<<i<< " "<<endl;


}
}

int main(){

int n;
cout<<"Enter a positive integer: "<<endl;
cin>>n;

if(checkPrimeNumber(n))
cout<< n << " is a prime no"<<endl;
else
cout<< n << " is not a prime no"<<endl;

cout<<"Prime numbers less than 100 are :"<<endl;

printPrime(n);

return 0 ;
}
OUTPUT

7.WAP to compute the factors of a given number.

#include <iostream>
using namespace std;

int main()
{
int num, fact = 1;
cout << "Enter a positive number :" << endl;
cin>>num;

for (int i = 1; i <= num; i++)


{
fact = fact * i;
}

cout << "Factorial of given number is :" << fact <<


endl;
return 0;
}

OUTPUT
8. Write a macro that swaps two numbers. WAP to use it.

// Write a macro that swaps two numbers. WAP to use it.


#include<iostream>

#define SWAP(a,b){ int temp; temp=a; a=b; b=temp;}

using namespace std;

int main(){
int x,y;
cout<<"Enter two numbers :"<<endl;
cin>>x>>y;
cout<<"BEFORE SWAP"<<endl;
cout<<"x = "<<x<<" y = "<<y<<endl;
SWAP(x,y);
cout<<"AFTER SWAP"<<endl;
cout<<"x = "<<x<<" y = "<<y<<endl;

return 0 ;
}

OUTPUT

9. WAP to print a triangle of stars as follows (take number of lines from user):
*
***
*****
*******
*********
#include<iostream>
using namespace std;
int main(){

for(int i=1; i<=5; i++)


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

return 0 ;}
OUTPUT

10. WAP to perform following actions on an array entered by the user:


i) Print the even-valued elements
ii) Print the odd-valued elements
iii) Calculate and print the sum and average of the elements of array
iv) Print the maximum and minimum element of array
v) Remove the duplicates from the array
vi) Print the array in reverse order
The program should present a menu to the user and ask for one of the options.
The menu should
also include options to re-enter array and to quit the program.

#include <iostream>
using namespace std;

void even(); // User defined function to check the


even elements of the array
void odd(); // User defined function to check the
odd elements of the array
void sum_and_avg(); // User defined function to find the
sum and average of elements of the array
void max_and_min(); // User defined function to the maximum
and minimum element of the array
void remove_duplicates(); // User defined function to remove
duplicate elements of the array
void reverse(); // User defined function to reverse the
array

int main()
{
int option; // Declaring variables
char choice; // Declaring variable

do
{
// Displaying Menu options
cout << "\n**********MENU*********" << endl;
cout << "ENTER 1 : TO PRINT EVEN VALUED ELEMENT" << endl;
cout << "ENTER 2 : TO PRINT EVEN VALUED ELEMENT" << endl;
cout << "ENTER 3 : TO PRINT SUM AND AVERAGE OF THE ARRAY"
<< endl;
cout << "ENTER 4 : TO PRINT MAXIMUM AND MINIMUM ELEMENT
OF ARRAY" << endl;
cout << "ENTER 5 : TO REMOVE DUPLICATES FROM THE ARRAY"
<< endl;
cout << "ENTER 6: TO PRINT THE ARRAY IN REVERSE ORDER" <<
endl;
cout << "ENTER 7 : TO QUIT" << endl;

cout << "\n\n Enter Your Choice : "; // Inputting the


choice from the user
cin >> option;

switch (option) // Checking the entered choice


{
case 1:
even(); // Calling the function
break;
case 2:
odd(); // Calling the function
break;
case 3:
sum_and_avg(); // Calling the function
break;
case 4:
max_and_min(); // Calling the function
break;
case 5:
remove_duplicates(); // Calling the function
break;
case 6:
reverse(); // Calling the function
break;
case 7:
cout << "Exiting Program........";
exit(1);
default:
cout << "\n Invalid Choice !";
break;
}
cout << " " << "Do you want to continue (Y/N)? "<<endl;
cin>>choice;
} while (choice == 'Y' || choice == 'y'); // repeat the loop
until user wants to exit the program
}

// Defining the function even()


void even()
{
char op;
int i, num, even = 0; // Initializations and declaration of
variables

cout << "\n Enter the size of an array : "; // Inputtin the
size of the array
cin >> num;

int array[num]; //
Initializing array of same size
cout << "\n Enter the elements of the array : "; //
Inoutting the elements in the array
for (i = 0; i < num; i++)
{
cin >> array[i];
}
cout << "\n Even numbers in the array are : "; // Displaying
the even elements of the array
for (i = 0; i < num; i++)
{
if (array[i] % 2 == 0)
{
even++;
cout << array[i]<<" ";
}
}
} // End of function even()

// Defining the function odd()


void odd()
{
char op; // Initialization of variable
int i, num, odd = 0; // Initialization and Declaration of
Variables

cout << "\n Enter the size of an array : "; //


Initializations and declaration of variables
cin >> num;

int array[num]; //
Initializing array of same shirt
cout << "\n Enter the elements of the array : "; // Inputtin
the size of the array
for (i = 0; i < num; i++)
{
cin>> array[i];
}

cout << "\n Odd numbers in the array are: "; // Displaying
the odd elements of the array

for (i = 0; i < num; i++)


{
if (array[i] % 2 != 0)
{
odd++;
cout<< array[i]<<" ";
}
}

} // End of function odd()

// Defining the function sum_and_avg()


void sum_and_avg()
{
char op;
int size, i, sum = 0; // Initialization and Declaration of
Variables

cout << "\n Enter the size of the arrays : "; // Inputting
the size of the array
cin >> size;
int arr[size]; //
Initializing the array of entered size
cout << "\n Enter the elements of the array :"; // Inputting
the elements in the array

// Calculating the Sum of elements of the array


for (i = 0; i < size; i++)
{
cin >> arr[i];
sum += arr[i];
}

cout << "\n The sum of the array is : \n"


<< sum;
// Displaying the sum of the elements of the array
cout<<"\n The average of the array is : "
<< ((float)sum / size); // Displaying the average of the
elements
of the array

} // End of function sum_and_avg()

// Defining the function max_min()


void max_and_min()
{
char op;
int i, max, min, size; // Declaration of Variables

cout<<"\n Enter the size of the arrays : "; // Inputting the


size of the array
cin>>size;

int arr[size];
cout<<"\n Enter the elements of the array : "; // Inputting
the elements in the array

for (i = 0; i < size; i++)


{
cin>>arr[i];
}

/* Assume first element as maximum and minimum */


max = arr[0];
min = arr[0];
/* Find maximum and minimum in all array elements*/
for (i = 1; i < size; i++)
{
/* If current element is greater than max */
if (arr[i] > max)
{
max = arr[i];
}

/* If current element is smaller than min */


if (arr[i] < min)
{
min = arr[i];
}
}

/* Print maximum and minimum element */


cout<<"\n Maximum element = "<< max;
cout<<"\n Minimum element = "<< min;

} // end of function max_and_min()

// Defining the function remove_duplicates()


void remove_duplicates()
{
int i,j,k,n,a[30];
cout<<"How many elements?";
cin>>n;
cout<<"\nEnter elements of array\n";

for(i=0;i<n;++i)
cin>>a[i];

for(i=0;i<n;++i)
for(j=i+1;j<n;)
{
if(a[i]==a[j])
{
for(k=j;k<n-1;++k)
a[k]=a[k+1];

--n;
}
else
++j;
}
cout<<"\n";
cout<<"After removing duplicate elements : ";
for(i=0;i<n;++i)
cout<<a[i]<<" ";

} // end of function remove_duplicates()

void reverse()
{
char op; // Declarations of Variables
int size, i; // Declarations of Variables

/* Input size of array */


cout<<"\n Enter size of the array : ";
cin>> size;

int arr[size];
/* Input array elements */
cout<<"\n Enter elements in array: ";
for (i = 0; i < size; i++)
{
cin>>arr[i];
}
// Print array in reversed order
cout<<"\n Array in reverse order: ";
int reverse_array[100];
for (int i = 0; i < size; i++)
{
reverse_array[i] = arr[size - i - 1];
}
cout << "Reversed Array :" << endl;
for (int i = 0; i < size; i++)
{
cout << reverse_array[i] << " ";
}
}

OUTPUT
11. WAP that prints a table indicating the number of occurrences of each
alphabet in the text
entered as command line arguments.
#include <iostream>
#include <cstring>
using namespace std;

void print_occ(string str, char checkCharacter);

int main()
{
string myString;
printf("Enter the string: ");
cin>>myString;
for (int i=0; i<myString.length(); i++){
print_occ(myString, myString[i]);
}
return 0;
}

void print_occ(string str, char checkCharacter)


{
int count = 0;

for (int i = 0; i < str.size(); i++)


{
if (str[i] == checkCharacter)
{
++ count;
}
}

cout << "Number of " << checkCharacter << " = " <<
count<<endl;
}

OUTPUT

12. Write a program that swaps two numbers using pointers.


#include<iostream>
using namespace std;

void swap(int *first , int *second)


{
int temp;

temp=*first;
*first=*second;
*second=temp;

int main()
{

int a,b;
cout<<"Enter the numbers :"<<endl;
cin>>a;
cin>>b;

cout<<"Before swap , a = " <<a<< " , b = "


<<b<<endl;
swap(&a , &b);
cout<<"After swap , a = "<<a<<" , b = "<<b<<endl;

return 0 ;
}

OUTPUT
13. Write a program in which a function is passed address of two variables and
then alter its
contents.

#include<iostream>
using namespace std;

void swap(int *p,int *q)


{
*p=*p+*q;
*q=*p-*q;
*p=*p-*q;
}

int main(){

int a=5 , b=7;


cout<<"Before Swap"<<endl;
cout<<"a = " <<a<< " b = " <<b<<endl;
cout<<"After Swap"<<endl;
swap(&a,&b);
cout<<"a = " <<a<< " b = " <<b<<endl;

return 0 ;
}

OUTPUT

14. Write a program which takes the radius of a circle as input from the user,
passes it to another
function that computes the area and the circumference of the circle and displays
the value of area
and circumference from the main() function.
#include <iostream>
using namespace std;

float area(float radius)


{
return (22 / 7 * radius * radius);
}

float circum(float radius)


{
return (2 * 22 / 7 * radius);
}

int main()
{

int radius;
cout << "Enter radius of circle :" << endl;
cin >> radius;
cout << "Area of circle :" << area(radius) << endl;
cout << "Circumference of circle :" <<
circum(radius) << endl;

return 0;
}

OUTPUT

15. Write a program to find sum of n elements entered by the user. To write this
program, allocate
memory dynamically using malloc() / calloc() functions or new operator.

#include <iostream>
#include <malloc.h>
using namespace std;

int main()
{
int n, i, *ptr, sum = 0;
cout << "Enter total number of elements :";
cin >> n;
ptr = (int *)malloc(n * sizeof(int));
if (ptr == NULL)
{
cout << "Memory not allocated" << endl;
}
else
{
cout << "Enter Elements :" << endl;
for (i = 0; i < n; i++)
{
cin >> ptr[i];
sum += ptr[i];
}
cout << "sum =" << sum;
free(ptr);
}
sum = 0;
cout << "\n Enter total number of elements :"
<< endl;
cin >> n;
ptr = (int *)calloc(n, sizeof(int));
if (ptr == NULL)
{
cout << "Memory not allocated" << endl;
}
else
{
cout << "Enter elements :" << endl;
for (i = 0; i < n; i++)
{
cin >> ptr[i];
sum += ptr[i];
}
cout << "Sum =" << sum;
free(ptr);
}

sum = 0;
cout << "\n Enter total number of elements :"
<< endl;
cin >> n;
ptr = new int(n);
if (ptr == NULL)
{
cout << "Memory not allocated"<<endl;
}
else
{
cout << "Enter elements :" << endl;
for (i = 0; i < n; i++)
{
cin >> ptr[i];
sum += ptr[i];
}
cout << "Sum =" << sum;
free(ptr);
}
}

OUTPUT
16. Write a menu driven program to perform following operations on strings:
a) Show address of each character in string
b) Concatenate two strings without using strcat function.
c) Concatenate two strings using strcat function.
d) Compare two strings
e) Calculate length of the string (use pointers)
f) Convert all lowercase characters to uppercase
g) Convert all uppercase characters to lowercase
h) Calculate number of vowels
i) Reverse the string

#include<iostream>
#include<cstring>

using namespace std;

void char_addr();
void str_con();
void str_con_cat();
void compare_str();
void strlen_ptr();
void lower_to_uper();
void uper_to_lower();
void vowels_count();
void reverse_string();
void menu();

int main()
{
menu();
return 0;
}

void menu()
{
printf("=========MENU=========\n");
printf("1. address of each character in string\n");
printf("2. Concatenate two strings without using strcat
function\n");
printf("3. Concatenate two strings using strcat function\n");
printf("4. Compare two strings\n");
printf("5. Calculate length of the string (use pointers)\n");
printf("6. Convert all lowercase characters to uppercase\n");
printf("7. Convert all uppercase characters to lowercase\n");
printf("8. Calculate number of vowels\n");
printf("9. Reverse the string\n");
int choice;
printf("Enter your choice (1-9): ");
scanf("%d", &choice);
switch (choice){
case 1:
char_addr();
break;
case 2:
str_con();
break;
case 3:
str_con_cat();
break;
case 4:
compare_str();
break;
case 5:
strlen_ptr();
break;
case 6:
lower_to_uper();
break;
case 7:
uper_to_lower();
break;
case 8:
vowels_count();
break;
case 9:
reverse_string();
break;
default:
printf("Invalid choice! Exiting!\n");
}
}

void char_addr()
{
char str[30];
cout<<"Enter your string: ";
cin>>str;
char *ptr_str[30];

for(int i=0;i<strlen(str);i++)
ptr_str[i]=&str[i];

printf("\nString Entered is : %s\n Address of string :",str);


for(int i=0;i<strlen(str);i++)
printf("\n%c's address : %p",str[i],ptr_str[i]);
printf("\n");
}

void str_con()
{
string str1, str2, str3;
cout<<"Enter first string: ";
cin>>str1;
cout<<"Enter second string: ";
cin>>str2;
str3 = str1 + str2;
cout<<"Concatanated string: "<<str3<<endl;
}

void str_con_cat()
{
char str1[30], str2[30];
cout<<"Enter a string: ";
cin>>str1;
cout<<"Enter another string: ";
cin>>str2;
int str_len = strlen(str1) + strlen(str2);
strcat(str1, str2);
cout<<"Concatanated string: "<<str1<<endl;
}

void compare_str()
{
char str1[50], str2[50];
cout<<"Enter string 1 : ";
gets(str1);
cout<<"Enter string 2 : ";
gets(str2);
if(strcmp(str1, str2)==0)
cout << "Strings are equal!";
else
cout << "Strings are not equal.";
}

void strlen_ptr()
{
char text[30];
char * str = text;
int count = 0;

cout<<"Enter any string: ";


cin>>text;
while(*(str++) != '\0') count++;

cout<<"Length of "<<text<<" is "<<count;


}

void lower_to_uper()
{
char str[30];
cout<<"Enter a string in lowercase: ";
cin>>str;
for (int i=0; i<strlen(str); i++){
str[i]=str[i]-32;
}
cout<<"Entered character in uppercase: ";
for (int i=0; i<strlen(str); i++){
cout<<str[i];
}
cout<<"\n";
}

void uper_to_lower()
{
char str[30];
cout<<"Enter a string in uppercase: ";
cin>>str;
for (int i=0; i<strlen(str); i++){
str[i]=str[i]+32;
}
cout<<"Entered character in lowercase: ";
for (int i=0; i<strlen(str); i++){
cout<<str[i];
}
cout<<"\n";
}

void vowels_count()
{
char str[30];
cout<<"Enter your string: ";
cin>>str;
int vow_cnt = 0;
for (int i=0; i<strlen(str); i++){
if (str[i] == 'a' ||
str[i] == 'e' ||
str[i] == 'i' ||
str[i] == 'o' ||
str[i] == 'u') vow_cnt++;
}
cout<<"total vowels: "<<vow_cnt<<endl;
}

void reverse_string()
{
string str, reverse;
cout<<"Enter your string: ";
cin>>str;
for (int i=str.size(); i>=0; i--){
reverse += str[i];
}
cout<<"reverse string : "<<reverse<<endl;
}

OUTPUT
17. Given two ordered arrays of integers, write a program to merge the two-
arrays to get
an ordered array.

#include <iostream>

using namespace std;

// Merge arr1[0..n1-1] and arr2[0..n2-1] into


// arr3[0..n1+n2-1]

void mergeArrays(int arr1[], int arr2[], int n1,

int n2, int arr3[])


{

int i = 0, j = 0, k = 0;

// Traverse both array


while (i < n1 && j < n2)

// Check if current element of first

// array is smaller than current element

// of second array. If yes, store first

// array element and increment first array

// index. Otherwise do same with second array

if (arr1[i] < arr2[j])

arr3[k++] = arr1[i++];

else

arr3[k++] = arr2[j++];
}

// Store remaining elements of first array

while (i < n1)

arr3[k++] = arr1[i++];

// Store remaining elements of second array

while (j < n2)

arr3[k++] = arr2[j++];
}

int main()
{

int arr1[] = {1, 3, 5, 7};


cout<<"1st ordered array of integers :"<<endl;
for(int i =0; i<4; i++)
{
cout<<arr1[i]<<" ";
}

int n1 = sizeof(arr1) / sizeof(arr1[0]);

int arr2[] = {2, 4, 6, 8};


cout<<"\n 2nd ordered array of integers :"<<endl;
for(int i =0; i<4; i++)
{
cout<<arr2[i]<<" ";
}

int n2 = sizeof(arr2) / sizeof(arr2[0]);

int arr3[n1 + n2];

mergeArrays(arr1, arr2, n1, n2, arr3);

cout << "\n Array after merging" << endl;

for (int i = 0; i < n1 + n2; i++)

cout << arr3[i] << " ";

return 0;
}

OUTPUT

18. WAP to display Fibonacci series (i)using recursion, (ii) using iteration

#include <iostream>
using namespace std;
// i) with recursion

int fib(int x)
{
if ((x == 1) || (x == 0))
{
return (x);
}
else{
return (fib(x-1)+fib(x-2));
}
}

// ii) Using iteration

void fibonacci(int num){


int x=0 , y=1 , z=0;
for(int i=0; i<num; i++){
cout<<x<<" ";
z=x+y;
x=y;
y=z;
}

int main()
{

int x , i = 0;
cout<<"*********FIBONACCI SERIES USING
RECURSION************"<<endl;
cout<<"Enter the number of terms of the
series :"<<endl;
cin>>x;
cout<<"------FIBONACCI SERIES------- : "<<endl;
while(i<x){
cout<<" "<<fib(i);
i++;
}

int num;
cout<<"\n *********FIBONACCI SERIES USING
ITERATION************"<<endl;
cout<<"Enter the number of terms of the
series :"<<endl;
cin>>num;
cout<<"------FIBONACCI SERIES------- : "<<endl;
fibonacci(num);

return 0;
}

OUTPUT

19. WAP to calculate Factorial of a number (i)using recursion, (ii) using


iteration.

#include<iostream>
using namespace std;

// i) USING RECURSION

int factorial(int n)
{
if(n > 1)
return n * factorial(n - 1);
else
return 1;
}

int main()
{
int n;
cout<<"********USING RECURSION*******"<<endl;
cout << "Enter a positive integer: ";
cin >> n;
cout << "Factorial of " << n << " = " <<
factorial(n);

// ii) USING ITERATION

cout<<"\n********USING ITERATION*******"<<endl;
int num , factorial =1;
cout<<"Enter a number :"<<endl;
cin>>num;
for(int i=1; i<=num; i++)
{
factorial*=i;

}
cout << "Factorial of " << num << " = " <<
factorial;

return 0;
}
OUTPUT
20. WAP to calculate GCD of two numbers (i) with recursion (ii) without
recursion.

#include<iostream>
using namespace std;

// Recursive function to return GCD of a and b .

int gcd(int a , int b)


{

if((a>=b)&&(a%b)==0)
return(b);
else
gcd(b,(a%b));
}

int main(){

int a,b;

cout<<"Enter 1st no :"<<endl;


cin>>a;
cout<<"Enter 2nd no :"<<endl;
cin>>b;
cout<<"GCD of "<<a<<" and "<<b<<" is "<<gcd(a,b);

return 0 ;
}

OUTPUT
21. Create Matrix class using templates. Write a menu-driven program to
perform following
Matrix operations (2-D array implementation): a) Sum b) Difference c) Product
d) Transpose

#include <iostream>
using namespace std;
const int rows = 3;
const int cols = 3;
class matrix
{
private:
int a[rows][cols];

public:
void read();
void show();
void transpose();
matrix add(matrix &b);
matrix sub(matrix &b);
matrix multiply(matrix &c);
};
int main()
{
matrix x, y, z;
cout << "Entry of first array X..." << endl;
x.read();
cout << "Entry of second array Y..." << endl;
y.read();
cout << "Press 1 for Sum " << endl;
cout << "Press 2 for Mutiplication" << endl;
cout << "Press 3 for Transpose of X" << endl;
cout << "Press 4 for subtraction" << endl;
int choice;
cin >> choice;
if (choice == 1)
{
z = x.add(y);
cout << "The resultant matrix" << endl;
z.show();
}
else if (choice == 3)
{
x.transpose();
cout << "After transpose.." << endl;
x.show();
}
else if (choice == 2)
{
z = x.multiply(y);
cout<<"After Multiplication "<<endl;
z.show();
}
else if (choice == 4)
{
z = x.sub(y);
cout << "The resultant matrix" << endl;
z.show();
}
else
{
cout << "Incorrect choice" << endl;
}
return 0;
}
void matrix::read()
{
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < cols; j++)
{
cout << "Enter Item [" << i << "][" << j << "] :";
cin >> a[i][j];
}
}
}
void matrix::show()
{
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < cols; j++)
{
cout << a[i][j] << "\t";
}
cout << endl;
}
}
void matrix::transpose()
{
int t;
for (int i = 0; i < rows; i++)
{
for (int j = i + 1; j < cols; j++)
{

t = a[i][j];
a[i][j] = a[j][i];
a[j][i] = t;
}
}
}

matrix matrix::add(matrix &b)


{
matrix c;
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < cols; j++)
{
c.a[i][j] = a[i][j] + b.a[i][j];
}
}

return c;
}

matrix matrix::sub(matrix &b)


{
matrix c;
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < cols; j++)
{
c.a[i][j] = a[i][j] - b.a[i][j];
}
}

return c;
}

matrix matrix::multiply(matrix &b)


{
matrix c;
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < cols; j++)
{
c.a[i][j] = 0;
for (int k = 0; k < cols; k++)
{
c.a[i][j] += a[i][k] * b.a[k][j];
}
}
}
return c;
}

OUTPUT

SUM
MULTIPLICATION

TRANSPOSE
SUBTRACTION

22. Create the Person class. Create some objects of this class (by taking
information from the
user). Inherit the class Person to create two classes Teacher and Student class.
Maintain the
respective information in the classes and create, display and delete objects of
these two classes
(Use Runtime Polymorphism).

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

//Create the Person class.


class Person
{
private:
string name;
int age;
public:
Person(){}

virtual void get(){


cout<<"Enter the person name: ";
getline(cin,name);
cout<<"Enter the person age: ";
cin>>age;
}
virtual void display(){
cout<<"The person name: "<<name<<"\n";
cout<<"The person age: "<<age<<"\n";
}
};

class Teacher:public Person{

private:
float salary;
public:
Teacher(){}
virtual void get(){
Person::get();
cout<<"Enter the teacher salary: ";
cin>>salary;
}
virtual void display(){
Person::display();
cout<<"The teacher salary: "<<salary<<"\n";
}
};

class Student:public Person{

private:
string grade;
public:
Student (){}
virtual void get(){
Person::get();
cout<<"Enter the student grade: ";
cin>>grade;
}
virtual void display(){
Person::display();
cout<<"The student grade:: "<<grade<<"\n";
}
};

int main(){
Person* persons[2];

Teacher* teacher=new Teacher();


teacher->get();
cout<<"\n";
fflush(stdin);
Student* student=new Student();
student->get();

persons[0]= teacher;
persons[1]= student;
cout<<"\n";
for(int i=0;i<2;i++){
//display the information about the persons using Polymorphism
persons[i]->display();
cout<<"\n";
delete persons[i];
}
system("pause");
return 0;
}

OUTPUT

23. Create a class Triangle. Include overloaded functions for calculating area.
Overload
assignment operator and equality operator.

#include<iostream>
#include<math.h>
#include<stdlib.h>
using namespace std;
class triangle
{float v1,v2,b,h;
double AREA;
public:
triangle(){
// Default Constructor
v1=v2=b=h=0;
AREA=0.0;
}
triangle(float v1,float v2, float b){
cout<<"Intialsing sides"<<endl;
this->v1=v1;
this->v2=v2;
this->b=b;
h=0;
AREA=area(v1,v2,b);
}
triangle(float h,float b){
cout<<"Intialsing the base and height"<<endl;
this->h=h;
this->b=b;
v1=v2=0;
AREA=area(h,b);
}
triangle(float k){
cout<<"Inside equilteral triangle Constructor"<<endl;
v1=v2=b=k;
h=0;
AREA=area(b);
}
double area(float s1, float s2, float s3){
cout<<" Calculating area with 3 sides"<<endl;
double X;
float s=s1+s2+s3;
s/=2;
X=sqrt((s)*(s-s1)*(s-s2)*(s-s3));
return (X);
}
double area(float h1, float b1)
{
cout<<"Calculating area with height and base"<<endl;
double X;
X=(0.5)*h1*b1;
return (X); }
double area(float s)
{
cout<<"Area of equilteral triangle"<<endl;
return (area(s,s,s));
}
int operator==(triangle X)
{cout<<" Comparing"<<endl;
int a=0;
if(this->AREA==X.AREA)
a=1;
return (a);

}
void operator=(triangle X)
{
cout<<"Assigning Values"<<endl;
this->v1=X.v1;
this->v2=X.v2;
this->h=X.h;
this->b=X.b;
AREA=X.AREA;
}
void disp(){
if(v1){
cout<<"Edge 1="<<v1<<endl<<"Edge 2= "<<v2<<endl<<"Edge
3="<<b<<endl;
}
if(h){
cout<<"height= "<<h<<endl<<"Base= "<<b;

}
cout<<endl<<"Area= "<<AREA;
}
};
void menu(triangle &x){
cout<<"What do you want"<<endl;
cout<<" 1.Using Heron Formula"<<endl<<"2. Equilteral
triangle"<<endl<<"3. Using Base and height"<<endl<<"4. Using Asg =
operator"<<endl<<"5.Using == operator"<<endl<<"6. Other choice"<<endl;
char ch;
cin>>ch;
switch(ch){
case '1':
{float a,b,c;
cout<<"Enter Values of 3 sides"<<endl;
cin>>a>>b>>c;
triangle t(a,b,c);
t.disp();
break; }
case '2':
{
cout<<"Enter one side"<<endl;
double s;

cin>>s;
triangle t(s);
t.disp();
break;
}
case '3':
{cout<<"Enter base and height"<<endl;
float h,b;
cin>>h>>b;
triangle t(b,h);
t.disp();
break;

}
case '4':
{
float a,b,c;
cout<<"Enter 3 sides"<<endl;
cin>>a>>b>>c;
triangle t(a,b,c);
x=t;
x.disp();
break;
}
case '5':
{
float a,b,c;
cout<<"Enter 3 sides of 1st triangle"<<endl;
cin>>a>>b>>c;
triangle t1(a,b,c);
cout<<"Enter 3 sides of 2nd triangle"<<endl;
cin>>a>>b>>c;
triangle t2(a,b,c);
if(t1==t2){
cout<<"Equal"<<endl;
}
else{
cout<<"Not Equal"<<endl;

}
}
default:
{ cout<<"Wrong choice"<<endl;}

}
}
int main(){
triangle x;
menu(x);
return 0;
}

OUTPUT

USING HERON’S FORMULA


EQUILATERAL TRIANGLE

USING BASE AND HEIGHT


USING ASG == OPERATOR

USING == OPERATOR

24. Create a class Box containing length, breath and height. Include following
methods in it:
a) Calculate surface Area
b) Calculate Volume
c) Increment, Overload ++ operator (both prefix & postfix)
d) Decrement, Overload -- operator (both prefix & postfix)
e) Overload operator == (to check equality of two boxes), as a friend function
f) Overload Assignment operator
g) Check if it is a Cube or cuboid ===
Write a program which takes input from the user for length, breath and height to
test the above
class.

#include <iostream>
using namespace std;
#include <conio.h>

class Box
{
int length, breadth, height;

public:
double surfacearea();
void print();
double volume();
Box operator++(int n);
Box operator++();
Box operator--(int n);
Box operator--();
Box operator=(Box b1);
friend int operator==(Box b1, Box b2);
int check();
Box();
};

Box::Box()
{
cout << "Enter the length , breadth and height
respectively : " << endl;
cin >> length >> breadth >> height;
}

int Box::check()
{
if (length == breadth == height)
return 1;
else
return 0;
}
double Box::surfacearea()
{
if (check() == 0)
return (2 * ((length * breadth) + (breadth)
* (height) + (height) * (length)));
else
return (6 * length * length);
}

double Box::volume()
{
return (length * breadth * height);
}

Box Box::operator++()
{
length++;
breadth++;
height++;
return (*this);
}

Box Box::operator--(int n)
{
length--;
breadth--;
height--;
return (*this);
}

Box Box::operator++(int n)
{
length++;
breadth++;
height++;
return (*this);
}

Box Box::operator--()
{
--length;
--breadth;
--height;
return (*this);
}

Box Box::operator=(Box b1)


{
length = b1.length;
breadth = b1.breadth;
height = b1.height;
return (*this);
}
int operator==(Box b1, Box b2)
{
if ((b1.length == b2.length) && (b1.breadth ==
b2.breadth) && (b1.height == b2.height))
cout << "The two boxes have equal
dimensions " << endl;
else
cout << "The two boxes are unequal " <<
endl;
}

void Box::print()
{
cout << endl;
cout << "The length is : " << length << endl;
cout << "The breadth is : " << breadth << endl;
cout << "The height is : " << height << endl;
}

int main()
{
int d = 1;
do
{
cout << "new start" << endl;
Box obj;
cout << "ENTER 1 : TO SHOW THE VOLUME " <<
endl;
cout << "ENTER 2 : TO SHOW THE SURFACE AREA
" << endl;
cout << "ENTER 3 : TO INCREMENT USING
POSTFIX " << endl;
cout << "ENTER 4 : TO INCREMENT USING
PREFIX " << endl;
cout << "ENTER 5 : TO DECREMENT USING
POSTFIX " << endl;
cout << "ENTER 6 : TO DECREMENT USING
PREFIX " << endl;
cout << "ENTER 7 : TO CHECK EQUALITY OF TWO
BOXES " << endl;
cout << "ENTER 8 : TO ASSIGN VALUES TO THE
BOX " << endl;
cout << "ENTER 9 : TO CHECK IF IT IS A CUBE
OR A CUBOID" << endl;
cout << "ENTER 10 : TO PRINT CURRENT BOX
STATUS " << endl;
cout << "ENTER 0 : TO QUIT " << endl;
cin >> d;
if (d == 1)
{
cout << "The volume is :" <<
obj.volume() << endl;
}

if (d == 2)
{
cout << "The surface area is :" <<
obj.surfacearea() << endl;
}

if (d == 3)
{
cout << "Increment using postfix :";
obj++;
obj.print();
}

if (d == 4)
{
cout << "Increment using prefix :";
++obj;
obj.print();
}

if (d == 5)
{
cout << "Decrement using postfix :";
obj--;
obj.print();
}

if (d == 6)
{
cout << "Decrement using prefix :";
--obj;
obj.print();
}

if (d == 7)
{
cout << "Enter dimensions of the
box :";
Box obj1;
if (obj1 == obj)
obj1.print();
}

if (d == 8)
{
cout << "To assign values to a box
object :" << endl;
Box b2 = obj;
b2.print();
}
if (d == 9)
{
if (obj.check() == 1)
cout << "It is a cube" << endl;
else
cout << "It is a cuboid" << endl;
}

if (d == 10)
{
obj.print();
}
cout << "ENTER 0 : TO QUIT" << endl;
cin >> d;

} while (d != 0);
return 1;
}

OUTPUT

25. Create a structure Student containing fields for Roll No., Name, Class, Year
and Total Marks.
Create 10 students and store them in a file.

#include<fstream>
#include<iostream>

using namespace std;


struct Student {
string roll_no,name,cls,year,marks;

Student(string roll_no, string name, string cls, string year,


string marks){
this->roll_no = roll_no;
this->name = name;
this->cls = cls;
this->year = year;
this->marks = marks;
}
void insert_data_into_file(int student_number){
ofstream ofile;
ofile.open("ques25.txt",ios::app);
ofile<<"deltails of student "<<student_number<<"\nRoll
no:"<<roll_no<<"\nName:"<<name<<"\nClass:"<<cls<<"\nYear:"<<year<<"\
nMarks:"<<marks<<"\n\n";
ofile.close();
}
};

int main(){
ofstream ofile;
string roll_no,name,cls,year,marks;
ofile.open("ques25.txt", ios::trunc); // open the file , clear its
previous content and close it up
ofile.close();
for (int i=0; i<2; i++){
cout<<"enter the details of student "<<i+1<<"\n\n";
cout<<"enter roll no : ";
cin>>roll_no;
cout<<"enter name : ";
cin>>name;
cout<<"enter class : ";
cin>>cls;
cout<<"enter year : ";
cin>>year;
cout<<"enter marks : ";
cin>>marks;
cout<<"\n\n";
Student s = Student(roll_no,name,cls,year,marks);
s.insert_data_into_file(i+1);

}
return 0;
}

OUTPUT
26. Write a program to retrieve the student information from file created in
previous question and
print it in following format:
Roll No. Name Marks

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

struct Student {
string roll_no,name,cls,year,marks;

Student(string roll_no, string name, string marks){


this->roll_no = roll_no;
this->name = name;
this->marks = marks;
}
void display(int student_number){
cout<<"details of student "<<student_number<<endl;
cout<<"Roll no : "<<roll_no<<"\nName : "<<name<<"\nMarks :
"<<marks<<"\n\n";
}
};
int main(){
ifstream ifile;
ifile.open("ques25.txt"); // your file here
string roll_no = "",name = "",marks = "";
int student = 1;
while (!ifile.eof()){
string line;
getline(ifile,line);
// keep track of number of student
int index = line.find(":"); // find the index of ':' chracter
at each line
// index = -1 when character not found
if (index != -1){
if (line.substr(0,index) == "Roll no")
roll_no = line.substr(index+1);
if (line.substr(0,index) == "Name")
name = line.substr(index+1);
if (line.substr(0,index) == "Marks")
marks = line.substr(index+1);
}
if (marks != ""){ // as soon as marks(last variable) gets the
value from the file, pass the data into struct and reset the values
Student s = Student(roll_no,name,marks);
s.display(student);
student++;
roll_no = "";
name = "";
marks = "";
}
}
ifile.close();
return 0;
}

OUTPUT
27. Copy the contents of one text file to another file, after removing all
whitespaces.

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

int main(){
char ch;
ifstream in("file1.txt" , ios::in|ios::binary);
if(!in){
cout<<"Cannot open file .";
return 1;
}
while(in){
in.get(ch);
if(in)
{
if(ch!=' ')
cout<<ch;
}
}
return 0 ;
}

OUTPUT
28. Write a function that reverses the elements of an array in place. The function
must accept only
one pointer value and return void.

#include <iostream>

using namespace std;

//a function that reverses the elements of an array in


place. The function must accept only one pointer value
and return void.
//The start point of the program

void reversArray(int* elements){


int startPosition=0;
int size = sizeof(elements);
while (startPosition < size)
{
int temp = elements[startPosition];
elements[startPosition] = elements[size];
elements[size] = temp;
startPosition++;
size--;
}
}
int main(){
int* elements;
int size;

cout<<"Enter size of array: ";


cin>>size;
elements=new int[size];

for(int i=0;i<size;i++){
cout<<"Enter element "<<(i+1)<<": ";
cin>>elements[i];
}

cout<<"\nArray elements:\n";
for(int i=0;i<size;i++){
cout<<elements[i]<<" ";
}
reversArray(elements);
cout<<"\n\nArray elements after reversing:\n";
for(int i=0;i<size;i++){
cout<<elements[i]<<" ";
}

cout<<"\n\n";

system("pause");
return 0;
}

OUTPUT

29. Write a program that will read 10 integers from user and store them in an
array. Implement
array using pointers. The program will print the array elements in ascending and
descending
order.
#include <iostream>
#include <math.h>
#define N 10

using namespace std;


int main(int argc, char **argv)
{
int *arr=new int[N];
int i;
for(i=0;i<N;i++)
{
cout<<"Input element #"<<i<<": ";
cin>>arr[i];
}

//ordering
int imin,j;
for(i=0;i<N;i++)
{
imin=i;
for(j=i+1;j<N;j++)
if(arr[j]<arr[imin])
imin=j;
j=arr[imin];
arr[imin]=arr[i];
arr[i]=j;
}

//output:
cout<<"In ascending order: ";
for(i=0;i<N;i++)
cout<<arr[i]<<" ";

cout<<endl<<"In descending order: ";


for(i=0;i<N;i++)
cout<<arr[N-i-1]<<" ";
return 0;
}

OUTPUT

You might also like