PPS Notes
PPS Notes
UNIT - IIntroduction
to Computing:
Computer Systems:
A computer is a system made of two major components: hardware and software. The computer
hardware is the physical equipment. The software is the collection of programs (instructions) that allow
the hardware to do its job.
Computer
Sys tem
Hardware Software
Computer Hardware
The hardware component of the computer system consists of five parts: input devices, central
processing unit (CPU) ,primary storage, output devices, and auxiliary storage devices.
The input device is usually a keyboard where programs and data are entered into the computers.
Examples of other input devices include a mouse, a pen or stylus, a touch screen, or an audio input unit.
The central processing unit (CPU) is responsible for executing instructions such as arithmetic
calculations,comparisons among data, and movement of data inside the system. Today’s computers may
have one ,two, or more CPUs .Primary storage ,also known as main memory, is a place where the
programs and data are stored temporarily during processing. The data in primary storage are erased
when we turn off a personal computer or when we log off from a time-sharing system.
The output device is usually a monitor or a printer to show output. If the output is shown on the
monitor, we say we have a soft copy. If it is printed on the printer, we say we have a hard copy.
Auxiliary storage, also known as secondary storage, is used for both input and output. It is the place
where the programs and data are stored permanently. When we turn off the computer, or programs
and data remain in the secondary storage, ready for the next time we need them.
Computer Software
Computer software is divided in to two broad categories: system software and application
software .System software manages the computer resources .It provides the interface between the
hardware and the users. Application software, on the other hand is directly responsible for helping users
solve their problems.
Softwa re
Syste m Application
softw are software
System Software:
System software consists of programs that manage the hardware resources of a computer and perform
required information processing tasks. These programs are divided into three classes: the operating
system, system support, and system development.
The operating system provides services such as a user interface, file and database access, and interfaces
to communication systems such as Internet protocols. The primary purpose of this software is to keep
the system operating in an efficient manner while allowing the users access to the system.
System support software provides system utilities and other operating services. Examples of system
utilities are sort programs and disk format programs. Operating services consists of programs that
provide performance statistics for the operational staff and security monitors to protect the system and
data.
The last system software category ,system development software, includes the language translators
that convert programs into machine language for execution ,debugging tools to ensure that the
programs are error free and computer –assisted software engineering(CASE) systems.
Application software
Application software is broken in to two classes :general-purpose software and application – specific
software. General purpose software is purchased from a software developer and can be used for more
than one application. Examples of general purpose software include word processors, database
management systems, and computer aided design systems. They are labeled general purpose because
they can solve a variety of user computing problems.
Application –specific software can be used only for its intended purpose.
A general ledger system used by accountants and a material requirements planning system used by a
manufacturing organization are examples of application-specific software. They can be used only for the
task for which they were designed they cannot be used for other generalized tasks.
Features of Memory
Following are the different features of the memory system that includes:
Classification of Memory
The following figure represents the classification of memory:
Primary or Main Memory
Primary memory is also known as the computer system's main memory that communicates directl
within the CPU, Auxiliary memory and the Cache memory. Main memory is used to kept programs o
data when the processor is active to use them. When a program or data is activated to execute, the
processor first loads instructions or programs from secondary memory into main memory, and then th
processor starts execution. Accessing or executing of data from primary memory is faster because i
has a cache or register memory that provides faster response, and it is located closer to the CPU. Th
primary memory is volatile, which means the data in memory can be lost if it is not saved when a
power failure occurs. It is costlier than secondary memory, and the main memory capacity is limited a
compared to secondary memory.
o SRAM
o DRAM
DRAM: DRAM (Dynamic Random-Access Memory) is a type of RAM that is used for the dynami
storage of data in RAM. In DRAM, each cell carries one-bit information. The cell is made up of two parts
a capacitor and a transistor. The size of the capacitor and the transistor is so small, requirin
millions of them to store on a single chip. Hence, a DRAM chip can hold more data than an SRAM chip
of the same size. However, the capacitor needs to be continuously refreshed to retain informatio
because DRAM is volatile. If the power is switched off, the data store in memory is lost.
Characteristics of DRAM
SRAM: SRMA (Static Random-Access Memory) is a type of RAM used to store static data in th
memory. It means to store data in SRAM remains active as long as the computer system has a powe
supply. However, data is lost in SRAM when power failures have occurred.
SRAM DRAM
The access time of SRAM is slow. The access time of DRAM is high.
It uses flip-flops to store each bit of information. It uses a capacitor to store each bit of
information.
Disadvantages of RAM
Advantages of ROM
1. It is a non-volatile memory in which stored information can be lost even power is turned off.
2. It is static, so it does not require refreshing the content every time.
3. Data can be stored permanently.
4. It is easy to test and store large data as compared to RAM.
5. These cannot be changed accidently
6. It is cheaper than RAM.
7. It is simple and reliable as compared to RAM.
8. It helps to start the computer and loads the OS.
Disadvantages of ROM
1. Store data cannot be updated or modify except to read the existing data.
2. It is a slower memory than RAM to access the stored data.
3. It takes around 40 minutes to destroy the existing data using the high charge of ultraviolet light.
RAM ROM
Read and write operations can be Only Read operation can be performed.
performed.
Data can be lost in volatile memory when Data cannot be lost in non-volatile memory when
the power supply is turned off. the power supply is turned off.
Storage data requires to be refreshed in Storage data does not need to be refreshed in
RAM. ROM.
The size of the chip is bigger than the ROM The size of the chip is smaller than the RAM chip
chip to store the data. to store the same amount of data.
Types of RAM: DRAM and SRAM Types of ROM: MROM, PROM, EPROM, EEPROM
Secondary Memory
Secondary memory is a permanent storage space to hold a large amount of data. Secondar
memory is also known as external memory that representing the various storage media (hard drives
USB, CDs, flash drives and DVDs) on which the computer data and program can be saved on a long
term basis. However, it is cheaper and slower than the main memory. Unlike primary memory
secondary memory cannot be accessed directly by the CPU. Instead of that, secondary memory data i
first loaded into the RAM (Random Access Memory) and then sent to the processor to read and update
the data. Secondary memory devices also include magnetic disks like hard disk and floppy disks, a
optical disk such as CDs and CDROMs, and magnetic tapes.
Hard Disk
A hard disk is a computer's permanent storage device. It is a non-volatile disk that permanently store
data, programs, and files, and cannot lose store data when the computer's power source is switche
off. Typically, it is located internally on computer's motherboard that stores and retrieves data usin
one or more rigid fast rotating disk platters inside an air-sealed casing. It is a large storage device
found on every computer or laptop for permanently storing installed software, music, tex
documentation, videos, operating system, and data until the user did not delete.
Floppy Disk
A floppy disk is a secondary storage system that consisting of thin, flexible magnetic coating disks fo
holding electronic data such as computer files. It is also known as Floppy Diskette that comes in thre
sizes like 8 inches, 5.5 inches and 3.5 inches. The stored data of a floppy disk can be accessed through
the floppy disk drive. Furthermore, it is the only way through a new program installed on a computer o
backup of the information. However, it is the oldest type of portable storage device, which can stor
data up to 1.44 MB. Since most programs were larger, that required multiple floppy diskettes to stor
large amounts of data. Therefore, it is not used due to very low memory storage.
CD (Compact Disc)
A CD is an optical disk storage device, stands for Compact Disc. It is a storage device used to store
various data types like audio, videos, files, OS, Back-Up file, and any other information useful to
computer. The CD has a width of 1.2 mm and 12 cm in height, which can store approximately 783 MB
of data size. It uses laser light to read and write data from the CDs.
Types of CDs
1. CD-ROM (Compact Disc Read Only Memory): It is mainly used for bulk size mass like audi
CDs, software and computer games at the time of manufacture. Users can only read data, text
music, videos from the disc, but they cannot modify or burnt it.
2. CD-R (Compact Disc Recordable): The type of Compact Disc used to write once by the user
after that, it cannot be modified or erased.
3. CD-RW (Compact Disc Rewritable): It is a rewritable CD disc, often used to write or delet
the stored data.
DVD Drive/Disc
DVD is an optical disc storage device, stands for Digital Video Display or Digital Versatile Disc.
has the same size as a CD but can store a larger amount of data than a compact disc. It was develope
in 1995 by Sony, Panasonic, Toshiba and Philips four electronics companies. DVD drives are divide
into three types, such as DVD ROM (Read Only Memory), DVD R (Recordable) and DVD
RW (Rewritable or Erasable). It can store multiple data formats like audio, videos, images, software
operating system, etc. The storing capacity of data in DVD is 4.7 GB to 17 GB.
Blu Ray is an Optical disc storage device used to store a large amount of data or high definition o
video recording and playing other media files. It uses laser technology to read the stored data of th
Blu-ray Disk. It can store more data at a greater density as compared to CD/ DVD. For example
compact discs allow us to store 700 MB of data, and in DVDs, it provides up to 8 GB of storag
capacity, while Blu-ray Discs provide 28 GB of space to store data.
Pen Drive
A pen drive is a portable device used to permanently store data and is also known as a USB flash drive
It is commonly used to store and transfer the data connected to a computer using a USB port. It doe
not have any moveable part to store the data; it uses an integrated circuit chip that stores the data. I
allows the users to store and transfer data like audio, videos, images, etc. from one computer to an
USB pen drive. The storing capacity of pen drives from 64 MB to 128 GB or more.
Cache Memory
It is a small-sized chip-based computer memory that lies between the CPU and the main memory. It i
a faster, high performance and temporary memory to enhance the performance of the CPU. It stores a
the data and instructions that are often used by computer CPUs. It also reduces the access time of dat
from the main memory. It is faster than the main memory, and sometimes, it is also called CPU
memory because it is very close to the CPU chip. The following are the levels of cache memory.
Advantages of Cache Memory
1. It is very costly as compared to the Main memory and the Secondary memory.
2. It has limited storage capacity.
Register Memory
The register memory is a temporary storage area for storing and transferring the data and th
instructions to a computer. It is the smallest and fastest memory of a computer. It is a part of compute
memory located in the CPU as the form of registers. The register memory is 16, 32 and 64 bits in size
It temporarily stores data instructions and the address of the memory that is repeatedly used t
provide faster response to the CPU.
Data can be access directly by the processor Data cannot be accessed directly by the I/O
or CPU. processor or CPU.
Stored data can be a volatile or non-volatile The nature of secondary memory is always non-
memory. volatile.
It is more costly than secondary memory. It is less costly than primary memory.
It required the power to retain the data in It does not require power to retain the data in
primary memory. secondary memory.
Examples of primary memory are RAM, ROM, Examples of secondary memory are CD, DVD,
Registers, EPROM, PROM and cache memory. HDD, magnetic tapes, flash disks, pen drive, etc.
UNIT -1 PART 2
What is C?
C is a general-purpose, procedural, high-level programming language used in the
development of computer software and applications, system programming, games,
web development, and more.
C language was developed by Dennis M. Ritchie at the Bell Telephone
Laboratories in 1972.
It is a powerful and flexible language which was first developed for the
programming of the UNIX operating System.
C is one of the most widely used programming languages.
C programming language is known for its simplicity and efficiency. It is the best
choice to start with programming as it gives you a foundational understanding of
programming.
Features of C Language
There are some key features of C language that show the ability and power of C
language:
Simplicity and Efficiency: The simple syntax and structured approach make
the C language easy to learn.
Fast Speed: C is one of the fastest programming language because C is a
static programming language, which is faster than dynamic languages like
Java and Python. C is also a compiler-based which is the reason for faster
code compilation and execution.
Portable: C provides the feature that you write code once and run it anywhere
on any computer. It shows the machine-independent nature of the C language.
Memory Management: C provides lower level memory management using
pointers and functions like realloc(), free(), etc.
Pointers: C comes with pointers. Through pointers, we can directly access or
interact with the memory. We can initialize a pointer as an array, variables,
etc.
Structured Language: C provides the features of structural programming
that allows you to code into different parts using functions which can be
stored as libraries for reusability.
Structure of the C Program
The basic structure of a C program is divided into 6 parts which makes it easy to
read, modify, document, and understand in a particular format. C program must
follow the below-mentioned outline in order to successfully compile and execute.
Debugging is easier in a well-structured C program.
Sections of the C Program
There are 6 basic sections responsible for the proper execution of a program.
Sections are mentioned below:
Documentation
Preprocessor Section
Definition
Global Declaration
Main() Function
Sub Programs
// Documentation
//description: program to find sum.
// Link
#include <stdio.h>
// Definition
#define X 20
// Global Declaration
intsum(int y);
// Main() Function
int main(void)
{
int y = 55;
printf("Sum: %d", sum(y));
return 0;
}
// Subprogram
intsum(int y)
{
return y + X;
}
Identifiers in C:-
Identifiers are the building blocks of a program. Identifiers are unique
names that are assigned to variables, structs, functions, and other entities.
They are used to uniquely identify the entity within the program. In the
below example “section” is an identifier assigned to the string type value.
char section = 'A';
Keywords are predefined or reserved words that have special meanings to the
compiler. These are part of the syntax and cannot be used as identifiers in the
program. A list of keywords in C or reserved words in the C programming
language are mentioned below:
auto break case char const continue default do
Printf function in C
C Printf allows us to output content and control the formatting of text on our screen.
Syntax of printf()
printf( "formatted_string",arguments_list);
Parameters
formatted_string: It is a string that specifies the data to be printed. It may
also contain a format specifier to print the value of any variable such as a
character and an integer.
arguments_list: These are the variable names corresponding to the format
specifier.
Example:
printf(“hello World”);
1. scanf("format string",argument_list);
Format Specifiers in C
The format specifier in C is used to tell the compiler about the type of
data to be printed or scanned in input and output operations. They
always start with a % symbol and are used in the formatted string in
functions like printf(), scanf, sprintf(), etc.
The C language provides a number of format specifiers that are
associated with the different data types such as %d for int, %c for char,
etc. In this article, we will discuss some commonly used format
specifiers and how to use [Link] of Format Specifiers in C
Data Types In C:
It specifies the type of data that the variable can store like integer, character,
floating, double, etc. Each data type requires different amounts of memory and
has some specific operations which can be performed over it.
Primitive data types are the most basic data types that are
Primitive Data
used for representing simple values such as integers, float,
Types
characters, etc.
Types Description
User Defined
The user-defined data types are defined by the user himself.
Data Types
The data types that are derived from the primitive or built-in
Derived Types
datatypes are referred to as Derived Data Types.
What is a variable in C?
A variable in C is a memory location with some name that helps store some form
of data and retrieves it when required. We can store different types of data in the
variable and reuse the same variable for storing some other data any number of
[Link] can be viewed as the names given to the memory location so that we
can refer to it without having to memorize the memory address. The size of the
variable depends upon the data type it stores.
C Variable Syntax
The syntax to declare a variable in C specifies the name and the type of the
variable.
Global Variable:-
o Global variables are those variables which are declared outside of all the
functions or block and can be accessed globally in a program.
o It can be accessed by any function present in the program.
o Once we declare a global variable, its value can be varied as used with
different functions.
o The lifetime of the global variable exists till the program executes. These
variables are stored in fixed memory locations given by the compiler and do
not automatically clean up.
o Global variables are mostly used in programming and useful for cases where
all the functions need to access the same data.
Example:
1. #include<stdio.h>
2. int a=50, b=40; // global variable
3. void main()
4. {
5. printf("a = %d and b=%d",a,b);
6. }
Local Variable:-
o Variables that are declared within or inside a function block are known
as Local variables.
o These variables can only be accessed within the function in which they are
declared.
o The lifetime of the local variable is within its function only, which means
the variable exists till the function executes. Once function execution is
completed, local variables are destroyed and no longer exist outside the
function.
o The reason for the limited scope of local variables is that local variables are
stored in the stack, which is dynamic in nature and automatically cleans up
the data stored within it.
o But by making the variable static with "static" keyword, we can retain the
value of local variable.
Example:
1. #include<stdio.h>
2. void main()
3. {
4. int x=50, y=40; //local variable
5. printf("x = %d and y=%d",x, y);
6. }
However, they can be accessed outside their scope as well using the concept
of pointers given here by pointing to the very exact memory location where the
variables reside. They are assigned a garbage value by default whenever they
are declared.
Example
#include<stdio.h>
intmain()
{
int a; //auto
char b;
float c;
printf("%d %c %f",a,b,c); // printing initial default value of automatic variables a,
b, and c.
return0;
}
[Link] Storage Class in C
This storage class is used to declare static variables which are popularly
used while writing programs in C language. Static variables have the
property of preserving their value even after they are out of their scope!
Hence, static variables preserve the value of their last use in their scope.
So we can say that they are initialized only once and exist till the
termination of the program. Thus, no new memory is allocated because
they are not re-declared.
Their scope is local to the function to which they were defined. Global
static variables can be accessed anywhere in the program. By default,
they are assigned the value 0 by the compiler.
Example
#include<stdio.h>
staticchar c;
staticinti;
staticfloat f;
staticchars[100];
voidmain()
{
printf("%d %d %f %s",c,i,f); // the initial default value of c, i, and f will be printed.
}
This storage class declares register variables that have the same
functionality as that of the auto variables. The only difference is that the
compiler tries to store these variables in the register of the
microprocessor if a free register is available. This makes the use of
register variables to be much faster than that of the variables stored in the
memory during the runtime of the program.
If a free registration is not available, these are then stored in the memory
only. Usually, a few variables which are to be accessed very frequently in
a program are declared with the register keyword which improves the
running time of the program. An important and interesting point to be
noted here is that we cannot obtain the address of a register variable
using pointers. Example
#include<stdio.h>
intmain()
{
registerint a; // variable a is allocated memory in the CPU register. The initial
default value of a is 0.
printf("%d",a);
}
Run Code >>
Extern storage class simply tells us that the variable is defined elsewhere
and not within the same block where it is used. Basically, the value is
assigned to it in a different block and this can be overwritten/changed in a
different block as well. So an extern variable is nothing but a global
variable initialized with a legal value where it is declared in order to be
used elsewhere. It can be accessed within any function/block. Example
#include<stdio.h>
int a;
intmain()
{
externint a; // variable a is defined globally, the memory will not be allocated to a
printf("%d",a);
}
Garbage
auto Automatic RAM Local Within function
Value
Global variables are declared outside Local Variables are declared within a function
all the function blocks. block.
The scope remains throughout the The scope is limited and remains within the
program. function only in which they are declared.
Any change in global variable Any change in the local variable does not affect
affects the whole program, wherever other functions of the program.
it is being used.
A global variable exists in the A local variable is created when the function is
program for the entire time the executed, and once the execution is finished, the
program is executed. variable is destroyed.
If the global variable is not If the local variable is not initialized, it takes the
initialized, it takes zero by default. garbage value by default.
Global variables are stored in the Local variables are stored in a stack in memory.
data segment of memory.
We cannot declare many variables We can declare various variables with the same
with the same name. name but in other functions.
Constant Variable:-
A constant is a name given to the variable whose values can’t be altered or
changed. A constant is very similar to variables in the C programming
language, but it can hold only a single variable during the execution of a
program. It means that once we assign value to the constant, then we can’t
change it throughout the execution of a program- it stays fixed.
1. const keyword
2. #define preprocessor
OR
Example:
constint a = 10 ;
2. Use of the ‘#define’ preprocessor:-We create the constants by making
use of the preprocessor directive, we must define it in the very beginning
of the program. It is because we must write all the preprocessor
directives before the global declaration.
Example:-
#include<stdio.h>
#include<conio.h>
#define PI 3.14
void main(){
int a, area ;
printf(“Enter the radius of the given circle here : “) ;
scanf(“%d”, &a) ;
area = PI * (a * a) ;
printf(“The area of the circle is = %d”, area) ;
}
Types of Constants:
Constant Variables
A constant is used to hold the fixed values A variable is used to hold some
which we can retrieve later but cannot value that can be changed
change. according to the requirement.
The constants are generally stored in the The variables are stored inside a
text segment as they are read-only data segment, heap, or stack
depending on the environment it is
Constant Variables
declared in.
We can only assign a value to the constant We can assign value to the variable
while defining it. anytime.
What is a compiler?
A compiler is a special program that translates a programming language's source
code into machine code, bytecode or another programming language. The source code
is typically written in a high-level, human-readable language such as Java or C++.A
compiler that supports the source programming language reads the files, analyzes the
code, and translates it into a format suitable for the target platform.
Interpreter
An interpreter is a computer program that is used to directly execute
program instructions written using one of the many high-level programming
languages. The interpreter transforms the high-level program into an
intermediate language that it then executes, or it could parse the high-level
source code and then performs the commands directly, which is done line by
line or statement by statement.
Introduction to Dubugger
Debugging is the process of detecting and removing of existing and potential errors (also called
as ‘bugs’) in a software code that can cause it to behave unexpectedly or crash. To prevent
incorrect operation of a software or system, debugging is used to find and resolve bugs or
defects.
Introduction to Linker
A linker is a program in a system, also known as a link editor and binder, which combines
object modules into a single object file. Generally, it is a program that performs the process of
linking; it takes one or multiple object files, which are generated by compiler. And, then
combines these files into an executable files. Modules are called for the different pieces of code,
which are written in programming languages. Linking is a process that helps to gather and
maintain a different piece of code into an executable file or single file. With the help of a linker,
a specific module is also linked into the system library.
Introduction to Loader
A loader is a major component of an operating system that ensures all necessary programs and
libraries are loaded, which is essential during the startup phase of running a program. It places
the libraries and programs into the main memory in order to prepare them for execution. Loading
involves reading the contents of the executable file that contains the instructions of the program
and then doing other preparatory tasks that are required in order to prepare the executable for
running, all of which takes anywhere from a few seconds to minutes depending on the size of the
program that needs to run.
Introduction to Assembler
The Assembler is a Software that converts an assembly language code to machine code. It takes
basic Computer commands and converts them into Binary Code that Computer’s Processor can
use to perform its Basic Operations. These instructions are assembler language or assembly
language.
Input: Algorithms take input data, which can be in various formats, such as numbers,
text, or images.
Processing: The algorithm processes the input data through a series of logical and
mathematical operations, manipulating and transforming it as needed.
Output: After the processing is complete, the algorithm produces an output, which
could be a result, a decision, or some other meaningful information.
Efficiency: A key aspect of algorithms is their efficiency, aiming to accomplish tasks
quickly and with minimal resources.
Optimization: Algorithm designers constantly seek ways to optimize their algorithms,
making them faster and more reliable.
Correctness: It must produce the correct and accurate output for all valid inputs.
Scalability: It should handle larger data sets and problem sizes without a significant
decrease in performance.
Reliability: The algorithm should consistently deliver correct results under different
conditions and environments.
Optimality: Striving for the most efficient solution within the given problem
constraints.
Analysing the problem:-The purpose of this step is to determine both the starting and ending
points for solving the problem. This process is analogous to a mathematician determining what is
given and what must be proven. A good problem description makes it easier to perform this step.
When determining the starting point, we should start by seeking answers to the following questions:
[Link]: Write the code to convert the steps followed by an algorithm to solve the
problem.
[Link] and debugging:- check the program that is working well or not according to
the requirements.
Examples:
Ex. 1. Write an algorithm to find the sum and product of two given numbers.
Step 1:Start
Step 2: Read A , B
Step 6:Stop
Step 1: START
Step 1: Start
factorial = 1
i =1
factorial = factorial*i
i = i+1
Step 7: Stop
Step 1: Start
Else if b > c
Print b is the largest number.
Else
Step 5: Stop
What is FlowChart?
Solution: Flowcharts have the following advantages when used to solve a problem:
(a) They are brief and to the point.
(b) They express clearly the logic of a given procedure.
(c) They are unambiguous as there can be only one direction of logic at any one time.
(d) They show readily whether all eventualities are covered.
Limitations: Complex and detailed charts can be laborious to plan and draw and the actions to
be taken in specified situations can be difficult when many decision paths are involved
Complexity It is easy to design and also very user It is comparatively difficult to create
friendly. and also a bit challenging to be
understood by a layman.
Geometrical It utilizes different types of geometrical An algorithm does not include any
diagrams shapes, symbols, and patterns. sort of geometrical pattern.
Scope of Usage A flowchart can be used in different Algorithms are used in the domain of
disciplines to describe a process. mathematics and computer science.
Branching and Simple to display branching and Hard to display branching and
Looping looping. looping.
1. Unary Operators- As the name suggests, unary operators act on or carry out
operations on a single operand only. For example, the increment and decrement
operators.
2. Binary Operators- Similarly, these are the operators that can take two operands as
inputs. For example, the addition (+), subtraction (-), multiplication (*), and division (/)
operators.
Listed in the table below are the different types of arithmetic operators in C, along with the
functions they perform.
Example
Operator Description
(C=10, D=20)
Relational Operators
The main purpose of relational operators in C is to conduct a value comparison of two
operands. For instance, they can be used to determine if an operand is greater than the other,
or to determine if one operand is equal to the other, and other such similar cases. In the table
below, we have listed the different types of relational operators with examples:
Operato Example
r Operator Name (Say we have two operands, i.e., 6 Result
Notation and 5)
Logical Operators
The logical operators are used when we want to combine two or more conditions or
constraints. They can also be utilized to enhance the evaluation of the initial condition under
consideration. The logical operators always produce results in a boolean value, i.e., either true
or false.
Operato
Name/ Description Example Result
r
Bitwise Operators
Bitwise operators in C are the ones that are used to carry out bit-level operations on the
operands. In this, the operands are first translated to bit-level prior to performing the calculation
on them. The advantage of carrying out operations like addition, subtraction, multiplication,
etc., at the bit level is that it makes for quicker processing times.
In the table below, you will find a list of all bitwise operators in C.
| Bitwise OR
^ Bitwise exclusive OR
~ Bitwise complement
Assignment Operators
An assignment operator is a symbol used in programming to assign a value to a variable or
constant. It is frequently indicated by the equals sign (=) or another symbol suited for the
computer language being used.
The variable or constant on the left side of the assignment operator receives the value on the
right side when the operator is used. This enables programmers to change and store data in
their code.
= c=d c=d
+= c += d c = c+d
-= c -= d c = c-d
*= c *= d c = c*d
/= c /= d c = c/d
%= c %= d a = a%b
Syntax
Special Operators
Special operators are operators that are intended to carry out particular operations or have a
distinct syntax that isolates them from ordinary operators. Programming requires the usage of
special operators because they enable developers to carry out particular operations and
change data in particular ways.
Size-of operator in C (sizeof): The sizeof operator is used to determine the size of a variable
or data type in bytes. It is often used when allocating memory or when dealing with structures
or arrays.
Address-of Operator (&):The memory address of a variable can be determined with the
address-of operator (&). It is commonly used when working with pointers or when passing
variables by reference.
Shift Operators
The shift operators are binary operations that move a binary number's bits to a certain number
of locations, either to the left or to the right. In both C and C++, the left shift operator (<<) fills
the empty locations with zeros and moves the bits of the left operand to the left by the number
of positions indicated by the right-hand operand. The right shift operator (>>) moves the bits of
the left operand to the right by the number of positions indicated by the right-hand operand.
Depending on the sign of the left-hand operand, the vacant positions are filled with either zeros
or ones.
Operato
Description Example
r
sizeof(x), where x is an
integer, will return 4.
A unary operator called sizeof sizeof(y), where y is float,
returns the number of bytes of data will return 4.
sizeof()
(for example, int, char, float, sizeof(z), where z is
double, etc.). double, will return 8.
sizeof(t), where t is an
integer, will return 1.
2. The ternary operator (?:) performs a boolean expression evaluation and, depending on
the outcome, returns one of two results.
3. The comma operator (,) enables the sequential evaluation of several expressions with
the result of the last expression being returned.
4. In C, pointers are manipulated using the pointer operations (* and &). A pointer variable
is declared with an asterisk (*), and a pointer can be dereferenced to obtain the value it
points to. To obtain a variable's memory location, use the ampersand (&).
2. Relational Operators: Depending on whether the condition has been satisfied or not,
these operators compare the values of two operands and return a true or false Boolean
value.
3. Logical Operators: These operators are used to apply logical operations to Boolean
values, such as AND, OR, and NOT.
4. Bitwise operators are used to perform operations on the operands' binary values.
6. Conditional Operators: These are used for making judgments based on conditions
given to be assessed.
What is the difference between prefix and postfix operators in C?
Answer:
Prefix operations are the operations in which the value is returned prior to the
operation whereas in postfix operations value is returned after updating the value in
the variable.
Example:
b=c=10;
a=b++;
Control Statements in C
Sequential statements:
Decision-Making Statements in C
if statement
The if statement is used for deciding between two paths based on a true
or false outcome. It is represented by the following flowchart −
Syntax
if(Boolean expr)
{
Expr;
...
}
if...else statement
The if – else statement offers an alternative path when the condition isn't
met.
Syntax
if(Boolean expr)
{
Expr;
...
}
else
{
Expr;
...
}
if else if ladder
if else if ladder in C programming is used to test a series of conditions
sequentially. Furthermore, if a condition is tested only when all
previous if conditions in the if-else ladder are false. If any of the
conditional expressions evaluate to be true, the appropriate code block
will be executed, and the entire if-else ladder will be terminated.
Syntax:
// any if-else ladder starts with an if statement only
if(condition) {
}
else if(condition) {
// this else if will be executed when condition in if is false and
// the condition of this else if is true
}
.... // once if-else ladder can have multiple else if
else { // at the end we put else
}
Example 1: Check whether a number is positive, negative or 0
#include <stdio.h>
intmain()
intn = 0;
// all Positive numbers will make this
// condition true
if(n > 0) {
printf("Positive");
// condition true
elseif(n < 0) {
printf("Negative");
else{
printf("Zero");
}
return0;
Output
Zero
Example 2: Calculate Grade According to marks
#include <stdio.h>
intmain()
intmarks = 91;
printf("A+ Grade");
printf("B Grade");
printf("C Grade");
printf("D Grade");
else
printf("F Failed");
return0;
nested if statements
switch statement
case constant-expression :
statement(s);
break;/* optional */
case constant-expression :
statement(s);
break;/* optional */
5
4
For example:
#include <stdio.h>
intmain() {
intnb = 7;
while (nb> 0) {
nb--;
if (nb == 5)
continue;
printf("%d\n", nb);
}}
goto statement
C also has a goto keyword. You can redirect the program flow to any
labelled instruction in the program.
Syntax
goto label;
..
.
label: statement;
With the goto statement, the flow can be directed to any previous step or
any subsequent step.
Looping:-
languages –
While Loop in C
A while loop is the most straightforward looping structure. While loop
syntax in C programming language is as follows:
#include<stdio.h>
#include<conio.h>
intmain()
{
intnum=1; //initializing the variable
while(num<=10) //while loop with condition
{
printf("%d\n",num);
num++; //incrementing operation
}
return 0;
}
Do-While loop in C
A do…while loop in C is similar to the while loop except that the
condition is always executed after the body of a loop. It is also called an
exit-controlled loop.
In the do-while loop, the body of a loop is always executed at least once.
After the body is executed, then it checks the condition. If the condition
is true, then it will again execute the body of a loop otherwise control is
transferred out of the loop.
#include<stdio.h>
#include<conio.h>
intmain()
{
intnum=1; //initializing the variable
do //do-while loop
{
printf("%d\n",2*num);
num++; //incrementing operation
}while(num<=10);
return 0;
}
A for loop is a repetition control structure that allows you to efficiently
write a loop that needs to execute a specific number of times.
Syntax
The initialization step is executed first, and only once. This step
allows you to declare and initialize any loop control variables. You
are not required to put a statement here, as long as a semicolon
appears.
Next, the condition is evaluated. If it is true, the body of the loop
is executed. If it is false, the body of the loop does not execute and
the flow of control jumps to the next statement just after the 'for'
loop.
After the body of the 'for' loop executes, the flow of control jumps
back up to the increment statement. This statement allows you to
update any loop control variables. This statement can be left blank,
as long as a semicolon appears after the condition.
The condition is now evaluated again. If it is true, the loop
executes and the process repeats itself (body of loop, then
increment step, and then again condition). After the condition
becomes false, the 'for' loop terminates.
Flow Diagram
Example
Live Demo
#include<stdio.h>
int a;
/* for loop execution */
for( a=10; a <20; a = a +1){
printf("value of a: %d\n", a);
}
return0;
}
Syntax: Syntax:
While Loop Do-While Loop
while(condition){ do{
// statements //statements
} }while(expression);
In While loop, no semicolon is
In Do-while loop, semicolon needed
needed after the end of the
after the end of the condition
condition.
While loop may or may not be Do-while loop will execute at least
executed at all. once.
While loop can lead to errors if Do-while loop help prevents error as
the condition is always false. it runs at least once.
Note: If there is only one statement in the body of the loop, whether it
is a for loop or a while loop, the curly braces are not required.
In C, what is the difference between a for loop and a while?
Difference between if else and switch:-
1. #include<stdio.h>
2. int main()
3. {
4. int n1=0,n2=1,n3,i,number;
5. printf("Enter the number of elements:");
6. scanf("%d",&number);
7. printf("\n%d %d",n1,n2);//printing 0 and 1
8. for(i=2;i<number;++i)//loop starts from 2 because 0 and 1 are already prin
ted
9. {
10. n3=n1+n2;
11. printf(" %d",n3);
12. n1=n2;
13. n2=n3;
14. }
15. return 0;
16. }
Output:
Enter the number of elements:15
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377
#include <stdio.h>
intmain()
inti, a = 1, count;
count = 0;
i = 2;
while(i<= a/2)
if(a%i == 0)
count++;
break;
i++;
}
if(count == 0 && a != 1 )
a++;
return 0;
Output:
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79
83 89 97
Unit-3
Arrays:
An array is defined as the collection of similar type of
data items stored at contiguous memory locations. Arrays
are the derived data type in C programming language
which can store the primitive type of data such as int,
char, double, float, etc. It also has the capability to store
the collection of derived data types, such as pointers,
structure, etc. The array is the simplest data structure
where each data element can be randomly accessed by
using its index number.
Properties of Array
Advantage of C Array
2) Ease of traversing:
By using the for loop, we can retrieve
the elements of an array easily.
3) Ease of sorting:
To sort the elements of the array, we
need a few lines of code only.
Disadvantage of C Array
Declaration of C Array
1. data_type array_name[array_size];
int marks[5];
Initialization of Array
C array example
1. #include<stdio.h>
2. int main(){
3. int i=0;
4. int marks[5];//declaration of array
5. marks[0]=80;//initialization of array
6. marks[1]=60;
7. marks[2]=70;
8. marks[3]=85;
9. marks[4]=75;
10. //traversal of array
11. for(i=0;i<5;i++){
12. printf("%d \n",marks[i]);
13. }//end of for loop
14. return 0;
15. }
Output
80
60
70
85
75
1. int marks[5]={20,30,40,50,60};
1. int marks[]={20,30,40,50,60};
2. // C program to declare and initialize the array in C.
1. #include<stdio.h>
2. int main(){
3. int i=0;
4. int marks[5]={20,30,40,50,60};//declaration and initializa
tion of array
5. //traversal of array
6. for(i=0;i<5;i++){
7. printf("%d \n",marks[i]);
8. }
9. return 0;
10. }
Output
20
30
40
50
/ C Program to demonstrate the use of array
#include <stdio.h>
intmain()
{
// array declaration and initialization
intarr[5] = { 10, 20, 30, 40, 50 };
return0;
}
Types of Array in C
1. #include<stdio.h>
2. void main ()
3. {
4. int i, j,temp;
5. int a[10] = { 10, 9, 7, 101, 23, 44, 12, 78, 34, 23};
6. for(i = 0; i<10; i++)
7. {
8. for(j = i+1; j<10; j++)
9. {
10. if(a[j] > a[i])
11. {
12. temp = a[i];
13. a[i] = a[j];
14. a[j] = temp;
15. }
16. }
17. }
18. printf("Printing Sorted Element List ...\n");
19. for(i = 0; i<10; i++)
20. {
21. printf("%d\n",a[i]);
22. }
23. }
1. data_type array_name[rows][columns];
#include <stdio.h>
intmain(void)
{
// an array with 3 rows and 2 columns.
intx[3][2] = { { 0, 1 }, { 2, 3 }, { 4, 5 } };
return(0);
}
1. #include <stdio.h>
2.
3. int main() {
4. int grades[5][4];
5.
6. // Prompt user to enter grades
7. for (int i = 0; i< 5; i++) {
8. printf("Enter grades for student %d:\n", i+1);
9. for (int j = 0; j < 4; j++) {
10. printf("Subject %d: ", j+1);
11. scanf("%d", &grades[i][j]);
12. }
13. }
14.
15. // Calculate average grade for each student
16. printf("\nAverage grade for each student:\n");
17. for (int i = 0; i< 5; i++) {
18. float sum = 0;
19. for (int j = 0; j < 4; j++) {
20. sum += grades[i][j];
21. }
22. float avg = sum / 4;
23. printf("Student %d: %.2f\n", i+1, avg);
24. }
25.
26. // Calculate average grade for each subject
27. printf("\nAverage grade for each subject:\n");
28. for (int j = 0; j < 4; j++) {
29. float sum = 0;
30. for (int i = 0; i< 5; i++) {
31. sum += grades[i][j];
32. }
33. float avg = sum / 5;
34. printf("Subject %d: %.2f\n", j+1, avg);
35. }
36.
37. return 0;
38. }
Multidimensional array in C
1. type array_name[size1][size2]...[sizeN];
Here, type is the data type of the elements that will be stored in
the array, array_name is the name of the array,
and size1, size2, ..., sizeN are the sizes of each dimension of the array.
// C program to print elements of Three-
Dimensional Array
#include <stdio.h>
intmain(void)
{
// initializing the 3-dimensional array
intx[2][3][2] = { { { 0, 1 }, { 2, 3 }, { 4,
5 } },
{ { 6, 7 }, { 8, 9 },
{ 10, 11 } } };
Output
Enter the number of rows and columns of the
matrices: 2 2
Enter the elements of matrix A:
1 2
3 4
Enter the elements of matrix B:
5 6
7 8
The sum of the two matrices is:
6 8
10 12
Program to Find the Transpose of a Matrix
#include<stdio.h>
intmain(){
inta[10][10], transpose[10][10], r, c;
printf("Enter rows and columns: ");
scanf("%d %d", &r, &c);
Output
Enter rows and columns: 2
3
Entered matrix:
1 4 0
5 2 7
Matrix multiplication in C
1. #include<stdio.h>
2. #include<stdlib.h>
3. int main(){
4. int a[10][10],b[10][10],mul[10][10],r,c,i,j,k;
5. system("cls");
6. printf("enter the number of row=");
7. scanf("%d",&r);
8. printf("enter the number of column=");
9. scanf("%d",&c);
10. printf("enter the first matrix element=\n");
11. for(i=0;i<r;i++)
12. {
13. for(j=0;j<c;j++)
14. {
15. scanf("%d",&a[i][j]);
16. }
17. }
18. printf("enter the second matrix element=\n");
19. for(i=0;i<r;i++)
20. {
21. for(j=0;j<c;j++)
22. {
23. scanf("%d",&b[i][j]);
24. }
25. }
26.
27. printf("multiply of the matrix=\n");
28. for(i=0;i<r;i++)
29. {
30. for(j=0;j<c;j++)
31. {
32. mul[i][j]=0;
33. for(k=0;k<c;k++)
34. {
35. mul[i][j]+=a[i][k]*b[k][j];
36. }
37. }
38. }
39. //for printing result
40. for(i=0;i<r;i++)
41. {
42. for(j=0;j<c;j++)
43. {
44. printf("%d\t",mul[i][j]);
45. }
46. printf("\n");
47. }
48. return 0;
49. }
Output:
enter the number of row=3
enter the number of column=3
enter the first matrix element=
1 1 1
2 2 2
3 3 3
enter the second matrix element=
1 1 1
2 2 2
3 3 3
multiply of the matrix=
6 6 6
12 12 12
18 18 18
return 0;
}
intmain()
{
// printing string
inti = 0;
while(arr[i]) {
printf("%c", arr[i++]);
}
return0;
}
Definition A simple data structure that A two-dimensional array stores a list of arrays with similar
sequentially stores elements of data types.
the same data type.
Dimensions A one-dimensional array has only A two-dimensional array has a total of two dimensions.
one dimension.
Size(bytes) The size of the 1D array is: The size of the 2D array is:
Total number of Bytes Total number of Bytes = size of(datatype of the
=sizeof(datatype of array variable of the array)* the size of the first index * the
variable)* size of the array. size of the second index.
Representation The 1D array represents multiple The 2D array represents multiple data items in the form
data items in the form of a list. of a table consisting of rows and columns.
Address Address of element arr[i] = Address of arr[i[[j] can be calculated in two ways:
calculation b+w*i Row Major:
Here b is the base address, w is Address of element arr[i][j]=b+(n(i-l1)+(j-l2))
the size of each element, and i Column Major:
is the index of the array. Address of element arr[i][j]=b+(m(j-l2)+(i-l1))
Here b is the base address, w is the size of each
element, n is the number of rows, and m is the
number of the column. l1 specifies the lower bound
of the row, and l2 identifies the lower bound of the
column.
Row column A one-dimensional array has no A two-dimensional array has a row-column matrix.
matrix row-column matrix.
#include <stdio.h>
intmain()
{ introws = 5;
printf("* ");
printf("\n");
return0;
}
* | 1 | A
* * | 1 2 | A B
* * * | 1 2 3 | A B C
* * * * | 1 2 3 4 | A B C D
* * * * * | 1 2 3 4 5 | A B C D E
#include <stdio.h>
intmain()
{ introws = 5;
printf(" ");
printf("* ");
}
printf("\n");
return0;
Output
* | 1 | A
* * | 1 2 | A B
* * * | 1 2 3 | A B C
* * * * | 1 2 3 4 | A B C D
* * * * * | 1 2 3 4 5 | A B C D E
#include <stdio.h>
intmain()
introws = 5;
// first loop to print all rows
printf(" ");
printf("* ");
printf("\n");
return0;
Output
* | 1 | A
* * * | 1 2 3 | A B C
* * * * * | 1 2 3 4 5 | A B C D E
* * * * * * * | 1 2 3 4 5 6 7 | A B C D E F
G
* * * * * * * * * | 1 2 3 4 5 6 7 8 9 | A B C D E F G
H I
// stars
#include <stdio.h>
intmain()
introws = 5;
printf("* ");
}
printf("\n");
Output
* * * * * | 1 2 3 4 5 | A B C D E
* * * * | 1 2 3 4 | A B C D
* * * | 1 2 3 | A B C
* * | 1 2 | A B
* | 1 | A
// of stars
#include <stdio.h>
intmain()
introws = 5;
printf(" ");
printf("* ");
printf("\n");
return0;
Output
* * * * * | 1 2 3 4 5 | A B C D E
* * * * | 1 2 3 4 | A B C D
* * * | 1 2 3 | A B C
* * | 1 2 | A B
* | 1 | A
// stars
#include <stdio.h>
intmain()
introws = 5;
// spaces
printf(" ");
}
// second inner loop for printing stars *
printf("* ");
printf("\n");
Output
* * * * * * * * * | 1 2 3 4 5 6 7 8 9 | A B C D E F G H
I
* * * * * * * | 1 2 3 4 5 6 7 | A B C D E F G
* * * * * | 1 2 3 4 5 | A B C D E
* * * | 1 2 3 | A B C
* | 1 | A
#include <stdio.h>
intmain()
{
introws = 5;
printf(" ");
else{
printf("* ");
printf("\n");
}
return0;
Output
* * * * * | 1 2 3 4 5 | A B C D E
* * | 1 5 | A E
* * | 1 5 | A E
* * | 1 5 | A E
* * * * * | 1 2 3 4 5 | A B C D E
Unit-4
Algorithmic Theory
What is Sorting?
Sorting refers to rearrangement of a given array or list of elements according to a
comparison operator on the elements. The comparison operator is used to decide the new
order of elements in the respective data structure. Sorting means reordering of all the
elements either in ascending or in descending order.
Bubble Sort –
// Driver program
int main()
{
int arr[] = { 64, 25, 12, 22, 11 };
int n = sizeof(arr) / sizeof(arr[0]);
// Function Call
selectionSort(arr, n);
cout << "Sorted array: \n";
printArray(arr, n);
return 0;
}
Output
Sorted array:
11 12 22 25 64
#include <bits/stdc++.h>
using namespace std;
int pivot=arr[high];
//Index of smaller element and Indicate
//the right position of pivot found so far
int i=(low-1);
for(int j=low;j<=high;j++)
{
//If current element is smaller than the pivot
if(arr[j]<pivot)
{
//Increment index of smaller element
i++;
swap(arr[i],arr[j]);
}
}
swap(arr[i+1],arr[high]);
return (i+1);
}
int pi=partition(arr,low,high);
//Recursion Call
//smaller element than pivot goes left and
//higher element goes right
quickSort(arr,low,pi-1);
quickSort(arr,pi+1,high);
}
}
int main() {
int arr[]={10,7,8,9,1,5};
int n=sizeof(arr)/sizeof(arr[0]);
// Function call
quickSort(arr,0,n-1);
//Print the sorted array
cout<<"Sorted Array\n";
for(int i=0;i<n;i++)
{
cout<<arr[i]<<" ";
}
return 0;
}
// This Code is Contributed By Diwakar Jha
Output
Sorted Array
1 5 7 8 9 10
Complexity Analysis of Quick Sort :
Time Complexity:
Best Case: Ω (N log (N))
The best-case scenario for quicksort occur when the pivot chosen at the each step
divides the array into roughly equal halves.
In this case, the algorithm will make balanced partitions, leading to efficient Sorting.
Average Case: θ ( N log (N))
Quicksort’s average-case performance is usually very good in practice, making it one
of the fastest sorting Algorithm.
Worst Case: O(N2)
The worst-case Scenario for Quicksort occur when the pivot at each step consistently
results in highly unbalanced partitions. When the array is already sorted and the pivot
is always chosen as the smallest or largest element. To mitigate the worst-case
Scenario, various techniques are used such as choosing a good pivot (e.g., median of
three) and using Randomized algorithm (Randomized Quicksort ) to shuffle the
element before sorting.
Auxiliary Space: O(1), if we don’t consider the recursive stack space. If we consider
the recursive stack space then, in the worst case quicksort could make O(N).
Advantages of Quick Sort:
It is a divide-and-conquer algorithm that makes it easier to solve problems.
It is efficient on large data sets.
It has a low overhead, as it only requires a small amount of memory to function.
Disadvantages of Quick Sort:
It has a worst-case time complexity of O(N 2), which occurs when the pivot is chosen
poorly.
It is not a good choice for small data sets.
It is not a stable sort, meaning that if two elements have the same key, their relative
order will not be preserved in the sorted output in case of quick sort, because here we
are swapping elements according to the pivot’s position (without considering their
original positions).
// UTILITY FUNCTIONS
// Function to print an array
void printArray(int A[], int size)
{
for (int i = 0; i < size; i++)
cout << A[i] << " ";
cout << endl;
}
// Driver code
int main()
{
int arr[] = { 12, 11, 13, 5, 6, 7 };
int arr_size = sizeof(arr) / sizeof(arr[0]);
Output
Given array is
12 11 13 5 6 7
Sorted array is
5 6 7 11 12 13
Complexity Analysis of Merge Sort:
Time Complexity:
Best Case: O(n log n), When the array is already sorted or nearly sorted.
Average Case: O(n log n), When the array is randomly ordered.
Worst Case: O(n log n), When the array is sorted in reverse order.
Space Complexity: O(n), Additional space is required for the temporary array
used during merging.
Syntax
Function Definition
The function definition consists of actual statements which are
executed when the function is called (i.e. when the program
control comes to the function).
return_type function_name (para1_type para1_name, para2_type
para2_name)
{
// body of the function
}
Function Call
A function call is a statement that instructs the compiler to
execute the function. We use the function name and
parameters in the function call.
Some important points:
Function return type tells what type of value is returned after all function is
executed. When we don’t want to return a value, we can use the void data type.
Function Arguments
Function Arguments (also known as Function Parameters) are the data that is
passed to a function.
Example:
int function_name(int var1, int var2);
Types of Functions
There are two types of functions in C:
1. Library Functions
2. User Defined Functions
Types of Functions in C
1. Library Function
// C program to implement
// the above approach
#include <math.h>
#include <stdio.h>
// Driver code
int main()
{
double Number;
Number = 49;
Output
// Driver code
int main()
{
int a = 30, b = 40;
// function call
int res = sum(a, b);
Output
Sum is: 70
int main()
{
int sum= add(10, 20);
return 0;
}
5. What is pass-by-value in C?
Pass-by value is a method of passing arguments to a function in which the
value of the argument is copied into the formal parameter of the function. Any
changes made to the formal parameter inside the function will not affect the
original argument passed to the function.
Values of variables are passed by the Pointer variables are necessary to define to
Simple technique. store the address values of variables.
C
// C program to illustrate call by value
#include <stdio.h>
// Function Prototype
void swapx(int x, int y);
// Main function
int main()
{
int a = 10, b = 20;
// Pass by Values
swapx(a, b); // Actual Parameters
return 0;
}
// two values
void swapx(int x, int y) // Formal Parameters
int t;
t = x;
x = y;
y = t;
// Function Prototype
void swapx(int*, int*);
// Main function
int main()
{
int a = 10, b = 20;
// Pass reference
swapx(&a, &b); // Actual Parameters
return 0;
}
t = *x;
*x = *y;
*y = t;
Unit-6
Recursion
Recursion is the technique of making a function call itself. This technique provides a way to break
complicated problems down into simple problems which are easier to solve.
Recursion Example
Adding two numbers together is easy to do, but adding a range of numbers is more complicated.
In the following example, recursion is used to add a range of numbers together by breaking it
down into the simple task of adding two numbers:
Example
int sum(int k);
int main() {
int result = sum(10);
printf("%d", result);
return 0;
}
int sum(int k) {
if (k > 0) {
return k + sum(k - 1);
} else {
return 0;
}
}
int nSum(int n)
{
// base condition to terminate the recursion when N = 0
if (n == 0) {
return 0;
}
return res;
}
int main()
{
int n = 5;
Examples of Recursion in C
Example 1: C Program to Find the Factorial of a Natural Number using Tail
Recursion.
C
int factorialTail(int n)
{
// Base case
if (n == 1 || n == 0) {
return 1;
}
else {
// Tail recursive call
return n * factorialTail(n - 1);
}
}
int main()
{
int n = 5;
return 0;
}
Output
int fibonacci(int n)
{
// Base case
// Fibonacci of 0 and 1 is the number itself
if (n <= 1) {
return n;
}
else {
// Tree recursive calls
return fibonacci(n - 1) + fibonacci(n - 2);
}
}
int main()
{
// function call
int n = fibonacci(3);
return 0;
}
Output
void functionA(int n)
{
if (n < 1) {
return;
}
printf("%d ", n);
n = n - 1;
int main()
{
// Function call
functionB(20);
return 0;
}
Output
20 10 9 4 3 1
Unit-7
Structures
C Structures
The structure in C is a user-defined data type that can be used to group items of
possibly different types into a single type. The struct keyword is used to define
the structure in the C programming language. The items in the structure are
called its member and they can be of any valid data type.
C Structure Declaration
We have to declare structure in C before using it in our program. In structure
declaration, we specify its member variables along with their datatype. We can
use the struct keyword to declare the structure in C using the following syntax:
Syntax
struct structure_name {
data_type member_name1;
data_type member_name1;
....
....
};
The above syntax is also called a structure template or structure prototype and
no memory is allocated to the structure in the declaration.
C Structure Definition
To use structure in our program, we have to define its instance. We can do that
by creating variables of the structure type. We can define structure variables
using two methods:
struct structure_name {
data_type member_name1;
data_type member_name1;
....
....
}variable1, varaible2, ...;
Syntax
structure_name.member1;
strcuture_name.member2;
In the case where we have a pointer to the structure, we can also use the arrow
operator to access the members.
Initialize Structure Members
Structure members cannot be initialized with the declaration.
We can initialize structure members in 3 ways which are as follows:
1. Using Assignment Operator.
2. Using Initializer List.
3. Using Designated Initializer List.
str;
struct structure_name
str.member1 = value1;
str.member2 = value2;
str.member3 = value3;
.
.
.
Example of Structure in C
The following C program shows how to use structures
C
#include <stdio.h>
struct str1 {
int i;
char c;
float f;
char s[30];
};
// declaring structure with name str2
struct str2 {
int ii;
char cc;
float ff;
// Driver code
int main()
// initializer list
" },
var2;
var2 = var1;
printf("Struct 1:\n\ti = %d, c = %c, f = %f, s = %s\n",
[Link], [Link]);
return 0;
Output
Struct 1:
i = 1, c = A, f = 1.000000, s = Swami vivekanand college
Struct 2:
i = 1, c = A, f = 1.000000, s = Swami vivekanand college
Struct 3
i = 5, c = a, f = 5.000000
Example 2
1. #include<stdio.h>
2. void main ()
3. {
4. char names[2][10],dummy; // 2-dimensioanal character array names is used to store the n
ames of the students
5. int roll_numbers[2],i;
6. float marks[2];
7. for (i=0;i<3;i++)
8. {
9.
10. printf("Enter the name, roll number, and marks of the student %d",i+1);
11. scanf("%s %d %f",&names[i],&roll_numbers[i],&marks[i]);
12. scanf("%c",&dummy); // enter will be stored into dummy character at each iteration
13. }
14. printf("Printing the Student details ...\n");
15. for (i=0;i<3;i++)
16. {
17. printf("%s %d %f\n",names[i],roll_numbers[i],marks[i]);
18. }
19. }
C Structure example3
1. #include<stdio.h>
2. #include <string.h>
3. struct employee
4. { int id;
5. char name[50];
6. }e1; //declaring e1 variable for structure
7. int main( )
8. {
9. //store first employee information
10. [Link]=101;
11. strcpy([Link], "Sonoo Jaiswal");//copying string into char array
12. //printing first employee information
13. printf( "employee 1 id : %d\n", [Link]);
14. printf( "employee 1 name : %s\n", [Link]);
15. return 0;
16. }
Let's see another example of the structure in C language to store many employees
information.
1. #include<stdio.h>
2. #include <string.h>
3. struct employee
4. { int id;
5. char name[50];
6. float salary;
7. }e1,e2; //declaring e1 and e2 variables for structure
8. int main( )
9. {
10. //store first employee information
11. [Link]=101;
12. strcpy([Link], "Sonoo Jaiswal");//copying string into char array
13. [Link]=56000;
14.
15. //store second employee information
16. [Link]=102;
17. strcpy([Link], "James Bond");
18. [Link]=126000;
19.
20. //printing first employee information
21. printf( "employee 1 id : %d\n", [Link]);
22. printf( "employee 1 name : %s\n", [Link]);
23. printf( "employee 1 salary : %f\n", [Link]);
24.
25. //printing second employee information
26. printf( "employee 2 id : %d\n", [Link]);
27. printf( "employee 2 name : %s\n", [Link]);
28. printf( "employee 2 salary : %f\n", [Link]);
29. return 0;
30. }
Output:
employee 1 id : 101
employee 1 name : Sonoo Jaiswal
employee 1 salary : 56000.000000
employee 2 id : 102
employee 2 name : James Bond
employee 2 salary : 126000.000000
Array of Structures
An array whose elements are of type structure is called array of structure. It is generally
useful when we need multiple structure variables in our program.
Need for Array of Structures
Suppose we have 50 employees and we need to store the data of 50 employees. So for
that, we need to define 50 variables of struct Employee type and store the data within that.
However, declaring and handling the 50 variables is not an easy task. Let’s imagine a
bigger scenario, like 1000 employees.
So, if we declare the variable this way, it’s not possible to handle this.
struct Employee emp1, emp2, emp3, .. . ... . .. ... emp1000;
For that, we can define an array whose data type will be struct Employee soo that will be
easily manageable.
Declaration of Array of Structures
struct structure_name array_name [number_of_elements];
Initialization of Array of Structures
We can initialize the array of structures in the following ways:
struct structure_name array_name [number_of_elements] = {
{element1_value1, element1_value2, ....},
{element2_value1, element2_value2, ....},
......
......
};
Example of Array of Structure in C
C
#include <stdio.h>
// structure template
struct Employee {
char Name[20];
int employeeID;
int WeekAttendence[7];
};
// driver code
int main()
emp[i].employeeID = i;
strcpy(emp[i].Name, "Amit");
int week;
int attendence;
emp[i].WeekAttendence[week] = week;
printf("\n");
// printing data
emp[i].employeeID, emp[i].Name);
printf("Attendence\n");
int week;
printf("\n");
}
return 0;
#include <stdio.h>
struct class {
int roll_no;
char grade;
float marks;
};
int i, len = 3;
// Display the contents of the array
class_record[i].roll_no);
class_record[i].marks);
printf("\n");
// Driver Code
int main()
{ 2, 'C', 67.5f },
{ 3, 'B', 70.5f } };
// Function Call to display
// the class_record
display(class_record);
return 0;
Output
Roll number : 1
Grade : A
Average marks : 89.50
Roll number : 2
Grade : C
Average marks : 67.50
Roll number : 3
Grade : B
Average marks : 70.50
#include <stdio.h>
struct candidate {
int roll_no;
char grade;
float marks[4];
};
printf("Marks secured:\n");
int i;
// Driver Code
int main()
// Initialize a structure
display(A);
return 0;
Output
Roll number : 1
Grade : A
Marks secured:
Subject 1 : 98.50
Subject 2 : 77.00
Access
elements [Link][index] array[index].member
syntax
Parameter Array within a Structure Array of Structures
Unit-8
Pointers
What is a Pointer in C?
A pointer is defined as a derived data type that can store the address of
other C variables or a memory location. We can access and manipulate
the data stored in that memory location using pointers.
Syntax of C Pointers
The syntax of pointers is similar to the variable declaration in C, but we
use the ( * ) dereferencing operator in the pointer declaration.
datatype * ptr;
where
ptr is the name of the pointer.
datatype is the type of data it is pointing to.
1. Pointer Declaration
In pointer declaration, we only declare the pointer but do not initialize it.
To declare a pointer, we use the ( * ) dereference operator before its
name.
Example
int *ptr;
The pointer declared here will point to some random memory address as it
is not initialized. Such pointers are called wild pointers.
2. Pointer Initialization
Pointer initialization is the process where we assign some initial value to
the pointer variable. We generally use the ( & ) addressof operator to get
the memory address of a variable and then store it in the pointer variable.
Example
int var = 10;
int * ptr;
ptr = &var;
We can also declare and initialize the pointer in a single step. This method
is called pointer definition as the pointer is declared and initialized at the
same time.
Example
int *ptr = &var;
Note: It is recommended that the pointers should always be initialized to
some value before starting using it. Otherwise, it may lead to number of
errors.
3. Pointer Dereferencing
Dereferencing a pointer is the process of accessing the value stored in the
memory address specified in the pointer. We use the same ( * )
dereferencing operator that we used in the pointer declaration.
Dereferencing a Pointer in C
C Pointer Example
// C program to illustrate Pointers
#include <stdio.h>
void abc()
{
int var = 10;
int* ptr;
printf("Value at ptr = %p \n", ptr);
printf("Value at var = %d \n", var);
printf("Value at *ptr = %d \n", *ptr);
}
int main()
{
abc();
return 0;
}
Output
Null Pointer
Void Pointer
Wild Pointer
Dangling Pointer
Null Pointer:-
Syntax:
Example:
#include<stdio.h>
int main()
printf(“var=%d”,*var);
Null Pointer
Void Pointer
Wild Pointer
Dangling Pointer
Null Pointer:
Syntax:
Example:
#include<stdio.h>
int main()
printf(“var=%d”,*var);
Void Pointer:
Syntax:
void *var;
Example:
#include<stdio.h>
int main()
int a=2;
void *ptr;
ptr= &a;
return 0;
Wild pointer:-
A wild pointer is only declared but not assigned an address of any variable.
They are very tricky, and they may cause segmentation errors.
Example:
#include<stdio.h>
int main()
int *ptr;
printf(“ptr=%d”,*ptr);
return 0;
}
Dangling Pointer:-
#include<stdio.h>
#include<stdlib.h>
int main()
int a=5;
ptr=&a;
free(ptr);
return 0;
Pointer arithmetic:
Increment: You can use this operator to jump from one index to the next
index in an array.
Syntax:
ptr++;
Example:
#include <stdio.h>
int main() {
int *ptr;
ptr = arr;
Decrement: You can use this operator to jump from one index to the
previous index in an array.
Syntax:
Ptr--;
Example:
#include<stdio.h>
int main()
int *ptr;
ptr = &arr[2];
ptr--;
}
Integers added to a Pointer: You can use this operator to jump from one
index to the next ith index in an array.
Syntax:
Example:
#include <stdio.h>
int main() {
int *ptr;
ptr = &arr[0];
ptr=ptr+2;
}
Integers Subtracted from a Pointer: You can use this operator to jump
from one index to the previous ith index in an array.
Syntax:
Example:
#include <stdio.h>
int main() {
int *ptr;
ptr = &arr[4];
ptr-=2;
Pointer to Pointer:
In this situation, a pointer will indirectly point to a variable via another
pointer.
Syntax:
Int **ptr;
Example:
#include <stdio.h>
int main ()
var = 10;
ptr1 = &var;
ptr2 = &ptr1;
return 0;
}
An Array of Pointer:
Syntax:
Example:
#include <stdio.h>
int main ()
int i, *ptr[3];
ptr[i] = &a[i];
}
return 0;
Call By Value:
In ‘call by value’, you must copy the variable's values and pass them in the
function call as a parameter. If you modify these parameters, then it doesn't
change the value of the actual variable.
Example:
#include<stdio.h>
num=num+100;
int main()
int x=100;
change(x);
printf("After function call x=%d \n",x);
return 0;
Call By Reference:
In call by reference, you must take the variable's address and pass it in the
function call as a parameter. If you modify these parameters, then it will
change the value of the actual variable as well.
Example:
#include<stdio.h>
(*num) += 100;
int main()
int x=100;
printf("Before function call x=%d \n",x);
return 0;
Trees: A tree is a data structure in which each node has one or more child
nodes. Self-referential structures are used to create the nodes and link
them together to form the tree structure.
Stacks and Queues: Stacks and queues are data structures used to store
and retrieve data in a particular order. Self-referential structures can be
used to create the nodes in the stack or queue and link them together to
form the structure.
The head pointer points to the first node, and the last
element of the list points to null. When the list is empty, the
head pointer points to null.
File handing in C is the process in which we create, open, read, write, and
close operations on a file. C language provides different functions such as
fopen(), fwrite(), fread(), fseek(), fprintf(), etc. to perform input, output,
and many different C file operations in our program.
Types of Files in C
A file can be classified into two types based on the way the file stores the
data. They are as follows:
Text Files
Binary Files
1. Text Files
A text file contains data in the form of ASCII characters and is
generally used to store a stream of characters.
Each line in a text file ends with a new line character (‘\n’).
It can be read or written by any text editor.
They are generally stored with .txt file extension.
Text files can also be used to store the source code.
2. Binary Files
A binary file contains data in binary form (i.e. 0’s and 1’s) instead of
ASCII characters. They contain data that is stored in a similar manner to
how it is stored in the main memory.
The binary files can be created only from within a program and their
contents can only be read by a program.
More secure as they are not easily readable.
They are generally stored with .bin file extension.
C File Operations
C file operations refer to the different possible operations that we can
perform on a file in C such as:
1. Creating a new file – fopen() with attributes as “a” or “a+” or
“w” or “w+”
2. Opening an existing file – fopen()
3. Reading from file – fscanf() or fgets()
4. Writing to a file – fprintf() or fputs()
5. Moving to a specific location in a file – fseek(), rewind()
6. Closing a file – fclose()
The highlighted text mentions the C function used to perform the file
operations.
Searches file. If the file is opened successfully fopen( ) loads it into memory
r and sets up a pointer that points to the first character in it. If the file cannot be
opened fopen( ) returns NULL.
Open for reading in binary mode. If the file does not exist, fopen( ) returns
rb
NULL.
Open for writing in text mode. If the file exists, its contents are overwritten. If
w the file doesn’t exist, a new file is created. Returns NULL, if unable to open the
file.
Open for writing in binary mode. If the file exists, its contents are overwritten.
wb
If the file does not exist, it will be created.
Searches file. If the file is opened successfully fopen( ) loads it into memory
and sets up a pointer that points to the last character in it. It opens only in the
a
append mode. If the file doesn’t exist, a new file is created. Returns NULL, if
unable to open the file.
Open for append in binary mode. Data is added to the end of the file. If the file
ab
does not exist, it will be created.
r+ Searches file. It is opened successfully fopen( ) loads it into memory and sets
Opening
Modes Description
up a pointer that points to the first character in it. Returns NULL, if unable to
open the file.
Open for both reading and writing in binary mode. If the file does not exist,
rb+
fopen( ) returns NULL.
Searches file. If the file exists, its contents are overwritten. If the file doesn’t
w+
exist a new file is created. Returns NULL, if unable to open the file.
Open for both reading and writing in binary mode. If the file exists, its contents
wb+
are overwritten. If the file does not exist, it will be created.
Searches file. If the file is opened successfully fopen( ) loads it into memory
and sets up a pointer that points to the last character in it. It opens the file in
a+
both reading and append mode. If the file doesn’t exist, a new file is created.
Returns NULL, if unable to open the file.
Open for both reading and appending in binary mode. If the file does not exist,
ab+
it will be created.
As given above, if you want to perform operations on a binary file, then
you have to append ‘b’ at the last. For example, instead of “w”, you have
to use “wb”, instead of “a+” you have to use “a+b”.
Example of Opening a File
C
#include <stdio.h>
#include <stdlib.h>
int main()
// fopen
FILE* fptr;
if (fptr == NULL) {
"now exit.");
exit(0);
return 0;
Output
The file is not opened. The program will now exit.
The file is not opened because it does not exist in the source directory.
But the fopen() function is also capable of creating a file if it does not
exist. It is shown below
Create a File in C
The fopen() function can not only open a file but also can create a file if it
does not exist already. For that, we have to use the modes that allow the
creation of a file if not found such as w, w+, wb, wb+, a, a+, ab, and ab+.
FILE *fptr;
fptr = fopen("[Link]", "w");
#include <stdio.h>
#include <stdlib.h>
int main()
// file pointer
FILE* fptr;
"exit now");
exit(0);
else {
return 0;
Output
The file is created Successfully.
Use formatted string and variable arguments list to take input from a
fscanf()
file.
Example:
FILE * fptr;
fptr = fopen(“[Link]”, “r”);
fscanf(fptr, "%s %s %s %d", str1, str2, str3, &year);
char c = fgetc(fptr);
Write to a File
The file write operations can be performed by the functions fprintf()
and fputs() with similarities to read operations. C programming
also provides some other functions that can be used to write data
to a file such as:
Function Description
fputs() Prints the whole line in the file and a newline at the end.
fwrite() This functions write the specified amount of bytes to the binary file.
Example:
FILE *fptr ;
fptr = fopen(“[Link]”, “w”);
fprintf(fptr, "%s %s %s %d", "We", "are", "in", 2012);
fputc("a", fptr);
Closing a File
The fclose() function is used to close the file. After successful file
operations, you must always close a file to remove it from the
memory.
Syntax of fclose()
fclose(file_pointer);
where the file_pointer is the pointer to the opened file.
Example:
FILE *fptr ;
fptr= fopen(“[Link]”, “w”);
---------- Some file Operations -------
fclose(fptr);
Examples of File Handing in C
Example 1: Program to Create a File, Write in it, And Close
the File
C
#include <stdio.h>
#include <string.h>
int main()
{
// Declare the file pointer
FILE* filePointer;
if (filePointer == NULL) {
else {
printf("The file is now opened.\n");
if (strlen(dataToBeWritten) > 0) {
fputs(dataToBeWritten, filePointer);
fputs("\n", filePointer);
return 0;
}
Example 2: Program to Open a File, Read from it, And Close the
File
C
#include <stdio.h>
#include <string.h>
int main()
FILE* filePointer;
// file
char dataToBeRead[50];
if (filePointer == NULL) {
else {
!= NULL) {
fclose(filePointer);
printf(
return 0;
Output
The file is now opened.
GeeksforGeeks-A Computer Science Portal for Geeks
Data successfully read from file GfgTest.c
The file is now closed.
This program reads the text from the file named GfgTest.c which we
created in the previous example and prints it in the console.
Read and Write in a Binary File
Till now, we have only discussed text file operations. The operations
on a binary file are similar to text file operations with little difference.
Opening a Binary File
To open a file in binary mode, we use the rb, rb+, ab, ab+, wb, and
wb+ access mode in the fopen() function. We also use the .bin file
extension in the binary filename.
Example
fptr = fopen("[Link]", "rb");
Write to a Binary File
We use fwrite() function to write data to a binary file. The data is
written to the binary file in the from of bits (0’s and 1’s).
Syntax of fwrite()
size_t fwrite(const void *ptr, size_t size, size_t nmemb,
FILE *file_pointer);
Parameters:
ptr: pointer to the block of memory to be written.
size: size of each element to be written (in bytes).
nmemb: number of elements.
file_pointer: FILE pointer to the output file stream.
Return Value:
Number of objects written.
Example: Program to write to a Binary file using fwrite()
C
#include <stdio.h>
#include <stdlib.h>
struct threeNum {
int main()
int n;
FILE* fptr;
exit(1);
int flag = 0;
num.n1 = n;
num.n2 = 5 * n;
num.n3 = 5 * n + 1;
fptr);
if (!flag) {
else {
fclose(fptr);
return 0;
}
Output
Write Operation Successful
#include <stdio.h>
#include <stdlib.h>
struct threeNum {
int n1, n2, n3;
};
int main()
int n;
FILE* fptr;
exit(1);
fclose(fptr);
return 0;
Output
n1: 1 n2: 5 n3: 6
n1: 2 n2: 10 n3: 11
n1: 3 n2: 15 n3: 16
n1: 4 n2: 20 n3: 21
fseek() in C
If we have multiple records inside a file and need to access a
particular record that is at a specific position, so we need to loop
through all the records before it to get the record. Doing this will waste
a lot of memory and operational time. To reduce memory consumption
and operational time we can use fseek() which provides an easier way
to get to the required data. fseek() function in C seeks the cursor to
the given record in the file.
Syntax for fseek()
int fseek(FILE *ptr, long int offset, int pos);
Example of fseek()
C
int main()
FILE* fp;
fp = fopen("[Link]", "r");
fseek(fp, 0, SEEK_END);
printf("%ld", ftell(fp));
return 0;
Output
81
rewind() in C
The rewind() function is used to bring the file pointer to the beginning
of the file. It can be used in place of fseek() when you want the file
pointer at the start.
Syntax of rewind()
rewind (file_pointer);
Example
C
#include <stdio.h>
int main()
FILE* fptr;
// using rewind()
rewind(fptr);
printf("%s", buf);
return 0;
Output
Geeks for Geeks