C and CPP by Nachiketa

Download as pdf or txt
Download as pdf or txt
You are on page 1of 69

LIST OF PROGRAMS

S. No. List of Experiments


1. WAP that calculates the Simple Interest and Compound Interest. The
Principal, Amount, Rate of Interest and Time are entered through the
keyboard.
2. WAP that accepts the marks of 5 subjects and finds the sum and
percentage marks obtained by the student.
3. WAP to calculate the area and circumference of a circle.
4. WAP that accepts the temperature in Centigrade and converts into
Fahrenheit using the formula C/5=(F32)/9.
5. WAP that swaps values of two variables using a third variable.
6. WAP that checks whether the two numbers entered by the user are equal
or not.
7. WAP to find the greatest of three numbers.
8. WAP that finds whether a given number is even or odd.
9. WAP that tells whether a given year is a leap year or not.
10. WAP that accepts marks of five subjects and finds percentage and prints
grades according to the following criteria: Between 90-100%--------------
Print ‘A’ 80-90% Print ‘B’ 60-80%-
--------Print ‘C’ Below 60% --------------------- Print ‘D’
11. WAP that takes two operands and one operator from the user and perform
the operation and prints the result by using Switch statement.
12. WAP to print the sum of all numbers up to a given number.
13. WAP to find the factorial of a given number.
14. WAP to print sum of even and odd numbers from 1 to N numbers.
15. WAP to print the Fibonacci series.
16. WAP to check whether the entered number is prime or not.
17. WAP to find the sum of digits of the entered number.
18. WAP to find the reverse of a number.
19. WAP to print Armstrong numbers from 1 to 100.
20. WAP to convert binary number into decimal number and vice versa.
21. WAP that simply takes elements of the array from the user and finds the
sum of these elements.
22. WAP that inputs two arrays and saves sum of corresponding elements of
these arrays in a third array and prints them.
23. WAP to find the minimum and maximum element of the array.
24. WAP to search an element in a array using Linear Search.
25. WAP to sort the elements of the array in ascending order using Bubble
Sort technique.
26. WAP to add and multiply two matrices of order nxn.
27. WAP that finds the sum of diagonal elements of a mxn matrix.
28. WAP to implement strlen (), strcat (), strcpy () using the concept of
Functions.
29. WAP that uses a class where the member functions are defined inside a
class.
30. WAP that uses a class where the member functions are defined outside a
class.
31. WAP to demonstrate the use of static data members.
32. WAP to demonstrate the use of const data members.
33. WAP to demonstrate the use of zero argument and parameterized
constructors.
34. WAP to demonstrate the use of dynamic constructor.
35. WAP to demonstrate the use of explicit constructor.
36. WAP to demonstrate the use of initializer list.
37. WAP to demonstrate the overloading of increment and decrement
operators.
38. WAP program to demonstrate the multilevel inheritance.
PROGRAM – 1
AIM :- WAP that calculates the Simple Interest and Compound Interest. The Principal,
Amount, Rate of Interest and Time are entered through the keyboard.
Code:-
#include<stdio.h>
#include<conio.h>
#include<math.h>

int main()
{
float p, t, r, si, ci;
clrscr();
printf("Enter principal amount (p): ");
scanf("%f", &p);
printf("Enter time in year (t): ");
scanf("%f", &t);
printf("Enter rate in percent (r): ");
scanf("%f", &r);

/* Calculating simple interest */


si = (p * t * r)/100.0;

/* Calculating compound interest */


ci = p * (pow(1+r/100, t) - 1);

printf("Simple Interest = %0.3f\n", si);


printf("Compound Interest = %0.3f", ci);
getch();
return(0);
}
Output:-
PROGRAM – 2
AIM :- WAP that accepts the marks of 5 subjects and finds the sum and percentage marks
obtained by the student.
Code:-
#include <stdio.h>
#include <conio.h>
void main()
{
int n1,n2,n3;
float avg;
clrscr();
printf("\nENTER THREE NUMBERS: " );
scanf("%d %d %d",&n1,&n2,&n3);
avg=(n1+n2+n3)/3;
printf("\nAVERAGE: %0.2f",avg);
getch();
}

Output:-
PROGRAM- 3
AIM:- 3. Write a program to add digits of a four digit number.
Code:-
#include<stdio.h>

int main ()
{
int num, sum = 0;

num = 1234;
printf("The number is = %d\n",num);

while(num!=0){
sum += num % 10;
num = num / 10;
}

//output
printf("Sum: %d\n",sum);

return 0;

Output:-
PROGRAM-4
AIM- 4. Write a program to check whether the person if eligible for voting or not.
Code:-
#include<stdio.h>

int main()
{
int a ;
printf("Enter the age of the person: ");
scanf("%d",&a);
if (a>=18)
{
printf("Eigibal for voting");
}
else
{
printf("Not eligibal for voting\n");
}

return 0;
}
Output:-
PROGRAM-5
AIM- 5. Write a program to find greatest of two numbers
Code:-
#include<stdio.h>
int main ()
{
int num1, num2;
num1=12,num2=13;
if (num1 == num2)
printf("both are equal");
else if (num1 > num2)
printf("%d is greater", num1);
else
printf("%d is greater", num2);
return 0;
}
}
Output:-
PROGRAM – 6
AIM - 6. Write a program to find out which type of triangle it is.
Code:-
#include<stdio.h>
int main()
{
int side_1, side_2, side_3;
printf("Enter the sides of the triangle:");
scanf("%d%d%d", &side_1, &side_2, &side_3);
if(side_1 == side_2 && side_2 == side_3)
{
printf("All the sides of this triangle are equal. So, the triangle is equilateral.\n");
}
else if(side_1 == side_2 || side_2 == side_3 || side_3 == side_1)
{
printf("Only two sides of this triangle are equal. So, the triangle is isosceles.\n");
}
else
{
printf("All the sides of this triangle are unequal. So, the triangle is scalene.\n");
}
return 0;
}
Output:-
PROGRAM- 7
AIM- WAP to find the greatest of three numbers.
Code:-
#include <stdio.h>
int main()
{
double n1, n2, n3;
printf("Enter three different numbers: ");
scanf("%lf %lf %lf", &n1, &n2, &n3);
if (n1 >= n2 && n1 >= n3)
printf("%.2f is the largest number.", n1);
if (n2 >= n1 && n2 >= n3)
printf("%.2f is the largest number.", n2);
if (n3 >= n1 && n3 >= n2)
printf("%.2f is the largest number.", n3);
return 0;
}
Output:-
PROGRAM-8
AIM- 8. Write a program to evaluate performance of the student.
CODE: -
#include <stdio.h>
int main()
{
int phy, chem, bio, math, comp;
float per;
printf("Enter five subjects marks: ");
scanf("%d%d%d%d%d", &phy, &chem, &bio, &math, &comp);
per = (phy + chem + bio + math + comp) / 5.0;
printf("Percentage = %.2f\n", per);
/* Find grade according to the percentage */
if(per >= 90)
{
printf("Grade A");
}
else if(per >= 80)
{
printf("Grade B");
}
else if(per >= 70)
{
printf("Grade C");
}
else if(per >= 60)
{
printf("Grade D");
}
else if(per >= 40)
{
printf("Grade E");
}
else
{
printf("Grade F");
}

return 0;
}
Output:-
PROGRAM-9
AIM - 9. Write a program to make a basic calculator.
Code:-
#include <stdio.h>
int main()
{
int number1, number2;
float answer;
char op;
printf (" Enter the operation to perform(+, -, *, /) \n ");
scanf ("%c", &op);
printf (" Enter the first number: ");
scanf(" %d", &number1);
printf (" Enter the second number: ");
scanf (" %d", &number2);
//addition
if (op == '+')
{
answer = number1 + number2;
printf (" %d + %d = %f", number1, number2, answer);
}
//substraction
else if (op == '-')
{
answer = number1 - number2;
printf (" %d - %d = %f", number1, number2, answer);
}
//multiplication
else if (op == '*')
{
answer = number1 * number2;
printf (" %d * %d = %f", number1, number2, answer);
}
//division
else if (op == '/')
{
if (number2 == 0)
{
printf (" \n Divisor cannot be zero. Please enter another value ");
scanf ("%d", &number2);
}
answer = number1 / number2;
printf (" %d / %d = %.2f", number1, number2, answer);
}
else
{
printf(" \n Enter valid operator ");
}
return 0;
}

Output
PROGRAM 10

AIM- 10. Write a program to print Fibonacci up-to the given limit.
Code:-
#include <stdio.h>
int main() {
int i, n;
int t1 = 0, t2 = 1;
int nextTerm = t1 + t2;
printf("Enter the number of terms: ");
scanf("%d", &n);
printf("Fibonacci Series: %d, %d, ", t1, t2);
for (i = 3; i <= n; ++i) {
printf("%d, ", nextTerm);
t1 = t2;
t2 = nextTerm;
nextTerm = t1 + t2;
}
return 0;
}

Output:-
PROGRAM – 11
AIM :- 11. Write a program to find the sum of digits of a number.
Code:-
#include<stdio.h>

int main ()
{
int num, sum = 0;
num = 1234;
printf("The number is = %d\n",num);
while(num!=0){
sum += num % 10;
num = num / 10;
}
printf("Sum: %d\n",sum);
return 0;

Output:-
PROGRAM – 12
AIM :- Write a program to find factorial of a number.
Code:-
#include <stdio.h>
int main() {
int i, fact = 1, number;
printf("Enter a number:");
scanf("%d", &number);

for (i = 1; i <= number; i++) {


fact = fact * i;
}
printf("Factorial of %d is: %d", number, fact);
return 0;
}

Output:-
PROGRAM- 13
AIM:- 13. Write a program to print table of any number.
Code:-
#include<stdio.h>
#include<conio.h>
int main()
{
int num, i, tab;
printf("Enter the number: ");
scanf("%d", &num);
printf("\nTable of %d is:\n", num);
for(i=1; i<=10; i++)
{
tab = num*i;
printf("%d * %2d = %2d\n", num, i, tab);
}
getch();
return 0;
}

Output:-
PROGRAM-14
AIM- 14.Write program for printing different pyramid pattern.

Code:-
#include <stdio.h>
int main() {
int i, j, rows;
printf("Enter the number of rows: ");
scanf("%d", &rows);
for (i = rows; i >= 1; --i) {
for (j = 1; j <= i; ++j) {
printf("* ");
}
printf("\n");
}
return 0;
}
Output:-
PROGRAM-15
AIM - 15. Write a program to find the sum and average of 50 students.
Code:
#include<stdio.h>
void main()
{
int n, numbers, i=0,Sum=0;
float Average;
printf("\nPlease Enter How many Number you want?\n");
scanf("%d",&n);
printf("\nPlease Enter the elements one by one\n");
while(i<n)
{
scanf("%d",&numbers);
Sum = Sum +numbers;
i++;
}

Average = Sum/n;
printf("\nSum of the %d Numbers = %d",n, Sum);
printf("\nAverage of the %d Numbers = %.2f",n, Average);
return 0;
}
Output:
PROGRAM – 16
AIM - 16. Write a program to sort the array elements
#include<stdio.h>
int main()
{
int a[6]= {12,5,10,9,7,6};
int temp;
int i, j;
printf("Before Sorting ");
for(i=0; i<6; i++)
{
printf("%d ",a[i]);
}
for(i=0; i<6; i++)
{
for(j=i+1; j<6; j++) { if(a[i]>a[j])
{
temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
}
printf("\nAfter Sorting ");
for(i=0; i<6; i++)
{
printf("%d ",a[i]);
}
return 0;
}
Output:-
PROGRAM- 17
AIM - WAP to add and multiply two matrices of order nxn.
Code:-
#include<stdio.h>
#include<conio.h>
void main()
{
int a[3][3], b[3][3], c[3][3]={0}, d[3][3]={0};
int i,j,k,m,n,p,q;
printf("Enter no. of rows and columns in matrix A: ");
scanf("%d%d",&m,&n);
printf("Enter no. of rows and columns in matrix B: ");
scanf("%d%d",&p,&q);
if(m!=p || n!=q)
{
printf("Matrix Addition is not possible");
return;
}
else if(n!=p)
{
printf("Matrix Multiplication is not possible");
return;
}
else
{
printf("Enter elements of matrix A: ");
for(i=0;i<m;i++)
for(j=0;j<n;j++)
scanf("%d", &a[i][j]);
printf("Enter elements of matrix B: ");
for(i=0;i<p;i++)
for(j=0;j<q;j++)
scanf("%d", &b[i][j]);
//Matrix Addition
for(i=0;i<m;i++)
for(j=0;j<n;j++)
c[i][j] = a[i][j] + b[i][j];
printf("\nResult of Matirx Addition:\n");
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
printf("%d ", c[i][j]);
printf("\n");
}
//Matrix Multiplication
for(i=0;i<m;i++)
for(j=0;j<q;j++)
for(k=0;k<p;k++)
d[i][j] += a[i][k]*b[k][j];
printf("\nResult of Matirx Multiplication:\n");
for(i=0;i<m;i++)
{
for(j=0;j<q;j++)
printf("%d ", d[i][j]);
printf("\n");
}
}
getch();
}
Output:-
PROGRAM-18
AIM- 18. Write a program to multiply 2 matrices.
CODE: -
#include<stdio.h>
int main ()
{
int mat1[2][3] = { {0, 1, 2}, {3, 4, 5} };
int mat2[3][2] = { {1, 2}, {3, 4}, {5, 6} };
int mul[2][2], i, j, k;

printf ("matrix 1 is :\n");


for (i = 0; i < 2; i++)
{
for (j = 0; j < 3; j++)
{
printf ("%d ", mat1[i][j]);
if (j == 3 - 1)
{
printf ("\n\n");
}
}
}

printf ("matrix 2 is :\n");


for (i = 0; i < 3; i++)
{
for (j = 0; j < 2; j++)
{
printf ("%d ", mat2[i][j]);
if (j == 2 - 1)
{
printf ("\n\n");
}
}
}
for (i = 0; i < 2; i++)
{
for (j = 0; j < 2; j++)
{
mul[i][j] = 0;
for (k = 0; k < 3; k++)
{
mul[i][j] += mat1[i][k] * mat2[k][j];
}
}
}

printf ("The product of the two matrices is: \n");


for (i = 0; i < 2; i++)
{
for (j = 0; j < 2; j++)
{
printf ("%d\t", mul[i][j]);
}
printf ("\n");
}
return 0;
}
Output:-
PROGRAM-19
AIM - 19. Write a program to perform sting operations

Code:-
# include <stdio.h>
# include <conio.h>
# include <string.h>
void main()
{
char str1[40], str2[40] ;
clrscr() ;
printf("Enter the first string : \n\n") ;
gets(str1) ;
printf("\nEnter the second string : \n\n") ;
gets(str2) ;
printf("\nString 1 = %s & String 2 = %s ", str1, str2) ;
printf("- Length is : %d and %d", strlen(str1), strlen(str2)) ;
printf("\n\nString 1 = %s & String 2 = %s ", str1, str2) ;
printf("- Uppercase is : %s and %s", strupr(str1), strupr(str2));
printf("\n\nString 1 = %s & String 2 = %s ", str1, str2) ;
printf("- Lowercase is : %s and %s", strlwr(str1), strlwr(str2));
printf("\n\nString 1 = %s & String 2 = %s ", str1, str2) ;
printf("- Reverse is : %s and %s", strrev(str1), strrev(str2)) ;
printf("\n\nString 1 = %s & String 2 = %s ", str1, str2) ;
printf("- String copy is : %s ", strcpy(str1,str2));
printf("\n\nString 1 = %s & String 2 = %s ", str1, str2) ;
printf("- Concatenation is : %s ", strcat(str1,str2));
printf("\n\nString 1 = %s & String 2 = %s ", str1, str2) ;
getch() ;
}
Output:-

Enter the first string :


Football

Enter the second string :


Rocks!

String 1 = Football & String 2 = Rocks! - Length is : 8 and 6


String 1 = Football & String 2 = Rocks! - Uppercase is : FOOTBALL and ROCKS!
String 1 = FOOTBALL & String 2 = ROCKS! - Lowercase is : football and rocks!

String 1 = football & String 2 = rocks! - Reverse is : llabtoof and !skcor


String 1 = llabtoof & String 2 = !skcor - String copy is : !skcor
String 1= !skcor & String 2= !skcor - Concatenation is : !skcor!skcor
String 1 = !skcor!skcor & String 2 = !skcor
PROGRAM -20
AIM- : 20. Write a program to calculate factorial of a number using recursive function
Code:-
#include<stdio.h>
int fact(int);
int main()
{
int x,n;
printf(" Enter the Number to Find Factorial :");
scanf("%d",&n);

x=fact(n);
printf(" Factorial of %d is %d",n,x);

return 0;
}
int fact(int n)
{
if(n==0)
return(1);
return(n*fact(n-1));
}
Output:-
PROGRAM – 21
AIM :- WAP that simply takes elements of the array from the user and finds the sum of
these elements.
Code:-
include <stdio.h>
int fibbonacci(int n) {
if(n == 0){
return 0;
} else if(n == 1) {
return 1;
} else {
return (fibbonacci(n-1) + fibbonacci(n-2));
}
}

int main() {
int n = 5;
int i;
printf("Fibbonacci of %d: " , n);
for(i = 0;i<n;i++) {
printf("%d ",fibbonacci(i));
}
}

Output:-
PROGRAM – 22
AIM 22. Write a program using function to swap two numbers using call by reference.

Code:-
#include <stdio.h>
swap (int *, int *);
int main()
{
int a, b;
printf("\nEnter value of a & b: ");
scanf("%d %d", &a, &b);
printf("\nBefore Swapping:\n");
printf("\na = %d\n\nb = %d\n", a, b);
swap(&a, &b);
printf("\nAfter Swapping:\n");
printf("\na = %d\n\nb = %d", a, b);
return 0;
}
swap (int *x, int *y)
{
int temp;
temp = *x;
*x = *y;
*y = temp;
}
Output:-
Enter value of a & b: 10 20
Before Swapping:
a = 10
b = 20
After Swapping:
a = 20
b = 10
PROGRAM- 23
AIM:- 23. Write a program to read an employee record using structure and print it.
Code:-
#include <stdio.h>
/*structure declaration*/
struct employee{
char name[30];
int empId;
float salary;
};
int main()
{
/*declare structure variable*/
struct employee emp;
/*read employee details*/
printf("\nEnter details :\n");
printf("Name ?:"); gets(emp.name);
printf("ID ?:"); scanf("%d",&emp.empId);
printf("Salary ?:"); scanf("%f",&emp.salary);

/*print employee details*/


printf("\nEntered detail is:");
printf("Name: %s" ,emp.name);
printf("Id: %d" ,emp.empId);
printf("Salary: %f\n",emp.salary);
return 0;
}
Output:-
PROGRAM-24
AIM- 24. Write a program to prepare salary chart of employee using array of structures
Code:-
#include <stdio.h>

// Define the structure "Employee"


struct Employee {
int employeeID;
char name[50];
float salary;
};

int main() {
struct Employee employee1, employee2, employee3;

// Input details for the first employee


printf("Input details for Employee 1:\n");
printf("Employee ID: ");
scanf("%d", &employee1.employeeID);
printf("Name: ");
scanf("%s", employee1.name); // Assuming names do not contain spaces
printf("Salary: ");
scanf("%f", &employee1.salary);

printf("\nInput details for Employee 2:\n");


printf("Employee ID: ");
scanf("%d", &employee2.employeeID);
printf("Name: ");
scanf("%s", employee2.name);
printf("Salary: ");
scanf("%f", &employee2.salary);

printf("\nInput details for Employee 3:\n");


printf("Employee ID: ");
scanf("%d", &employee3.employeeID);
printf("Name: ");
scanf("%s", employee3.name);
printf("Salary: ");
scanf("%f", &employee3.salary);

struct Employee highestSalaryEmployee;


if (employee1.salary >= employee2.salary && employee1.salary >= employee3.salary) {
highestSalaryEmployee = employee1;
} else if (employee2.salary >= employee1.salary && employee2.salary >=
employee3.salary) {
highestSalaryEmployee = employee2;
} else {
highestSalaryEmployee = employee3;
}

// Display information for the employee with the highest salary


printf("\nEmployee with the Highest Salary:\n");
printf("Employee ID: %d\n", highestSalaryEmployee.employeeID);
printf("Name: %s\n", highestSalaryEmployee.name);
printf("Salary: %.2f\n", highestSalaryEmployee.salary);

return 0;
}
Output:-
PROGRAM-25
1. AIM- Write a program to count the number of characters, spaces, tabs, new line
characters in a file.
Code:-
#include<stdio.h>
#include<conio.h>
int main()
{
FILE *fp;
char ch, fname[30];
int noOfChar=0, noOfSpace=0, noOfTab=0, noOfNewline=0;
printf("Enter file name with extension: ");
gets(fname);
fp = fopen(fname, "r");
while(fp)
{
ch = fgetc(fp);
if(ch==EOF)
break;
noOfChar++;
if(ch==' ')
noOfSpace++;
if(ch=='\t')
noOfTab++;
if(ch=='\n')
noOfNewline++;
}
fclose(fp);
printf("\nNumber of characters = %d", noOfChar);
printf("\nNumber of spaces = %d", noOfSpace);
printf("\nNumber of tabs = %d", noOfTab);
printf("\nNumber of newline = %d", noOfNewline);
getch();
return 0;
}
Output:-
PROGRAM – 26

AIM: Write a program to receive strings from keyboard and write them to a file.
Code:
#include <stdio.h>
#include <stdlib.h>

int main() {
char sentence[1000];
FILE *fptr;
fptr = fopen("program.txt", "w");
if (fptr == NULL) {
printf("Error!");
exit(1);
}
printf("Enter a sentence:\n");
fgets(sentence, sizeof(sentence), stdin);
fprintf(fptr, "%s", sentence);
fclose(fptr);
return 0;
}

Output
PROGRAM- 27

AIM- 27. Write a program to copy a file to another.


Code:-
#include <stdio.h>
#include <stdlib.h>

void main()
{
FILE *fptr1, *fptr2;
char ch, fname1[20], fname2[20];

printf("\n\n Copy a file in another name :\n");


printf("- \n");
printf(" Input the source file name : ");
scanf("%s",fname1);
fptr1=fopen(fname1, "r");
if(fptr1==NULL)
{
printf(" File does not found or error in opening.!!");
exit(1);
}
printf(" Input the new file name : ");
scanf("%s",fname2);
fptr2=fopen(fname2, "w");
if(fptr2==NULL)
{
printf(" File does not found or error in opening.!!");
fclose(fptr1);
exit(2);
}
while(1)
{
ch=fgetc(fptr1);
if(ch==EOF)
{
break;
}
else
{
fputc(ch, fptr2);
}
}
printf(" The file %s copied successfully in the file %s. \n\n",fname1,fname2);
fclose(fptr1);
fclose(fptr2);
getchar();
}

Output:-
PROGRAM-28
AIM- Write a program to read strings from a file and display them on screen.
CODE: -
#include <stdio.h>
#include<ctype.h>
#include<stdlib.h>
int main(){
char ch;
FILE *fp;
fp=fopen("std1.txt","w");
printf("enter the text.press cntrl Z:
");
while((ch = getchar())!=EOF){
putc(ch,fp);
}
fclose(fp);
fp=fopen("std1.txt","r");
printf("text on the file:
");
while ((ch=getc(fp))!=EOF){
if(ch == ',')
printf("\t\t");
else
printf("%c",ch);
}
fclose(fp);
return 0;
}
Output:
OOPS
PROGRAMMING
USING C++
PROGRAM-29

AIM - Write a program that uses a class where the member functions are defined inside a
class.
Code:-
BRIEF DESCRIPTION:

Member functions are defined inside a class and provide the behavior or actions that objects
of that class can perform. They are also referred to as methods. Member functions can access
and manipulate the data members (variables) of the class and can interact with other objects
of the same or different classes.
PRE-EXPERIMENT QUESTIONS:

1. What is Class and Object?


2. What is global variables.?
3. Difference between normal function and member function of the class?

Explanation:

#include<iostream.h>
class car
{
Private:
Int car_number;
Char car_model[10];
Public:
void getdata()
{
cout<<"Enter car number: "; cin>>car_number;
cout<<"\n Enter car model: "; cin>>car_model;
}
void showdata()
{
cout<<"Car number is "<<car_number; cout<<"\n Car model is "<<car_model;
}
};
// main function start
Int main()

{
Car c1; c1.gatdata() c1.showdata(); return 0;
}

Output:

Enter car number: 6325


Enter car model: 2021
Car number is 6325
Car model is 2021
PROGRAM -30
AIM- : Write a program that uses a class where the member functions are defined outside a
class.
Code:-
BRIEF DESCRIPTION:

Defining member functions outside the class in C++ is a way to separate the declaration and
implementation of the functions. This approach provides modularity and improves code
organization, especially when dealing with large classes.
To define a member function outside the class ,you need to follow these steps:-
1. Declare the member function inside the class declaration, including the function's
return type, name, and parameters.
2. Outside the class declaration, use the scope resolution operator :: followed by the class
name and the member function's name to indicate that you are defining the function
belonging to that class.
3. Provide the function definition, including the return type, name, and parameters, just
as you would for any other function.
4. Implement the function's logic within the definition. You can access the class's private
members and perform any necessary operations.
.
PRE EXPERIMENT QUESTIONS:

1. Explain the member function?


2. Difference between global and local variables of the class?
3. What are different member function in c++?

Explanation:
#include<iostream.h>
class car
{
Private:
Int car_number;
Char car_model[10];
Public:void getdata();
void showdata();
};
void car ::getdata()
{
cout<<"Enter car number: "; cin>>car_number;
cout<<"\n Enter car model: "; cin>>car_model;
}
void car ::showdata()
{
cout<<"Car number is "<<car_number; cout<<"\n Car model is "<<car_model;
}
int main()
{
car c1;
c1.gatdata() ;
c1.showdata();
return 0;
}
Output:
Enter car number: 6325
Enter car model: 2021
Car number is 6325 Car model is 2021
PROGRAM -31
AIM- : Write a program to demonstrate the use of static data members.

Code:-
BRIEF DESCRIPTION: C++, a static data member is a class member that is shared among
all
instances (objects) of the class. It is associated with the class itself rather than with
individual objects. Here's an overview of static data members in C++.

PRE-EXPERIMENT QUESTIONS:
1. What is Static Data Member?
2. What are the different ways of define data members?
Explanation:
#include <iostream>
using namespace std;
class A
{
public:
A()
{
cout << "A's Constructor Called " << endl;
}
};

class B
{
static A a;
public: B()
{
cout << "B's Constructor Called " << endl;
}
};
// Driver code
int main()
{
B b; return 0;
}
POST EXPERIMENT QUESTIONS:

1.How to define static data member .


2.What is static ?
PROGRAM-32
AIM: Write a program to demonstrate the use of const data members.
BRIEF DESCRIPTION:

In C++, a const data member is a class member whose value cannot be modified once it is
initialized. Here's an overview of const data members in C++:
Declaration and Initialization: A const data member is declared in the class declaration and
must be initialized at the point of declaration or in the constructor's initializer list. It is
typically declared as private to ensure that its value remains constant.
PRE EXPERIMENT QUESTIONS:

1. What are const?


2. What are the different types data members?
3. How to declare const data member in c++?

#include<iostream>
using namespace std;
class Demo
{
int val; public:
Demo(int x = 0)
{
val = x;
}
int getValue() const
{
return val;
}
};
int main() {
const Demo d(28);
Demo d1(8);
cout << "The value using object d : " << d.getValue(); cout << "\nThe value using object d1 :
" << d1.getValue(); return 0;
}

POST EXPERIMENT QUESTIONS:

1. How to declare const data type.


2. What are the difference between static and const data members?
PROGRAM:33
AIM:. Write a program to demonstrate the use of zero argument and parameterized
constructors.
BRIEF DESCRIPTION:
In C++, a parameterized constructor is a special member function of a class that is used to
initialize objects of that class with specific values. It accepts parameters as arguments,
allowing the caller to provide values during object creation. Here's an overview of
parameterized constructors:
Declaration and Definition: A parameterized constructor is declared within the class
declaration like any other member function. It has parameters corresponding to the values
needed to initialize the object. The constructor definition provides the implementation for the
constructor.
PRE EXPERIMENT QUESTIONS:
1. What is an constructor?
2. What are the various types of constructor in c++
3.How can we determine the width and height of triangle using constructor?
EXPLANATION:
class math
{
private: int a,b,c;
public:
math(int x,int y)
{
a=x; b=y;
}
void add()
{
c=a+b;
cout<<"Total : "<<c;
}
};
int main()
{
math o(10,25);
o.add();
return 0;
}
Output: Total : 35

POST EXPERIMENT QUESTIONS:

1. Explain how to set the constructor.


2. What is the difference between an constructor and destructor?
PROGRAM :34
AIM :Write a program to demonstrate the use of dynamic constructor.

BRIEF DESCRIPTION:
C++ provides different types of constructors, such as default constructors, parameterized
constructors, copy constructors, and move constructors. These constructors are called
implicitly based on the object creation syntax or specific scenarios.
Dynamic memory allocation in C++ involves the use of operators like new and delete to
allocate and deallocate memory at runtime. However, this is not directly related to
constructor.
PRE EXPERIMENT QUESTIONS:
1. What is the correct syntax of new and delete operator
2. What id dynamic memory allocation?
3. What is memory management concepts?
Explanation:
#include<iostream> using namespace std;
class example
{
const char* ptr;
public:
// default constructor example()
{
// allocating memory at run time by using the new keyword ptr = new char[15];
ptr = "Hi from example constructor ";
}
void display()
{
cout << ptr;
}
};

int main()
{
example obj1; obj1.display();
}
POST EXPERIMENT QUESTIONS:

1. What is pointer?
2. What are steps of define pointer to pointer?
PROGRAM:35
AIM: 35. Write a program to demonstrate the use of explicit constructor.
BRIEF DESCRIPTION:
In C++, the explicit keyword is used to qualify a constructor declaration. It affects the way
the constructor is used for implicit type conversions. Here's an overview of explicit
constructors:
Implicit Type Conversions: By default, constructors that can be called with a single
argument can also be used for implicit type conversions. For example, if a class has a
constructor that takes an int parameter, it can be used to implicitly convert an int value to an
object of the class
PRE EXPERIMENT QUESTIONS:
1. How call a member function in c++?
2. What is explicit call?
3. How do we define constructor in c++?
Explanation: #include<iostream.h> class A
{
int data;
public:
A(int a):data(a)
{
cout<<"A::Construcor...\n";
};

friend void display(A obj);


};
void display(A obj)
{
cout<<"Valud of data in obj :="<< obj.data<<endl;
}

int main()
{
//Call display with A object i.e.
a1. display(5000);
return (0);
}

Output
A::Construcor... B::Construcor... function display..

POST EXPERIMENT QUESTIONS:

1. What is implicit call?


2. Difference between implicit and explicit call in c++.
PROGRAM:36
AIM: Write a program to demonstrate the use of initializer list.
BRIEF DESCRIPTION:
In C++, the initializer list is a special syntax used in constructors to initialize the data
members of a class. It provides a concise and efficient way to initialize member variables
when an object is created. Here's an overview of the initializer list:
Syntax: The initializer list is placed after the constructor's parameter list and is enclosed
within parentheses. Each member variable is initialized using a comma-separated list of
member initializations.
Constructor(datatype value1, datatype value2):
datamember(value1),datamember(value2);
{
Body of function
}
PRE EXPERIMENT QUESTIONS:

1. What is datamembers?
2. What is initializer list?

EXPLANATION:
#include<iostream>
using namespace std;
class Point
{
private:
int x; int y;
public:
Point(int i = 0, int j = 0):
x(i), y(j)
{}
/* The above use of Initializer list is optional as the constructor can also be written as:
Point(int i = 0, int j = 0)
{ x = i;
y = j;
}
*/
int getX() const
{
return x;
}
int getY()
const
{
return y;
}
};
int main()
{
Point t1(21, 15);
cout<<"x = "<<t1.getX()<<", "; cout<<"y = "<<t1.getY(); return 0;
}
OUTPUT:
x = 21, y = 15
POST EXPERIMENT QUESTIONS

1. How to define data member in constructor ?


2. What is initializer list?
3. What are the features initializer list in c++?
PROGRAM:37
AIM: Write a program to demonstrate the overloading of increment and decrement
operators.
BRIEF DESCRIPTION:
Operator overloading in C++ allows you to define the behavior of operators when applied to
user-defined types. It enables you to extend the functionality of operators beyond their built-
in capabilities. Here's an overview of operator overloading:
Syntax: Operator overloading is performed by defining a function or a method that is
associated with a specific operator. The function or method is invoked when the
corresponding operator is used with operands of the user-defined type.
PRE-EXPERIMENT QUESTIONS:
Q1. What is operator overloading?
Q2. What is the binary and unary operator ?

Explanation:
#include<iostream.h>
Class Check
{
Private: int i;
Public: Check():i(0){ } Void operator ++()
{++i;}
void Display()
{
cout<<”i=”<<i<<endl;
}
};
int main()
{
Check obj;
Obj.Display();
++obj;
Obj.Display() ;
Return 0;
}

Output

i=0 i=1

POST EXPERIMENT QUESTIONS:

Q1.Write a program to overload -unary operator.


Q2. What is overloading?
PROGRAM:38
1. AIM: Write a program to demonstrate the multilevel inheritance.

BRIEF DESCRIPTION:
In C++, multilevel inheritance is a type of inheritance where a derived class is derived from
another derived class. It involves creating a class hierarchy with multiple levels of derived
classes. Here's an overview of multilevel inheritance:
Syntax: In multilevel inheritance, each derived class serves as the base class for the next
level of derived class.
class A
{
……..
}
class B: public A
{
………..
}
Class C: public B
{
………..
}
PRE-EXPERIMENT QUESTIONS:
Q1. What is Inheritance ?
Q2. Which inheritance is most important explain.
Explanation:
#include <iostream>
using namespace std;
class Vehicle
{
public:
void vehicle(){
cout<<"I am a vehicle\n";
}
};
class FourWheeler : public Vehicle
{
public:
void fourWheeler()
{
<<"I have four wheels\n";
}
};
class Car : public FourWheeler
{
public:
void car(){
cout<<"I am a car\n";
}
};
int main(){ Car obj;
obj.car();
obj.fourWheeler();
obj.vehicle();
return 0;
}

Output
I am a car
I have four wheels I am a vehicle
POST-EXPERIMENT QUESTIONS:
Q1. Different types of inheritance.
Q2. What is hybrid inheritance?.
PROGRAM:39
AIM: Write a program to demonstrate the exception handling.
BRIEF DESCRIPTION: Exception handling in C++ provides a mechanism to handle
runtime errors and exceptional conditions that may occur during program execution. It llows
you to catch and handle exceptions, preventing program termination and providing a way to
recover from errors. Here's an overview of exception handling
PRE-EXPERIMENT QUESTIONS:
1. What is exception ?
2. How to handle exception in c++?
3. What is try block?

Explanation:
#include <iostream>
using namespace std;
double division(int a, int b) { if( b == 0 ) {
throw "Division by zero condition!";
}
return (a/b);
}
int main () { int x = 50; int y = 0; double z = 0;
try
{
z = division(x, y); cout << z << endl;
} catch (const char* msg) { cerr << msg << endl;
}
return 0;
}

Output: Division by zero condition

You might also like