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

Unit1 Algorithms

The document provides an overview of algorithms, defining them as finite sets of rules for problem-solving, and highlighting their applications in fields such as computer science, mathematics, and artificial intelligence. It discusses the characteristics, properties, types, advantages, and disadvantages of algorithms, as well as asymptotic notations used for analyzing their performance. Additionally, it outlines the fundamental stages of problem-solving, including understanding the problem, designing algorithms, and verifying their correctness.

Uploaded by

Chaudhri Upeksha
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)
9 views

Unit1 Algorithms

The document provides an overview of algorithms, defining them as finite sets of rules for problem-solving, and highlighting their applications in fields such as computer science, mathematics, and artificial intelligence. It discusses the characteristics, properties, types, advantages, and disadvantages of algorithms, as well as asymptotic notations used for analyzing their performance. Additionally, it outlines the fundamental stages of problem-solving, including understanding the problem, designing algorithms, and verifying their correctness.

Uploaded by

Chaudhri Upeksha
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/ 62

BZ GROW MORE INSTITUTE OF MSC(CA&IT)

Basic Concepts of Algorithms:-


The word Algorithm means ” A set of finite rules or instructions to be
followed in calculations or other problem-solving operations ”
Or
” A procedure for solving a mathematical problem in a finite number of
steps that frequently involves recursive operations”.

Use of the Algorithms:


Algorithms play a crucial role in various fields and have many
applications. Some of the key areas where algorithms are used include:
1. Computer Science: Algorithms form the basis of computer
programming and are used to solve problems ranging from simple
sorting and searching to complex tasks such as artificial
intelligence and machine learning.
2. Mathematics: Algorithms are used to solve mathematical
problems, such as finding the optimal solution to a system of linear
equations or finding the shortest path in a graph.
3. Operations Research: Algorithms are used to optimize and make
decisions in fields such as transportation, logistics, and resource
allocation.

ASSI.PRO.UPEKSHA CHAUDHRI 1
BZ GROW MORE INSTITUTE OF MSC(CA&IT)

4. Artificial Intelligence: Algorithms are the foundation of artificial


intelligence and machine learning, and are used to develop
intelligent systems that can perform tasks such as image
recognition, natural language processing, and decision-making.
5. Data Science: Algorithms are used to analyze, process, and
extract insights from large amounts of data in fields such as
marketing, finance, and healthcare.
What is the need for algorithms?
1. Algorithms are necessary for solving complex problems efficiently
and effectively.
2. They help to automate processes and make them more reliable,
faster, and easier to perform.
3. Algorithms also enable computers to perform tasks that would be
difficult or impossible for humans to do manually.
4. They are used in various fields such as mathematics, computer
science, engineering, finance, and many others to optimize
processes, analyze data, make predictions, and provide solutions
to problems.
What are the Characteristics of an Algorithm?

ASSI.PRO.UPEKSHA CHAUDHRI 2
BZ GROW MORE INSTITUTE OF MSC(CA&IT)

As one would not follow any written instructions to cook the recipe, but
only the standard one. Similarly, not all written instructions for
programming are an algorithm. For some instructions to be an algorithm,
it must have the following characteristics:
• Clear and Unambiguous: The algorithm should be unambiguous.
Each of its steps should be clear in all aspects and must lead to
only one meaning.
• Well-Defined Inputs: If an algorithm says to take inputs, it should
be well-defined inputs. It may or may not take input.
• Well-Defined Outputs: The algorithm must clearly define what
output will be yielded and it should be well-defined as well. It
should produce at least 1 output.
• Finite-ness: The algorithm must be finite, i.e. it should terminate
after a finite time.
• Feasible: The algorithm must be simple, generic, and practical,
such that it can be executed with the available resources. It must
not contain some future technology or anything.
• Language Independent: The Algorithm designed must be
language-independent, i.e. it must be just plain instructions that
can be implemented in any language, and yet the output will be the
same, as expected.
• Input: An algorithm has zero or more inputs. Each that contains a
fundamental operator must accept zero or more inputs.
• Output: An algorithm produces at least one output. Every
instruction that contains a fundamental operator must accept zero
or more inputs.
• Definiteness: All instructions in an algorithm must be
unambiguous, precise, and easy to interpret. By referring to any of
the instructions in an algorithm one can clearly understand what is
to be done. Every fundamental operator in instruction must be
defined without any ambiguity.
• Finiteness: An algorithm must terminate after a finite number of
steps in all test cases. Every instruction which contains a

ASSI.PRO.UPEKSHA CHAUDHRI 3
BZ GROW MORE INSTITUTE OF MSC(CA&IT)

fundamental operator must be terminated within a finite amount of


time. Infinite loops or recursive functions without base conditions
do not possess finiteness.
• Effectiveness: An algorithm must be developed by using very
basic, simple, and feasible operations so that one can trace it out
by using just paper and pencil.
Properties of Algorithm:
• It should terminate after a finite time.
• It should produce at least one output.
• It should take zero or more input.
• It should be deterministic means giving the same output for the
same input case.
• Every step in the algorithm must be effective i.e. every step should
do some work.
Types of Algorithms:
There are several types of algorithms available. Some important
algorithms are:
1. Brute Force Algorithm:
It is the simplest approach to a problem. A brute force algorithm is the
first approach that comes to finding when we see a problem.
2. Recursive Algorithm:
A recursive algorithm is based on recursion. In this case, a problem is
broken into several sub-parts and called the same function again and
again.
3. Backtracking Algorithm:
The backtracking algorithm builds the solution by searching among all
possible solutions. Using this algorithm, we keep on building the solution
following criteria. Whenever a solution fails we trace back to the failure
point build on the next solution and continue this process till we find the
solution or all possible solutions are looked after.

ASSI.PRO.UPEKSHA CHAUDHRI 4
BZ GROW MORE INSTITUTE OF MSC(CA&IT)

4. Searching Algorithm:
Searching algorithms are the ones that are used for searching elements
or groups of elements from a particular data structure. They can be of
different types based on their approach or the data structure in which the
element should be found.
5. Sorting Algorithm:
Sorting is arranging a group of data in a particular manner according to
the requirement. The algorithms which help in performing this function
are called sorting algorithms. Generally sorting algorithms are used to
sort groups of data in an increasing or decreasing manner.
6. Hashing Algorithm:
Hashing algorithms work similarly to the searching algorithm. But they
contain an index with a key ID. In hashing, a key is assigned to specific
data.
7. Divide and Conquer Algorithm:
This algorithm breaks a problem into sub-problems, solves a single sub-
problem, and merges the solutions to get the final solution. It consists of
the following three steps:
• Divide
• Solve
• Combine

Advantages of Algorithms:
• It is easy to understand.
• An algorithm is a step-wise representation of a solution to a given
problem.
• In an Algorithm the problem is broken down into smaller pieces or
steps hence, it is easier for the programmer to convert it into an
actual program.
Disadvantages of Algorithms:

ASSI.PRO.UPEKSHA CHAUDHRI 5
BZ GROW MORE INSTITUTE OF MSC(CA&IT)

• Writing an algorithm takes a long time so it is time-consuming.


• Understanding complex logic through algorithms can be very
difficult.
• Branching and Looping statements are difficult to show in
Algorithms(imp).

Algorithm Fundamental:

Introduction – Notion of Algorithm :-


symptotic Notations:
• Asymptotic Notations are mathematical tools used to analyze the
performance of algorithms by understanding how their efficiency
changes as the input size grows.
• These notations provide a concise way to express the behavior of
an algorithm’s time or space complexity as the input size
approaches infinity.
• Rather than comparing algorithms directly, asymptotic analysis
focuses on understanding the relative growth rates of algorithms’
complexities.
• It enables comparisons of algorithms’ efficiency by abstracting
away machine-specific constants and implementation details,
focusing instead on fundamental trends.
• Asymptotic analysis allows for the comparison of algorithms’ space
and time complexities by examining their performance
characteristics as the input size varies.
• By using asymptotic notations, such as Big O, Big Omega, and Big
Theta, we can categorize algorithms based on their worst-case,
best-case, or average-case time or space complexities, providing
valuable insights into their efficiency.
There are mainly three asymptotic notations:
1. Big-O Notation (O-notation)
ASSI.PRO.UPEKSHA CHAUDHRI 6
BZ GROW MORE INSTITUTE OF MSC(CA&IT)

2. Omega Notation (Ω-notation)


3. Theta Notation (Θ-notation)
1. Theta Notation (Θ-Notation):
Theta notation encloses the function from above and below. Since it
represents the upper and the lower bound of the running time of an
algorithm, it is used for analyzing the average-case complexity of an
algorithm.
.Theta (Average Case) You add the running times for each possible input
combination and take the average in the average case.
Let g and f be the function from the set of natural numbers to itself. The
function f is said to be Θ(g), if there are constants c1, c2 > 0 and a
natural number n0 such that c1* g(n) ≤ f(n) ≤ c2 * g(n) for all n ≥ n0

Theta notation
Mathematical Representation of Theta notation:
Θ (g(n)) = {f(n): there exist positive constants c1, c2 and n0 such that 0 ≤
c1 * g(n) ≤ f(n) ≤ c2 * g(n) for all n ≥ n0}
Note: Θ(g) is a set
The above expression can be described as if f(n) is theta of g(n), then the
value f(n) is always between c1 * g(n) and c2 * g(n) for large values of n
(n ≥ n0). The definition of theta also requires that f(n) must be non-
negative for values of n greater than n0.
The execution time serves as both a lower and upper bound on the
algorithm’s time complexity.
ASSI.PRO.UPEKSHA CHAUDHRI 7
BZ GROW MORE INSTITUTE OF MSC(CA&IT)

It exist as both, most, and least boundaries for a given input value.
A simple way to get the Theta notation of an expression is to drop low-
order terms and ignore leading constants. For example, Consider the
expression 3n3 + 6n2 + 6000 = Θ(n3), the dropping lower order terms is
always fine because there will always be a number(n) after which Θ(n3)
has higher values than Θ(n2) irrespective of the constants involved. For a
given function g(n), we denote Θ(g(n)) is following set of functions.
Examples :
{ 100 , log (2000) , 10^4 } belongs to Θ(1)
{ (n/4) , (2n+3) , (n/100 + log(n)) } belongs to Θ(n)
{ (n^2+n) , (2n^2) , (n^2+log(n))} belongs to Θ( n2)
Note: Θ provides exact bounds.
2. Big-O Notation (O-notation):
Big-O notation represents the upper bound of the running time of an
algorithm. Therefore, it gives the worst-case complexity of an algorithm.
.It is the most widely used notation for Asymptotic analysis.
.It specifies the upper bound of a function.
.The maximum time required by an algorithm or the worst-case time
complexity.
.It returns the highest possible output value(big-O) for a given input.
.Big-O(Worst Case) It is defined as the condition that allows an algorithm
to complete statement execution in the longest amount of time possible.

If f(n) describes the running time of an algorithm, f(n) is O(g(n)) if there


exist a positive constant C and n0 such that, 0 ≤ f(n) ≤ cg(n) for all n ≥
n0
It returns the highest possible output value (big-O)for a given input.
The execution time serves as an upper bound on the algorithm’s
time complexity.

ASSI.PRO.UPEKSHA CHAUDHRI 8
BZ GROW MORE INSTITUTE OF MSC(CA&IT)

Mathematical Representation of Big-O Notation:


O(g(n)) = { f(n): there exist positive constants c and n0 such that 0 ≤ f(n)
≤ cg(n) for all n ≥ n0 }
For example, Consider the case of Insertion Sort. It takes linear time in
the best case and quadratic time in the worst case. We can safely say
that the time complexity of the Insertion sort is O(n2).
Note: O(n2) also covers linear time.
If we use Θ notation to represent the time complexity of Insertion sort,
we have to use two statements for best and worst cases:
• The worst-case time complexity of Insertion Sort is Θ(n2).
• The best case time complexity of Insertion Sort is Θ(n).
The Big-O notation is useful when we only have an upper bound on the
time complexity of an algorithm. Many times we easily find an upper
bound by simply looking at the algorithm.
Examples :
{ 100 , log (2000) , 10^4 } belongs to O(1)
U { (n/4) , (2n+3) , (n/100 + log(n)) } belongs to O(n)
U { (n^2+n) , (2n^2) , (n^2+log(n))} belongs to O( n^2)
Note: Here, U represents union, we can write it in these manner
because O provides exact or upper bounds .
3. Omega Notation (Ω-Notation):

ASSI.PRO.UPEKSHA CHAUDHRI 9
BZ GROW MORE INSTITUTE OF MSC(CA&IT)

Omega notation represents the lower bound of the running time of an


algorithm. Thus, it provides the best case complexity of an algorithm.
The execution time serves as a lower bound on the algorithm’s time
complexity.
It is defined as the condition that allows an algorithm to complete
statement execution in the shortest amount of time.
Let g and f be the function from the set of natural numbers to itself. The
function f is said to be Ω(g), if there is a constant c > 0 and a natural
number n0 such that c*g(n) ≤ f(n) for all n ≥ n0

Mathematical Representation of Omega notation :


Ω(g(n)) = { f(n): there exist positive constants c and n0 such that 0 ≤
cg(n) ≤ f(n) for all n ≥ n0 }

Fundamentals of Algorithmic Solving :-


Fundamental stages of Problem Solving

Problem solving is both an art and science. As there are no guidelines


available to solve the problem, the problem solving is called an art as
high creativity is needed for solving problems effectively. Thus by art, we
mean one has to be creative, novel and adventurous and by science, we
mean the problem solving should be based on sound mathematical and
logical guidelines.
ASSI.PRO.UPEKSHA CHAUDHRI 10
BZ GROW MORE INSTITUTE OF MSC(CA&IT)

The problem solving stages are given as follows:

1. Problem Understanding
2. Algorithm Planning
3. Design of algorithms
4. Algorithm Verification and Validation
5. Algorithm analysis
6. Algorithm Implementation
7. Perform post-mortem analysis

1. Problem Understanding:
Is it possible to solve the given problem? This falls under the domain
called computability theory. Computability theory deals with the
solvability of the given problem.

2. Design of Algorithms
Algorithm design is the next stage of problem solving. Algorithm design
is a way of developing the algorithmic solutions using the appropriate
design strategy.
.

3. Algorithm Verification and validation


Algorithm verification and validation is the process of checking algorithm
correctness. An algorithm is expected to give correct output for all valid
inputs. This process is called algorithm validation. Once validation is
over, program proving or program verification starts.

ASSI.PRO.UPEKSHA CHAUDHRI 11
BZ GROW MORE INSTITUTE OF MSC(CA&IT)

Verification is done by giving mathematical proofs. Mathematical proofs


are rigorous and better than scientific methods. Program correctness
itself a major study by itself. Proofs are given as follows:
1. Proof by assertion: Assertion assert some facts. It can be given
throughout the program and assertions expressed are in predicate
calculus. If it can be proved that, if for every legal input, if it leads to a
logical output, then it can be said that the given algorithm is correct.
2. Mathematical Induction: Mathematical induction is a technique can be
used to prove recursive algorithms.
5. Algorithm Analysis
Once the algorithm is proved correct, then the analysis starts. Analysis is
important for two reasons. They are as follows:
1. To decide efficiency of algorithms
2. To compare algorithms for deciding the effective solutions for a given
problem.
Algorithm analysis as a domain is called Algorithmic Complexity theory.
What is a complexity? Well, complexity is assumed to be with respect to
size of the input. Sorting of an array with 10 numbers is easy: but the
same problem with 1 million is difficult. So there is a connection with the
complexity and the size of the input.
The complexity of two or more algorithms can be done based on
measures that can be categorized into two types.

1. Subjective measures.
2. Objective measures.
Subjective measures include factors like ease of implementation or style
of the algorithm or understandability of algorithms. But the problem with
the subjective measures are that they vary from person to person. Hence
Objective measures are preferable.

6. Implementation of algorithm as a program and performance analysis

ASSI.PRO.UPEKSHA CHAUDHRI 12
BZ GROW MORE INSTITUTE OF MSC(CA&IT)

After the algorithms are designed, it is implemented as a program. This


stage requires the selection of a programming language. After the
program is written, then the program must be tested. Sometimes, the
program may not give expected results due to errors. The process of
removing the errors is called debugging. Once program is available,
they can be verified with a bench mark dataset. It is called experimental
algorithmics. This is called performance analysis. Thus, Profiling is
a process of running a program on a datasets and measuring the
time/space requirement of the program.

7. Postmortem analysis
A theoretical best solution for the given problem is called lower bound of
the algorithm. The worst case estimate of behavior of the algorithm is
called upper bound. The difference between upper and lower bound is
called algorithmic gap. Technically, no algorithmic gaps should exist.
But practically, there may be vast gap present between two
bounds.Problem solving process ends with postmortem analysis. Any
analysis should end with the valuable insight. Insights like Is the problem
solvable? Are there any limits of this algorithm? and Is the algorithm
efficient? are asked and collected.
Refining the algorithms is to bring these gaps short by reefing planning,
design, implementation and analysis. Thus problem solving is not linear
but rather this is a cycle.

Important Problem types :-

Searching
ASSI.PRO.UPEKSHA CHAUDHRI 13
BZ GROW MORE INSTITUTE OF MSC(CA&IT)

A fundamental problem that involves finding or accessing data from a


collection of items stored in a data structure. Binary search is one
example of a searching algorithm.

• Graph problems
Graph theory is a key topic in computer science that's important for
algorithms and data structures.

Combinatorial problems
The analysis of discrete structures is important for understanding the
properties of those structures and for analyzing algorithms.

Convex hulls
A building block for more sophisticated geometric algorithms.

Minimum spanning trees


Important for connecting points with the least amount of connecting
material.

ASSI.PRO.UPEKSHA CHAUDHRI 14
BZ GROW MORE INSTITUTE OF MSC(CA&IT)

Randomized algorithms
Important in both theoretical computing science and real-world
applications.

Fundamentals of the Analysis Framework – The analysis framework for


algorithm efficiency has several fundamentals, including:
• Time efficiency: Also known as time complexity, this measures how
fast an algorithm runs.
• Space efficiency: Also known as space complexity, this measures
how much memory an algorithm needs to run, including the space
it needs for input and output.
• Notations: The analysis framework uses three notations: "big oh"
(O), "big omega" (Ω), and "big theta" (Θ).
• Best, worst, and average case efficiencies: The analysis framework
measures the efficiency of an algorithm in these three cases.
• Input size: The analysis framework measures the input size of an
algorithm.
• Running time: The analysis framework measures the running time
of an algorithm.
• Order of growth: The analysis framework measures the order of
growth of an algorithm.

Asymptotic Notations and Basic Efficiency Classes:- Asymptotic


Notations:
• Asymptotic Notations are mathematical tools used to analyze the
performance of algorithms by understanding how their efficiency
changes as the input size grows.

ASSI.PRO.UPEKSHA CHAUDHRI 15
BZ GROW MORE INSTITUTE OF MSC(CA&IT)

• These notations provide a concise way to express the behavior of


an algorithm’s time or space complexity as the input size
approaches infinity.
• Rather than comparing algorithms directly, asymptotic analysis
focuses on understanding the relative growth rates of algorithms’
complexities.
• It enables comparisons of algorithms’ efficiency by abstracting
away machine-specific constants and implementation details,
focusing instead on fundamental trends.
• Asymptotic analysis allows for the comparison of algorithms’ space
and time complexities by examining their performance
characteristics as the input size varies.
• By using asymptotic notations, such as Big O, Big Omega, and Big
Theta, we can categorize algorithms based on their worst-case,
best-case, or average-case time or space complexities, providing
valuable insights into their efficiency.
There are mainly three asymptotic notations:
1. Big-O Notation (O-notation)
2. Omega Notation (Ω-notation)
3. Theta Notation (Θ-notation)
1. Theta Notation (Θ-Notation):
Theta notation encloses the function from above and below. Since it
represents the upper and the lower bound of the running time of an
algorithm, it is used for analyzing the average-case complexity of an
algorithm.
.Theta (Average Case) You add the running times for each possible input
combination and take the average in the average case.
Let g and f be the function from the set of natural numbers to itself. The
function f is said to be Θ(g), if there are constants c1, c2 > 0 and a
natural number n0 such that c1* g(n) ≤ f(n) ≤ c2 * g(n) for all n ≥ n0

ASSI.PRO.UPEKSHA CHAUDHRI 16
BZ GROW MORE INSTITUTE OF MSC(CA&IT)

Theta notation
Mathematical Representation of Theta notation:
Θ (g(n)) = {f(n): there exist positive constants c1, c2 and n0 such that 0 ≤
c1 * g(n) ≤ f(n) ≤ c2 * g(n) for all n ≥ n0}
Note: Θ(g) is a set
The above expression can be described as if f(n) is theta of g(n), then the
value f(n) is always between c1 * g(n) and c2 * g(n) for large values of n
(n ≥ n0). The definition of theta also requires that f(n) must be non-
negative for values of n greater than n0.
The execution time serves as both a lower and upper bound on the
algorithm’s time complexity.
It exist as both, most, and least boundaries for a given input value.
A simple way to get the Theta notation of an expression is to drop low-
order terms and ignore leading constants. For example, Consider the
expression 3n3 + 6n2 + 6000 = Θ(n3), the dropping lower order terms is
always fine because there will always be a number(n) after which Θ(n3)
has higher values than Θ(n2) irrespective of the constants involved. For a
given function g(n), we denote Θ(g(n)) is following set of functions.
Examples :
{ 100 , log (2000) , 10^4 } belongs to Θ(1)
{ (n/4) , (2n+3) , (n/100 + log(n)) } belongs to Θ(n)
{ (n^2+n) , (2n^2) , (n^2+log(n))} belongs to Θ( n2)
Note: Θ provides exact bounds.

ASSI.PRO.UPEKSHA CHAUDHRI 17
BZ GROW MORE INSTITUTE OF MSC(CA&IT)

2. Big-O Notation (O-notation):


Big-O notation represents the upper bound of the running time of an
algorithm. Therefore, it gives the worst-case complexity of an algorithm.
.It is the most widely used notation for Asymptotic analysis.
.It specifies the upper bound of a function.
.The maximum time required by an algorithm or the worst-case time
complexity.
.It returns the highest possible output value(big-O) for a given input.
.Big-O(Worst Case) It is defined as the condition that allows an algorithm
to complete statement execution in the longest amount of time possible.

If f(n) describes the running time of an algorithm, f(n) is O(g(n)) if there


exist a positive constant C and n0 such that, 0 ≤ f(n) ≤ cg(n) for all n ≥
n0
It returns the highest possible output value (big-O)for a given input.
The execution time serves as an upper bound on the algorithm’s
time complexity.

Mathematical Representation of Big-O Notation:


O(g(n)) = { f(n): there exist positive constants c and n0 such that 0 ≤ f(n)
≤ cg(n) for all n ≥ n0 }
For example, Consider the case of Insertion Sort. It takes linear time in
the best case and quadratic time in the worst case. We can safely say

ASSI.PRO.UPEKSHA CHAUDHRI 18
BZ GROW MORE INSTITUTE OF MSC(CA&IT)

that the time complexity of the Insertion sort is O(n2).


Note: O(n2) also covers linear time.
If we use Θ notation to represent the time complexity of Insertion sort,
we have to use two statements for best and worst cases:
• The worst-case time complexity of Insertion Sort is Θ(n2).
• The best case time complexity of Insertion Sort is Θ(n).
The Big-O notation is useful when we only have an upper bound on the
time complexity of an algorithm. Many times we easily find an upper
bound by simply looking at the algorithm.
Examples :
{ 100 , log (2000) , 10^4 } belongs to O(1)
U { (n/4) , (2n+3) , (n/100 + log(n)) } belongs to O(n)
U { (n^2+n) , (2n^2) , (n^2+log(n))} belongs to O( n^2)
Note: Here, U represents union, we can write it in these manner
because O provides exact or upper bounds .
3. Omega Notation (Ω-Notation):
Omega notation represents the lower bound of the running time of an
algorithm. Thus, it provides the best case complexity of an algorithm.
The execution time serves as a lower bound on the algorithm’s time
complexity.
It is defined as the condition that allows an algorithm to complete
statement execution in the shortest amount of time.
Let g and f be the function from the set of natural numbers to itself. The
function f is said to be Ω(g), if there is a constant c > 0 and a natural
number n0 such that c*g(n) ≤ f(n) for all n ≥ n0

ASSI.PRO.UPEKSHA CHAUDHRI 19
BZ GROW MORE INSTITUTE OF MSC(CA&IT)

Mathematical Representation of Omega notation :


Ω(g(n)) = { f(n): there exist positive constants c and n0 such that 0 ≤
cg(n) ≤ f(n) for all n ≥ n0 }
Let us consider the same Insertion sort example here. The time
complexity of Insertion Sort can be written as Ω(n), but it is not very
useful information about insertion sort, as we are generally interested in
worst-case and sometimes in the average case.
Examples :
{ (n^2+n) , (2n^2) , (n^2+log(n))} belongs to Ω( n^2)
U { (n/4) , (2n+3) , (n/100 + log(n)) } belongs to Ω(n)
U { 100 , log (2000) , 10^4 } belongs to Ω(1)
Note: Here, U represents union, we can write it in these manner
because Ω provides exact or lower bounds.
Properties of Asymptotic Notations:
1. General Properties:
If f(n) is O(g(n)) then a*f(n) is also O(g(n)), where a is a constant.
Example:
f(n) = 2n²+5 is O(n²)
then, 7*f(n) = 7(2n²+5) = 14n²+35 is also O(n²).
Similarly, this property satisfies both Θ and Ω notation.
We can say,
ASSI.PRO.UPEKSHA CHAUDHRI 20
BZ GROW MORE INSTITUTE OF MSC(CA&IT)

If f(n) is Θ(g(n)) then a*f(n) is also Θ(g(n)), where a is a constant.


If f(n) is Ω (g(n)) then a*f(n) is also Ω (g(n)), where a is a constant.
2. Transitive Properties:
If f(n) is O(g(n)) and g(n) is O(h(n)) then f(n) = O(h(n)).
Example:
If f(n) = n, g(n) = n² and h(n)=n³
n is O(n²) and n² is O(n³) then, n is O(n³)
Similarly, this property satisfies both Θ and Ω notation.

Basic Concepts of Flowchart, Algorithm:- A flowchart is a type of


diagram that represents a workflow or process. A flowchart can also be
defined as a diagrammatic representation of an algorithm, a step-by-step
approach to solving a task.
Flowchart symbols
Different types of boxes are used to make flowcharts flowchart Symbols.
All the different kinds of boxes are connected by arrow lines. Arrow lines
are used to display the flow of control. Let’s learn about each box in
detail.

Symbol Name Symbol Representation

Terminal/Terminator

ASSI.PRO.UPEKSHA CHAUDHRI 21
BZ GROW MORE INSTITUTE OF MSC(CA&IT)

Symbol Name Symbol Representation

Process

Decision

ASSI.PRO.UPEKSHA CHAUDHRI 22
BZ GROW MORE INSTITUTE OF MSC(CA&IT)

Symbol Name Symbol Representation

Document

Data or Input/Output

Stored Data

ASSI.PRO.UPEKSHA CHAUDHRI 23
BZ GROW MORE INSTITUTE OF MSC(CA&IT)

Symbol Name Symbol Representation

Flow Arrow

Comment or
Annotation

Predefined process

ASSI.PRO.UPEKSHA CHAUDHRI 24
BZ GROW MORE INSTITUTE OF MSC(CA&IT)

Symbol Name Symbol Representation

On-page
connector/reference

Off-page
connector/reference

Uses of Flowcharts in Computer Programming/Algorithms


The following are the uses of a flowchart:
• It is a pictorial representation of an algorithm that increases the
readability of the program.
• Complex programs can be drawn in a simple way using a
flowchart.
• It helps team members get an insight into the process and use this
knowledge to collect data, detect problems, develop software, etc.
• A flowchart is a basic step for designing a new process or adding
extra features.

ASSI.PRO.UPEKSHA CHAUDHRI 25
BZ GROW MORE INSTITUTE OF MSC(CA&IT)

• Communication with other people becomes easy by drawing


flowcharts and sharing them.
When to Use Flowchart?
Flowcharts are mainly used in the below scenarios:
• It is most importantly used when programmers make projects. As a
flowchart is a basic step to make the design of projects pictorially, it
is preferred by many.
• When the flowcharts of a process are drawn, the programmer
understands the non-useful parts of the process. So flowcharts are
used to separate sound logic from the unwanted parts.
• Since the rules and procedures of drawing a flowchart are
universal, a flowchart serves as a communication channel to the
people who are working on the same project for better
understanding.
• Optimizing a process becomes easier with flowcharts. The
efficiency of the code is improved with the flowchart drawing.
Types of Flowcharts
Three types of flowcharts are listed below:
1. Process flowchart: This type of flowchart shows all the activities
that are involved in making a product. It provides a pathway to
analyze the product to be built. A process flowchart is most
commonly used in process engineering to illustrate the relation
between the major as well as minor components present in the
product. It is used in business product modeling to help
understand employees about the project requirements and gain
some insight into the project.
2. Data flowchart: As the name suggests, the data flowchart is used
to analyze the data, specifically it helps in analyzing the structural
details related to the project. Using this flowchart, one can easily
understand the data inflow and outflow from the system. It is most
commonly used to manage data or to analyze information to and
fro from the system.

ASSI.PRO.UPEKSHA CHAUDHRI 26
BZ GROW MORE INSTITUTE OF MSC(CA&IT)

3. Business Process Modeling Diagram: Using this flowchart or


diagram, one can analytically represent the business process and
help simplify the concepts needed to understand business
activities and the flow of information. This flowchart illustrates the
business process and models graphically which paves the way for
process improvement.
Types of boxes used to make a flowchart
There are different types of boxes that are used to make flowcharts. All
the different kinds of boxes are connected to one another by arrow lines.
Arrow lines are used to display the flow of control. Let’s learn about each
box in detail.
1. Terminal

This box is of an oval shape which is used to indicate the start or end of
the program. Every flowchart diagram has an oval shape that depicts the
start of an algorithm and another oval shape that depicts the end of an
algorithm. For example:

ASSI.PRO.UPEKSHA CHAUDHRI 27
BZ GROW MORE INSTITUTE OF MSC(CA&IT)

2. Data

This is a parallelogram-shaped box inside which the inputs or outputs are


written. This basically depicts the information that is entering the system
or algorithm and the information that is leaving the system or algorithm.
For example: if the user wants to input a from the user and display it, the
flowchart for this would be:

ASSI.PRO.UPEKSHA CHAUDHRI 28
BZ GROW MORE INSTITUTE OF MSC(CA&IT)

3. Process

This is a rectangular box inside which a programmer writes the main


course of action of the algorithm or the main logic of the program. This is
the crux of the flowchart as the main processing codes is written inside
this box. For example: if the programmer wants to add 1 to the input
given by the user, he/she would make the following flowchart:

ASSI.PRO.UPEKSHA CHAUDHRI 29
BZ GROW MORE INSTITUTE OF MSC(CA&IT)

4. Decision

This is a rhombus-shaped box, control statements like if, condition like a


> 0, etc are written inside this box. There are 2 paths from this one which
is “yes” and the other one is “no”. Every decision has either yes or no as
an option, similarly, this box has these as options. For example: if the

ASSI.PRO.UPEKSHA CHAUDHRI 30
BZ GROW MORE INSTITUTE OF MSC(CA&IT)

user wants to add 1 to an even number and subtract 1 if the number is


odd, the flowchart would be:

5. Flow

This arrow line represents the flow of the algorithm or process. It


represents the direction of the process flow. in all the previous examples,
we included arrows in every step to display the flow of the program.
arrow increases the readability of the program.
6. On-Page Reference

ASSI.PRO.UPEKSHA CHAUDHRI 31
BZ GROW MORE INSTITUTE OF MSC(CA&IT)

This circular figure is used to depict that the flowchart is in continuation


with the further steps. This figure comes into use when the space is less
and the flowchart is long. Any numerical symbol is present inside this
circle and that same numerical symbol will be depicted before the
continuation to make the user understand the continuation. Below is a
simple example depicting the use of On-Page Reference

Advantages of Flowchart
• It is the most efficient way of communicating the logic of the
system.
• It acts as a guide for a blueprint during the program design.
• It also helps in the debugging process.
• Using flowcharts we can easily analyze the programs.
• flowcharts are good for documentation.
Disadvantages of Flowchart

ASSI.PRO.UPEKSHA CHAUDHRI 32
BZ GROW MORE INSTITUTE OF MSC(CA&IT)

• Flowcharts are challenging to draw for large and complex


programs.
• It does not contain the proper amount of details.
• Flowcharts are very difficult to reproduce.
• Flowcharts are very difficult to modify.
Solved Examples on FlowChart
Question 1. Draw a flowchart to find the greatest number among
the 2 numbers.
Solution:
Algorithm:
1. Start
2. Input 2 variables from user
3. Now check the condition If a > b, goto step 4, else goto step 5.
4. Print a is greater, goto step 6
5. Print b is greater
6. Stop
FlowChart:

ASSI.PRO.UPEKSHA CHAUDHRI 33
BZ GROW MORE INSTITUTE OF MSC(CA&IT)

Array:-
An array is a type of linear data structure that is defined as a collection of
elements with same or different data types. They exist in both single
dimension and multiple dimensions. These data structures come into
picture when there is a necessity to store multiple elements of similar
nature together at one place.

The difference between an array index and a memory address is that the
array index acts like a key value to label the elements in the array.
ASSI.PRO.UPEKSHA CHAUDHRI 34
BZ GROW MORE INSTITUTE OF MSC(CA&IT)

However, a memory address is the starting address of free memory


available.
Following are the important terms to understand the concept of Array.
• Element − Each item stored in an array is called an element.
• Index − Each location of an element in an array has a numerical
index, which is used to identify the element.
Syntax
Creating an array in C and C++ programming languages −
data_type array_name[array_size]={elements separated by commas}
or,
data_type array_name[array_size];
Array Representation
Arrays are represented as a collection of buckets where each bucket
stores one element. These buckets are indexed from '0' to 'n-1', where n
is the size of that particular array. For example, an array with size 10 will
have buckets indexed from 0 to 9.
This indexing will be similar for the multidimensional arrays as well. If it is
a 2-dimensional array, it will have sub-buckets in each bucket. Then it will
be indexed as array_name[m][n], where m and n are the sizes of each
level in the array.

ASSI.PRO.UPEKSHA CHAUDHRI 35
BZ GROW MORE INSTITUTE OF MSC(CA&IT)

As per the above illustration, following are the important points to be


considered.
• Index starts with 0.
• Array length is 9 which means it can store 9 elements.
• Each element can be accessed via its index. For example, we can
fetch an element at index 6 as 23.

2D Array
2D array can be defined as an array of arrays. The 2D array is organized
as matrices which can be represented as the collection of rows and
columns.
How to declare 2D Array
The syntax of declaring two dimensional array is very much similar to
that of a one dimensional array, given as follows.
1. int arr[max_rows][max_columns];
however, It produces the data structure which looks like following.

ASSI.PRO.UPEKSHA CHAUDHRI 36
BZ GROW MORE INSTITUTE OF MSC(CA&IT)

Above image shows the two dimensional array, the elements are
organized in the form of rows and columns. First element of the first row
is represented by a[0][0] where the number shown in the first index is the
number of that row while the number shown in the second index is the
number of the column.
How do we access data in a 2D array
Due to the fact that the elements of 2D arrays can be random accessed.
Similar to one dimensional arrays, we can access the individual cells in a
2D array by using the indices of the cells. There are two indices attached
to a particular cell, one is its row number while the other is its column
number.
However, we can store the value stored in any particular cell of a 2D
array to some variable x by using the following syntax.
1. int x = a[i][j];

ASSI.PRO.UPEKSHA CHAUDHRI 37
BZ GROW MORE INSTITUTE OF MSC(CA&IT)

where i and j is the row and column number of the cell respectively.
We can assign each cell of a 2D array to 0 by using the following code:
1. for ( int i=0; i<n ;i++)
2. {
3. for (int j=0; j<n; j++)
4. {
5. a[i][j] = 0;
6. }
7. }
Initializing 2D Arrays
The syntax to declare and initialize the 2D array is given as follows.
1. int arr[2][2] = {0,1,2,3};
The number of elements that can be present in a 2D array will always be
equal to (number of rows * number of columns).
Example : Storing User's data into a 2D array and printing it.
C Example :
1. #include <stdio.h>
2. void main ()
3. {
4. int arr[3][3],i,j;
5. for (i=0;i<3;i++)
6. {
7. for (j=0;j<3;j++)
8. {
9. printf("Enter a[%d][%d]: ",i,j);
10. scanf("%d",&arr[i][j]);

ASSI.PRO.UPEKSHA CHAUDHRI 38
BZ GROW MORE INSTITUTE OF MSC(CA&IT)

11. }
12. }
13. printf("\n printing the elements ....\n");
14. for(i=0;i<3;i++)
15. {
16. printf("\n");
17. for (j=0;j<3;j++)
18. {
19. printf("%d\t",arr[i][j]);
20. }
21. }

A multi-dimensional array can be defined as an array that has more


than one dimension. Having more than one dimension means that
it can grow in multiple directions. Some popular multidimensional
arrays are 2D arrays and 3D arrays. In this article, we will learn
about multidimensional arrays in C programming language.
Syntax
The general form of declaring N-dimensional arrays is shown
below:
type arr_name[size1][size2]….[sizeN];
• type: Type of data to be stored in the array.
• arr_name: Name assigned to the array.
• size1, size2,…, sizeN: Size of each dimension.
Examples
Two-dimensional array: int two_d[10][20]; Three-dimensional
array: int three_d[10][20][30];
Size of Multidimensional Arrays

ASSI.PRO.UPEKSHA CHAUDHRI 39
BZ GROW MORE INSTITUTE OF MSC(CA&IT)

The total number of elements that can be stored in a


multidimensional array can be calculated by multiplying the size of
both dimensions. Consider the array arr[10][20]:
• The array int arr[10][20] can store total of (10*20) = 200 elements.
To get the size in bytes, we multiply the size of a single element (in
bytes) by the total number of elements in the array.
• The size of array int arr[10][20] = 10 * 20 * 4 = 800 bytes, where
the size of int is 4 bytes.
Types of Multidimensional Arrays
In C, there can be many types of arrays depending on their
dimensions but two of them are most commonly used:
1. Two-Dimensional Array (2D Array)
2. Three-Dimensional Array (3D Array)
Two-Dimensional (2D) Arrays in C
A two-dimensional array or 2D array is the simplest form of the
multidimensional array. We can visualize a two-dimensional array
as one-dimensional arrays stacked vertically forming a table with
‘m’ rows and ‘n’ columns. In C, arrays are 0-indexed, so the row
number ranges from 0 to (m-1) and the column number ranges
from 0 to (n-1).

ASSI.PRO.UPEKSHA CHAUDHRI 40
BZ GROW MORE INSTITUTE OF MSC(CA&IT)

Declaration of 2D Array
A 2D array with m rows and n columns can be created as:
type arr_name[m][n];
where,
• type: Type of data to be stored in each element.
• arr_name: Name assigned to the array.
• m: Number of rows.
• n: Number of columns.
For example, we can declare a two-dimensional integer array with
name ‘arr’ with 10 rows and 20 columns as:
int arr[10][20];
Initialization of 2D Arrays
We can initialize a 2D array by using a list of values enclosed inside
‘{ }’ and separated by a comma as shown in the example below:
int arr[3][4] = {0, 1 ,2 ,3 ,4 , 5 , 6 , 7 , 8 , 9 , 10 , 11}

ASSI.PRO.UPEKSHA CHAUDHRI 41
BZ GROW MORE INSTITUTE OF MSC(CA&IT)

or
int arr[3][4] = {{0, 1, 2, 3}, {4, 5, 6, 7}, {8, 9, 10, 11}};
The elements will be stored in the array from left to right and top to
bottom. So, the first 4 elements from the left will be filled in the first
row, the next 4 elements in the second row, and so on. This is
clearly shown in the second syntax where each set of inner braces
represents one row.
In list initialization, we can skip specifying the size of the row. The
compiler will automatically deduce it in this case. So, the below
declaration is valid.
type arr_name[][n] = {…values…};
It is still compulsory to define the number of columns.
Note: The number of elements in initializer list should always be
either less than or equal to the total number of elements in the
array.
2D Array Traversal
Traversal means accessing all the elements of the array one by
one. An element in two-dimensional array is accessed using row
indexes and column indexes inside array subscript operator [].
arr_name[i][j]
where, i and j are row index and column index.
To traverse the whole array, we will use two loops. One loop to go
over each row from top to bottom and the other nested inside it to
access each element in the current row from left to right.
Example of 2D Array
The below example demonstrates the row-by-row traversal of a 2D
array.
C
// C Program to illustrate the 2D array
#include <stdio.h>

ASSI.PRO.UPEKSHA CHAUDHRI 42
BZ GROW MORE INSTITUTE OF MSC(CA&IT)

int main() {

// Create and initialize an array with 3 rows


// and 2 columns
int arr[3][2] = { { 0, 1 }, { 2, 3 }, { 4, 5 } };

// Print each array element's value


for (int i = 0; i < 3; i++) {
for (int j = 0; j < 2; j++) {
printf("arr[%d][%d]: %d ", i, j, arr[i][j]);
}
printf("\n");
}
return 0;
}

Output
arr[0][0]: 0 arr[0][1]: 1
arr[1][0]: 2 arr[1][1]: 3
arr[2][0]: 4 arr[2][1]: 5
Time Complexity: O(n * m), where n and m are numbers of rows
and columns respectively.
Auxiliary Space: O(1)

ASSI.PRO.UPEKSHA CHAUDHRI 43
BZ GROW MORE INSTITUTE OF MSC(CA&IT)

Pointer:-
Pointers are one of the core components of the programming language.
A pointer can be used to store the memory address of other variables,
functions, or even other pointers. The use of pointers allows low-level
memory access, dynamic memory allocation, and many other
functionality in C.
In this article, we will discuss C pointers in detail, their types, uses,
advantages, and disadvantages with examples.
What is a Pointer
A pointer is defined as a derived data type that can store the address of
other C variables or a memory location. We can access and manipulate
the data stored in that memory location using pointers.
As the pointers in tore the memory addresses, their size is independent
of the type of data they are pointing to. This size of pointers in C only
depends on the system architecture.
Syntax of C Pointers
The syntax of pointers is similar to the variable declaration in C, but we
use the ( * ) dereferencing operator in the pointer declaration.
datatype * ptr;
where
• ptr is the name of the pointer.
• datatype is the type of data it is pointing to.
The above syntax is used to define a pointer to a variable. We can also
define pointers to functions, structures, etc.
How to Use Pointers?
The use of pointers in can be divided into three steps:
1. Pointer Declaration
2. Pointer Initialization
3. Pointer Dereferencing
ASSI.PRO.UPEKSHA CHAUDHRI 44
BZ GROW MORE INSTITUTE OF MSC(CA&IT)

1. Pointer Declaration
In pointer declaration, we only declare the pointer but do not initialize it.
To declare a pointer, we use the ( * ) dereference operator before its
name.
Example
int *ptr;
The pointer declared here will point to some random memory address as
it is not initialized. Such pointers are called wild pointers.
2. Pointer Initialization
Pointer initialization is the process where we assign some initial value to
the pointer variable. We generally use the ( &: ampersand ) addressof
operator to get the memory address of a variable and then store it in the
pointer variable.
Example
int var = 10;
int * ptr;
ptr = &var;
We can also declare and initialize the pointer in a single step. This
method is called pointer definition as the pointer is declared and
initialized at the same time.
Example
int *ptr = &var;
Note: It is recommended that the pointers should always be initialized to
some value before starting using it. Otherwise, it may lead to number of
errors.
3. Pointer Dereferencing
Dereferencing a pointer is the process of accessing the value stored in
the memory address specified in the pointer. We use the same ( * )
dereferencing operator that we used in the pointer declaration.

ASSI.PRO.UPEKSHA CHAUDHRI 45
BZ GROW MORE INSTITUTE OF MSC(CA&IT)

Dereferencing a Pointer in C
C Pointer Example
C
// C program to illustrate Pointers
#include <stdio.h>

void geeks()
{
int var = 10;

// declare pointer variable


int* ptr;

// note that data type of ptr and var must be same


ptr = &var;

// assign the address of a variable to a pointer


printf("Value at ptr = %p \n", ptr);
printf("Value at var = %d \n", var);
ASSI.PRO.UPEKSHA CHAUDHRI 46
BZ GROW MORE INSTITUTE OF MSC(CA&IT)

printf("Value at *ptr = %d \n", *ptr);


}

// Driver program
int main()
{
geeks();
return 0;
}

Output
Value at ptr = 0x7ffca84068dc
Value at var = 10
Value at *ptr = 10
Types of Pointers
Pointers in C can be classified into many different types based on the
parameter on which we are defining their types. If we consider the type
of variable stored in the memory location pointed by the pointer, then the
pointers can be classified into the following types:
1. Integer Pointers
As the name suggests, these are the pointers that point to the integer
values.
Syntax
int *ptr;

These pointers are pronounced as Pointer to Integer.


Similarly, a pointer can point to any primitive data type. It can point also
point to derived data types such as arrays and user-defined data types
such as structures.
ASSI.PRO.UPEKSHA CHAUDHRI 47
BZ GROW MORE INSTITUTE OF MSC(CA&IT)

2. Array Pointer
Pointers and Array are closely related to each other. Even the array name
is the pointer to its first element. They are also known as Pointer to
Arrays. We can create a pointer to an array using the given syntax.
Syntax
char *ptr = &array_name;

Pointer to Arrays exhibits some interesting properties which we


discussed later in this article.
3. Structure Pointer
The pointer pointing to the structure type is called Structure Pointer or
Pointer to Structure. It can be declared in the same way as we declare
the other primitive data types.
Syntax
struct struct_name *ptr;

In C, structure pointers are used in data structures such as linked lists,


trees, etc.
4. Function Pointers
Function pointers point to the functions. They are different from the rest
of the pointers in the sense that instead of pointing to the data, they point
to the code. Let’s consider a function prototype – int func (int,
char), the function pointer for this function will be
Syntax
int (*ptr)(int, char);

Union:-
The Union is a user-defined data type in C language that can contain
elements of the different data types just like structure. But unlike
structures, all the members in the C union are stored in the same

ASSI.PRO.UPEKSHA CHAUDHRI 48
BZ GROW MORE INSTITUTE OF MSC(CA&IT)

memory location. Due to this, only one member can store data at the
given instance.

Syntax of Union in C
The syntax of the union in C can be divided into three steps which are as
follows:
C Union Declaration
In this part, we only declare the template of the union, i.e., we only
declare the members’ names and data types along with the name of the
union. No memory is allocated to the union in the declaration.
union union_name {
datatype member1;
datatype member2;
...
};

ASSI.PRO.UPEKSHA CHAUDHRI 49
BZ GROW MORE INSTITUTE OF MSC(CA&IT)

Keep in mind that we have to always end the union declaration with a
semi-colon.
Different Ways to Define a Union Variable
We need to define a variable of the union type to start using union
members. There are two methods using which we can define a union
variable.
1. With Union Declaration
2. After Union Declaration
1. Defining Union Variable with Declaration
union union_name {
datatype member1;
datatype member2;
...
} var1, var2, ...;
2. Defining Union Variable after Declaration
union union_name var1, var2, var3...;
where union_name is the name of an already declared union.
Access Union Members
We can access the members of a union by using the ( . ) dot
operator just like structures.
var1.member1;
where var1 is the union variable and member1 is the member of the
union.
The above method of accessing the members of the union also works for
the nested unions.
var1.member1.memberA;
Here,
• var1 is a union variable.
• member1 is a member of the union.

ASSI.PRO.UPEKSHA CHAUDHRI 50
BZ GROW MORE INSTITUTE OF MSC(CA&IT)

• memberA is a member of member1.


Initialization of Union in C
The initialization of a union is the initialization of its members by simply
assigning the value to it.
var1.member1 = some_value;
One important thing to note here is that only one member can contain
some value at a given instance of time.
Example of Union
C
// C Program to demonstrate how to use union
#include <stdio.h>

// union template or declaration


union un {
int member1;
char member2;
float member3;
};

// driver code
int main()
{

// defining a union variable


union un var1;

// initializing the union member


ASSI.PRO.UPEKSHA CHAUDHRI 51
BZ GROW MORE INSTITUTE OF MSC(CA&IT)

var1.member1 = 15;

printf("The value stored in member1 = %d",


var1.member1);

return 0;
}

Output
The value stored in member1 = 15

Structure: Structure and Pointer:-


A structure pointer is defined as the pointer which points to the address
of the memory block that stores a structure known as the structure
pointer. Complex data structures like Linked lists, trees, graphs, etc. are
created with the help of structure pointers. The structure pointer tells the
address of a structure in memory by pointing the variable to the structure
variable.
Example:

• C

// C program to demonstrate structure pointer


#include <stdio.h>

struct point {
int value;
};

ASSI.PRO.UPEKSHA CHAUDHRI 52
BZ GROW MORE INSTITUTE OF MSC(CA&IT)

int main()
{

struct point s;

// Initialization of the structure pointer


struct point* ptr = &s;

return 0;
}

In the above code s is an instance of struct point and ptr is the struct
pointer because it is storing the address of struct point.
Accessing the Structure Member with the Help of Pointers
There are two ways to access the members of the structure with the help
of a structure pointer:
1. With the help of (*) asterisk or indirection operator and (.) dot
operator.
2. With the help of ( -> ) Arrow operator.
Below is the program to access the structure members using the
structure pointer with the help of the dot operator.
• C

// C Program to demonstrate Structure pointer


#include <stdio.h>
#include <string.h>

ASSI.PRO.UPEKSHA CHAUDHRI 53
BZ GROW MORE INSTITUTE OF MSC(CA&IT)

struct Student {
int roll_no;
char name[30];
char branch[40];
int batch;
};

int main()
{

struct Student s1;


struct Student* ptr = &s1;

s1.roll_no = 27;
strcpy(s1.name, "Kamlesh Joshi");
strcpy(s1.branch, "Computer Science And Engineering");
s1.batch = 2019;

printf("Roll Number: %d\n", (*ptr).roll_no);


printf("Name: %s\n", (*ptr).name);
printf("Branch: %s\n", (*ptr).branch);
printf("Batch: %d", (*ptr).batch);

return 0;

ASSI.PRO.UPEKSHA CHAUDHRI 54
BZ GROW MORE INSTITUTE OF MSC(CA&IT)

Output:
1

Structure and Array:-


When dealing with a large set of related data and different data types,
organizing and managing it efficiently is crucial. In C programming, the
combination of arrays and structures i.e. array of structures provides a
powerful tool for managing that. In this article, we discuss the concept of
an Array of Structures in C.
What is Array?
The array is a homogeneous collection of elements stored in the
continuous memory location. The size of the array is fixed and we can
randomly access the elements using their index.
Declaration of Array
array_type array_name[size];

What is Structure?
The structure is one of the user-defined data types in C that can contain
elements of different types as its members.
Declaration of a Structure in C
struct structure_name{
memberType memberName;
...
...
};
Array of Structures
An array whose elements are of type structure is called array of
structure. It is generally useful when we need multiple structure variables
in our program.
ASSI.PRO.UPEKSHA CHAUDHRI 55
BZ GROW MORE INSTITUTE OF MSC(CA&IT)

Need for Array of Structures


Suppose we have 50 employees and we need to store the data of 50
employees. So for that, we need to define 50 variables of struct
Employee type and store the data within that. However, declaring and
handling the 50 variables is not an easy task. Let’s imagine a bigger
scenario, like 1000 employees.
So, if we declare the variable this way, it’s not possible to handle this.
struct Employee emp1, emp2, emp3, .. . ... . .. ... emp1000;
For that, we can define an array whose data type will be struct Employee
soo that will be easily manageable.
Declaration of Array of Structures
struct structure_name array_name [number_of_elements];
Initialization of Array of Structures
We can initialize the array of structures in the following ways:
struct structure_name array_name [number_of_elements] = {
{element1_value1, element1_value2, ....},
{element2_value1, element2_value2, ....},
......
......
};
The same initialization can also be done as:
struct structure_name array_name [number_of_elements] = {
element1_value1, element1_value2 ....,
element2_value1, element2_value2 .....
};
GNU C compilers supports designated initialization for structures so we
can also use this in the initialization of an array of structures.
struct structure_name array_name [number_of_elements] = {
{.element3 = value, .element1 = value, ....},
{.element2 = value, .elementN = value, ....},
......
......
ASSI.PRO.UPEKSHA CHAUDHRI 56
BZ GROW MORE INSTITUTE OF MSC(CA&IT)

};

Example of Array of Structure in C


• C

// C program to demonstrate the array of structures


#include <stdio.h>

// structure template
struct Employee {
char Name[20];
int employeeID;
int WeekAttendence[7];
};

// driver code
int main()
{
// defining array of structure of type Employee
struct Employee emp[5];

// adding data
for (int i = 0; i < 5; i++) {
emp[i].employeeID = i;
strcpy(emp[i].Name, "Amit");
int week;

ASSI.PRO.UPEKSHA CHAUDHRI 57
BZ GROW MORE INSTITUTE OF MSC(CA&IT)

for (week = 0; week < 7; week++) {


int attendence;
emp[i].WeekAttendence[week] = week;
}
}
printf("\n");

// printing data
for (int i = 0; i < 5; i++) {
printf("Emplyee ID: %d - Employee Name: %s\n",
emp[i].employeeID, emp[i].Name);
printf("Attendence\n");
int week;
for (week = 0; week < 7; week++) {
printf("%d ", emp[i].WeekAttendence[week]);
}
printf("\n");
}

return 0;
}

Output
Emplyee ID: 0 - Employee Name: Amit
Attendence
0123456
Emplyee ID: 1 - Employee Name: Amit
Attendence
ASSI.PRO.UPEKSHA CHAUDHRI 58
BZ GROW MORE INSTITUTE OF MSC(CA&IT)

0123456
Emplyee ID: 2 - Employee Name: Amit
Attendence
0123456
Emplyee ID: 3 - Employee Name: Amit
Attendence
0123456
Emplyee ID: 4 - Employee Name: Amit
Attendence
0123456

Structure within Structure:-


A nested structure is a structure within structure. One structure can be
declared inside another structure in the same way structure members
are declared inside a structure.
Syntax:
struct name_1
{
member1;
member2;
.
.
membern;
struct name_2
{
member_1;
member_2;
.
.
member_n;
}, var1
} var2;

ASSI.PRO.UPEKSHA CHAUDHRI 59
BZ GROW MORE INSTITUTE OF MSC(CA&IT)

example:-

#include <stdio.h>
#include <string.h>

// Declaration of the
// dependent structure
struct Employee
{
int employee_id;
char name[20];
int salary;
};

// Declaration of the
// Outer structure
struct Organisation
{
char organisation_name[20];
char org_number[20];

// Dependent structure is used


// as a member inside the main
// structure for implementing
// nested structure
struct Employee emp;

ASSI.PRO.UPEKSHA CHAUDHRI 60
BZ GROW MORE INSTITUTE OF MSC(CA&IT)

};

// Driver code
int main()
{
// Structure variable
struct Organisation org;

// Print the size of organisation


// structure
printf("The size of structure organisation : %ld\n",
sizeof(org));

org.emp.employee_id = 101;
strcpy(org.emp.name, "Robert");
org.emp.salary = 400000;
strcpy(org.organisation_name,
"GeeksforGeeks");
strcpy(org.org_number, "GFG123768");

// Printing the details


printf("Organisation Name : %s\n",
org.organisation_name);
printf("Organisation Number : %s\n",

ASSI.PRO.UPEKSHA CHAUDHRI 61
BZ GROW MORE INSTITUTE OF MSC(CA&IT)

org.org_number);
printf("Employee id : %d\n",
org.emp.employee_id);
printf("Employee name : %s\n",
org.emp.name);
printf("Employee Salary : %d\n",
org.emp.salary);
}

Output:
The size of structure organisation : 68
Organisation Name : GeeksforGeeks
Organisation Number : GFG123768
Employee id : 101
Employee name : Robert
Employee Salary : 400000

ASSI.PRO.UPEKSHA CHAUDHRI 62

You might also like