[go: up one dir, main page]

0% found this document useful (0 votes)
56 views52 pages

CSE Practice Solutions

The document provides answers to 7 questions about computer science concepts. It discusses Von Neumann architecture, the fetch-execute cycle of a CPU, algorithms, the main components of a computer including the motherboard, CPU, GPU, RAM, storage, power supply and input/output devices. It defines software and the main categories of operating systems and application software. It also describes programming tools like flowcharts, hierarchy charts and pseudocode. Finally, it discusses the differences between high-level, low-level and middle-level programming languages.

Uploaded by

khasin306
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)
56 views52 pages

CSE Practice Solutions

The document provides answers to 7 questions about computer science concepts. It discusses Von Neumann architecture, the fetch-execute cycle of a CPU, algorithms, the main components of a computer including the motherboard, CPU, GPU, RAM, storage, power supply and input/output devices. It defines software and the main categories of operating systems and application software. It also describes programming tools like flowcharts, hierarchy charts and pseudocode. Finally, it discusses the differences between high-level, low-level and middle-level programming languages.

Uploaded by

khasin306
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/ 52

CSE PRACTISE QUESTION ANSWERS

QUIZ-1

01.Briefly discuss Von Neumann Architecture.

Answer:

Von Neumann architecture was first published by John von Neumann in 1945.

His computer architecture design consists of a Control Unit, Arithmetic and Logic Unit (ALU), Memory
Unit, Registers and Inputs/Outputs.

Von Neumann architecture is based on the stored-program computer concept, where instruction data
and program data are stored in the same memory. This design is still used in most computers
produced today.

1|Page
Central Processing Unit (CPU)

The Central Processing Unit (CPU) is the electronic circuit responsible for executing the instructions of
a computer program.

It is sometimes referred to as the microprocessor or processor.

The CPU contains the ALU, CU and a variety of registers.

Registers

Registers are high speed storage areas in the CPU. All data must be stored in a register before it can
be processed.

Arithmetic and Logic Unit (ALU)

The ALU allows arithmetic (add, subtract, etc ) and logic (AND, OR, NOT, etc ) operations to be carried
out.

Control Unit (CU)

The control unit controls the operation of the computer’s ALU, memory and input/output devices,
telling them how to respond to the program instructions it has just read and interpreted from the
memory unit.

The control unit also provides the timing and control signals required by other computer
components.

Memory Unit

The memory unit consists of RAM, sometimes referred to as primary or main memory. Unlike a hard
drive (secondary memory), this memory is fast and also directly accessible by the CPU.

RAM is split into partitions. Each partition consists of an address and its contents (both
in binary form).

The address will uniquely identify every location in the memory.

2|Page
Loading data from permanent memory (hard drive), into the faster and directly accessible temporary
memory (RAM), allows the CPU to operate much quicker.

https://www.computerscience.gcse.guru/theory/von-neumann-architecture

02.What are the steps associated with the execution of a program?

Answer:

A computer program is made up of sets of instructions which are encoded using the binary
numbering system. The fetch – decode – execute cycle is the order of steps that the Central
Processing Unit (CPU) uses to follow instructions.

The CPU is the brain of the computer and known as the processor. It is responsible for implementing
a sequence of commands called a program. A program takes inputs, processes them and outputs
results. CPUs are found everywhere, like in mobile phones, computer tablets and washing machines.

Control Unit – controls all parts of the computer system. It manages the four basic operations of the
Fetch Execute Cycle as follows:

• Fetch – gets the next program command from the computer’s memory
• Decode – deciphers what the program is telling the computer to do
• Execute – carries out the requested action
• Repeat
Fetch the instruction pointed
to by the instruction pointer

Add number of bytes in the instruction


to the instruction pointer

Execute Instruction

NO
Is it the halt
instruction

YES

STOP CPU

3|Page
03.What is algorithm?

Answer:

A programming algorithm is a procedure or formula used for solving a problem. It is based on


conducting a sequence of specified actions in which these actions describe how to do something, and
computer will do it exactly that way every time. An algorithm works by following a procedure, made
up of inputs. Once it has followed all the inputs, it will see a result, also known as output.

An algorithm is a step-by-step, precise, mechanical procedure designed to convert some input into a
desired output

04. What are the major components of a computer? Briefly discuss about them.

Answer:

A computer is any machine that can be programmed to carry out a set of algorithms and arithmetic
instructions.

Computers are made of two parts.

Hardware
This is the part you can see. It includes peripherals such as mice, hard drives, memory (RAM)
keyboards and other input and output devices.

Software
This consists of the part you can't touch or see physically. There are system software such as drivers
which control how a device works. For example, printer drivers allow the control of printers from
computers. And then there are user software such as browsers, media players, games and so on.

4|Page
The Seven main components that make up a typical, present-day computer include:

• A motherboard
• A Central Processing Unit (CPU)
• A Graphics Processing Unit (GPU)
• Random Access Memory (RAM)
• Power Supply
• Storage: Solid State Drive (SSD) or Hard Disk Drive (HDD)
• Input devices
• Output devices

Motherboard
All components of a computer communicate through a circuit board called the motherboard. The
mother board directly connects every other component to each other allowing said computing to
happen.

Central Processing Unit (CPU)


The CPU is often called the "brain" of a computer. The processor has a variety of functions but mainly
it (like it states) processes the computers functions.

Graphics Processing Unit (GPU)

A graphics card is a type of display adapter or video card installed within most computing devices to
display graphical data with high clarity, color, definition and overall appearance. A graphics card
provides high-quality visual display by processing and executing graphical data using advanced
graphical techniques, features and functions.

Storage
All computers need somewhere to store their data. Modern computers either use a
Hard Disk Drive (HDD) or Solid State Drive (SSD).

HDDs are made of an actual disk onto which data is stored. The disk is read by a mechanical arm.
(HDDs are cheaper than SSDs, but are slowly becoming more and more obsolete).

5|Page
SSDs have no moving parts and are faster than a hard drive, because no time is spent waiting for a
mechanical arm to find data on a physical location on the disk.

Power Supply

Helps run the power to each of your components either directly or through your motherboard.

Input devices
this includes mice, keyboards, touchscreens, joysticks, sensors and other devices that can get an input
signal to a computer.

Output devices

Output devices help us see information processed by the computer. Screens, VR headsets,
headphones, AR systems to name a few.

https://www.quora.com/What-are-the-primary-components-of-a-computer

05. What is software? What are the main categories?

Answer:

Software, instructions that tell a computer what to do. Software comprises the entire set of
programs, procedures, and routines associated with the operation of a computer system. The term
was coined to differentiate these instructions from hardware—i.e., the physical components of a
computer system. A set of instructions that directs a computer’s hardware to perform a task is called a
program, or software program.

Two main categories (for this class):

6|Page
01. Operating System (OS)
A set of programs that manages a computer’s hardware devices and controls their processes. Most
modern operating systems are capable of running multiple programs at once.

UNIX, Linux, Mac OS X, and Windows are examples.

02. Application Software


Programs that make the computer useful for the user. Application Software solves specific problems
or supply a service. Word processors, spreadsheets, databases, etc.

06.What are programming tools?

Answer:

A programming tool may be any software program or utility that aids software developers or
programmers in creating, editing, debugging, maintaining and/or performing any programming or
development-specific task. A programming tool is also known as a software development tool.

Flowcharts
A chart that consists of symbols connected by arrows. Within each symbol is a phrase presenting the
activity at that step. The shape of the symbol indicates the type of operation that is to occur.

Hierarchy Charts
A chart that shows the overall program structure. These charts describe what each part, or module,
does and how they are related. These modules intentionally omit details of how they work.

Pseudocode
An abbreviated plain English version of actual computer code. Kind of a mix between English and
code. THERE IS NO OFFICIAL SYNTAX TO PSEUDOCODE.

7|Page
07.What is the high level, low level and middle level programming languages? Discuss how
are they different from each other?

Answer:

As we know, to communicate with a person, we need a specific language, similarly to communicate


with computers, programmers also need a language is called Programming language. A programming
language is a computer language that is used by programmers (developers) to communicate
with computers. It is a set of instructions written in any specific language ( C, C++, Java, Python) to
perform a specific task.

Three Types of Programming Language:

01. Low-level programming language


Low-level language is machine-dependent (0s and 1s) programming language. The processor
runs low- level programs directly without the need of a compiler or interpreter, so the programs
written in low-level language can be run very fast.

Low-level language is further divided into two parts -

i. Machine Language

Machine language is a type of low-level programming language. It is also called as machine code
or object code. Machine language is easier to read because it is normally displayed in binary or
hexadecimal form (base 16) form. It does not require a translator to convert the programs because
computers directly understand the machine language programs.

The advantage of machine language is that it helps the programmer to execute the programs
faster than the high-level programming language.

ii. Assembly Language

Assembly language (ASM) is also a type of low-level programming language that is designed for
specific processors. It represents the set of instructions in a symbolic and human-
understandable form. It uses an assembler to convert the assembly language to machine
language.

8|Page
02. High-level programming language
High-level programming language (HLL) is designed for developing user-friendly software programs
and websites. This programming language requires a compiler or interpreter to translate the program
into machine language (execute the program).

The main advantage of a high-level language is that it is easy to read, write, and maintain.

High-level programming language includes Python, Java, JavaScript, PHP, C#, C++, Objective C,
Cobol, Perl, Pascal, LISP, FORTRAN, and Swift programming language.

A high-level language is further divided into three parts:

i. Procedural Oriented programming language

Procedural Oriented Programming (POP) language is derived from structured programming and based
upon the procedure call concept. It divides a program into small procedures called routines or
functions.

Procedural Oriented programming language is used by a software programmer to create a program


that can be accomplished by using a programming editor like IDE, Adobe Dreamweaver, or Microsoft
Visual Studio.

The advantage of POP language is that it helps programmers to easily track the program flow and code
can be reused in different parts of the program.

The advantage of POP language is that it helps programmers to easily track the program flow and code
can be reused in different parts of the program.

Example: C, FORTRAN, Basic, Pascal, etc.

ii. Object-Oriented Programming language

Object-Oriented Programming (OOP) language is based upon the objects. In this programming
language, programs are divided into small parts called objects. It is used to implement real-world

9|Page
entities like inheritance, polymorphism, abstraction etc in the program to makes the program reusable,
efficient, and easy-to-use.

The main advantage of object-oriented programming is that OOP is faster and easier to execute,
maintain, modify, as well as debug.

Example: C++, Java, Python, C#, etc.

iii. Natural language

Natural language is a part of human languages such as English, Russian, German, and Japanese. It is
used by machines to understand, manipulate, and interpret human's language. It is used by developers
to perform tasks such as translation, automatic summarization, Named Entity Recognition (NER),
relationship extraction, and topic segmentation.

The main advantage of natural language is that it helps users to ask questions in any subject and directly
respond within seconds.

Middle-level programming language

Middle-level programming language lies between the low-level programming language and high-
level programming language. It is also known as the intermediate programming language and
pseudo-language.

A middle-level programming language's advantages are that it supports the features of high-level
programming, it is a user-friendly language, and closely related to machine language and human
language.

Example: C, C++, language

https://www.javatpoint.com/programming-language

10 | P a g e
Key Differences
i. Speed

In terms of speed, programs written in low-level languages are faster than those written in
middle and high-level languages. This is because these programs do not need to be
interpreted or compiled. They interact directly with the registers and memory.

On the other hand, programs written in a high-level language are relatively slower. The
main reason for this is they written in human language. This means that the computer is
forced to translate and interpret them into human language before it executes them. All
these processes are time consuming.

The speed of the mid-level language is in between the high and low-level languages. It is
neither too high nor too low.

ii. Memory Requirement

This is another parameter that we can use to differentiate these three types of languages.
Low-level languages are very efficient in terms of memory. They consume less memory. This
is very different to high-level languages which are known for being memory-intensive. They
consume a lot of memory especially when we consider that the fact that these languages
still run on a specific runtime environment. The memory-efficiency of medium level
programming languages is not that high as compared to the ones of high-level languages.

iii. Ease of use

Low-level languages are friendly to the machines but unfriendly to the human
programmers. As a human programmer, it is quite hard to deal with binaries and
mnemonics. The fact that each instruction is designed for a specific computer architecture
makes the language more technical. In short, low-level languages are difficult to learn.

On the other hand, high-level languages are human-friendly. They consist of English
statements which can be learned and memorized with ease. This explains why they are the
most popular type of programming language.

11 | P a g e
iv. Portability

In this context, the term portability refers to the ability of a language to be used in different
computers. Low-level programming languages are less portable. This is because their
instructions are machine -dependent. This simply means that each instruction is written for
a particular machine. The codes for a particular machine cannot run in another computer
architecture.

High-level languages are machine independent. One code can be used on a different
machine and even on a different architecture without any difficulties. This means that high-
level programming languages are highly portable. You can transfer a program written in a
high-level language from one environment to another and it will still work.

v. Abstraction

In this context, abstraction refers to the relationship between the language with computer
hardware. It is minimal or even zero abstraction between low-level languages with
computer hardware. These languages interact seamlessly with the computer memory and
register.

The gap between mid-level languages and hardware is quite significant. It is bigger than
that of low-level languages but smaller than the one with high-level languages.

As expected, high-level languages have the maximum level of abstraction. This is because
they operate from the topmost level of a computer where there is minimal interaction with
hardware.

12 | P a g e
08.Discuss the differences of compiled language and interpreted language.

Answer:

Compiled Language:

A compiled language is a programming language which are generally compiled not interpreted. It is
one where the program once compiled is expressed in the instruction of the targeted machine; this
machine code is undecipherable by humans. In this language, compiled programs run faster than
interpreted programs.

Compiled languages- C, C++, C#, COBOL, etc.

EXECUTABLE
PROGRAM
TEXT EDITOR COMPILED BYTE CODE OR
TEXT FILE MACHINE CODE

OUTPUT

Interpreted Language:

An interpreted language is a programming language which are generally interpreted without


compiling a program into machine instructions. It is one where the instructions are not directly
executed by other programs. While in this language, interpreted programs can be modified while the
program is running.

Interpreted Languages- JAVA SCRIPT, PERL, PYTHON, etc.

PROGRAM ONE LINE AT A TIME


TEXT EDITOR INTERPRETED
TEXT FILE

EXECUTABLE
OUTPUT
BYTE CODE

13 | P a g e
Differences between Compiled language and interpreted language

COMPILED LANGUAGE INTERPRETED LANGUAGE


01 A compiled language is a programming An interpreted language is a programming
language whose implementations are language whose implementations execute
typically compilers and not interpreters. instructions directly and freely, without
previously compiling a program into
machine-language instructions.
02 In this language, once the program is While in this language, the instructions are
compiled it is expressed in the not directly executed by the target machine.
instructions of the target machine.
03 There are at least two steps to get from There is only one steps to get from source
source code to execution. code to execution.
04 In this language, compiled programs run While in this language, interpreted programs
faster than interpreted programs. can be modified while the program is
running.
05 In this language, compilation errors In this language, all the debugging occurs at
prevent the code from compiling. run-time.
06 The code of compiled language can be A program written in an interpreted language
executed directly by the computer’s CPU. is not compiled, it is interpreted.
07 This language delivers better This language delivers relatively slower
performance. performance.

08 Example of compiled language – C, C++, Example of Interpreted language – JavaScript,


C#, CLEO, COBOL, etc. Perl, Python, BASIC, etc.

https://www.geeksforgeeks.org/difference-between-compiled-and-interpreted-language/

09. Discuss the differences of Structured Programming and Object Oriented Programming.

Answer:

Structured programming is a logical programming method that is considered a precursor to object-


oriented programming (OOP). Structured programming facilitates program understanding and
modification and has a top-down design approach, where a system is divided into compositional
subsystems.

14 | P a g e
Object-oriented programming (OOP) is a software programming model constructed around
objects. This model compartmentalizes data into objects (data fields) and describes object contents
and behavior through the declaration of classes (methods).

Differences between Structured programming and Object-oriented programming

Structured Programming Object Oriented Programming


01 Structured programming is designed which Object oriented programming is designed which
focuses on process/logical and then data focuses on data
required for that process.

02 Structured programming follows top-down Object oriented programming follows bottom-up


approach. approach.

03 Structured programming is also known as Object oriented programming supports inheritance,


modular programming and a subset of encapsulation, abstraction, polymorphisms, etc.
procedural programming language.

04 In structured programming, programs are In Object oriented programming, programs are


divided into small self-contained functions. divided into small entities called objects.

05 Structured programming is less secured as Object oriented programming is more secure as


there is no way of data hiding. having data hiding feature.

06 Structured programming can solve moderately Object oriented programs can solve any complex
complex programs. programs.

07 Structured programming provides less Object oriented programming provides more


reusability, more function dependent. reusability, less function dependency.

08 Less abstraction and less flexibility. More abstraction and more flexibility.

15 | P a g e
10.What is an identifier?

Answer:

Identifiers are names for entities in a C program, such as variables, arrays, functions, structures,
unions and labels. An identifier can be composed only of uppercase, lowercase letters, underscore
and digits, but should start only with an alphabet or an underscore.
Rules of identifier: http://aboutc.weebly.com/identifiers.html

11.What is a variable?

Answer:

Variables are used to store information to be referenced and manipulated in a computer program.
They also provide a way of labeling data with a descriptive name, so our programs can be understood
more clearly by the reader and ourselves. It is helpful to think of variables as containers that hold
information. Their sole purpose is to label and store data in memory. This data can then be used
throughout your program.

https://launchschool.com/books/ruby/read/variables

12.What is a constant? Demonstrate different ways of using constants in C programming.

Answer:

As the name suggests the name constants is given to such variables or values in C/C++ programming
language which cannot be modified once they are defined. They are fixed values in a program. There
can be any types of constants like integer, float, octal, hexadecimal, character constants etc. Every
constant has some range.

In C/C++ program we can define constants in two ways:

01. Using “#define “ preprocessor directive: This directive is used to declare an alias name for existing
variable or any value. We can use this to declare a constant

#define identifierName value

16 | P a g e
02. Using a “const” keyword: Using const keyword to define constants is as simple as defining variables,
the difference is you will have to precede the definition with a const keyword.

Const int var=5

Below program shows how to use const to declare constants of different data types:

#include <stdio.h>
int main()

{
// int constant
const int int Val = 10;

// Real constant
const float float Val = 4.14;

// char constant
const char char Val = 'A';

// string constant
const char string Val[10] = "ABC";

printf("Integer constant:%d \n", int Val );

printf("Floating point constant: %.2f\n", float Val );

printf("Character constant: %c\n", char Val );

printf("String constant: %s\n", string Val);

return 0;
}

17 | P a g e
13.What are the most used data types in C programming?

Answer:

Each variable in C has an associated data type. Each data type requires different amounts of memory
and has some specific operations which can be performed over it.

The most use data types in C programming in given below:

Char: The most basic data type in C. It stores a single character and requires a single byte of
memory in almost all compilers.

Int : As the name suggests, an int variable is used to store an integer.

Float : It is used to store decimal numbers (numbers with floating point value) with single
precision.

Double : It is used to store decimal numbers (numbers with floating point value) with double
precision.

FUNCTIONS
14.Write a program demonstrating the use of user defined functions.

Answer:

C function can be classified into two categories, namely


(i) library functions and (ii) user-defined function.

A user-defined function (UDF) is a common fixture in programming languages, and the main tool
of programmers for creating applications with reusable code. Since programs are mostly
composed of code that comes from the programmer, or in this case the user, most of it is
composed of user-defined functions occasionally punctuated by built-in functions.

main() is an example of user-defined functions.

18 | P a g e
Here is an example to add two integers. To perform this task, we have created an user-
defined addNumbers()

#include <stdio.h>
int addNumbers(int a, int b); // function prototype

int main()
{
int n1,n2,sum;

printf("Enters two numbers: ");


scanf("%d %d",&n1,&n2);

sum = addNumbers(n1, n2); // function call


printf("sum = %d",sum);

return 0;
}

int addNumbers(int a, int b) // function definition


{
int result;
result = a+b;
return result; // return statement
}

15.What are formal parameters and actual parameters? Discuss by giving examples.

Answer:

Actual Parameters:

The parameters used in the function call are called actual parameters. These are the actual values that
are passed to the function. The actual parameters may be in the form of constant values or variables.
The data types of actual parameters must match with the corresponding data types of formal
parameters (variables) in the function definition

19 | P a g e
Formal Parameters:

The parameters used in the header of function definition are called formal parameters of the function.
These parameters are used to receive values from the calling function.

Example:

1. int sum(int a, int b) //Statement 1


2. {
3. return a+b;
4. }
5. int main()
6. {
7. int x=10,y=20;
8. int s = sum(x,y); //Statement 2
9. return 0;
10. )

In Statement 1, the variables a and b are called FORMAL PARAMETERS.


In Statement 2 the arguments x and y are called ACTUAL PARAMETERS.

The Major Difference Between Actual Parameters and Formal Parameters

Former Parameters Actual Parameters


01 The Actual parameters are the values The Formal Parameters are the variables defined
that are passed to the function when it is by the function that receives values when the
invoked. function is called.
02 The actual parameters are passed by the The formal parameters are in the called function.
calling function.
03 In actual parameters, there is no In formal parameters, the data types of the
mentioning of data types. Only the value receiving values should be included.
is mentioned.

16.Discuss global scope and local scope.

ANSWER:

A scope in any programming is a region of the program where a defined variable can have its
existence and beyond that variable it cannot be accessed.

20 | P a g e
There are three places where variables can be declared in C programming language –

• Inside a function or a block which is called local variables.


• Outside of all functions which is called global variables.
• In the definition of function parameters which are called formal parameters.

Local Variables
Variables that are declared inside a function or block are called local variables. They can be used only
by statements that are inside that function or block of code. Local variables are not known to
functions outside their own. The following example shows how local variables are used. Here all the
variables a, b, and c are local to main() function.

#include <stdio.h>

int main () {

/* local variable declaration */


int a, b;
int c;

/* actual initialization */
a = 10;
b = 20;
c = a + b;

printf ("value of a = %d, b = %d and c = %d\n", a, b, c);

return 0;
}

Global Variables
Global variables are defined outside a function, usually on top of the program. Global variables hold
their values throughout the lifetime of your program and they can be accessed inside any of the
functions defined for the program.

21 | P a g e
A global variable can be accessed by any function. That is, a global variable is available for use
throughout your entire program after its declaration. The following program show how global variables
are used in a program.
#include <stdio.h>

/* global variable declaration */


int g;

int main ()
{

/* local variable declaration */


int a, b;

/* actual initialization */
a = 10;
b = 20;
g = a + b;

printf ("value of a = %d, b = %d and g = %d\n", a, b, g);

return 0;
}

https://www.tutorialspoint.com/cprogramming/c_scope_rules.htm

RECURSION
17.What is recursion?

Answer:

Recursion means defining a problem in terms of itself. This can be a very powerful tool in writing
algorithms. Recursion comes directly from Mathematics, where there are many examples of
expressions written in terms of themselves.

Recursion is the process of defining a problem (or the solution to a problem) in terms of (a simpler
version of) itself.

18.What is recursive function? What are base case and general case? Briefly discuss.

Answer:

A recursive function is a function that calls itself during its execution. The process may repeat several
times, outputting the result and the end of each iteration.

22 | P a g e
Base Case:
A proper recursive function must always have a base case: The base case is a way to
return without making a recursive call. In other words, it is the mechanism that stops this process of
ever more recursive calls and an ever growing stack of function calls waiting on the return of
other function calls.

General Case:
The general case is the place where the recursive calls are made repeatedly. Here the
base case is needed to stop the repeated calls.

19.What is stack? What are push and pop operations?

Answer:

Stack is a linear data structure which follows a particular order in which the operations are performed.
The order may be LIFO (Last In First Out) or FILO (First In Last Out). There are many real-life
examples of a stack. Consider an example of plates stacked over one another in the canteen.

Push:

Push operation refers to inserting an element in the stack. Since there’s only one position at which
the new element can be inserted — Top of the stack, the new element is inserted at the top of the
stack.

Pop:

Pop operation refers to the removal of an element. Again, since we only have access to the element
at the top of the stack, there’s only one element that we can remove. We just remove the top of the
stack.

https://afteracademy.com/blog/stack-and-its-basic-operations

23 | P a g e
20.Discuss “goto” statements.

Answer:

The goto statement allows us to transfer control of the program to the specified label. The label is an
identifier. When the goto statement is encountered, the control of the program jumps to label: and
starts executing the code.

Example:

#include <stdio.h>

int main(void)

int n , a = 0, product = 1 ;

printf("Enter a number : ");

scanf("%d", &n);

a = n ;

Label1:

product = product * a ;

a = a - 1;

if(a == 0)

goto Label2;

else

goto Label1;

Label2:

printf("Factorial of %d is %d\n", n,

product);

return 0;

24 | P a g e
QUIZ- 02 TOPICS

LOOPS
The looping can be defined as repeating the same process multiple times until a specific condition satisfies. There
are three types of loops used in the C language.

The looping simplifies the complex problems into the easy ones. It enables us to alter the flow of the program
so that instead of writing the same code again and again, we can repeat the same code for a finite number of
times. For example, if we need to print the first 10 natural numbers then, instead of using the printf statement
10 times, we can print inside a loop which runs up to 10 iterations.

ADVANTAGE WITH LOOPING STATEMENT

• Reduce length of Code


• Take less memory space.
• Burden on the developer is reducing.
• Time consuming process to execute the program is reduced.

TYPES OF LOOPS:

1. do while
2. while
3. for

1. DO WHILE LOOP:
The do-while loop continues until a given condition satisfies. It is also called post tested loop. It is used when it
is necessary to execute the loop at least once (mostly menu driven programs).

The syntax of do-while loop in c language is given below:

Do
{
//code to be executed
}
while(condition);

The statement is first executed. If the loop repetition condition is true, the statement

25 | P a g e
is repeated. Otherwise, the loop is exited. In this type of loops the test condition is tested or evaluated
at the end of loop body. Therefore, the loop body will execute at least once, irrespective of whether the
test condition is true or false. do – while loop is exit controlled loop or, post-test loop.

2. WHILE LOOP:
The while loop in c is to be used in the scenario where we don't know the number of iterations in
advance. The block of statements is executed in the while loop until the condition specified in the
while loop is satisfied. It is also called a pre-tested loop.

The syntax of while loop in c language is given below:

while(condition)
{
//code to be executed
}

In while Loop, at first, the loop condition is checked. If condition is true then control goes inside the
loop body. Otherwise goes outside the body. while loop repeats in clock wise direction. In this type of
loop, the test condition is tested before entering the loop body. It can be called entry-controlled loop
or pre-test loop.

3. FOR LOOP:
The for loop is used in the case where we need to execute some part of the code until the given
condition is satisfied. The for loop is also called as a pre-tested loop. It is better to use for loop if
the number of iterations is known in advance.

The syntax of for loop in c language is given below:

for(initialization; condition; incr/decr)


{
//code to be executed
}
The initialization expression set the initial value of the loop control variable. The loop repetition
condition tests the value of the loop control variable. The update expression updates the loop control
variable. In this type of loop, the test condition is tested before entering the loop body. It can be called
entry-controlled loop or pre-test loop.

26 | P a g e
DIFFERENCE BETWEEN FOR AND WHILE LOOP IN C

FOR LOOP WHILE LOOP

Initialization may be either in loop Initialization is always outside the loop.


statement or outside the loop.

Once the statement(s) is executed then Increment can be done before or after the
after increment is done. execution of the statement(s).

It is normally used when the number of It is normally used when the number of
iterations is known. iterations is unknown.

Condition is a relational expression. Condition may be expression or non-zero


value.

It is used when initialization and increment It is used for complex initialization.


is simple.

For is entry controlled loop. While is also entry controlled loop.

for (init ; condition ; iteration ) while ( condition )


{ {
statement(s); statement(s);
} }

27 | P a g e
DIFFERENCE BETWEEN FOR AND DO-WHILE LOOP IN C

FOR LOOP DO-WHILE LOOP

Statement(s) is executed once the condition Condition is checked after the statement(s)
is checked. is executed.

It might be that statement(s) gets executed Statement(s) is executed at least once.


zero times.

For the single statement, bracket is not Brackets are always compulsory.
compulsory.

Initialization may be outside or in condition Initialization may be outside or within the


box. loop.

for loop is entry-controlled loop. do-while is exit controlled loop.

for ( init ; condition ; iteration ) do


{ {
statement (s); statement(s);
} }
while (condition);

28 | P a g e
DIFFERENCE BETWEEN WHILE AND DO-WHILE LOOP IN C

WHILE DO-WHILE

Condition is checked first then statement(s) Statement(s) is executed at least once,


is executed. thereafter condition is checked.

It might occur statement(s) is executed zero At least once the statement(s) is executed.
times, If condition is false.

No semicolon at the end of while. Semicolon at the end of while.


while(condition) while(condition);

If there is a single statement, brackets are Brackets are always required.


not required.

Variable in condition is initialized before the variable may be initialized before or within
execution of loop. the loop.

while loop is entry controlled loop. do-while loop is exit controlled loop.

while(condition) do
{ {
statement(s); statement(s);
} }
while(condition);

29 | P a g e
DIFFERENCE BETWEEN FOR, WHILE AND DO WHILE LOOP

Sr. FOR LOOP WHILE LOOP DO WHILE LOOP


No

1. Syntax: For(initialization; Syntax: While(condition), { . Syntax: Do { . Statements; }


condition;updating), { . Statements; . } While(condition);
Statements; }

2. It is known as entry controlled It is known as entry It is known as exit controlled


loop controlled loop. loop.

3. If the condition is not true first If the condition is not true Even if the condition is not
time than control will never first time than control will true for the first time the
enter in a loop never enter in a loop. control will enter in a loop.

4. There is no semicolon; after There is no semicolon; after There is semicolon; after the
the condition in the syntax of the condition in the syntax condition in the syntax of the
the for loop. of the while loop. do while loop.

5. Initialization and updating is Initialization and updating is Initialization and updating is


the part of the syntax. not the part of the syntax. not the part of the syntax

30 | P a g e
NESTED LOOP:

When a loop written inside the body of another loop then, it is known as nesting of loop. Any type of
loop can be nested in any type such as while, do while, for.
Any number of loops can be defined inside another loop, i.e., there is no restriction for defining any
number of loops. The nesting level can be defined at n times. One can define any type of loop inside
another loop; for example, one can define 'while' loop inside a 'for' loop.

Syntax of Nested loop

Outer_loop
{
Inner_loop
{
// inner loop statements.
}
// outer loop statements.
}

ARREY
Array is the collection of similar data types or collection of similar entity stored in contiguous memory
location. Array of character is a string. Each data item of an array is called an element. And each element
is unique and located in separated memory location. Each of elements of an array share a variable but
each element having different index no. known as subscript.

An array can be a single dimensional or multi-dimensional and number of subscripts determines its
dimension. And number of subscripts is always starts with zero. Array variable can store more than
one value at a time where other variable can store one value at a time.

Declaration of an array is done in the following manner.

Its syntax is

Data type array name [size];

int v[100];

int marks[5];

31 | P a g e
The declaration of an array tells the compiler that, the data type, name of the array, size of the array
and for each element it occupies memory space. Like for int data type, it occupies 2 bytes for each
element and for float it occupies 4 bytes for each element etc. The size of the array operates the number
of elements that can be stored in an array.

int arr[7];

0 1 2 3 4 5 6

TWO-DIMENSIONAL ARRAY

Two-dimensional array is known as matrix. The array declaration in both the array i.e.in single
dimensional array single subscript is used and in two-dimensional array two subscripts are used. Its
syntax: Data-type array name[row][column];

We can say 2-d array is a collection of 1-D array placed one below the other. Total no. of elements in
2-D array is calculated as row*column.

int arr [3] [4];

0,0 0,1 0,2 0,3


1,0 1,1 1,2 1,3
2,0 2,1 2,2 2,3

DIFFERENCES BETWEEN 1D ARRAY & 2D ARRAY


1. One Dimensional (1D) array is an array which is represented either in one row or in one
column. On the other hand, Two-Dimensional (2D) array is a fixed-length, homogeneous data
type, row and column-based data structure which is used to store similar data type element in
a row and column-based structure.
2. The one-dimensional arrays are known as vectors and the two-dimensional array is referred to
as a matrix or a table.
3. A one-dimensional array has one subscript but a two-dimensional array has two subscripts,
one denotes the row and another denotes the column.
4. We can say 2-d array is a collection of 1-D array placed one below the other.
5. The elements number of a 1D array is equal to its column number or row number only but in
2D’s case, elements number will be the equal of the multiplication of column numbers and row
numbers (row*column).
6. 1D array’s syntax: Data type array name [size];
2D array’s syntax: Data-type array name[row][column];

32 | P a g e
Header File
A header file is a file with extension .h which contains C function declarations to be shared between several source files.
Header files contain the set of pre-defined standard library functions that can be included in C programs. But, to use
these various library functions, the appropriate header files need to be included.

There are two types of header files defined in a program:

o System defined header file: The header file which is predefined is known as a system defined
header file.
o User-defined header file: The header file which is defined by the user is known as a user-
defined header file.

Syntax is as below.

#include <file>

Or,

#include "file"

The first kind of file inclusion is implemented for including system-oriented header files. This technique
(with angular braces) searches for the file-name in the standard list of system directories or within the
compiler's directory of header files.

Whereas, the second kind of header file is used for user-defined header files or other external files for
the program. This technique is used to search for the file(s) within the directory that contains the current
file.

Example:

Program.c file

#include<stdio.h>

#include "myheader.h"

int main(void)

33 | P a g e
int n1, n2;

printf("Enter number : ");

scanf("%d", &n1);

n2 = square(n1);

printf("Square of %d is %d\n", n1, n2);

return 0;

myheader.h file

int square(int n)

return n*n;

34 | P a g e
Structure
Structure in c is a user-defined data type that enables us to store the collection of different data types. Each
element of a structure is called a member. Structures can simulate the use of classes and templates as it can
store various information.

The “struct” keyword is used to define the structure.

struct structure_name
{
data_type member1;
data_type member2;
.
.
data_type memeberN;
};

In C, there are cases where we need to store multiple attributes of an entity. It is not necessary that an entity has
all the information of one type only. It can have different attributes of different data types. For example, an
entity Student may have its name (string), roll number (int), marks (float). To store such type of information
regarding an entity student, we can follow this approach. We can use a special data structure to store the
collection of different data types.
For example,
struct employee
{
int id;
char name[20];
float salary;
};

Declaring structure variables

A structure variable can either be declared with structure declaration or as a separate declaration like
basic types.

35 | P a g e
#include<stdio.h> #include<stdio.h>
struct studentinfo struct studentinfo
{ {
int id; int id;
int theorymarks[5]; int theorymarks[5];
int labmarks[4]; int labmarks[4];
double gpa; double gpa;
}; }std1, std2;
int main(void) int main(void)
{ {
struct studentinfo std1, std2; // operations
// more operations return 0;
return 0; }
}

Example of array of structure:

#include<stdio.h>
struct student
{
int id;
double individual_grade[2]; // two courses only
double credit[2]; // two courses only
double gpa;
};
int main(void)
{
int n , i , j;
double val = 0, total_credit = 0;
printf("How many students ? : ");
scanf("%d", &n);
struct student std[n];
printf("\nFor each student, enter information: \n");
for(i=0; i<n ; i=i+1)
36 | P a g e
{
val = 0, total_credit = 0;
printf("\nFor Student no %d,\nEnter ID : ", i+1);
scanf("%d", &std[i].id);
printf("Enter marks and credit hour of each subject : \n");
for(j=0; j<2; j=j+1)
{
printf("Course No %d : \n", j+1);
printf("Enter marks : ");
scanf("%lf", &std[i].individual_grade[j]);
printf("Enter credit hour : ");
scanf("%lf", &std[i].credit[j]);
val = val + (std[i].individual_grade[j] * std[i].credit[j]);
total_credit = total_credit + std[i].credit[j];
}
std[i].gpa = val / total_credit;
}
printf("\n\nStudent IDs and GPAs : \n");
for(i=0; i<n ; i=i+1)
{
printf("Student ID %d\t GPA %lf\n", std[i].id, std[i].gpa);
}
return 0;
}

37 | P a g e
Complexity Analysis
The term algorithm complexity measures how many steps are required by the algorithm to solve the given
problem. It evaluates the order of count of operations executed by an algorithm as a function of input data size.

A data structure is a scheme of arranging data in computer memory for efficient manipulation, together with the
operations (algorithms) on the data.

An algorithm is a finite, unambiguous sequence of steps for solving a problem in a finite amount of time and
space. A program is an implementation of an algorithm in a particular programming language. The efficient
implementation of algorithms is important in computing, and this depends on suitable data structures.

MOTIVATIONS FOR COMPLEXITY ANALYSIS


There are often many different algorithms to solve a particular problem. Thus, it makes sense to develop
techniques that allow us to

• Compare different algorithms with respect to their “efficiency”


• choose the most efficient algorithm for a problem.
• The efficiency of any algorithmic solution to a problem is a measure of the: Ø
o Time efficiency: the time it takes to execute.
o Space efficiency: the space (primary or secondary memory) it uses.

We will focus on an algorithm’s efficiency with respect to time. Often time efficiency is more important than
space complexity. More and more space available but time is still a problem.

BEST, AVERAGE, AND WORST-CASE COMPLEXITIES


There are three cases in determining the efficiency of an algorithm:

1. Best-case complexity: B(n), the minimum time needed to execute an algorithm for an input of size n
2. Average-case complexity: A(n), the average time needed to execute an algorithm for an input of size n
3. Worst-case complexity: T(n), the maximum time needed to execute an algorithm for an input of size n

We are usually interested in the worst-case complexity: what are the most operations that might be performed
for a given problem size. – Easier to compute – Usually close to the actual running time – Crucial to real-time
systems (e. g. air-traffic control) • Best case depends on the input • Average case is often difficult to compute

Example:

• Linear Search Complexity:


o Best Case: Item found at the beginning: One comparison.
o Worst Case: Item found at the end or not found: n comparisons.
o Average Case: Item may be found at index 0, or 1, or 2, . . . or n – 1. Average number of
comparisons is: (1 + 2 +. . . + n) / n = (n+1) / 2

38 | P a g e
Asymptotic Notation
The efficiency of an algorithm depends on the amount of time, storage and other resources required to execute
the algorithm. Counting the exact number of basic operations can become difficult if the size of a program gets
huge. This "approximate" measure of efficiency is called asymptotic complexity.
The asymptotic complexity measure does not give the exact number of operations of an algorithm, but it gives
an upper bound for that number. The efficiency is measured with the help of asymptotic notations. An algorithm
may not have the same performance for different types of inputs. With the increase in the input size, the
performance will change. The study of change in performance of the algorithm with the change in the order of
the input size is defined as asymptotic analysis.
To simplify analysis by getting rid of unneeded information (like “rounding” 1,000,001≈1,000,000). We want to
say in a formal way 3n2 ≈ n2.
For example: In bubble sort, when the data structure is already sorted, the time taken by the algorithm is linear
i.e., the best case. But, when the data structure is in reverse condition, the algorithm takes the maximum time
to sort the elements i.e., the worst case. When the data structure is neither sorted nor in reverse order, average
time is needed. These durations are denoted using asymptotic notations.
There are mainly three asymptotic notations:

• Big-O notation
• Omega notation
• Theta notation

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


Big-O notation represents the upper bound of the running time of an algorithm. Thus, it gives the worst-case
complexity of an algorithm.
2. 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.
3. 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.

39 | P a g e
Linear Search Binary Search
Linear search is the simplest search algorithm and often called sequential search. In this type of searching, we
simply traverse the list completely and match each element of the list with the item whose location is to be found.
If the match found then location of the item is returned otherwise the algorithm return NULL. Its average time
complexity is O(n).

Linear search is mostly used to search an unordered list in which the items are not sorted. The algorithm of linear
search is given as follows.

Algorithm:

o LINEAR_SEARCH (A, N, VAL)


o Step 1: [INITIALIZE] SET POS = -1
o Step 2: [INITIALIZE] SET I = 1
o Step 3: Repeat Step 4 while I<=N
o Step 4: IF A[I] = VAL
SET POS = I
PRINT POS
Go to Step 6
[END OF IF]
SET I = I + 1
[END OF LOOP]
o Step 5: IF POS = -1
PRINT " VALUE IS NOT PRESENTIN THE ARRAY "
[END OF IF]
o Step 6: EXIT

40 | P a g e
Binary Search
Binary search is the search technique which works efficiently on the sorted lists. Hence, in order to search an
element into some list by using binary search technique, we must ensure that the list is sorted.

Binary search follows divide and conquer approach in which, the list is divided into two halves and the item is
compared with the middle element of the list. If the match is found then, the location of middle element is
returned otherwise, we search into either of the halves depending upon the result produced through the match.

Binary search algorithm is given below:

Algorithm:

o Step 1: [INITIALIZE] SET BEG = lower_bound


END = upper_bound, POS = - 1
o Step 2: Repeat Steps 3 and 4 while BEG <=END
o Step 3: SET MID = (BEG + END)/2
o Step 4: IF A[MID] = VAL
SET POS = MID
PRINT POS
Go to Step 6
ELSE IF A[MID] > VAL
SET END = MID - 1
ELSE
SET BEG = MID + 1
[END OF IF]
[END OF LOOP]
o Step 5: IF POS = -1
PRINT "VALUE IS NOT PRESENT IN THE ARRAY"
[END OF IF]
o Step 6: EXIT

41 | P a g e
Linear Search vs Binary Search
• A linear search scans one item at a time, without jumping to any item.
1. The worst-case complexity is O(n), sometimes known an O(n) search
2. Time taken to search elements keep increasing as the number of elements are
increased.
• A binary search however, cut down your search to half as soon as you find middle of
a sorted list.
1. The middle element is looked to check if it is greater than or less than the value to
be searched.
2. Accordingly, search is done to either half of the given list

• Input data needs to be sorted in Binary Search and not in Linear Search
• Linear search does the sequential access whereas Binary search access data
randomly.
• Time complexity of linear search -O(n), Binary search has time complexity O(log n).
• Linear search performs equality comparisons and Binary search performs ordering
comparisons

42 | P a g e
QUIZ- 03 TOPICS

Pointer
Pointer variables are special variables that are used to store address rather than values. A pointer is a variable
whose value is the address of another variable, i.e., direct address of the memory location. Like any variable or
constant, one must declare a pointer before using it to store any variable address.

Pointer Syntax: type *var-name

Here, type is the pointer's base type; it must be a valid C data type and var name is the name of the pointer
variable. The asterisk * used to declare a pointer is the same asterisk used for multiplication. However, in this
statement the asterisk is being used to designate a variable as a pointer. Some of the valid pointer declarations
are as the following.

int *ip; /* pointer to an integer */


double *dp; /* pointer to a double */
float *fp; /* pointer to a float */

char *ch; /* pointer to a character */

The actual data type of the value of all pointers, whether integer, float, character, or otherwise, is the same, a
long hexadecimal number that represents a memory address. The only difference between pointers of different
data types is the data type of the variable or constant that the pointer points to. Unless the type of address the
pointer is pointing to is mentioned, compiler cannot know how to use that pointer; hence, the original data
type should be mentioned.

43 | P a g e
Dynamic Memory Allocation
C language requires the numbers of elements in an array to be specified at compile time. But we may
not always be able to do so. Our initial judgement of size, if it is wrong, may cause failure of the program
or wastage of memory space. Many languages permit a programmer to specify an array’s size at run
time. Such languages have the ability to calculate and assign, during execution, the memory space
required by the variables in a program. The process of allocating memory at run time is known as
dynamic memory allocation.

Although C does not inherently have this facility, there are four library routines known as “memory
management functions” that can be used for allocating and freeing memory during program execution.
They are listed in the following table. These functions help us build complex application programs that
use the available memory intelligently.

FUNCTION TASK

malloc Allocates request size of bytes and returns a pointer to the first byte of the allocated space.

Allocates space for an array of elements, initializes them to zero and then returns a pointer to
calloc
the memory.

free Frees previously allocated space.

realloc Modifies the size of previously allocated space.

• Malloc:
A block of memory may be allocated using the function malloc. The malloc function reserves a block of
memory of specified size and returns a pointer of type void. This means that we can assign it to any
type of pointer. It takes the following form:
ptr = (cast-type *) malloc(byte-size);

ptr is a pointer of type cast-type. The malloc returns a pointer (of cast-type) to an area of memory with
size byte-size.

Example:
x = (int *) malloc (100 *sizeof(int));

On successful execution of this statement, a memory space equivalent to “100 times the size of int”
bytes are reserved and the address of the first byte of the memory allocated is assigned to the pointer
x of type int.

44 | P a g e
• Calloc:
calloc is another memory allocation function that is normally used for requesting memory space at run
time for storing derived data types such as arrays and structures. While malloc allocates a single block
of storage space, calloc allocates multiple blocks of storage, each of the same size, and then sets all
bytes to zero. The general form of calloc is:
ptr = (cast-type *) calloc (n, elem-size);

The above statement allocates contiguous space for n blocks, each of size elem-size bytes. All bytes
are initialized to zero and a pointer to the first byte of the allocated region is returned. If there is not
enough space, a NULL pointer is returned.

• Free
Compile time storage of a variable is allocated and released by the system in accordance with its storage
class. With the dynamic runtime allocation, it is our responsibility to release the space when it is not
required. The release of storage space becomes important when the storage is limited. When we no
longer need the data we stored in a block of memory, and we do not intend to use that block for storing
any other information, we may release that block of memory for future use, using the free function:
free (ptr);

ptr is a pointer to a memory block, which has already been created by malloc or calloc. Use of an
invalid pointer in the call may create problems and cause system-crash. We should keep in mind that it
is not the pointer that is being released but rather what it points to.

• Realloc
It is likely that we discover later, the previously allocated memory is not sufficient and we need
additional space for more elements. It is also possible that the memory allocated is much larger than
necessary and we want to reduce it. In both the cases, we can change the memory size already allocated
with the help of the function realloc. This process is called the reallocation of memory. For example, if
the original allocation is done by the statement

ptr = malloc(size);

45 | P a g e
then, reallocation of space may be done by the statement

ptr = realloc(ptr, newsize);

This function allocates a new memory space of size newsize to the pointer variable ptr and returns
newsize may be larger or smaller than the size. Remember, the new memory block ay or may not begin
at the same place as the old one. In case, it is not able to find additional space in the same region, it
will create the same in an entirely new region and move the contents of the old block into the new
block. The function guarantees that the old data will remain intact. If the function is unsuccessful in
locating additional space, it returns a NULL pointer and the original block is freed (lost). This implies
that it is necessary to test the success of the operation before proceeding further.

46 | P a g e
Link List
A linked list is a linear collection of homogeneous data elements, called nodes, where
linear order is maintained by means of links or pointers.

Each node has two parts:

1. The first part contains the data (information of the element) and
2. The second part contains the address of the next node (link /next pointer field) in
the list.
Data part of the link can be an integer, a character, a String or an object of any kind.

Linked list

• Linear collection of self-referential structures, called nodes, connected by pointer


links.
• Accessed via a pointer to the first node of the list.
• Subsequent nodes are accessed via the link-pointer member stored in each node.
47 | P a g e
• Link pointer in the last node is set to null to mark the end of list.
• Data stored dynamically
• each node is created as necessary.
• Length of a list can increase or decrease.
• Becomes full only when the system has insufficient memory to satisfy dynamic
storage allocation requests

Differences between link list and array:

1. Size:
Since data can only be stored in contiguous blocks of memory in an array, its
size cannot be altered at runtime due to the risk of overwriting other data.
However, in a linked list, each node points to the next one such that data can
exist at scattered (non-contiguous) addresses; this allows for a dynamic size
that can change at runtime.
2. Memory allocation:
For arrays at compile time and at runtime for linked lists. but, a dynamically
allocated array also allocates memory at runtime.
3. Memory efficiency:
For the same number of elements, linked lists use more memory as a reference
to the next node is also stored along with the data. However, size flexibility in
linked lists may make them use less memory overall; this is useful when there
is uncertainty about size or there are large variations in the size of data
elements; memory equivalent to the upper limit on the size has to be allocated
(even if not all of it is being used) while using arrays, whereas linked lists can
increase their sizes step-by-step proportionately to the amount of data.

4. Execution time:
Any element in an array can be directly accessed with its index; however in the
case of a linked list, all the previous elements must be traversed to reach any
element. Also, better cache locality in arrays (due to contiguous memory
allocation) can significantly improve performance. As a result, some operations

48 | P a g e
(such as modifying a certain element) are faster in arrays, while some others
(such as inserting/deleting an element in the data) are faster in linked lists.

Types of linked lists


1. Singly linked list
2. Circular, singly linked list
3. Doubly linked list
4. Circular, doubly linked list

Singly link list:


It begins with a pointer to the first node and it terminates with a null pointer. It only
traversed in one direction.
Singly linked list operations

Insertion:
• Insertion of a node at the front
• Insertion of a node at any position in the list
• Insertion of a node at the end
Deletion:
• Deletion at front
• Deletion at any position
• Deletion at end
Display:

• Displaying/Traversing the elements of a list

49 | P a g e
❑ INSERTING A NODE AT THE BEGINNING

Algorithm:

1.Create a new node.


2.if (header = = NULL)
3. header = new;
4.else
5.{
6. new -> link = header;
7. header = new;
8.}

❑ INSERTING A NODE AT THE END

Algorithm:

1. new=malloc(sizeof(struct node));
2. ptr = header;
3. while(ptr -> link!= NULL)
4. ptr = ptr -> link;
5. ptr -> link = new;

❑ INSERTING A NODE AT THE GIVEN POSITION

Algorithm: position:3

1. new=malloc(sizeof(struct node));
2. ptr = header;
3. for(i=1;i < pos-1;i++)
4. ptr = ptr -> link;
5. new -> link = ptr -> link;
6. ptr -> link = new;

50 | P a g e
❑ DELETING NODE AT THE BEGINNING
Algorithm:
1. if (header = = NULL)
2. print “List is Empty”;
3. else
4. {
5. ptr = header;
6. header = header -> link;
7. free(ptr);
8. }

❑ DELETING NODE AT THE END


Algorithm:
1. ptr = header;
2. while(ptr -> link != NULL)
3. ptr1=ptr;
4. ptr = ptr -> link;
5. ptr1 -> link = NULL;
6. free(ptr);

❑ DELETING NODE AT THE GIVEN POSITION


Algorithm:
1. ptr = header ;
2. for(i=1;i<pos-1;i++)
3. ptr = ptr -> link;
4. ptr1 = ptr -> link;
5. ptr -> link = ptr1-> link;
6. free(ptr1);

51 | P a g e
❑ TRAVERSING AN ELEMENTS OF A LIST
Algorithm:
1. if(header = = NULL)
2. print “List is empty”;
3. else
4. for (ptr = header ; ptr != NULL ; ptr = ptr -> link)
5. print “ptr->data”;

52 | P a g e

You might also like