C and CPP by Nachiketa
C and CPP by Nachiketa
C and CPP by Nachiketa
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);
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);
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;
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:-
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);
int main() {
struct Employee employee1, employee2, employee3;
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
void main()
{
FILE *fptr1, *fptr2;
char ch, fname1[20], fname2[20];
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:
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:
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:
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:
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:
#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;
}
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";
};
int main()
{
//Call display with A object i.e.
a1. display(5000);
return (0);
}
Output
A::Construcor... B::Construcor... function display..
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
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
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;
}