CSE Practice Solutions
CSE Practice Solutions
QUIZ-1
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.
Registers
Registers are high speed storage areas in the CPU. All data must be stored in a register before it can
be processed.
The ALU allows arithmetic (add, subtract, etc ) and logic (AND, OR, NOT, etc ) operations to be carried
out.
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).
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
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
Execute Instruction
NO
Is it the halt
instruction
YES
STOP CPU
3|Page
03.What is algorithm?
Answer:
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.
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.
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
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.
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.
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:
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.
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.
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.
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.
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.
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 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.
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.
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.
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.
EXECUTABLE
PROGRAM
TEXT EDITOR COMPILED BYTE CODE OR
TEXT FILE MACHINE CODE
OUTPUT
Interpreted Language:
EXECUTABLE
OUTPUT
BYTE CODE
13 | P a g e
Differences between Compiled language and interpreted language
https://www.geeksforgeeks.org/difference-between-compiled-and-interpreted-language/
09. Discuss the differences of Structured Programming and Object Oriented Programming.
Answer:
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).
06 Structured programming can solve moderately Object oriented programs can solve any complex
complex programs. programs.
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
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.
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
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.
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";
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.
Char: The most basic data type in C. It stores a single character and requires a single byte of
memory in almost all compilers.
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:
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.
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;
return 0;
}
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:
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 –
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 () {
/* actual initialization */
a = 10;
b = 20;
c = a + b;
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>
int main ()
{
/* actual initialization */
a = 10;
b = 20;
g = a + b;
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.
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 ;
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.
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).
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.
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.
26 | P a g e
DIFFERENCE BETWEEN FOR AND WHILE LOOP IN C
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.
27 | P a g e
DIFFERENCE BETWEEN FOR AND DO-WHILE LOOP IN C
Statement(s) is executed once the condition Condition is checked after the statement(s)
is checked. is executed.
For the single statement, bracket is not Brackets are always compulsory.
compulsory.
28 | P a g e
DIFFERENCE BETWEEN WHILE AND DO-WHILE LOOP IN C
WHILE DO-WHILE
It might occur statement(s) is executed zero At least once the statement(s) is executed.
times, If condition is false.
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
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.
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.
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.
Its syntax is
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.
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.
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;
scanf("%d", &n1);
n2 = square(n1);
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.
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;
};
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; }
}
#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.
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.
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:
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
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:
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.
Algorithm:
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.
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.
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.
• 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
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.
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
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.
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:
49 | P a g e
❑ INSERTING A NODE AT THE BEGINNING
Algorithm:
Algorithm:
1. new=malloc(sizeof(struct node));
2. ptr = header;
3. while(ptr -> link!= NULL)
4. ptr = ptr -> link;
5. ptr -> link = new;
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. }
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