C and C++ Answer Key ESE

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 16

Hindusthan College of Engineering and Technology

An Autonomous Institution, Approved by AICTE, New Delhi Affiliated to Anna University Accredited by NBA (AERO, AUTO, CIVIL,
CSE, ECE, EEE, IT, MECH, MECHATRONICS) Accredited by NAAC with ‘A++’ Grade| An ISO Certified Institution
Valley Campus, Pollachi Highway, Coimbatore 641032.
AUTONOMOUS UG /
PG - DEGREE EXAMINATION
END SEMESTER EXAMINATION
PROGRAMME & BRANCH: B. E-BME SEMESTER: II
22CS2154&ESSENTIALS OF C AND ACADEMIC 2023-2024
COURSE CODE & NAME:
C++ PROGRAMMING YEAR:
3 HOURS MAXIMUM 100 MARKS
DURATION:
MARK:
DATE AND SESSION: 01.07.24 (FN)
Answer Key
1. write a C program to find the factorial of a number using for loop.

# include<stdio.h>
int main(){
int x,fact=1,n;
printf("Enter a number to find factorial: ");
scanf("%d",&n);
for(x=1;x<=n;x++)
fact=fact*x;
printf("Factorial of %d is: %d",n,fact);
return 0;}
Output: Enter a number to find factorial:5
Factorial of 5 is 120
2. list the types of operators in C.
1. Arithmetic Operators
2. Relational Operators
3. Logical Operators
4. Bitwise Operators
5. Assignment Operators
6. Other Operators
3. how does C++ class differ from structures from C?

Structure Class

A structure is a collection of A class in C++ is a single structure that


variables of different data types with contains a collection of related variables
the same name. and functions.

The struct keyword can be used to The keyword class can be used to declare a
declare a structure. class.
4. Define inline function with example.
An inline function is a function that is expanded in line when it is called. When the inline
function is called whole code of the inline function gets inserted or substituted at the point of the
inline function call. This substitution is performed by the C++ compiler at compile time.
Syntax:
inline return-type function-name(parameters)
{
// function code
}
5. mention any four operators that cannot be overloaded.
1. Conditional or Ternary Operator (?:) cannot be overloaded.
2. Size of Operator (sizeof) cannot be overloaded.
3. Scope Resolution Operator (::) cannot be overloaded.
4. Class member selector Operator (.) cannot be overloaded.
6.Define copy constructor and its use.
A copy constructor in C++ is typically used when you want to initialize a new object using
the values of an existing object of the same class. They are particularly useful when you
want to create a deep copy of an object to avoid issues with shared references.
7.state the rules for the order of constructor execution in inheritance.

For single inheritance, the base class constructor is called before the derived class
constructor.
For multiple inheritance, base class constructors are called in the order they are listed in the
derived class's inheritance list.
8. write the significance of pure virtual functions in C++.
A pure virtual function in C++ is used to define an interface or an abstract base class,
which cannot be instantiated on its own but can be used as a blueprint for creating concrete derived
classes.
9. Compare and contrast error and exception.

10. draw a neat diagram to show exception handling model in C++.

PART B
11.a) Enumerate the difference between else-if-ladder and switchcase(4m).

11. b) write a C program to create a mark sheet for students using structures.(10 m)
#include <stdio.h>
struct class
{
int number;
char name[20];
int mark[3];
int total;
} s1;
void main()
{
int i;
printf("\n enter the Roll number, ");
scanf("%d", &s1.number);
printf("\n enter the name, ");
scanf("%s", &s1.name);
printf("\n Enter the marks :");
scanf("%d", &s1.mark[0]);
scanf("%d", &s1.mark[1]);
scanf("%d", &s1.mark[2]);
printf("\n ______________________");
for(i=0; i <2; i++)
{
scanf("%d", &s1.mark[i]);
}
s1.total = s1.mark[0] + s1.mark[1] + s1.mark[2];
printf("\n Name : %s", s1.name);
printf("\n Rollno :%d", s1.number);
printf("\n Mark1 :%d", s1.mark[0]);
printf("\n Mark2 :%d", s1.mark[1]);
printf("\n Mark3 :%d", s1.mark[2]);
printf("\n Total :%d", s1.total);
}

Output:
enter the Roll number: 1
enter the name: Amutha
Enter the marks :86 85 90
_____________________
Name : Amutha
Rollno :1
Mark1 :86
Mark2 :85
Mark3 :90
Total :261
12. write a c program to count no of positive number negative number and zeros in the array.(14
m)

#include<stdio.h>
#include<stdio.h>
#define N 10
int main()
{
int a[N], i, p = 0, n = 0, z = 0;
printf("Enter %d integer numbers\n", N);
for(i = 0; i < N; i++)
scanf("%d", &a[i]);
for(i = 0; i < N; i++)
{
if(a[i] > 0)
p++;
else if(a[i] < 0)
n++;
else
z++;
}
printf("\nPositive no: %d\nNegative no: %d\nZeros: %d\n", p, n, z);
return 0;
}
Output:

Enter 10 numbers : 12
3
-56
0
-34
23
0
0
56
-76
Positive numbers=4
Negative numbers=3
Zero=3
13. Program To Accept The Student Detail Such As Name And 3 Different marks By
Get_Data() Method And Display The Name And Average Of Marks Using Display()
Method. Define A Friend Class For Calculating The Average Of Marks Using The Method
Mark_Avg().(14m)
#include <iostream>
#include <string>
class Student;
class AverageCalculator {
public:
static float calculateAverage(Student& student);
};
class Student {
private:
std::string name;
float marks[3];
public:
void getData() {
std::cout << "Enter student name: ";
std::getline(std::cin, name);
std::cout << "Enter marks for three subjects:\n";
for (int i = 0; i < 3; i++) {
std::cout << "Subject " << (i + 1) << ": ";
std::cin >> marks[i];
}
}
void display() {
std::cout << "Student name: " << name << std::endl;
std::cout << "Average marks: " << AverageCalculator::calculateAverage(*this)
<< std::endl;
}
friend class AverageCalculator;
};
float AverageCalculator::calculateAverage(Student& student) {
float sum = 0;
for (int i = 0; i < 3; i++) {
sum += student.marks[i];
}
return sum / 3;
}
int main() {
Student student;
student.getData();
student.display();
return 0;
}
Output:
Enter student name: sibi
Enter marks for three subjects:
Subject 1: 78
Subject 2: 89
Subject 3: 65
Student name: sibi
Average marks: 77.3333
14.a) explain the ways in which member function of class can be defined and called using suitable
program. (7 m)

Defining Member Function: Member Functions can be defined in two places

(i) Inside the class definition and

(ii) ii) Outside the class definition

syntax:

Example:

14.b )explain static data member and static member function. How to declare them?iilustrate with
example(7m)

Static data members are class members that are declared using static keywords. A static
member has certain special characteristics which are as follows:
 Only one copy of that member is created for the entire class and is shared by all the
objects of that class, no matter how many objects are created.
 It is initialized before any object of this class is created, even before the main starts.
 It is visible only within the class, but its lifetime is the entire program.
Syntax:
static data_type data_member_name;
static Member Function in C++
Static Member Function in a class is the function that is declared as static because of which
function attains certain properties as defined below:
 A static member function is independent of any object of the class.
 A static member function can be called even if no objects of the class exist.
 A static member function can also be accessed using the class name through the scope
resolution operator.
Synatax:
class_name::function_name (parameter);

15.explain the following with respect to C++ with example.(14 m)


i)constructor

Constructors:
Constructors are member functions of a class which are used to initialize the
data members of the class objects. These functions are automatically called when
an object of its class is created. There is no need to call these functions.
There are three types of constructors.
1. Default Constructors
Syntax of Default Constructor
className() {
// body_of_constructor
}
2. Parameterized Constructors

Syntax of Parameterized Constructor


className (parameters...)
{
// body
}
3. Copy Constructors

Syntax of Copy Constructor


ClassName (ClassName &obj)
{
// body_containing_logic
}

ii)NEW operator
Dynamic constructors are used when memory is allocated dynamically using the dynamic memory
allocator, i.e., the new keyword, in a constructor in C++. This allows us to initialize the objects
dynamically.

Syntax For Dynamic Constructor In C++:

class className {
//data member
char* p;
Access_specifier:
className(){
// allocating memory at run time
p = new char[6]; }
};

iii)destructor

Destructor is an instance member function that is invoked automatically whenever an object is


going to be destroyed. Meaning, a destructor is the last function that is going to be called before
an object is destroyed.
Syntax
The syntax for defining the destructor within the class:
~ <class-name>() {
// some instructions
}
The syntax for defining the destructor outside the class:
<class-name> :: ~<class-name>() {
// some instructions
}
16.illustrate how to use the class variables for holding account details and how to construct these
variables at run time using dynamic initialization.(14 m)
#include <iostream>
#include <string> // for std::string
class BankAccount {
private:
std::string accountNumber;
std::string accountHolderName;
double balance;
public:
// Constructor with dynamic initialization using std::string
BankAccount(const std::string& accNumber, const std::string& accHolderName, double
initialBalance)
: accountNumber(accNumber), accountHolderName(accHolderName), balance(initialBalance)
{
std::cout << "Account created for " << accountHolderName << " with initial balance: " <<
balance << std::endl;
}
// Function to deposit money
void deposit(double amount) {
balance += amount;
std::cout << "Deposited " << amount << ". New balance: " << balance << std::endl;
}
// Function to withdraw money
void withdraw(double amount) {
if (amount <= balance) {
balance -= amount;
std::cout << "Withdrew " << amount << ". New balance: " << balance << std::endl;
} else {
std::cout << "Insufficient funds." << std::endl;
}
}
// Function to display account details
void display() const {
std::cout << "Account Number: " << accountNumber << std::endl;
std::cout << "Account Holder: " << accountHolderName << std::endl;
std::cout << "Balance: " << balance << std::endl;
}
};
int main() {
// Create a bank account object with dynamic initialization using std::string
BankAccount account("1234567890", "John Doe", 1000.0);
// Display account details
account.display();
// Perform some transactions
account.deposit(500.0);
account.withdraw(300.0);
account.withdraw(1500.0);
// Display updated account details

account.display();
return 0; // Destructor will be called automatically here for std::string
}
17.a)create a base class name ‘Shape; with two members base and height a member function for
initialization and a virtual function to compute area(). Derive two specific classes triangle and
rectangle which override the function area().use these classes in main function and display the area of
triangle and rectangle using virtual function.(10 m)
#include <iostream>
class Shape {
protected:
double base;
double height;
public:
// Constructor to initialize base and height
Shape(double b, double h) : base(b), height(h) {}
// Virtual function to compute area (to be overridden by derived classes)
virtual double computeArea() const = 0; // Pure virtual function
};
class Triangle : public Shape {
public:
// Constructor using base class constructor
Triangle(double b, double h) : Shape(b, h) {}
// Override computeArea() for Triangle
double computeArea() const override {
return 0.5 * base * height;
}
};
class Rectangle : public Shape {
public:
// Constructor using base class constructor
Rectangle(double b, double h) : Shape(b, h) {}
// Override computeArea() for Rectangle
double computeArea() const override {
return base * height; }};
int main() {
// Create a Triangle object
Triangle triangle(5.0, 3.0);
std::cout << "Area of Triangle: " << triangle.computeArea() << std::endl;
// Create a Rectangle object
Rectangle rectangle(4.0, 6.0);
std::cout << "Area of Rectangle: " << rectangle.computeArea() << std::endl;
return 0;
}

17.b)Brief about abstract base class and virtual base class with suitable syntax(4 m)
Virtual base class
Virtual base classes are used in virtual inheritance in a way of preventing multiple “instances” of
a given class appearing in an inheritance hierarchy when using multiple inheritances
Syntax for Virtual Base Classes:

Syntax 1:
class B : virtual public A
{
};
Syntax 2:
class C : public virtual A
{
};

Abstract Classes
Abstract Class is a class which contains at least one Pure Virtual function in it. Abstract
classes are used to provide an Interface for its sub classes. Classes inheriting an Abstract Class
must provide definition to the pure virtual function, otherwise they will also become abstract
class.Pure virtual Functions are virtual functions with no definition. Declaration of pure virtual
function
virtual void display () =0; // pure function
18.Discuss the role of access specifier s in inheritance and show their visibility when they are inherited
as public, private and protected. (14 m)

Inheritance Definition: The procedure of creating a new class from one or more existing classes is
termed inheritance.

Syntax:

class name_of_the_derived_class: access specifiers name_of_the_base_class


{// member variables of new class (derived class)

The following are the possible syntaxes of declaration:


It is important to note the following points:
When a public access specifier is used (Ex. 1), the public members of the base
o
class are public members of the derived class. Similarly, the protected members of
the base class are protected members of the derived class.
o When a private access specifier is used, the public and protected members of the
base class are the private members of the derived class.
19.what is exception explain with example. How to control is transformed and handled in c++
program.(14m)
Exceptions

Exceptions are run time anomalies or unusual condition that a program may encounter
during execution.
Examples:
 Division by zero
 Access to an array outside of its bounds
 Running out of memory
 Running out of disk space

Principles of Exception Handling: Similar to errors, exceptions are also of two types. They are
as follows:

 Synchronous exceptions: The exceptions which occur during the program execution due
to some fault in the input data.
For example: Errors such as out of range, overflow, division by zero
 Asynchronous exceptions: The exceptions caused by events or faults unrelated
(external) to the program and beyond the control of the program.
For Example: Key board failures, hardware disk failures
The Keywords try, throw, and catch
Exception handling mechanism basically builds upon three keywords:

 try
 catch
 throw

The keyword try is used to preface a block of statements which may generate exceptions.
Syntax of try statement:
try
{
statement 1;
statement 2;
}

When an exception is detected, it is thrown using a throw statement in the try block.

Syntax of throw statement


 throw (excep);
 throw excep;
 throw; // re-throwing of an exception

A catch block defined by the keyword ‘catch’ catches the exception and handles it
appropriately. The catch block that catches an exception must immediately follow the try
block that throws the exception
Syntax of catch statement:
try
{
Statement 1;
Statement 2;
}
catch ( argument)
{
statement 3; // Action to be taken
}
20.write a c++ program to demonstrate a template function for Bubble sort for integers with example.
(14 m)

#include<iostream>
using namespace std;
int main()
{
int n, i, arr[50], j, temp;
cout<<"Enter the Size (max. 50): ";
cin>>n;
cout<<"Enter "<<n<<" Numbers: ";
for(i=0; i<n; i++)
cin>>arr[i];
cout<<"\nSorting the Array using Bubble Sort Technique..\n";
for(i=0; i<(n-1); i++)
{
for(j=0; j<(n-i-1); j++)
{
if(arr[j]>arr[j+1])
{
temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
}
}
}
cout<<"\nArray Sorted Successfully!\n";
cout<<"\nThe New Array is: \n";
for(i=0; i<n; i++)
cout<<arr[i]<<" ";
cout<<endl;
return 0;
}

Output:
Enter the Size (max. 50): 5
Enter 5 Numbers: 12
56
45
21 Enter
10
Sorting the Array using Bubble Sort Technique..
Array Sorted Successfully!
The New Array is:
10 12 21 45 56
PART C

21.a)write a program to add two complex numbers using object as arguments. (10 m)

#include <iostream>
class Complex {
private:
float real;
float imag;
public:
// Constructor to initialize complex number
Complex(float r = 0, float i = 0) : real(r), imag(i) {}
// Function to display the complex number
void display() const {
std::cout << real << " + " << imag << "i" << std::endl;
}
// Function to add two complex numbers
Complex add(const Complex& other) const {
return Complex(real + other.real, imag + other.imag);
}
};
int main() {
// Creating complex number objects
Complex num1(3.4, 5.6);
Complex num2(1.2, 3.8);
// Displaying the complex numbers
std::cout << "Complex number 1: ";
num1.display();
std::cout << "Complex number 2: ";
num2.display();
// Adding two complex numbers using add() method
Complex sum = num1.add(num2);
// Displaying the sum of complex numbers
std::cout << "Sum of complex numbers: ";
sum.display();
return 0;
}
21.b)write a class template to represent a generic vector .include member functions to perform the
following task.(10 m)
i)to crate the vector
ii)to modify the value of a given element
iii)to multiply by a scalar value
iv)to display the vector in the form(10,20,30,….)

#include <iostream>
#include <vector>
template <typename T>
class GenericVector {
private:
std::vector<T> elements;
public:
// Constructor to create the vector with given size and initial value
GenericVector(int size, T initialValue = T()) : elements(size, initialValue)
{}
// Function to modify the value of a given element
void modifyElement(int index, T value) {
if (index >= 0 && index < elements.size()) {
elements[index] = value;
} else {
std::cerr << "Index out of bounds" << std::endl;
} }
// Function to multiply the vector by a scalar value
void multiplyByScalar(T scalar) {
for (auto& elem : elements) {
elem *= scalar;
} }
// Function to display the vector in the form (10, 20, 30, ...)
void display() const {
std::cout << "(";
for (size_t i = 0; i < elements.size(); ++i) {
std::cout << elements[i];
if (i < elements.size() - 1) {
std::cout << ", ";
} }
std::cout << ")" << std::endl;
}};
int main() {
// Create a GenericVector of integers with size 3 and initial value 0
GenericVector<int> vec(3);
// Modify the value of elements
vec.modifyElement(0, 10);
vec.modifyElement(1, 20);
vec.modifyElement(2, 30);
// Display the vector
std::cout << "Vector after modification: ";
vec.display();
// Multiply the vector by a scalar value
vec.multiplyByScalar(2);
// Display the vector after multiplication
std::cout << "Vector after multiplication by 2: ";
vec.display();
return 0; }

You might also like