0% found this document useful (0 votes)
8 views

Object

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views

Object

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 12

Assignment

Directorate of Online Education

SESSION APR 2023


PROGRAM BACHELOR OF COMPUTER APPLICATION (BCA)
SEMESTER II
COURSE CODE & NAME DCA1203 – OBJECT ORIENTED PROGRAMMING
NAME: THAHSHIN SHAFRIYA
ROLL NO: 2214509750
SET-2
1.

Control statements are those that alter the order in which statements are executed. For instance,
statements like If, If-else, Switch-Case, and while-do. Boolean expressions are utilized in
computer programming languages to Boolean expressions are employed as conditional
expressions in a statement to change the direction of control. Such a Boolean expression's value
is inherent in the place that the programme has reached. For instance, if statement S is reached,
then the expression E should be true. Determine logical values A Boolean expression can specify
values as true or false. Using three address instructions and logical operators, these Boolean
expressions can be computed concurrently with arithmetic expression. The grammatical context
of the Boolean expression determines its intended application.
i) It is always legal in C programming to nest if-else statements, which means you can use
one if or else if statement inside another if or else if statement(s).
Syntax
The syntax for a nested if statement is as follows −
if( Boolean expression 1) {

/* Executes when the Boolean expression 1 is true */


if(Boolean expression 2) {
/* Executes when the Boolean expression 2 is true */
}
}

You can nest else if...else in the similar way as you have nested if statements.
Example
#include <stdio.h>
int main () {

/* local variable definition */


int a = 100;
int b = 200;

/* check the boolean condition */


if( a == 100 ) {

/* if condition is true then check the following */


if( b == 200 ) {
/* if condition is true then print the following */
printf("Value of a is 100 and b is 200\n" );
}
}

printf("Exact value of a is : %d\n", a );


printf("Exact value of b is : %d\n", b );

return 0;
}
When the above code is compiled and executed, it produces the following result −
Value of a is 100 and b is 200
Exact value of a is : 100
Exact value of b is : 200

ii) C switch Statement


The switch statement allows us to execute one code block among many alternatives.You can do
the same thing with the if...else..if ladder. However, the syntax of the switch statement is much
easier to read and write.

Syntax of switch...case
switch (expression)
{
case constant1:
// statements
break;

case constant2:
// statements
break;
.
.
.
default:
// default statements
}
The expression is evaluated once and compared with the values of each case label.
• If there is a match, the corresponding statements after the matching label are executed.
For example, if the value of the expression is equal to constant2, statements after case
constant2: are executed until break is encountered.
• If there is no match, the default statements are executed.
b) Iteration is a method used in computer programming where a sequence of instructions or
structures are repeated until a condition is satisfied or a predetermined number of times. An
iteration is the process of repeating the first set of instructions. A loop is defined as the repeating
execution of a set of instructions.
Iteration is the repetition of a process in a computer program, usually done with the help of
loops.
An example of an iteration programming language is as follows:
Consider a database table containing 1000 student records. Each record contains the following
fields:
• First name
• Last name
• Roll no
If one wants to copy all the student records from the database and print them, the best way to
retrieve the record is to iterate or loop through each record. It can be executed using the for loop
statement as shown below:
for (int i=0;i<1000;i++)
{
Print first name and last name from table
}
In the above example, i is an iterator starting from the first student record to the last student
record.
I. A while loop in C programming repeatedly executes a target statement as long as a given
condition is true.
Syntax
The syntax of a while loop in C programming language is −
while(condition) {
statement(s);
}

Here, statement(s) may be a single statement or a block of statements. The condition may be any
expression, and true is any nonzero value. The loop iterates while the condition is true.
When the condition becomes false, the program control passes to the line immediately following
the loop.
II. Unlike for and while loops, which test the loop condition at the top of the loop, the
do...while loop in C programming checks its condition at the bottom of the loop.
A do...while loop is similar to a while loop, except the fact that it is guaranteed to execute at least
one time.
Syntax
The syntax of a do...while loop in C programming language is −
do {
statement(s);
} while( condition );

Notice that the conditional expression appears at the end of the loop, so the statement(s) in the
loop executes once before the condition is tested. If the condition is true, the flow of control jumps
back up to do, and the statement(s) in the loop executes again. This process repeats until the given
condition becomes false.
2.
Java's static keyword is mostly utilised for memory management. With variables, methods, blocks,
and nested classes, the static keyword can be used. The static keyword is a property of the class
rather than a class instance.
This static could be:
1. Variable (also called as a class variable)
2. Method (often referred to as a class method)
3.Block
4.Nest class
Static Java variable
A variable is considered static if you declare it to be static. The common characteristic shared by
all objects, which is not specific to each object, can be referred to by the static variable, for
instance, the name of the employer for employees, the name of the college for students, etc. When
the class is loaded, the static variable only receives one memory allocation in the class area.

//Java Program to demonstrate the use of static variable


class Student{
int rollno;//instance variable
String name;
static String college ="ITS";//static variable
//constructor
Student(int r, String n){
rollno = r;
name = n;
}
//method to display the values
void display (){System.out.println(rollno+" "+name+" "+college);}
}
//Test class to show the values of objects
public class TestStaticVariable1{
public static void main(String args[]){
Student s1 = new Student(111,"Karan");
Student s2 = new Student(222,"Aryan");
//we can change the college of all objects by the single line of code
//Student.college="BBDIT";
s1.display();
s2.display();
}
}
Functions are by default global in C. A function is static if the term "static" is used before its name.
For instance, the static fun() method is shown below.
static int fun(void)
printf ("I am a static function");
}
Access to static functions is limited to the file in which they are declared, unlike global functions
in C. So, we make functions static when we want to limit access to them. The use of the same
function name in many files can be another justification for keeping functions static.
3. Inheritance is a tool for expanding and reusing existing classes without changing them, creating
hierarchical relationships between them. A class can be embedded into an object via inheritance.
Let's say you include a class A object (x) in the class declaration of class B. Class B will
consequently have access to all of class A's public data members and member functions. However,
in class B, object x is required in order to access class A's data members and member functions.
I) Multiple Inheritance: A situation where a derived class inherits from two or more base classes
is referred to as multiple inheritance. The derived class can use the members (methods and
attributes) of several base classes as a result.
The syntax for multiple inheritance is as follows:
class DerivedClass : public BaseClass1, public BaseClass2 { // class members and methods };
Example:
class Animal { public: void eat() { std::cout << "Animal is eating." << std::endl; } }; class Flyable
{
public: void fly() { std::cout << "Flying in the sky." << std::endl; } }; class Bird : public Animal,
public
Flyable { // additional class members and methods }; int main() { Bird bird; bird.eat(); // Output:
Animal is eating. bird.fly(); // Output: Flying in the sky. return 0; }
In this example, we have two base classes, Animal and Flyable, and a derived class Bird that
inherits from both of them using multiple inheritance. The derived class Bird can access the eat()
method from the Animal class and the fly() method from the Flyable class.
ii. Multi-level Inheritance: Multi-level inheritance refers to a situation where a derived class
inherits from another derived class, forming a chain of inheritance. It allows for the creation of a
hierarchical structure where each derived class inherits the properties and behaviors of its parent
class. The syntax for multi-level inheritance is as follows:
cppCopy code
class DerivedClass : public BaseClass { // class members and methods };
Example:
cppCopy code
class Vehicle { public: void drive() { std::cout << "Driving the vehicle." << std::endl; } }; class
Car :
public Vehicle { // additional class members and methods }; class SportsCar : public Car { //
additional class members and methods }; int main() { SportsCar sportsCar; sportsCar.drive(); //
Output: Driving the vehicle. return 0; }
In this example, we have a base class Vehicle, a derived class Car that inherits from Vehicle, and
another derived class SportsCar that inherits from Car. The SportsCar class can access the drive()
method from the Vehicle class due to multi-level inheritance.
iii. Hierarchical Inheritance: Hierarchical inheritance refers to a scenario where multiple derived
classes inherit from a single base class. It allows the creation of a hierarchy where different derived
classes can share common properties and behaviors inherited from the base class. The syntax for
hierarchical inheritance is the same as single inheritance:
cppCopy code
class DerivedClass : public BaseClass { // class members and methods };
4.
A key idea in object-oriented programming is olymorphism, which enables objects of various
classes to be considered as belonging to the same base class. The ability to use the same interface
for many object types gives the code flexibility and extension. Due to polymorphism, methods can
be overridden in derived classes and different implementations can be used depending on the type
of the object being used at the moment.
For a better understanding, let's talk about the two types of polymorphism, their subtypes, and
offer some examples:
i. Static polymorphism, commonly referred to as compile-time polymorphism: Function
overloading and operator overloading enable compile-time polymorphism. Multiple functions or
operators can share the same name while having various parameter lists or operating modes.
Based on factors like the amount of arguments, the kind of arguments, or the context in which it
is used, the suitable function or operator is chosen at compile time.
Function overloading allows for the coexistence of several functions with the same name but
various argument values in the same scope. Based on the inputs supplied during the function call,
the suitable function is chosen. Here's an illustration:
#include <iostream>
class Math { public: int add(int num1, int num2)
{ return num1 + num2; }
double add(double num1, double num2)
{ return num1 + num2; } };
int main()
{ Math math;
std::cout << math.add(5, 7) << std::endl; // Output: 12 (integers) std::cout << math.add(3.5, 2.8)
<<
std::endl;
// Output: 6.3 (doublesm) return 0; } ```
In this example, the `Math` class has two `add()`
methods: one that takes two integer parameters and another that takes two double parameters.

The appropriate `add()` method is selected based on the argument types provided during the
function call.

b) Operator Overloading: Operator overloading allows operators to exhibit different behaviors


when applied to different types of objects or operands. It provides a way to define custom
behaviors for operators. Here's an example:
#include <iostream>
class Complex { private: double real; double imag; public:
Complex(double r = 0.0, double i = 0.0) : real(r), imag(i) {} Complex operator+(const Complex&
other) { Complex result;
result.real = this->real + other.real; result.imag = this->imag + other.imag; return result; }
void display()
{ std::cout << "Real: " << real << ", Imaginary: " << imag << std::endl; } };
int main() {
Complex c1(2.5, 3.7); Complex c2(1.2, 0.9); Complex sum = c1 + c2; sum.display(); // Output:
Real:
3.7, Imaginary: 4.6 return 0; }
``` In this example, the `Complex` class overloads the `+` operator to perform addition between
two `Complex` objects. The `operator+()` function is called when the `+` operator is used with two
`Complex` objects.
ii. Run-time Polymorphism (also known as Dynamic Polymorphism): In runtime polymorphism,
the compiler selects which function call should be connected to the object after resolving it at
runtime. Dynamic or late binding polymorphism are other names for it. Through the use of virtual
functions and function overriding, this kind of polymorphism is carried out.
5. Making an instance of a file handling class and passing the filename as a parameter to the
constructor are required steps when opening a file using a constructor. The file is then opened by
the constructor, enabling additional operations to be carried out on it. Here is a C++ example
programme that shows how to open a file by using a constructor:
#include <iostream>
#include <fstream>
class FileHandler {
private:
std::ifstream file;
public:
FileHandler(const std::string& filename) {
file.open(filename);
if (!file) {
std::cout << "Error opening file." << std::endl;
}
}
void readContents() {
std::string line;
while (std::getline(file, line)) {
std::cout << line << std::endl;
}
}
~FileHandler() {
if (file.is_open()) {
file.close();
}
}
};
int main() {
FileHandler file("example.txt");
file.readContents();
return 0;
}
The File Handler class in this illustration has a constructor that accepts a filename as a parameter.
The open() method of std::ifstream is used inside the constructor to open the file. A notice is shown
if the file cannot be opened. The file's contents are read line by line using the read Contents()
method, which prints them to the console.
A File Handler instance is created in the main() function, with the constructor receiving the
filename "example.txt". The constructor is automatically invoked to open the file. The file's
contents are then read and displayed by using the read Contents() function. Last but not least, the
destructor is automatically invoked when the File Handler object exits scope, ensuring that the file
is closed.
6. Programming data structures called sequence containers provide for quick access to elements
based on their location in a linear sequence. The sequence containers vectors and deques are two
that are frequently utilised.
I. Vector: A dynamic array that can dynamically resize itself as elements are added or removed is
known as a vector.
It enables effective insertion and deletion of items at the end of the sequence and offers quick
random access to elements. Since the memory block in vectors is contiguous, all of the items are
stored close to one another, making memory access quick and easy.
The syntax for declaring a vector in C++ is as follows:
#include <vector>
std::vector<DataType> vectorName;
Example:
#include <iostream>
#include <vector>
int main() {
std::vector<int> numbers; // Declaration of a vector of integers
numbers.push_back(5); // Inserting elements at the end of the vector
numbers.push_back(10);
numbers.push_back(15);
std::cout << "Size of the vector: " << numbers.size() << std::endl; // Output: 3
std::cout << "Elements of the vector: ";
for (const auto& number : numbers) {
std::cout << number << " ";
}
// Output: Elements of the vector: 5 10 15
return 0;
}
In this illustration, we build a vector of numbers to hold integers. The push_back() function inserts
elements at the end and adds them to the vector. The vector's element count is determined using
the size() method, and the elements are iterated over and shown using a loop.
ii. Deque: Also known as a "double-ended queue," Deque is a sequence container that effectively
accommodates element insertion and deletion at both ends. With quick random access like vectors
and effective insertion and deletion at both ends like lists, it combines the capability of both types
of data structures. Deques allocate memory in chunks, enabling the storage of elements in distinct
memory blocks.
The syntax for declaring a deque in C++ is as follows
#include <deque>
std::deque<DataType> dequeName;
```
Example:
#include <iostream>
#include <deque>
int main() {
std::deque<int> numbers; // Declaration of a deque of integers
numbers.push_back(5); // Inserting elements at the end of the deque
numbers.push_back(10);
numbers.push_front(2); // Inserting elements at the beginning of the deque
numbers.push_front(7);
std::cout << "Size of the deque: " << numbers.size() << std::endl; // Output: 4
std::cout << "Elements of the deque: ";
for (const auto& number : numbers) {
std::cout << number << " ";
}
// Output: Elements of the deque: 7 2 5 10
return 0;
}
In this example, we create a deque `numbers` to store integers. Elements are added to the deque
using the `push_back()` function, which inserts elements at the end, and the `push_front()`
function,
which inserts elements at the beginning.

You might also like