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

Average Value of Array

kjsodoinh

Uploaded by

Rakesh Mukesh
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views

Average Value of Array

kjsodoinh

Uploaded by

Rakesh Mukesh
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 10

DATA STRUCTURES AND APPLICATION

CAP4103

School of Engineering
Department of Computer Science and Engineering

Submitted By
Student Name Rakesh Dey sarkar
Enrolment Number 230160307023
Programme Masters in Computer Application
Department Computer Science and Engineering
Session/Semester 2023-2025/Second Semester
Submitted To
Faculty Name Ms. Sapna Sharma
Q1.What is Data Structure ? Explain Various Types of Data Structure
.
Ans: A data structure is a way of organizing and storing data to perform operations
efficiently. It defines a set of rules or conventions for organizing and managing data,
which allows for easier access, modification, and processing. Data structures are
essential components in computer science and are used in various applications to
solve different types of problems.

There are two main types of data structures:

1. Primitive Data Structures:


 These are the basic or fundamental data structures.
 Examples include integers, floating-point numbers, characters, and
booleans.
2. Composite Data Structures:
 These structures are built by combining primitive data types and
organizing them in a specific way.
 Examples include arrays, linked lists, stacks, queues, trees, and graphs.

Common operations performed on data structures include:

 Insertion: Adding new data.


 Deletion: Removing existing data.
 Traversal: Visiting and processing all elements.
 Searching: Finding the location of a specific element.
 Sorting: Arranging elements in a specific order.

The choice of a data structure depends on the requirements of the specific


application and the operations that need to be performed efficiently. Each data
structure has its own advantages and disadvantages, and selecting the right one is
crucial for optimizing the performance of algorithms and overall system efficiency.
Data structures are fundamental components in computer science that enable
efficient organization, storage, and manipulation of data. There are various types of
data structures, each with its own characteristics, use cases, and advantages. Here, I'll
explain some of the most common types:

1. Arrays:
 An array is a collection of elements, each identified by an index or a
key.
 Elements in an array are stored in contiguous memory locations.
 Accessing elements in an array is fast, O(1) time complexity.
 Insertion and deletion operations can be slow, especially in the middle,
as shifting may be required.
2. Linked Lists:
 A linked list is a linear data structure where elements are stored in
nodes, and each node points to the next node in the sequence.
 Dynamic in nature, which means it can grow or shrink during program
execution.
 Insertion and deletion are generally faster compared to arrays,
especially in the middle.
 Random access to elements is slower, O(n) time complexity.
3. Stacks:
 A stack is a last-in, first-out (LIFO) data structure.
 Elements can only be added or removed from the top of the stack.
 Common operations include push (to add an element) and pop (to
remove the top element).
 Used for managing function calls, undo mechanisms, and parsing
expressions.
4. Queues:
 A queue is a first-in, first-out (FIFO) data structure.
 Elements are added at the rear (enqueue) and removed from the front
(dequeue).
 Common operations include enqueue and dequeue.
 Used in scenarios like job scheduling, breadth-first search algorithms.
5. Trees:
 A hierarchical data structure with a root node and subtrees of child
nodes.
 Binary Trees have at most two children per node.
 Binary Search Trees (BST) maintain an ordering property that allows for
efficient search, insertion, and deletion.
 Common tree-based algorithms include binary search, AVL trees, and
heaps.
6. Graphs:
 A collection of nodes (vertices) and edges connecting these nodes.
 Directed graphs have edges with a direction, while undirected graphs
do not.
 Used to represent relationships between entities and solve problems
like shortest path algorithms and network flow.
7. Hash Tables:
 Utilizes a hash function to map keys to indices in an array.
 Provides fast insertion, deletion, and lookup operations on average,
with O(1) complexity.
 Collision resolution methods, like chaining or open addressing, handle
situations where multiple keys map to the same index.
Average value of array
 Method overloading occurs when there are multiple
public class AverageArray { methods in the same class with the same name but
different parameters.
public static void main(String[] args) {  The methods must have the same name, but their
parameter lists must differ in either the number of
// Sample array parameters or the data

int[] numbers = {10, 20, 30, 40, 50};


 types of parameters, or both.
// Calculate the sum of all elements in the array  Overloaded methods may or may not have the same
return type.
int sum = 0;
 Overloading is resolved at compile-time, based on the
for (int number : numbers) { number and type of arguments passed.
Ex-
sum += number;
public class OverloadingExample {
}
public int add(int a, int b) {
// Calculate the average
return a + b;
double average = (double) sum / numbers.length;
}
// Output the result
public double add(double a, double b) {
System.out.println("Average value of the array: " + average);
return a + b;
}
}
}
public int add(int a, int b, int c) {

return a + b + c;
write a program to find the factorial value of the number entered
throught the keyboard }

import java.util.Scanner; public static void main(String[] args) {

OverloadingExample obj = new OverloadingExample();

public class Factorial { System.out.println("Sum of 5 and 3 is: " + obj.add(5, 3));

public static void main(String[] args) { System.out.println("Sum of 2.5 and 3.7 is: " + obj.add(2.5, 3.7));

Scanner scanner = new Scanner(System.in); System.out.println("Sum of 1, 2, and 3 is: " + obj.add(1, 2, 3));

} }

System.out.print("Enter a number to calculate its factorial: "); Method Overriding:

int number = scanner.nextInt();  Method overriding occurs when a subclass provides a


specific implementation of a method that is already
long factorial = calculateFactorial(number); provided by its superclass.
 The method in the subclass must have the same
System.out.println("Factorial of " + number + " is: " + factorial);
signature (name and parameter list) as the method in the
superclass.
scanner.close();
 Overridden methods have the same return type as the
} method in the superclass or a covariant return type
(subtype of the return type in the superclass).
public static long calculateFactorial(int n) {
 Overriding is resolved at runtime based on the object
type.
if (n < 0) {
class Animal {
public void sound() {
throw new IllegalArgumentException("Factorial is not defined for System.out.println("Animal makes a sound");
negative numbers."); }
}
}
class Dog extends Animal {
long factorial = 1; @Override
public void sound() {
for (int i = 1; i <= n; i++) { System.out.println("Dog barks");
}
factorial *= i; }

public class OverridingExample {


}
System.out.println("Display method with integer parameter: " + num);

return factorial;
}

Method Overloading: // Overloaded display method with a String parameter


public static void main(String[] args) {
Animal animal = new Animal();
animal.sound(); // Output: Animal makes a sound
public void display(String message) {
Animal dog = new Dog();
dog.sound(); // Output: Dog barks System.out.println("Display method with String parameter: " +
} message);
}
}
Q.create a class employees with a static variables employment type
= "full time" .create a static method show() to print the name , d
designation, employment type of each employee
public static void main(String[] args) {
public class Employees {

// Static variable DisplayOverload obj = new DisplayOverload();

static String employmentType = "full time";

// Calling each overloaded display method


// Instance variables
obj.display();
String name;

String designation; obj.display(10);

obj.display("Hello, World!");

// Constructor
}
public Employees(String name, String designation) {
}
this.name = name;

this.designation = designation;

}
1. 
Objects and Classes: Object: An instance of a class that
encapsulates data (attributes) and behavior (methods). Think
of it as a real-world entity like a car or a bank account.
// Static method to print employee details

public static void show(Employees employee) {


2.  Class: A blueprint that defines the properties and methods
of an object. It's like a template for creating multiple objects
System.out.println("Name: " + employee.name); with the same characteristics.

System.out.println("Designation: " + employee.designation); 2. Pillars of OOP:  Encapsulation: Bundling data and related methods
System.out.println("Employment Type: " + employmentType); together within an object, restricting direct access to internal data for better
protection and control.  Abstraction: Focusing on essential details and
System.out.println("-----------------------------"); hiding unnecessary complexity, presenting a simplified view of an object's
functionality.  Inheritance: Creating new classes (subclasses) that inherit
}
properties and methods from existing classes (superclasses), promoting code
public static void main(String[] args) { reuse and reducing redundancy.  Polymorphism: Objects of different classes
responding differently to the same method call based on their own
// Creating employee objects implementation, enabling flexible and dynamic behaviour. Java Programming
Basics:
Employees employee1 = new Employees("John", "Manager");

Employees employee2 = new Employees("Alice", "Developer"); 1. Data Types: Data types define the kind of data a variable can hold. Java
offers various primitive and reference data types:
Employees employee3 = new Employees("Bob", "Designer");
Primitive Data Types:  int: Stores whole numbers (e.g., -10, 25)  double:
Stores floating-point numbers (e.g., 3.14, -5.2)  boolean: Stores true or false
// Calling static method to display employee details values  char: Stores single characters (e.g., 'a', '$')  byte, short, long:
Specialized numerical types for specific ranges
System.out.println("Employee Details:");

System.out.println("-----------------------------"); } Reference Data Types:  String: Represents sequences of characters (e.g.,


"Hello, world!")  Array: Ordered collection of elements of the same data
show(employee1); type  Object: Instance of a class, encapsulating data and methods

show(employee2); 2. Control and Looping Structures: These control the flow of program
execution: Control Structures:  if-else: Makes decisions based on conditions
show(employee3);  switch: Multi-way branching based on values  while: Repeats a block of
code until a condition is false  for: Repeats a block of code a specific
}
number of times  do-while: Repeats a block at least once, then checks the
} condition Looping Structures:  for-each: Iterates over elements in a
collection

3. Classes: Classes are blueprints for creating objects. They define the
properties (attributes) and behaviors (methods) of objects
create a class overload the method display () three time in the class

public class DisplayOverload {


Inheritance and its Types in Java: Inheritance is a fundamental object-
// Overloaded display method with no parameters oriented programming concept that allows creating new classes (subclasses)
that inherit properties and behaviors from existing classes (superclasses).
This promotes code reuse, reduces redundancy, and fosters hierarchical
public void display() {
relationships between objects. Here's a breakdown of the different types of
inheritance in Java: 1. Single Inheritance:  A subclass inherits from only one
System.out.println("Display method without parameters"); parent class.  Most commonly used type for clear and maintainable class
hierarchies.  Example: A Car class inherits from a Vehicle class. 2. Multilevel
} Inheritance:  A subclass inherits from another subclass, which in turn
inherits from another, forming a chain.  Useful for representing deep
hierarchies with specialization at each level.  Example: A SportsCar class
inherits from a Car class, which inherits from a Vehicle class. 3. Hierarchical
// Overloaded display method with an integer parameter Inheritance:  Multiple subclasses inherit from the same parent class,
creating a tree-like structure.  Useful for modelling situations where
public void display(int num) { multiple subclasses share common functionalities but have unique
specializations.  Example: A Sedan class, an SUV class, and a Truck class all
inherit from a Vehicle class. 4. Hybrid Inheritance (Not supported in Java): 
A subclass inherits from more than one parent class directly, creating a
diamond-shaped structure.  Java doesn't allow this type due to potential
ambiguity and complexity issues

Thread Handling in Java: Thread handling is a fundamental concept for


building concurrent and responsive applications in Java. Here's a breakdown
of the key points: 1. Thread Life Cycle: A thread goes through various states
during its lifetime:  New: Thread is created but not yet started.  Runnable:
Thread is ready to run, waiting for CPU resources.  Running: Thread is
actively executing its code on the CPU.  Blocked: Thread is waiting for a
resource like I/O or synchronization.  Waiting: Thread is waiting for another
thread to perform an action.  Timed Waiting: Thread is waiting for a specific
time period to elapse.  Terminated: Thread has finished its execution. 2.
Creating Threads in Java: There are two main ways to create threads in Java:
 Extending the Thread class: Define a subclass of Thread and override its
run() method to implement the thread's logic.  Implementing the Runnable
interface: Define a class that implements Runnable and provide its run()
method implementation. You then create a Thread object and pass the
Runnable instance to its constructor. Example (Using Runnable): Java class
MyRunnable implements Runnable { @Override public void run() { //
Thread's logic here System.out.println("Running from a separate
thread!"); } } public class Main { public static void main(String[] args)
{ MyRunnable runnable = new MyRunnable(); Thread thread = new
Thread(runnable); thread.start(); // Starts the thread execution } }

Q.2 What do you mean by Array? Describe storage structure of


array. Also explain various types of Arrays in Details.

Ans: An array is a fundamental data structure in computer science that stores a


collection of elements, each identified by an index or a key. The elements in an array
are stored in contiguous memory locations, meaning they are placed next to each
other in the computer's memory. This arrangement allows for efficient access to
individual elements by their index.

Key characteristics of arrays include:

1. Indexing: Elements in an array are accessed using an index or a key. The


index is typically an integer that starts from zero for the first element, one for
the second, and so on.
2. Contiguous Memory: Array elements are stored in adjacent memory
locations. This feature enables quick and direct access to any element based
on its index.
3. Fixed Size: In most programming languages, the size of an array is fixed at
the time of declaration. Once defined, the size usually cannot be changed
during runtime. Some languages, however, support dynamic arrays or
resizable arrays.

Here's a simple example in Python:

# Declaring an array

my_array = [1, 2, 3, 4, 5]
# Accessing elements

first_element = my_array[0] # Value: 1

second_element = my_array[1] # Value: 2

# Modifying elements

my_array[2] = 10 # Array becomes [1, 2, 10, 4, 5]

Arrays are widely used in programming for tasks like storing lists of items, iterating
through collections, and implementing algorithms that require constant-time access
to elements. Despite their efficiency for random access, arrays may have limitations,
such as fixed size and potential inefficiencies in insertions and deletions, particularly
in the middle of the array. In such cases, other data structures like linked lists may be
more suitable.

The storage structure of arrays is characterized by the arrangement of elements in


contiguous memory locations. This arrangement provides several advantages, such
as efficient random access and simplicity in memory addressing. Here are the key
aspects of the storage structure in arrays:

1. Contiguous Memory Allocation:


 Array elements are stored one after the other in memory, in contiguous
or consecutive locations. This means that the memory addresses of
array elements are sequential.
 The contiguous storage allows for direct and efficient access to any
element using its index. The memory address of the first element is
used as a reference point.
2. Indexing:
 Elements in an array are accessed using indices. The index indicates the
position of an element within the array.
 The formula for accessing the memory location of an element is often
based on the starting address of the array and the size of each element.
For example, if the array starts at address A and each element occupies
S bytes, the address of the element at index i is given by A + i * S.
3. Fixed-size Allocation:
 The size of an array is typically fixed at the time of declaration. Once
defined, the array size remains constant throughout its lifetime.
Fixed-size allocation simplifies memory management and allows for

direct computation of memory addresses during compilation.
4. Memory Efficiency:
 Contiguous storage makes efficient use of memory, as there is no need
for additional space between elements. This is in contrast to some data
structures, like linked lists, which may require extra memory for
pointers.
 The absence of extra memory overhead results in better cache locality,
which can improve performance by reducing cache misses during data
access.

Here's a simple illustration of the storage structure of an array in memory:

| Element 0 | Element 1 | Element 2 | Element 3 | ... | Element n-1 |


|-----------|-----------|-----------|-----------|-----|-------------|
^ Starting address of the array

In this diagram, each box represents the memory location of an array element, and
the arrow indicates the starting address of the array. Accessing an element involves a
direct calculation based on the index and the size of each element. This simplicity
and efficiency in memory addressing make arrays a fundamental and widely used
data structure in programming.

In computer science, arrays come in various types, each serving specific purposes and
addressing different requirements. Here are some of the common types of arrays:

1.One-dimensional Array:
 A simple, linear array where elements are stored in a single line or row.
 Accessing elements involves using a single index.
 Examples include arrays of integers, characters, or floating-point
numbers.
# One-dimensional array in Python

my_array = [1, 2, 3, 4, 5]

2.Multi-dimensional Array:
 Arrays with more than one dimension. Common types include 2D arrays
(matrices) and 3D arrays.
 Elements are accessed using multiple indices corresponding to the array's
dimensions.
Useful for representing tables, grids, and matrices.
# Two-dimensional array (matrix) in Python

matrix = [

[1, 2, 3],

[4, 5, 6],

[7, 8, 9]

3. Dynamic Array:
 An array that can dynamically resize during runtime.
 Provides a higher-level abstraction than traditional fixed-size arrays.
Commonly used in languages like Python wi

You might also like