0% found this document useful (0 votes)
10 views193 pages

PPS Notes

The document provides an overview of computer systems, detailing the components of hardware and software, including input devices, CPU, memory types, and storage classifications. It explains the functions of primary memory (RAM and ROM), their characteristics, advantages, and disadvantages, as well as the various types of ROM. Additionally, it covers the features of memory, access methods, and the importance of memory in computing.

Uploaded by

radher50055
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views193 pages

PPS Notes

The document provides an overview of computer systems, detailing the components of hardware and software, including input devices, CPU, memory types, and storage classifications. It explains the functions of primary memory (RAM and ROM), their characteristics, advantages, and disadvantages, as well as the various types of ROM. Additionally, it covers the features of memory, access methods, and the importance of memory in computing.

Uploaded by

radher50055
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Unit -1

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 System General Application


Operati ng suppor t Developme n Purpose Specific
Systems

Fig: Types of 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.

What is computer memory?


Computer memory is any physical device, used to store data, information or instruction temporarily o
permanently. It is the collection of storage units that stores binary information in the form of bits. Th
memory block is split into a small number of components, called cells. Each cell has a unique addres
to store the data in memory, ranging from zero to memory size minus one. For example, if the size o
computer memory is 64k words, the memory units have 64 * 1024 = 65536 locations or cells. Th
address of the memory's cells varies from 0 to 65535.

Why do we need a computer memory?


In the computer system, we need computer memory to store various types of data like text, images
video, audio, documents, etc. We can retrieve it when the data is required. For example, when we writ
and execute any computer program, it is initially stored in primary memory. If the processor does no
need particular items for a longer time, the program or data is automatically saved into the permanen
or secondary memory. Then the data is called from secondary memory to main memory and perform
the execution of codes.

Features of Memory
Following are the different features of the memory system that includes:

1. Location: It represents the internal or external location of the memory in a computer. Th


internal memory is inbuilt in computer memory. It is also known as primary memory. th
example of primary memory are registers, cache and main memory. Whereas, external memor
is the separate storage device from the computer, such as disk, tape, USB pen drive.
2. Capacity: It is the most important feature of computer memory. Storage capacity can vary i
external and internal memory. External devices' storage capacity is measured in terms of bytes
whereas the internal memory is measured with bytes or words. The storage word length ca
vary in bits, such as 8, 16 or 32 bits.
3. Access Methods: Memory can be accessed through four modes of memory.
o DMA: As the name specifies, Direct Memory Address (DMA) is a method that allow
input/output (I/O) devices to access or retrieve data directly or from the main memory.
o Sequential Access Method: The sequential access method is used in a data storag
device to read stored data sequentially from the computer memory. Whereas, the dat
received from random access memory (RAM) can be in any order.
o Random Access Method: It is a method used to randomly access data from memory
This method is the opposite of SAM. For example, to go from A to Z in random access, we
can directly jump to any specified location. In the Sequential method, we have to follow a
intervening from A to Z to reach at the particular memory location.
o Associative Access Method: It is a special type of memory that optimizes searc
performance through defined data to directly access the stored information based on
memory address.
4. Unit of transfer: As the name suggests, a unit of transfer measures the transfer rate of bit
that can be read or write in or out of the memory devices. The transfer rate of data can b
different in external and internal memory.
o Internal memory: The transfer rate of bits is mostly equal to the word size.
o External memory: The transfer rate of bit or unit is not equal to the word length. It i
always greater than a word or may be referred to as blocks.
5. Performance: The performance of memory is majorly divided into three parts.
o Access Time: In random access memory, it represents the total time taken by memor
devices to perform a read or write operation that an address is sent to memory.
o Memory Cycle Time: Total time required to access memory block and additiona
required time before starting second access.
o Transfer rate: It describes the transfer rate of data used to transmit memory to or from
an external or internal memory device. Bit transfer can be different for different externa
and internal devices.
6. Physical types: It defines the physical type of memory used in a computer such as magnetic
semiconductor, magneto-optical and optical.
7. Organization: It defines the physical structure of the bits used in memory.
8. Physical characteristics: It specifies the physical behavior of the memory like volatile, non
volatile or non-erasable memory. Volatile memory is known as RAM, which requires power t
retain stored information, and if any power loss has occurred, stored data will be lost. Non
volatile memory is a permanent storage memory that is used to obtain any stored information
even when the power is off. Non-erasable memory is a type of memory that cannot be erase
after the manufactured like ROM because at the time of manufactured ROM are programmed.

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.

The primary memory is further divided into two parts:

1. RAM (Random Access Memory)


2. ROM (Read Only Memory)

Random Access Memory (RAM)


Random Access Memory (RAM) is one of the faster types of main memory accessed directly by th
CPU. It is the hardware in a computer device to temporarily store data, programs or program results. I
is used to read/write data in memory until the machine is working. It is volatile, which means if a powe
failure occurs or the computer is turned off, the information stored in RAM will be lost. All data stored i
computer memory can be read or accessed randomly at any time.

There are two types of RAM:

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

1. It requires continuously refreshed to retain the data.


2. It is slower than SRAM
3. It holds a large amount of data
4. It is the combination of capacitor and transistor
5. It is less expensive as compared to SRAM
6. Less power consumption

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.

Characteristics of Static Ram

1. It does not require to refresh.


2. It is faster than DRAM
3. It is expensive.
4. High power consumption
5. Longer life
6. Large size
7. Uses as a cache memory

SRAM Vs. DRAM

SRAM DRAM

It is a Static Random-Access Memory. It is a Dynamic Random Access Memory.

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.

It does not require periodic refreshing to It requires periodically refreshing to preserve


preserve the information. the information.

It uses in cache memory. It is used in the main memory.

The cost of SRAM is expensive. The cost of DRAM is less expensive.

It has a complex structure. Its structure is simple.

It requires low power consumption. It requires more power consumption.


Advantages of RAM

o It is a faster type of memory in a computer.


o It requires less power to operate.
o Program loads much faster
o More RAM increases the performance of a system and can multitask.
o Perform read and write operations.
o The processor can read information faster than a hard disc, floppy, USB, etc.

Disadvantages of RAM

o Less RAM reduces the speed and performance of a computer.


o Due to volatile, it requires electricity to preserve the data.
o It is expensive than ROM
o It is unreliable as compared to ROM
o The Size of RAM is limited.

Read-Only Memory (ROM)


ROM is a memory device or storage medium that is used to permanently store information inside
chip. It is a read-only memory that can only read stored information, data or programs, but we canno
write or modify anything. A ROM contains some important instructions or program data that ar
required to start or boot a computer. It is a non-volatile memory; it means that the stored informatio
cannot be lost even when the power is turned off or the system is shut down.
Types of ROM

There are five types of Read Only Memory:

1. MROM (Masked Read Only Memory)


MROM is the oldest type of read-only memory whose program or data is pre-configured by th
integrated circuit manufacture at the time of manufacturing. Therefore, a program or instructio
stored within the MROM chip cannot be changed by the user.
2. PROM (Programmable Read Only Memory)
It is a type of digital read-only memory, in which the user can write any type of information o
program only once. It means it is the empty PROM chip in which the user can write the desired
content or program only once using the special PROM programmer or PROM burner device; afte
that, the data or instruction cannot be changed or erased.
3. EPROM (Erasable and Programmable Read Only Memory)
It is the type of read only memory in which stored data can be erased and re-programmed onl
once in the EPROM memory. It is a non-volatile memory chip that holds data when there is n
power supply and can also store data for a minimum of 10 to 20 years. In EPROM, if we want t
erase any stored data and re-programmed it, first, we need to pass the ultraviolet light for 4
minutes to erase the data; after that, the data is re-created in EPROM.
4. EEPROM (Electrically Erasable and Programmable Read Only Memory)
The EEROM is an electrically erasable and programmable read only memory used to erase store
data using a high voltage electrical charge and re-programmed it. It is also a non-volatil
memory whose data cannot be erased or lost; even the power is turned off. In EEPROM, th
stored data can be erased and reprogrammed up to 10 thousand times, and the data erase on
byte at a time.
5. Flash ROM
Flash memory is a non-volatile storage memory chip that can be written or programmed in sma
units called Block or Sector. Flash Memory is an EEPROM form of computer memory, and th
contents or data cannot be lost when the power source is turned off. It is also used to transfe
data between the computer and digital devices.

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 Vs. ROM

RAM ROM

It is a Random-Access Memory. It is a Read Only Memory.

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.

It is a faster and expensive memory. It is a slower and less expensive memory.

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.

Features of Secondary Memory

o Its speed is slower than the primary/ main memory.


o Store data cannot be lost due to non-volatile nature.
o It can store large collections of different types, such as audio, video, pictures, text, software, etc
o All the stored data in a secondary memory cannot be lost because it is a permanent storag
area; even the power is turned off.
o It has various optical and magnetic memories to store data.

Types of Secondary Memory


The following are the types of secondary memory devices:

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 Disc (BD)

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. Cache memory is the faster memory as compared to the main memory.


2. It stores all data and instructions that are repeatedly used by the CPU for improving th
performance of a computer.
3. The access time of data is less than the main memory.

Disadvantage 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.

Primary Vs. Secondary Memory

Primary Memory Secondary Memory


It is also known as temporary memory. It is also known as a permanent memory.

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 is a faster memory. It is a slower memory.

It has limited storage capacity. It has a large storage capacity.

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';

Rules to Name an Identifier in C


A programmer has to follow certain rules while naming variables. For the valid
identifier, we must follow the given below set of rules.
1. An identifier can include letters (a-z or A-Z), and digits (0-9).
2. An identifier cannot include special characters except the ‘_’ underscore.
3. Spaces are not allowed while naming an identifier.
4. An identifier can only begin with an underscore or letters.
5. We cannot name identifiers the same as keywords because they are reserved
words to perform a specific task. For example, printf, scanf, int, char, struct,
etc. If we use a keyword’s name as an identifier the compiler will throw an
error.
6. The identifier must be unique in its namespace.
7. C language is case-sensitive so, ‘name’ and ‘NAME’ are different identifiers.
Keywords in C:

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

double else enum extern float for goto if

int long register return short signed sizeof static

struct switch typedef union unsigned void volatile while

Role of main Function in C


he main function in C is the entry point of a program where the execution of a
program starts. It is a user-defined function that is mandatory for the execution of
a program because when a C program is executed, the operating system starts
executing the statements in the main() function.
Syntax of C main() Function
return_typemain() {
// Statement 1;
// Statement 2;
// and so on..
return;
}
Types of C main Functions
1. Main function with no arguments and void return type
Example:
Void main()
{
// statements
}
2. Main function with no arguments and int return type
Example:
intmain()
{
// statements
return 0;
}

3. Main function with the Command Line Arguments

intmain(intargc, char *argv[])

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”);

Scanf() in C:-The scanf() function is a commonly used input function in the C


programming language. It allows you to read input from the user or from a file and
store that input in variables of different data types.

The syntax of scanf

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.

The data types in C can be classified as follows:


Types Description

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.

Data type variable name;


Here,
 data_type: Type of data that a variable can store.
 variable_name: Name of the variable given by the user.
 Example
 Introllno; // integer variable
char a; // character variable
float fees; // float variables

Rules for Variable Names in C Programming


There are rules for defining the variables in C Programming, and those rules are as
follows:
 Variable names will always start with an alphabet and underscore. Example:
num, name, a, x, _value.
 Variable names in C will never start with a digit. Example: 4name, is an invalid
name.
 Variables should be declared with their data type. Variable names without data
type will generate errors. For example, int a =2 is valid. a = 2 is an invalid
variable.
 C is a strongly typed language, you cannot change the data type of a variable after
its definition.
 Reserved keywords cannot be used as a variable name in C programming.
 No white spaces are allowed within the variable name.
What is the Scope and Lifetime of a Variable
The scope is the variable region in which it can be used. Beyond that area, you
cannot use a variable. The local and global are two scopes for C variables. The
local scope is limited to the code or function in which the variable is declared.
Global scope is the entire program. Global variables can be used anywhere
throughout the program.
Lifetime is the life or alive state of a variable in the memory. It is the time for
which a variable can hold its memory. The lifetime of a variable is static and
automatic. The static lifetime variable remains active till the end of the program.
An automatic lifetime variable or global variable activates when they are called
else they vanish when the function executes.
The scope of variables can be defined with their declaration, and variables are
declared mainly in two ways:
o Global Variable: Outside of all the functions
o Local Variable: Within a function block:

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. }

1. What is a storage class in C?

A storage class specifier in the C programming language controls how variables


are allocated, accessed, and stored in memory. It establishes a variable's range,
lifetime, and visibility within a program.

Types of Storage Class in C


There are four types of storage classes in C,
 Automatic storage class in C
 Static storage class in c
 Register storage class in c
 External storage class in c

[Link] Storage Class in C


This is the default storage class for all the variables declared inside a function
or a block. Hence, the keyword auto is rarely used while writing programs in C
language. Auto variables can be only accessed within the block/function they
have been declared and not outside them (which defines their scope). Of
course, these can be accessed within nested blocks within the parent
block/function in which the auto variable was declared.

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.
}

[Link] Storage Class in C

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 >>

4. External Storage Class in C

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);
}

Overview of storage classes in C

Storage Names of Storage Default


Scope Lifetime
Classes class Place Value

Garbage
auto Automatic RAM Local Within function
Value

Till the end of the main


extern External RAM Zero Global program Maybe declared
anywhere in the program

Till the end of the main


static Static RAM Zero Local program, Retains value
between multiple functions call
Garbage
register Register Register Local Within function
Value

Difference between Global Variable and Local Variable

Global Variable Local Variable

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.

It can be accessed throughout the It can only be accessed by the function


program by all the functions present statements in which it is declared and not by the
in the program. other functions.

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.

Use of the Constants in C


A constant is basically a named memory location in a program that holds a single
value throughout the execution of that program. It can be of any data type-
character, floating-point, string and double, integer, etc. There are various types of
constants in C. It has two major categories- primary and secondary constants.
Character constants, real constants, and integer constants, etc., are types of primary
constants. Structure, array, pointer, union, etc., are types of secondary constants.

What are Literals in C?


Literals are referred to as the values that we assign to the variables that remain
constant throughout the execution of a program. For instance, the
expression “constint =10;”, is a type of constant expression, while we refer to the
value 10 as a constant integer literal.
Ways to define constant in C

There are two ways to define constant in C programming.

1. const keyword
2. #define preprocessor

1. Use of Constkeyword:-The ‘const’ keyword is used to create a constant of


any given datatype in a program. For creating a constant, we have to prefix
the declaration of the variable with the ‘const’ keyword.

Syntax for constant variable is:-

const datatype constantName = value ;

OR

const datatype constantName ;

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:

Difference between Constant and Variables


The following table lists the differences between the constant and variables in C:

Constant Variables

A constant is a variable or value that cannot A variable is a name associated


be altered once defined. with some memory location.

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.

A variable can only be defined


A constant can be defined by
using the standard variable
using #define or const keyword.
definition syntax.

Example: #define pi 3.14 Example: intvar = 25;


constint pi = 3.14; var = 10;

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.

What is an Assembly Language?


An assembly language is a low-level language. It gives instructions to the processors for
different tasks. It is specific for any processor. The machine language only consists of 0s and 1s
therefore, it is difficult to write a program in it. On the other hand, the assembly language is
close to a machine language but has a simpler language and code.
Unit-1 Part2
Algorithm
An algorithm is a set of commands that must be followed for a computer to perform
calculations or other problem-solving [Link] to its formal definition, an
algorithm is a finite set of instructions carried out in a specific order to perform a
particular task.
How algorithms work:

 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.

 Implementation: Algorithms are implemented in various programming languages,


enabling computers to execute them and produce desired outcomes.

 Qualities of a Good Algorithm


 Efficiency: A good algorithm should perform its task quickly and use minimal
resources.

 Correctness: It must produce the correct and accurate output for all valid inputs.

 Clarity: The algorithm should be easy to understand and comprehend, making it


maintainable and modifiable.

 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.

 Robustness: Capable of handling unexpected inputs or errors gracefully without


crashing.

 Adaptability: Ideally, it can be applied to a range of related problems with minimal


adjustments.

 Simplicity: Keeping the algorithm as simple as possible while meeting its


requirements, avoiding unnecessary complexity.

Steps to solve the problem

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:

 What data are available?


 Where is that data?
 What formulas pertain to the problem?
 What rules exist for working with the data?
 What relationships exist among the data values?

2. Developing an algorithm/Flowchart:- An algorithm is a plan for solving a problem, but


plans come in several levels of detail. It's usually better to start with a high-level algorithm that
includes the major part of a solution, but leaves the details until later. We can use an everyday
example to demonstrate a high-level algorithm.

1) Problem: I need a send a birthday card to my brother, Mark.


2) Analysis: I don't have a card. I prefer to buy a card rather than make one myself.
3) High-level algorithm:
4) Go to a store that sells greeting cards
Select a card
Purchase a card
Mail the card

[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.

Algorithm: To find the sum and product of two given numbers:

Step 1:Start

Step 2: Read A , B

Step 3: Set Sum= A+B

Step 4: Set Product=A*B

Step 5: Print Sum, Product

Step 6:Stop

Ex.2 Write an algorithm to find the area of rectangle:

Step 1: START

Step2: INPUT length,breadth,area=0

Step 3: SET area=length*breadth

Step 4: PRINT area


Step 5: STOP

Ex 3:Find the factorial of a number

Step 1: Start

Step 2: Declare variables n, factorial and i.

Step 3: Initialize variables

factorial = 1

i =1

Step 4: Read value of n

Step 5: Repeat the steps until i == n

factorial = factorial*i

i = i+1

Step 6: Display factorial

Step 7: Stop

Ex.4Find the largest number among three numbers

Step 1: Start

Step 2: Declare variables a,b and c.

Step 3: Read variables a,b and c.

Step 4: If a > b and a >c then

Print a is the largest number.

Else if b > c
Print b is the largest number.

Else

Print c is the largest number.

Step 5: Stop

What is FlowChart?

A flowchart is a type of diagram that represents a workflow or process. A flowchart can


also be defined as a diagrammatic representation of an algorithm, a step-by-step
approach to solving a task.
What are the advantages and limitations of flowcharts when used to solve a problem?

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

Difference Between Algorithm And Flowchart


Parameters Flowchart Algorithm

Description A flowchart is a graphical An algorithm is a procedure or set of


representation of the steps a program rules that defines how a program is
takes to process data. In this, we can to be executed. Or we can say that it
use several geometric patterns to is a set of instructions for solving a
illustrate the numerous actions the well-defined computational problem.
program carries out.

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.

Use A flowchart is used in documenting, An algorithm is used to represent the


designing, and analyzing a program in concept of decidability.
different disciplines.

Users A Flowchart doesn’t demand the An algorithm demands the


knowledge of a computer knowledge of a computer
programming language. programming language.

Debugging It is easy to debug the errors in It is difficult to debug the errors in


flowcharts. algorithms.

Implementation In flowcharts, no rules are used. In algorithms, predefined rules are


used.

Branching and Simple to display branching and Hard to display branching and
Looping looping. looping.

Solution In a flowchart, the solution is In an algorithm, the solution is


represented in a graphical format. presented in non non-computer
language.

Operators are symbols that we use when performing operations on one or


more operands. The primary types of operators in C are arithmetic, logical,
relational, conditional, bitwise, and assignment.
Arithmetic Operators
These are the operators that help us perform arithmetic and mathematical operations on
operands. Arithmetic operators can be divided into two types:

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)

This operator adds the two


+ C + D = 30
operands given as input.
It subtracts the value of the
− second operand from the C − D = -10
first one.

This operator multiplies the


* C * D = 200
two operands.

Divides the operand in the


/ numerator by the operand in D / C= 2
the denominator.

The modulus operator gives


% out the remainder for an D%C=0
integer division.

The increment operator


++ increases the integer value C++ = 11
by one.

The decrement operator


-- decreases the integer value C-- = 9
by one.

The Increment and Decrement


Operators
As mentioned before, increment and decrement operators are unary operators
that increase and decrease the value of an operand, respectively. The
decrement and increment operators can be divided into two groups, as follows:

Type of Sample Operator


Description/ Explanation
Operator Expression
Prefix Here, q increases the initial
Increment ++q value by 1, after which the
Operator program uses the value of q.

Postfix The program uses the current


Increment q++ value of q and later on
Operator increases the value of q by 1.

Prefix Here, q decreases the value


Decrement –q by 1 first, and then the
Operator program uses the value of q.

Postfix The program uses the current


Decrement q– value of q and then decreases
Operator the value of q by 1.

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)

== Equal to 6 == 5 is evaluated to 0 False

> Greater than 6 > 5 is evaluated to 1 True

< Less than 6 < 5 is evaluated to 0 False

!= Not equal to 6!= 5 is evaluated to 1 True


Greater than or
>= 6 >= 5 is evaluated to 1 True
equal to

<= Less than or equal to 6 <= 5 is evaluated to 0 False

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

Logical AND operator If c= 6 and d = 5 then,


&& It returns true only if all expression ((c==5) && (d>5)) False
conditions are true. equals to 0.

Logical OR operator If c = 6 and d = 5 then,


|| It returns true if either one expression ((c==6) || (d>5)) True
of the conditions is true. equals 1.

Logical NOT operator


If c = 6 then, expression !
! It returns true only if the False
(c==6) equals to 0.
condition is false.

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.

Operators Meaning of operators

& Bitwise AND

| Bitwise OR

^ Bitwise exclusive OR

~ Bitwise complement

<< Shift left

>> Shift right

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.

Operator Example Same as

= 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

Ternary or Conditional Operators


Ternary or conditional operators to assess a condition and return a value based on whether the
condition is true or false. The name for ternary operators comes from the fact that it requires
three operands—the condition to be evaluated, the value to be returned if the condition is true,
and the value to be returned if the condition is false.

Syntax

condition ? value_if_true : value_if_false

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.

&x; returns the actual


It returns the memory location address of the variable.
&
address of a variable. It can be any address in
the memory like 4, 70,104.

If Condition is true ? then


The conditional operator is the
value X : otherwise value
?: combination of two expressions
Y will be returned as
(?:).
output.

The star or asterisk operator acts as a *a, it points to the variable


* pointer to a variable.
a
What is a special operator in C?

There is no specific "special operator" in the C programming language. However, certain


operators have a reputation for being "special" due to their particular or specialized capability.
These consist of:

1. The sizeof operator- It returns a data type's or variable's size in bytes.

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 (&).

5. Operators for conditional compilation (#ifdef, #ifndef, #endif): These preprocessor


directives are used to conditionally compile specific code sections based on whether or
not a particular macro is declared.
What are the types of C operators?

The different types of operators in C are as follows:

1. Arithmetic operators: These operators are used to execute addition, subtraction,


multiplication, division, and modulus operations in mathematics.

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.

5. Assignment Operators: These operators are used to assign a variable a value.

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++;

What is the difference between the ‘=’ and ‘==’ operators?


Answer:
‘=’ is a type of assignment operator that places the value in right to the variable on left,
Whereas ‘==’ is a type of relational operator that is used to compare two elements if
the elements are equal or not.

Control Statements in C

Control statements in C are programming constructs that are used to


control the flow of execution in a program. They allow a programmer to
specify conditions that determine which statements are executed and
which are skipped, to loop through statements until a condition is met, or
to jump to a different part of the program.
o Control statements in C are classified into following:
o Sequential
o Decision or branching
o Repetition or iteration

Sequential statements:

A computer program is sequential in nature and runs from top to bottom


by default. The decision-making statements in C provide an alternative
line of execution. You can ask a group of statements to be repeatedly
executed till a condition is satisfied.
o

Decision-Making Statements in C

In C, decision-making statements are technology structures enabling


programmers to make decisions based on specific conditions or criteria.
In C, there are three primary decision-making statements that you can
use:

The statements below in C can be used to make decisions.


 If Statement.
 If..else statement.
 if..else-if ladder
 Nested if statement.
 Switch statement.
 Jump Statement.(break, continue,goto)

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;
...
}

An if statement consists of a boolean expression followed by one or


more statements.

if...else statement

The if – else statement offers an alternative path when the condition isn't
met.
Syntax
if(Boolean expr)
{
Expr;
...
}
else
{
Expr;
...
}

An if statement can be followed by an optional else statement, which


executes when the Boolean expression is false.

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

// C Program to check whether a number is positive, negative or 0 using if


else if ladder

#include <stdio.h>

intmain()

intn = 0;
// all Positive numbers will make this

// condition true

if(n > 0) {

printf("Positive");

// all Negative numbers will make this

// condition true

elseif(n < 0) {

printf("Negative");

// if a number is neither Positive nor Negative

else{

printf("Zero");
}

return0;

Output
Zero
Example 2: Calculate Grade According to marks

// C Program to Calculate Grade According to marks

// using the if else if ladder

#include <stdio.h>

intmain()

intmarks = 91;

if(marks <= 100 && marks >= 90)

printf("A+ Grade");

elseif(marks < 90 && marks >= 80)


printf("A Grade");

elseif(marks < 80 && marks >= 70)

printf("B Grade");

elseif(marks < 70 && marks >= 60)

printf("C Grade");

elseif(marks < 60 && marks >= 50)

printf("D Grade");

else

printf("F Failed");

return0;

nested if statements

Nested if statements are required to Build intricate decision trees,


evaluating multiple nested conditions for nuanced program flow.
You can use one if or else if statement inside another if or else if
statement(s).

switch statement

A switch statement Simplifies multi-way Choices by evaluating a single


variable against multiple values, executing specific code based on the
match. It allows a variable to be tested for equality against a list of
values.
Syntax
switch(expression){

case constant-expression :
statement(s);
break;/* optional */
case constant-expression :
statement(s);
break;/* optional */

/* you can have any number of case statements */


default:/* Optional */
statement(s);
}

As in if statements, You can use one switch statement inside another


switch statement(s).
break statement
#include <stdio.h>
intmain() {
intnum = 5;
while (num> 0) {
if (num == 3)
break;
printf("%d\n", num);
num--;
}}
Output:

5
4

C, the break statement is used in switch – case construct as well as in a


loop. When used inside a loop, it causes the repetition to be abandoned.
continue statement
In C, the continue statement causes the conditional test and increment
portions of the loop to [Link] you want to skip to the next
iteration but remain in the loop, you should use the continue statement.

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

The syntax for a goto statement in C is as follows −

goto label;
..
.
label: statement;

With the goto statement, the flow can be directed to any previous step or
any subsequent step.

Looping:-

Loops are a programming construct that makes a portion of code repeat


a certain number of times or until the desired condition is met.
Repetitive tasks are common in programming, and loops are essential to
save time and minimize errors.
Programming languages provide various control structures that allow for
more complicated execution paths. A loop statement allows us to
execute a statement or group of statements multiple times. Given below
is the flowchart of a loop statement in most of the programming

languages –

C’ programming language provides us with three types of loop


constructs:

1. The while loop

2. The do-while loop

3. The for loop

While Loop in C
A while loop is the most straightforward looping structure. While loop
syntax in C programming language is as follows:

Syntax of While Loop in C


while (condition)
{
statements;
}
It is an entry-controlled loop. In while loop, a condition is evaluated
before processing a body of the loop. If a condition is true then and only
then the body of a loop is executed. After the body of a loop is executed
then control again goes back at the beginning, and the condition is
checked if it is true, the same process is executed until the condition
becomes false. Once the condition becomes false, the control goes out of
the loop.

Following program illustrates while loop in C programming example:

#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.

Syntax of Do-While Loop in C


do {
statements
} while (expression);
As we saw in a while loop, the body is executed if and only if the
condition is true. In some cases, we have to execute a body of the loop at
least once even if the condition is false. This type of operation can be
achieved by using a do-while 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 syntax of a for loop in C programming language is −


for ( initialization; condition; increment ) {
statement(s);
}

Here is the flow of control in a 'for' loop −

 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 main (){

int a;
/* for loop execution */
for( a=10; a <20; a = a +1){
printf("value of a: %d\n", a);
}

return0;
}

Difference Between While and Do While Loop


While and do while loops are defined as control structures that repeat a
block of code until the condition that is given is true.
The main difference between the two loops is that the while loop checks
the condition before the execution of the statement(s) whereas the do-
while loop ensures that the statement(s) are executed at least once before
evaluating the condition. While loop is entry-controlled and Do-while is
exit controlled.
While Loop Do-While Loop

In the While loop, the condition In Do while-loop, the statement is


is tested before any statement is executed at least once even if the
executed. condition is false

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 is an entry-controlled Do-while loop is an exit-controlled


loop. loop.

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:-

Difference between break and continue:

Program to find the factorial of the number


Write a program to print fibnocii series

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

Write a program to print prime no 1 to 100

#include <stdio.h>

intmain()

inti, a = 1, count;

while(a <= 100)

count = 0;

i = 2;

while(i<= a/2)

if(a%i == 0)

count++;

break;

i++;

}
if(count == 0 && a != 1 )

printf(" %d ", a);

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.

C array is beneficial if you have to store similar elements.


For example, if we want to store the marks of a student in
6 subjects, then we don't need to define different
variables for the marks in the different subject. Instead of
that, we can define an array which can store the marks in
each subject at the contiguous memory locations.

Properties of Array

The array contains the following properties.

o Each element of an array is of same data type and


carries the same size, i.e., int = 4 bytes.
o Elements of the array are stored at contiguous
memory locations where the first element is stored
at the smallest memory location.
o Elements of the array can be randomly accessed
since we can calculate the address of each element
of the array with the given base address and the size
of the data element.

Advantage of C Array

1) Code Optimization: Less code to the access the data.

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.

4) Random Access: We can access any element randomly


using the array.

Disadvantage of C Array

1) Fixed Size: Whatever size, we define at the time of


declaration of the array, we can't exceed the limit.

Declaration of C Array

We can declare an array in the c language in the


following way.

1. data_type array_name[array_size];

int marks[5];

Initialization of Array

The simplest way to initialize an array is by using the


index of each element. We can initialize each element of
the array by using the index. Consider the following
example.
1. marks[0]=80;//initialization of array
2. marks[1]=60;
3. marks[2]=70;
4. marks[3]=85;
5. marks[4]=75;

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

C Array: Declaration with Initialization

We can initialize the c array at the time of declaration.


Let's see the code.

1. int marks[5]={20,30,40,50,60};

In such case, there is no requirement to define the size . So it


may also be written as the following code.

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 };

// modifying element at index 2


arr[2] = 100;

// traversing array using for loop


printf("Elements in Array: ");
for(inti = 0; i< 5; i++) {
printf("%d ", arr[i]);
}

return0;
}

Types of Array in C

There are two types of arrays based on the number of


dimensions it has. They are as follows:
1. One Dimensional Arrays (1D Array)
2. Two Dimensional Arrays
3. Multidimensional Arrays

1. One Dimensional Array in C

The One-dimensional arrays, also known as 1-D arrays in C are


those arrays that have only one dimension. A one dimensional
array in C contains a series of elements of the same datatype. The
elements are zero-indexed, meaning the first element is in position or
index 0, and the last element is in position or index (array size) - 1.
Syntax of 1D Array in C
array_name [size];
Write a program to print 10 no. using array
#include<stdio.h>
intmain()
{
intn[10],i;
printf(“\n enter 10 numbers”);
for(i=0;i<10;i++)
{
Scanf(“%d”,&n[i]);
}
for(i=0;i<10;i++)
{
Printf(“\n %d”,n[i]);
}
Return 0;
}

C Array Example: Sorting an array

In the following program, we are using bubble sort


method to sort the array in ascending order.

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. }

Two Dimensional Array in C

The two-dimensional array can be defined as an array of


arrays. The 2D array is organized as matrices which can
be represented as the collection of rows and columns. It
provides ease of holding the bulk of data at once which
can be passed to any number of functions wherever
required.

Declaration of two dimensional Array in C

The syntax to declare the 2D array is given below.

1. data_type array_name[rows][columns];

Consider the following example.


1. Intmatrix[4][3];

Here, 4 is the number of rows, and 3 is the number of


columns.

 // C Program to illustrate 2d array


 #include <stdio.h>

 intmain()
 {

 // declaring and initializing 2d array
 intarr[2][3] = { 10, 20, 30, 40, 50, 60 };

 printf("2D Array:\n");
 // printing 2d array
 for(inti = 0; i< 2; i++) {
 for(intj = 0; j < 3; j++) {
 printf("%d ",arr[i][j]);
 }
 printf("\n");
 }

 return0;
 }

// C Program to print the elements of a


// Two-Dimensional array

#include <stdio.h>

intmain(void)
{
// an array with 3 rows and 2 columns.
intx[3][2] = { { 0, 1 }, { 2, 3 }, { 4, 5 } };

// output each array element's value


for(inti = 0; i< 3; i++) {
for(intj = 0; j < 2; j++) {
printf("Element at x[%i][%i]: ", i,
j);
printf("%d\n", x[i][j]);
}
}

return(0);
}

Write a program that prompts the user to enter the


grades for each student and subject, and then
calculates the average grade for
each student and subject:

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

Multidimensional arrays are one of the most powerful features


of the C programming language. They allow you to store data in
a table-like format, where each row and column can be
accessed using an index. In this blog post, we'll look at
multidimensional arrays in C, including their syntax, example
usage, and output.

Syntax of Multidimensional Arrays in C

To create a multidimensional array in C, you need to specify


the number of dimensions and the size of each dimension. The general
syntax for declaring a multidimensional array is as follows:

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 each element's value


for(inti = 0; i< 2; ++i) {
for(intj = 0; j < 3; ++j) {
for(intk = 0; k < 2; ++k) {
printf("Element at x[%i][%i][%i]
= %d\n", i,
j, k, x[i][j][k]);
}
}
}
return(0);
}

There are some examples related to arrays:

Program to Add Two Matrices


1. #include <stdio.h>
2. int main() {
3. int m, n, i, j;
4. int a[m][n], b[m][n], c[m][n];
5.
6. printf("Enter the number of rows and columns of the ma
trices: ");
7. scanf("%d%d", &m, &n);
8. printf("Enter the elements of matrix A: \n");
9. for (i = 0; i < m; i++) {
10. for (j = 0; j < n; j++) {
11. scanf("%d", &a[i][j]);
12. }
13. }
14. printf("Enter the elements of matrix B: \n");
15. for (i = 0; i < m; i++) {
16. for (j = 0; j < n; j++) {
17. scanf("%d", &b[i][j]);
18. }
19. }
20. // add the matrices
21. for (i = 0; i < m; i++) {
22. for (j = 0; j < n; j++) {
23. c[i][j] = a[i][j] + b[i][j];
24. }
25. }
26. // print the result
27. printf("The sum of the two matrices is: \n");
28. for (i = 0; i < m; i++) {
29. for (j = 0; j < n; j++) {
30. printf("%d ", c[i][j]);
31. }
32. printf("\n");
33. }
34. return 0;
35. }

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);

// asssigning elements to the matrix


printf("\nEnter matrix elements:\n");
for (inti = 0; i< r; ++i)
for (int j = 0; j < c; ++j) {
printf("Enter element a%d%d: ", i + 1, j + 1);
scanf("%d", &a[i][j]);
}

// printing the matrix a[][]


printf("\nEntered matrix: \n");
for (inti = 0; i< r; ++i)
for (int j = 0; j < c; ++j) {
printf("%d ", a[i][j]);
if (j == c - 1)
printf("\n");
}

// computing the transpose


for (inti = 0; i< r; ++i)
for (int j = 0; j < c; ++j) {
transpose[j][i] = a[i][j];
}

// printing the transpose


printf("\nTranspose of the matrix:\n");
for (inti = 0; i< c; ++i)
for (int j = 0; j < r; ++j) {
printf("%d ", transpose[i][j]);
if (j == r - 1)
printf("\n");
}
return0;
}
Run Code

Output
Enter rows and columns: 2
3

Enter matrix elements:


Enter element a11: 1
Enter element a12: 4
Enter element a13: 0
Enter element a21: 5
Enter element a22: 2
Enter element a23: 7

Entered matrix:
1 4 0
5 2 7

Transpose of the matrix:


1 5
4 2
0 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

Write a program to search a given number from a list of n


numbers.
#include<stdio.h>
I
intmain()
{
inta[50],i ,s,loc,n;
printf(“\n enter no of elements in the list”);
scanf(“%d”,&n);
printf(“enter elements”);
for(i=0;i<n;i++)
{
scanf(“%d”,&a[i]);
printf(“\n enter element to search”);
scanf(“%d”,&s);
for(i=0;i<n,i++)
{
if(s==a[i])
{
loc=i+1;
printf(“\n Element %d is present at %d position”,s,loc);
break;
}
}
if(i==n)
printf(“\n element is not present in the list”);

return 0;
}

Array of Characters (Strings)


In C, we store the words, i.e., a sequence of characters in the
form of an array of characters terminated by a NULL character.
These are called strings in C language.

// C Program to illustrate strings


#include <stdio.h>

intmain()
{

// creating array of character


chararr[10] = { 'e', 'd', 'u', 'c',’a’, 't',
'i', 'o', 'n', '\0'};

// printing string
inti = 0;
while(arr[i]) {
printf("%c", arr[i++]);
}
return0;
}

Important Points to Remember About Array in C


 Fixed Size: Arrays have a fixed size determined at declaration.
 Zero-Based Index: Array elements are accessed using indices
starting from 0.
 Homogeneous: Arrays store elements of the same data type.
 Declaration: Declare an array by specifying its data type and size
(e.g., intnumbers[5]).
 Initialization: You can initialize arrays at declaration or later using
curly braces (e.g., intnumbers[5] = {1, 2, 3, 4, 5}).
 Accessing Elements: Access elements using square brackets
(e.g., numbers[2]).
 Bound Checking: C arrays do not have built-in boundary checks,
so be cautious to avoid accessing out-of-bounds indices.
 Arrays are passed to functions by reference,
Passing to Functions:
allowing modifications within the function to affect the original
array.
Difference Between One-Dimensional and Two-
Dimensional Array
Parameters One-dimensional array(1D) Two-dimensional array(2D)

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.

Declaration Syntax: Syntax:


type variable_name[size]; type variable_name[size1][size2];
Here type refers to the data Here type refers to datatype size1 refers to the
type, and size refers to the number of rows, and size2 to the number of columns
number of elements that the of the array.
array can hold.

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.

Programs to Print Patterns in C


1. Right Half Pyramid Pattern in C

// C program to print right half pyramid pattern of star

#include <stdio.h>

intmain()

{ introws = 5;

// first loop for printing rows

for(inti = 0; i< rows; i++) {

// second loop for printing character in each rows

for(intj = 0; j <= i; j++) {

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

2. Left Half Pyramid Pattern in C

// c program to print left half pyramid pattern of star

#include <stdio.h>

intmain()

{ introws = 5;

// first loop is for printing the rows

for(inti = 0; i< rows; i++) {

// loop for printing leading whitespaces

for(intj = 0; j < 2 * (rows - i) - 1; j++) {

printf(" ");

// loop for printing * character

for(intk = 0; k <= i; k++) {

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

3. Full Pyramid Pattern in C

// C program to print the full pyramid pattern of stars

#include <stdio.h>

intmain()

introws = 5;
// first loop to print all rows

for(inti = 0; i< rows; i++) {

// inner loop 1 to print white spaces

for(intj = 0; j < 2 * (rows - i) - 1; j++) {

printf(" ");

// inner loop 2 to print star * character

for(intk = 0; k < 2 * i + 1; k++) {

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

4. Inverted Right Half Pyramid Pattern in C

// C program to print the inverted right half pyramid of

// stars

#include <stdio.h>

intmain()

introws = 5;

// first loop to print all rows

for(inti = 0; i< rows; i++) {

// first inner loop to print the * in each row

for(intj = 0; j < rows - i; j++) {

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

5. Inverted Left Half Pyramid Pattern in C

// C program to print the inverted left half pyramid pattern

// of stars

#include <stdio.h>

intmain()

introws = 5;

// first loop for printing all rows


for(inti = 0; i< rows; i++) {

// first inner loop for printing white spaces

for(intj = 0; j < 2 * i; j++) {

printf(" ");

// second inner loop for printing star *

for(intk = 0; k < rows - i; k++) {

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

6. Inverted Full Pyramid Pattern in C

// C program to print the inverted full pyramid pattern of

// stars

#include <stdio.h>

intmain()

introws = 5;

// first loop for printing all rows

for(inti = 0; i< rows; i++) {

// first inner loop for printing leading white

// spaces

for(intj = 0; j < 2 * i; j++) {

printf(" ");

}
// second inner loop for printing stars *

for(intk = 0; k < 2 * (rows - i) - 1; k++) {

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

Hollow Square Pattern in C

// C Program to print hollow square pattern using * star

#include <stdio.h>

intmain()
{

introws = 5;

// outer loop to iterator through each row

for(inti = 0; i< rows; i++) {

// inner loop to print * star in each row

for(intj = 0; j < rows; j++) {

// statement to check boundry condition

if(i> 0 &&i< rows - 1 && j > 0

&& j < rows - 1) {

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.

Characteristics of Sorting Algorithms:


 Time Complexity: Time complexity, a measure of how long it
takes to run an algorithm, is used to categorize sorting
algorithms. The worst-case, average-case, and best-case
performance of a sorting algorithm can be used to quantify the
time complexity of the process.
 Space Complexity: Sorting algorithms also have space
complexity, which is the amount of memory required to execute
the algorithm.
 Stability: A sorting algorithm is said to be stable if the relative
order of equal elements is preserved after sorting. This is
important in certain applications where the original order of
equal elements must be maintained.
 In-Place Sorting: An in-place sorting algorithm is one that does
not require additional memory to sort the data. This is important
when the available memory is limited or when the data cannot
be moved.
 Adaptivity: An adaptive sorting algorithm is one that takes
advantage of pre-existing order in the data to improve
performance.

Basics of Sorting Algorithms:


Bubble sort
Selection sort
Quick sort
Merge sort

Bubble Sort –

Bubble Sort is the simplest sorting algorithm that works


by repeatedly swapping the adjacent elements if they are
in the wrong order. This algorithm is not suitable for large
data sets as its average and worst-case time complexity is
quite high.
Bubble Sort Algorithm
In Bubble Sort algorithm,
 traverse from left and compare adjacent elements and
the higher one is placed at right side.
 In this way, the largest element is moved to the
rightmost end at first.
 This process is then continued to find the second largest
and place it and so on until the data is sorted.
 Implementation of Bubble Sort
 Below is the implementation of the bubble sort. It can be
optimized by stopping the algorithm if the inner loop didn’t
cause any swap.
 C++CJavaPython3C#JavascriptPHP
 // Optimized implementation of Bubble sort
 #include <bits/stdc++.h>
 using namespace std;

 // An optimized version of Bubble Sort
 void bubbleSort(int arr[], int n)
 {
 int i, j;
 bool swapped;
 for (i = 0; i < n - 1; i++) {
 swapped = false;
 for (j = 0; j < n - i - 1; j++) {
 if (arr[j] > arr[j + 1]) {
 swap(arr[j], arr[j + 1]);
 swapped = true;
 }
 }

 // If no two elements were swapped
 // by inner loop, then break
 if (swapped == false)
 break;
 }
 }

 // Function to print an array
 void printArray(int arr[], int size)
 {
 int i;
 for (i = 0; i < size; i++)
 cout << " " << arr[i];
 }

 // Driver program to test above functions
 int main()
 {
 int arr[] = { 64, 34, 25, 12, 22, 11, 90 };
 int N = sizeof(arr) / sizeof(arr[0]);
 bubbleSort(arr, N);
 cout << "Sorted array: \n";
 printArray(arr, N);
 return 0;
 }
 // This code is contributed by shivanisinghss2110

Time Complexity: O(N2)


Auxiliary Space: O(1)
Advantages of Bubble Sort:
 Bubble sort is easy to understand and implement.
 It does not require any additional memory space.
 It is a stable sorting algorithm, meaning that elements with the same key value
maintain their relative order in the sorted output.
Disadvantages of Bubble Sort:
 Bubble sort has a time complexity of O(N 2) which makes it very slow for large data
sets.
 Bubble sort is a comparison-based sorting algorithm, which means that it requires a
comparison operator to determine the relative order of elements in the input data set. It
can limit the efficiency of the algorithm in certain cases.

Selection Sort – Data Structure and Algorithm Tutorials



Selection sort is a simple and efficient sorting algorithm that works by


repeatedly selecting the smallest (or largest) element from the unsorted portion
of the list and moving it to the sorted portion of the list.
The algorithm repeatedly selects the smallest (or largest) element from the
unsorted portion of the list and swaps it with the first element of the unsorted
part. This process is repeated for the remaining unsorted portion until the entire
list is sorted
// C++ program for implementation of
// selection sort
#include <bits/stdc++.h>
using namespace std;
// Function for Selection sort
void selectionSort(int arr[], int n)
{
int i, j, min_idx;

// One by one move boundary of


// unsorted subarray
for (i = 0; i < n - 1; i++) {

// Find the minimum element in


// unsorted array
min_idx = i;
for (j = i + 1; j < n; j++) {
if (arr[j] < arr[min_idx])
min_idx = j;
}

// Swap the found minimum element


// with the first element
if (min_idx != i)
swap(arr[min_idx], arr[i]);
}
}

// Function to print an array


void printArray(int arr[], int size)
{
int i;
for (i = 0; i < size; i++) {
cout << arr[i] << " ";
cout << endl;
}
}

// 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;
}

// This is code is contributed by rathbhupendra

Output
Sorted array:
11 12 22 25 64

Complexity Analysis of Selection Sort


Time Complexity: The time complexity of Selection Sort
is O(N2) as there are two nested loops:
 One loop to select an element of Array one by one = O(N)
 Another loop to compare that element with every other Array
element = O(N)
 Therefore overall complexity = O(N) * O(N) = O(N*N) = O(N 2)
Auxiliary Space: O(1) as the only extra memory used is for
temporary variables while swapping two values in Array. The
selection sort never makes more than O(N) swaps and can be
useful when memory writing is costly.

Advantages of Selection Sort Algorithm


 Simple and easy to understand.
 Works well with small datasets.

Disadvantages of the Selection Sort Algorithm


 Selection sort has a time complexity of O(n^2) in the worst and
average case.
 Does not work well on large datasets.
 Does not preserve the relative order of items with equal keys
which means it is not stable.
Quick sort:-
QuickSort is a sorting algorithm based on the Divide and Conquer algorithm that picks an
element as a pivot and partitions the given array around the picked pivot by placing the
pivot in its correct position in the sorted array.

How does QuickSort work?


The key process in quickSort is a partition(). The target of partitions is to place the pivot
(any element can be chosen to be a pivot) at its correct position in the sorted array and
put all smaller elements to the left of the pivot, and all greater elements to the right of the
pivot.
Partition is done recursively on each side of the pivot after the pivot is placed in its correct
position and this finally sorts the array.

#include <bits/stdc++.h>
using namespace std;

int partition(int arr[],int low,int high)


{
//choose the pivot

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);
}

// The Quicksort function Implement

void quickSort(int arr[],int low,int high)


{
// when low is less than high
if(low<high)
{
// pi is the partition return index of pivot

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).

Merge Sort – Data Structure and Algorithms Tutorials


Last Updated : 07 May, 2024



Merge sort is a sorting algorithm that follows the divide-and-


conquer approach. It works by recursively dividing the input array into smaller
subarrays and sorting those subarrays then merging them back together to
obtain the sorted array.
In simple terms, we can say that the process of merge sort is to divide the
array into two halves, sort each half, and then merge the sorted halves back
together. This process is repeated until the entire array is sorted.
Merge Sort Algorithm

How does Merge Sort work?


Merge sort is a popular sorting algorithm known for its efficiency and stability. It
follows the divide-and-conquer approach to sort a given array of elements.
Here’s a step-by-step explanation of how merge sort works:
1. Divide: Divide the list or array recursively into two halves until it can no
more be divided.
2. Conquer: Each subarray is sorted individually using the merge sort
algorithm.
3. Merge: The sorted subarrays are merged back together in sorted order. The
process continues until all elements from both subarrays have been merged.
Implementation of Merge Sort:
// C++ program for Merge Sort
#include <bits/stdc++.h>
using namespace std;

// Merges two subarrays of array[].


// First subarray is arr[begin..mid]
// Second subarray is arr[mid+1..end]
void merge(int array[], int const left, int const mid,
int const right)
{
int const subArrayOne = mid - left + 1;
int const subArrayTwo = right - mid;

// Create temp arrays


auto *leftArray = new int[subArrayOne],
*rightArray = new int[subArrayTwo];

// Copy data to temp arrays leftArray[] and rightArray[]


for (auto i = 0; i < subArrayOne; i++)
leftArray[i] = array[left + i];
for (auto j = 0; j < subArrayTwo; j++)
rightArray[j] = array[mid + 1 + j];

auto indexOfSubArrayOne = 0, indexOfSubArrayTwo = 0;


int indexOfMergedArray = left;

// Merge the temp arrays back into array[left..right]


while (indexOfSubArrayOne < subArrayOne
&& indexOfSubArrayTwo < subArrayTwo) {
if (leftArray[indexOfSubArrayOne]
<= rightArray[indexOfSubArrayTwo]) {
array[indexOfMergedArray]
= leftArray[indexOfSubArrayOne];
indexOfSubArrayOne++;
}
else {
array[indexOfMergedArray]
= rightArray[indexOfSubArrayTwo];
indexOfSubArrayTwo++;
}
indexOfMergedArray++;
}

// Copy the remaining elements of


// left[], if there are any
while (indexOfSubArrayOne < subArrayOne) {
array[indexOfMergedArray]
= leftArray[indexOfSubArrayOne];
indexOfSubArrayOne++;
indexOfMergedArray++;
}

// Copy the remaining elements of


// right[], if there are any
while (indexOfSubArrayTwo < subArrayTwo) {
array[indexOfMergedArray]
= rightArray[indexOfSubArrayTwo];
indexOfSubArrayTwo++;
indexOfMergedArray++;
}
delete[] leftArray;
delete[] rightArray;
}

// begin is for left index and end is right index


// of the sub-array of arr to be sorted
void mergeSort(int array[], int const begin, int const end)
{
if (begin >= end)
return;

int mid = begin + (end - begin) / 2;


mergeSort(array, begin, mid);
mergeSort(array, mid + 1, end);
merge(array, begin, mid, end);
}

// 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]);

cout << "Given array is \n";


printArray(arr, arr_size);

mergeSort(arr, 0, arr_size - 1);

cout << "\nSorted array is \n";


printArray(arr, arr_size);
return 0;
}

// This code is contributed by Mayank Tyagi


// This code was revised by Joshua Estes

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.

Advantages of Merge Sort:


 Stability: Merge sort is a stable sorting algorithm, which means it maintains
the relative order of equal elements in the input array.
 Guaranteed worst-case performance: Merge sort has a worst-case time
complexity of O(N logN), which means it performs well even on large
datasets.
 Simple to implement: The divide-and-conquer approach is straightforward.

Disadvantage of Merge Sort:


 Space complexity: Merge sort requires additional memory to store the
merged sub-arrays during the sorting process.
 Not in-place: Merge sort is not an in-place sorting algorithm, which means it
requires additional memory to store the sorted data. This can be a
disadvantage in applications where memory usage is a concern.
Unit-5
C Functions


A function in C is a set of statements that when called perform some


specific task. It is the basic building block of a C program that provides
modularity and code reusability. The programming statements of a
function are enclosed within { } braces, having certain meanings and
performing certain operations. They are also called subroutines or
procedures in other languages.
Syntax of Functions in C
The syntax of function can be divided into 3 aspects:
1. Function Declaration
2. Function Definition
3. Function Calls
Function Declarations
In a function declaration, we must provide the function name, its return type,
and the number and type of its parameters. A function declaration tells the
compiler that there is a function with the given name defined somewhere else in
the program.

Syntax

return_type name_of_the_function (parameter_1, parameter_2);

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

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);

How Does C Function Work?


Working of the C function can be broken into the following steps as mentioned
below:
1. Declaring a function: Declaring a function is a step where we declare a
function. Here we define the return types and parameters of the function.
2. Defining a function:
3. Calling the function: Calling the function is a step where we call the
function by passing the arguments in the function.
4. Executing the function: Executing the function is a step where we can run
all the statements inside the function to get the final result.
5. Returning a value: Returning a value is the step where the calculated value
after the execution of the function is returned. Exiting the function is the final
step where all the allocated memory to the variables, functions, etc is
destroyed before giving full control to the main function.

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

A library function is also referred to as a “built-in function”. Built-in functions


have the advantage of being directly usable without being defined, whereas
user-defined functions must be declared and defined before being used.
For Example:
pow(), sqrt(), strcmp(), strcpy() etc.
Advantages of C library functions
 C Library functions are easy to use and optimized for better performance.
 C library functions save a lot of time i.e, function development time.
 C library functions are convenient as they always work.
Example:
C

// C program to implement
// the above approach
#include <math.h>
#include <stdio.h>

// Driver code
int main()
{
double Number;
Number = 49;

// Computing the square root with


// the help of predefined C
// library function
double squareRoot = sqrt(Number);

printf("The Square root of %.2lf = %.2lf",


Number, squareRoot);
return 0;
}

Output

The Square root of 49.00 = 7.00

2. User Defined Function

Functions that the programmer creates are known as User-Defined functions


or “tailor-made functions”. User-defined functions can be improved and
modified according to the need of the programmer. Whenever we write a
function that is case-specific and is not defined in any header file, we need to
declare and define our own functions according to the syntax.
Advantages of User-Defined Functions
 Changeable functions can be modified as per need.
 The Code of these functions is reusable in other programs.
 These functions are easy to understand, debug and maintain.
Example:
C
// C program to show
// user-defined functions
#include <stdio.h>

int sum(int a, int b)


{
return a + b;
}

// Driver code
int main()
{
int a = 30, b = 40;

// function call
int res = sum(a, b);

printf("Sum is: %d", res);


return 0;
}

Output
Sum is: 70

Difference between User-Defined Function and Library


Function

User-Defined Functions Library Functions


[Link].

These functions are not predefined


1 in the Compiler. These functions are predefined in the
compiler of C language.

These functions are created by These functions are not created by


2
users as per their own requirements. users as their own.

3 User-defined functions are not Library Functions are stored in a


User-Defined Functions Library Functions
[Link].

stored in library files. special library file.

If the user wants to use a particular


library function then the user has to
There is no such kind of requirement
add the particular library of that
to add a particular library.
function in the header file of the
4
program.

Execution of the program begins Execution of the program does not


5
from the user-define function. begin from the library function.

6 Example: sum(), fact(),…etc. Example: printf(), scanf(), sqrt(),…etc.

What are Actual Parameters in C?


Actual parameters are the values that are passed to the function during a
function call. They are also known as arguments. Actual parameters are used
to provide the values to the formal parameters of the function. Actual
parameters can be of any data type such as int, float, char, etc.

Syntax of Actual Parameters in C

function_name(actual_parameter1, actual_parameter2, ...);

Example of Actual Parameters in C

int main()
{
int sum= add(10, 20);
return 0;
}

3. What are formal parameters in C?


Formal parameters, also known as parameters or function parameters,
are the variables declared in the function definition that receive the
values passed as arguments during a function call.
Syntax of Formal Parameters in C
return_type function_name(parameter1_type parameter1_name, parameter2_type
parameter2_name, ... )
{
// function body
}
Example of Formal Parameters in C
int add(int a, int b)
{
return a + b;
}
4.

3. What is the difference between actual parameters and formal


parameters in C?
The main difference between actual parameters and formal parameters is that
actual parameters are the values passed to a function during a function call,
whereas formal parameters are the variables declared in the function
definition that receive these values.

Difference Between Actual and Formal Parameters in


C
Here, are some of the differences between actual and formal parameters in C:

Actual Parameters Formal Parameters

1. Actual parameters are


1. They can have default values, which are used
the values or references
if no value is passed in as an actual parameter
that are passed into the
when the function is called.
function when it is called.

2. They are also called


2. Formal parameters are also called function
arguments or parameter
parameters or function arguments.
values.

3. Actual parameters 3. They are the placeholders for the values or


Actual Parameters Formal Parameters

provide input to the


references that will be passed into the function.
function.

4. They have a scope that


4. Formal parameters have a scope that is
is limited to the function call
limited to the function in which they are defined.
in which they are used.

5. Actual parameters can [Link] are used by the function to perform


be expressions that are operations and computations on the values or
evaluated before they are references that are passed into the function as
passed into the function. actual parameters.

4. How are actual parameters and formal parameters passed in C?


In C, actual parameters and formal parameters can be passed by value or by
reference. By default, C uses pass-by-value, but pass-by-reference can be
achieved by passing pointers to the arguments.

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.

6. What is pass by reference in C?


Pass by reference is a method of passing arguments to a function in which the
address of the argument is passed to the formal parameter of the function.
Any changes made to the formal parameter inside the function will affect the
original argument passed to the function.

Difference between the Call by Value and Call by


Reference in C
The following table lists the differences between the call-by-value and call-by-
reference methods of parameter passing.

Call By Value Call By Reference

While calling a function, instead of passing the


While calling a function, we pass the
values of variables, we pass the address of
values of variables to it. Such functions
variables(location of variables) to the function
are known as “Call By Values”.
known as “Call By References.

In this method, the value of each variable


In this method, the address of actual variables
in the calling function is copied into
in the calling function is copied into the
corresponding dummy variables of the
dummy variables of the called function.
called function.

With this method, the changes made to


With this method, using addresses we would
the dummy variables in the called
have access to the actual variables and hence
function have no effect on the values of
we would be able to manipulate them.
actual variables in the calling function.

In call-by-values, we cannot alter the


In call by reference, we can alter the values of
values of actual variables through
variables through function calls.
function calls.

Values of variables are passed by the Pointer variables are necessary to define to
Simple technique. store the address values of variables.

This method is preferred when we have


This method is preferred when we have to
to pass some small values that should
pass a large amount of data to the function.
not change.
Call By Value Call By Reference

Call by value is considered safer as Call by reference is risky as it allows direct


original data is preserved modification in original data

Example of Call by Value

The following example demonstrates the call-by-value method


of parameter passing

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

printf("In the Caller:\na = %d b = %d\n", a, b);

return 0;
}

// Swap functions that swaps

// two values
void swapx(int x, int y) // Formal Parameters

int t;

t = x;

x = y;

y = t;

printf("Inside Function:\nx = %d y = %d\n", x, y);

Example of Call by Reference


The following C program is an example of a call-by-reference method.
C

// C program to illustrate Call by Reference


#include <stdio.h>

// Function Prototype
void swapx(int*, int*);

// Main function
int main()
{
int a = 10, b = 20;

// Pass reference
swapx(&a, &b); // Actual Parameters

printf("Inside the Caller:\na = %d b = %d\n", a, b);

return 0;
}

// Function to swap two variables


// by references
void swapx(int* x, int* y) // Formal Parameters
{
int t;

t = *x;
*x = *y;
*y = t;

printf("Inside the Function:\nx = %d y = %d\n", *x, *y);


}

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;
}
}

Example: C Program to Implement Recursion


In the below C program, recursion is used to calculate the sum of the first N natural
numbers.
C
// C Program to calculate the sum of first N natural numbers
// using recursion
#include <stdio.h>

int nSum(int n)
{
// base condition to terminate the recursion when N = 0
if (n == 0) {
return 0;
}

// recursive case / recursive call


int res = n + nSum(n - 1);

return res;
}
int main()
{
int n = 5;

// calling the function


int sum = nSum(n);

printf("Sum of First %d Natural Numbers: %d", n, sum);


return 0;
}

Examples of Recursion in C
Example 1: C Program to Find the Factorial of a Natural Number using Tail
Recursion.
C

// C program to find the factorail using tail recursion


#include <stdio.h>

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;

int fact1 = factorialTail(n);


printf("Resursive Factorial of %d: %d \n", n, fact1);

return 0;
}

Output

Resursive Factorial of 5: 120

Example 2: C Program to find the Fibonacci Number using Tree Recursion


C
// C Program to find the fibonacci number using tree
// recursion
#include <stdio.h>

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);

// print 5th fibonacci number


printf("%d", n);

return 0;
}

Output

Example 3: C Program to Illustrate the Indirect Recursion


C

// C Program to Illustrate the Indirect Recursion


#include <stdio.h>

void functionA(int n)
{
if (n < 1) {
return;
}
printf("%d ", n);
n = n - 1;

// Indirect recursive call to functionB


functionB(n);
}
void functionB(int n)
{
if (n < 2) {
return;
}

printf("%d ", n);


n = n / 2;

// Indirect recursive call to functionA


functionA(n);
}

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:

1. Structure Variable Declaration with Structure Template

struct structure_name {
data_type member_name1;
data_type member_name1;
....
....
}variable1, varaible2, ...;

2. Structure Variable Declaration after Structure Template

// structure declared beforehand


struct structure_name variable1, variable2, .......;
Access Structure Members
We can access structure members by using the ( . ) dot operator.

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.

1. Initialization using Assignment Operator

str;
struct structure_name
str.member1 = value1;
str.member2 = value2;
str.member3 = value3;
.
.
.

2. Initialization using Initializer List

struct structure_name str = { value1, value2, value3 };


In this type of initialization, the values are assigned in sequential order as they
are declared in the structure template.

3. Initialization using Designated Initializer List

str = { .member1 = value1, .member2 =


struct structure_name
value2, .member3 = value3 };

Example of Structure in C
The following C program shows how to use structures

 C

// C program to illustrate the use of structures

#include <stdio.h>

// declaring structure with name str1

struct str1 {

int i;

char c;

float f;

char s[30];

};
// declaring structure with name str2

struct str2 {

int ii;

char cc;

float ff;

} var; // variable declaration with structure template

// Driver code

int main()

// variable declaration after structure template

// initialization with initializer list and designated

// initializer list

struct str1 var1 = { 1, 'A', 1.00, " Swamivivekanandcollege

" },

var2;

struct str2 var3 = { .ff = 5.00, .ii = 5, .cc = 'a' };

// copying structure using assignment operator

var2 = var1;
printf("Struct 1:\n\ti = %d, c = %c, f = %f, s = %s\n",

var1.i, var1.c, var1.f, var1.s);

printf("Struct 2:\n\ti = %d, c = %c, f = %f, s = %s\n",

var2.i, var2.c, var2.f, var2.s);

printf("Struct 3\n\ti = %d, c = %c, f = %f\n", [Link],

[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

// C program to demonstrate the array of structures

#include <stdio.h>

// structure template

struct Employee {

char Name[20];

int employeeID;

int WeekAttendence[7];

};

// driver code

int main()

// defining array of structure of type Employee

struct Employee emp[5];


// adding data

for (int i = 0; i < 5; i++) {

emp[i].employeeID = i;

strcpy(emp[i].Name, "Amit");

int week;

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

int attendence;

emp[i].WeekAttendence[week] = week;

printf("\n");

// printing data

for (int i = 0; i < 5; i++) {

printf("Emplyee ID: %d - Employee Name: %s\n",

emp[i].employeeID, emp[i].Name);

printf("Attendence\n");

int week;

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

printf("%d ", emp[i].WeekAttendence[week]);

printf("\n");
}

return 0;

// C program to demonstrate the

// usage of an array of structures

#include <stdio.h>

// Declaring a structure class

struct class {

int roll_no;

char grade;

float marks;

};

// Function to displays the contents

// of the array of structures

void display(struct class class_record[3])

int i, len = 3;
// Display the contents of the array

// of structures here, each element

// of the array is a structure of class

for (i = 0; i < len; i++) {

printf("Roll number : %d\n",

class_record[i].roll_no);

printf("Grade : %c\n", class_record[i].grade);

printf("Average marks : %.2f\n",

class_record[i].marks);

printf("\n");

// Driver Code

int main()

// Initialize of an array of structures

struct class class_record[3] = { { 1, 'A', 89.5f },

{ 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

Array within a Structure


A structure is a data type in C that allows a group of related variables to be treated as a
single unit instead of separate entities. A structure may contain elements of different data
types – int, char, float, double, etc. It may also contain an array as its member. Such
an array is called an array within a structure. An array within a structure is a member of
the structure and can be accessed just as we access other elements of the structure.

/ C program to demonstrate the


// use of an array within a structure

#include <stdio.h>

// Declaration of the structure candidate

struct candidate {

int roll_no;

char grade;

// Array within the structure

float marks[4];

};

// Function to displays the content of

// the structure variables

void display(struct candidate a1)

printf("Roll number : %d\n", a1.roll_no);


printf("Grade : %c\n", [Link]);

printf("Marks secured:\n");

int i;

int len = sizeof([Link]) / sizeof(float);

// Accessing the contents of the

// array within the structure

for (i = 0; i < len; i++) {

printf("Subject %d : %.2f\n", i + 1, [Link][i]);

// Driver Code

int main()

// Initialize a structure

struct candidate A = { 1, 'A', { 98.5, 77, 89, 78.5 } };


// Function to display structure

display(A);

return 0;

Output
Roll number : 1
Grade : A
Marks secured:
Subject 1 : 98.50
Subject 2 : 77.00

ifference between Array of Structures and Array within


Structures
Below is the tabular difference between the Array within a Structure and Array of
Structures:
Parameter Array within a Structure Array of Structures

A structure contains an array as its An array in which each element


Basic idea member variable. is of type structure.

struct class { int a, b, c; }


struct class { int ar[10]; } a1, a2, a3;
Syntax students[10];

Can be accessed using the dot operator


Can be accessed by indexing just
just as we access other elements of the
as we access an array.
Access structure.

Access
elements [Link][index] array[index].member
syntax
Parameter Array within a Structure Array of Structures

Array within the structure will be stored


There will be some empty space
in sequential memory and structure
between structure elements due
Memory padding is not dependent on the size of
to structure padding.
Structure the array.

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.

How to Use Pointers?


The use of pointers in C can be divided into three steps:
1. Pointer Declaration
2. Pointer Initialization
3. Pointer Dereferencing

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

Value at ptr = 0x7fff1038675c


Value at var = 10
Value at *ptr = 10

What Are the Advantages of Pointers in C?

 Pointers in C programming are helpful to access a memory location


 Pointers are an effective way to access the array structure elements
 Pointers are used for the allocation of dynamic memory and the distribution
 Pointers are used to build complicated data structures like a linked list, graph,
tree, etc
What Are the Disadvantages of Pointers?

 Pointers are a bit difficult to understand


 Pointers can cause several errors, such as segmentation errors or
unrequired memory access
 If a pointer has an incorrect value, it may corrupt the memory
 Pointers may also cause memory leakage
 The pointers are relatively slower than the variables
Some important points related to pointers

 The Pointers in C programming is simply a storage location for data in


memory
 Pointers can be used to traverse the array more efficiently
 You can use function pointers to invoke a function dynamically
 Pointer arithmetic is the process of performing arithmetic operations on a
pointer
 In an array of pointers, pointers can point to functions, making it simple to
call different functions

What Are the Different Types of Pointers?

There are majorly four types of pointers, they are:

 Null Pointer
 Void Pointer
 Wild Pointer
 Dangling Pointer
Null Pointer:-

If you assign a NULL value to a pointer during its declaration, it is called


Null Pointer.

Syntax:

Int *var = NULL;

Example:

#include<stdio.h>

int main()

int *var = NULL;

printf(“var=%d”,*var);

What Are the Different Types of Pointers?

There are majorly four types of pointers, they are:

 Null Pointer
 Void Pointer
 Wild Pointer
 Dangling Pointer

Null Pointer:

If you assign a NULL value to a pointer during its declaration, it is called


Null Pointer.

Syntax:

Int *var = NULL;

Example:

#include<stdio.h>

int main()

int *var = NULL;

printf(“var=%d”,*var);

Void Pointer:

When a pointer is declared with a void keyword, then it is called a void


pointer. To print the value of this pointer, you need to typecast it.

Syntax:

void *var;

Example:

#include<stdio.h>
int main()

int a=2;

void *ptr;

ptr= &a;

printf("After Typecasting, a = %d", *(int *)ptr);

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:-

 Suppose there is a pointer p pointing at a variable at memory 1004. If


you deallocate this memory, then this p is called a dangling pointer.
 You can deallocate a memory using a free() function.
Example:

#include<stdio.h>

#include<stdlib.h>

int main()

int *ptr=(int *)malloc(sizeof(int));

int a=5;

ptr=&a;

free(ptr);

//now this ptr is known as dangling pointer.

printf(“After deallocating its memory *ptr=%d”,*ptr);

return 0;

What Are the Use Cases of Pointers in C?


 Pointer arithmetic
 Pointer to pointer
 Array of pointers
 Call by value
 Call by reference

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 arr[3] = {50, 150, 200};

int *ptr;

ptr = arr;

for (int i = 0; i < 3; i++)

printf(“Value of *ptr = %d\n”,*ptr);

printf(“Address of *ptr = %d\n”,ptr);


ptr++;

 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 arr[3]={50, 150, 200};

int *ptr;

ptr = &arr[2];

for (int i=0;i<3;i++)

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

printf("Address of *ptr = %d\n\n", ptr);

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:

ptr+=i; // where ‘i’ is an integer

Example:

#include <stdio.h>

int main() {

int arr[5] = {10, 100, 200, 300, 500};

int *ptr;

ptr = &arr[0];

for (int i = 0; i < 5; i++) {

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

printf("Address of *ptr = %d\n\n", ptr);

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:

ptr-=i; // where ‘i’ is an integer

Example:

#include <stdio.h>

int main() {

int arr[5] = {10, 100, 200, 300, 500};

int *ptr;

ptr = &arr[4];

for (int i = 0; i<5; i++)

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

printf("address of *ptr = %d\n\n", ptr);

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 ()

int var, *ptr1, **ptr2;

var = 10;

ptr1 = &var;

ptr2 = &ptr1;

printf("Value of var = %d\n", var );

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

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

return 0;

}
An Array of Pointer:

An array of the pointer is an array whose every element is a pointer.

Syntax:

int *arr[n] //where n is size of array.

Example:

#include <stdio.h>

int main ()

int a[3] = {10, 100, 200},n=3;

int i, *ptr[3];

for ( i = 0; i < 3; i++)

ptr[i] = &a[i];

for ( i = 0; i < n; i++)

printf("Value of a[%d] = %d\n", i, *ptr[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>

void change(int num)

printf("Before adding value inside function num=%d\n",num);

num=num+100;

printf("After adding value inside function num=%d\n",num);

int main()

int x=100;

printf("Before function call x=%d \n",x);

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>

void change(int *num)

printf("Before adding value inside function num=%d \n",*num);

(*num) += 100;

printf("After adding value inside function num=%d \n",*num);

int main()

int x=100;
printf("Before function call x=%d \n",x);

change(&x);//passing reference in function

printf("After function call x=%d \n",x);

return 0;

What is the Self Referential Structure in C?

A self-referential structure is a structure that contains a pointer to a variable


of the same type. This allows the structure to refer to itself, creating a
linked data structure.A self-referential structure can be used to create a
linked list by defining a structure that contains a data element and a pointer
to the next element in the list. The pointer points to a variable of the same
type, allowing the structure to refer to itself and creating a linked structure.

Application Self-referential Structures in C

Here are some common applications of self-referential structures in C


programming:

 Linked lists: A linked list is a collection of nodes, each of which contains a


data item and a pointer to the next node in the list. Self-referential
structures are used to create these nodes and link them together to form a
list.

 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.

 Graphs: A graph is a collection of nodes and edges, where the edges


represent the connections between the nodes. Self-referential structures
are used to create the nodes and link them together to form the graph
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.

Notion of linked list (no implementation)


 A linked list is a common data structure made of a chain
of nodes in which each node contains a value and a pointer
to the next node in the chain.

 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.

 Linked lists can dynamically increase in size and it is easy to


insert and delete from a linked list because unlike arrays, we
only need to change the pointers of the previous element
and the next element to insert or delete an element.

 Linked lists are typically used to create file systems,


adjacency lists, and hash tables
Unit-9
File Handling in C
File Handling in C

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.

Why do we need File Handling in C?


So far the operations using the C program are done on a prompt/terminal
which is not stored anywhere. The output is deleted when the program is
closed. But in the software industry, most programs are written to store
the information fetched from the program. The use of file handling is
exactly what the situation calls for.
In order to understand why file handling is important, let us look at a few
features of using files:
 Reusability: The data stored in the file can be accessed, updated, and
deleted anywhere and anytime providing high reusability.
 Portability: Without losing any data, files can be transferred to
another in the computer system. The risk of flawed coding is minimized
with this feature.
 Efficient: A large amount of input may be required for some programs.
File handling allows you to easily access a part of a file using few
instructions which saves a lot of time and reduces the chance of errors.
 Storage Capacity: Files allow you to store a large amount of data
without having to worry about storing everything simultaneously in a
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.

Functions for C File Operations


File Pointer in C
A file pointer is a reference to a particular position in the opened file. It is
used in file handling to perform all file operations such as read, write,
close, etc. We use the FILE macro to declare the file pointer variable. The
FILE macro is defined inside <stdio.h> header file.
Syntax of File Pointer
FILE* pointer_name;
File Pointer is used in almost all the file operations in C.
Open a File in C
For opening a file in C, the fopen() function is used with the filename or
file path along with the required access modes.
Syntax of fopen()
FILE* fopen(const char *file_name, const char *access_mode);
Parameters
 file_name: name of the file when present in the same directory as the
source file. Otherwise, full path.
 access_mode: Specifies for what operation the file is being opened.
Return Value
 If the file is opened successfully, returns a file pointer to it.
 If the file is not opened, then returns NULL.

File opening modes in C


File opening modes or access modes specify the allowed operations on
the file to be opened. They are passed as an argument to the fopen()
function. Some of the commonly used file access modes are listed below:
Opening
Modes Description

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

// C Program to illustrate file opening

#include <stdio.h>

#include <stdlib.h>
int main()

// file pointer variable to store the value returned by

// fopen

FILE* fptr;

// opening the file in read mode

fptr = fopen("[Link]", "r");

// checking if the file is opened successfully

if (fptr == NULL) {

printf("The file is not opened. The program will "

"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");

Example of Opening a File


 C

// C Program to create a file

#include <stdio.h>

#include <stdlib.h>

int main()

// file pointer

FILE* fptr;

// creating file using fopen() access mode "w"

fptr = fopen("[Link]", "w");

// checking if the file is created


if (fptr == NULL) {

printf("The file is not opened. The program will "

"exit now");

exit(0);

else {

printf("The file is created Successfully.");

return 0;

Output
The file is created Successfully.

Reading From a File


The file read operation in C can be performed using functions fscanf() or
fgets(). Both the functions performed the same operations as that of scanf
and gets but with an additional parameter, the file pointer. There are also
other functions we can use to read from a file. Such functions are listed
below:
Functio
n Description

Use formatted string and variable arguments list to take input from a
fscanf()
file.

fgets() Input the whole line from the file.


Functio
n Description

fgetc() Reads a single character from the file.

fgetw() Reads a number from a file.

fread() Reads the specified bytes of data from a binary 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

Similar to printf(), this function use formatted string and varible


fprintf()
arguments list to print output to the file.

fputs() Prints the whole line in the file and a newline at the end.

fputc() Prints a single character into the file.

fputw() Prints a number to the file.

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

// C program to Open a File,

// Write in it, And Close the File

#include <stdio.h>

#include <string.h>

int main()

{
// Declare the file pointer

FILE* filePointer;

// Get the data to be written in file

char dataToBeWritten[50] = "GeeksforGeeks-A Computer "

"Science Portal for Geeks";

// Open the existing file GfgTest.c using fopen()

// in write mode using "w" attribute

filePointer = fopen("GfgTest.c", "w");

// Check if this filePointer is null

// which maybe if the file does not exist

if (filePointer == NULL) {

printf("GfgTest.c file failed to open.");

else {
printf("The file is now opened.\n");

// Write the dataToBeWritten into the file

if (strlen(dataToBeWritten) > 0) {

// writing in the file using fputs()

fputs(dataToBeWritten, filePointer);

fputs("\n", filePointer);

// Closing the file using fclose()


fclose(filePointer);

printf("Data successfully written in file "


"GfgTest.c\n");
printf("The file is now closed.");
}

return 0;
}
Example 2: Program to Open a File, Read from it, And Close the
File
C

// C program to Open a File,


// Read from it, And Close the File

#include <stdio.h>

#include <string.h>

int main()

// Declare the file pointer

FILE* filePointer;

// Declare the variable for the data to be read from

// file

char dataToBeRead[50];

// Open the existing file GfgTest.c using fopen()

// in read mode using "r" attribute


filePointer = fopen("GfgTest.c", "r");

// Check if this filePointer is null

// which maybe if the file does not exist

if (filePointer == NULL) {

printf("GfgTest.c file failed to open.");

else {

printf("The file is now opened.\n");

// Read the dataToBeRead from the file

// using fgets() method

while (fgets(dataToBeRead, 50, filePointer)

!= NULL) {

// Print the dataToBeRead


printf("%s", dataToBeRead);

// Closing the file using fclose()

fclose(filePointer);

printf(

"Data successfully read from file GfgTest.c\n");

printf("The file is now closed.");

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

// C program to write to a Binary file using fwrite()

#include <stdio.h>

#include <stdlib.h>

struct threeNum {

int n1, n2, n3;


};

int main()

int n;

// Structure variable declared here.

struct threeNum num;

FILE* fptr;

if ((fptr = fopen("C:\\[Link]", "wb")) == NULL) {

printf("Error! opening file");

// If file pointer will return NULL

// Program will exit.

exit(1);

int flag = 0;

// else it will return a pointer to the file.

for (n = 1; n < 5; ++n) {

num.n1 = n;
num.n2 = 5 * n;

num.n3 = 5 * n + 1;

flag = fwrite(&num, sizeof(struct threeNum), 1,

fptr);

// checking if the data is written

if (!flag) {

printf("Write Operation Failure");

else {

printf("Write Operation Successful");

fclose(fptr);

return 0;
}

Output
Write Operation Successful

Reading from Binary File


The fread() function can be used to read data from a binary file in C.
The data is read from the file in the same form as it is stored i.e. binary
form.
Syntax of fread()
size_t fread(void *ptr, size_t size, size_t nmemb, FILE
*file_pointer);
Parameters:
 ptr: pointer to the block of memory to read.
 size: the size of each element to read(in bytes).
 nmemb: number of elements.
 file_pointer: FILE pointer to the input file stream.
Return Value:
 Number of objects written.
Example: Program to Read from a binary file using fread()
C

// C Program to Read from a binary file using fread()

#include <stdio.h>

#include <stdlib.h>

struct threeNum {
int n1, n2, n3;

};

int main()

int n;

struct threeNum num;

FILE* fptr;

if ((fptr = fopen("C:\\[Link]", "rb")) == NULL) {

printf("Error! opening file");

// If file pointer will return NULL

// Program will exit.

exit(1);

// else it will return a pointer to the file.

for (n = 1; n < 5; ++n) {

fread(&num, sizeof(struct threeNum), 1, fptr);

printf("n1: %d\tn2: %d\tn3: %d\n", num.n1, num.n2,


num.n3);

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

// C Program to demonstrate the use of fseek() in C


#include <stdio.h>

int main()

FILE* fp;

fp = fopen("[Link]", "r");

// Moving pointer to end

fseek(fp, 0, SEEK_END);

// Printing position of pointer

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

// C program to illustrate the use of rewind

#include <stdio.h>

int main()

FILE* fptr;

fptr = fopen("[Link]", "w+");

fprintf(fptr, "Geeks for Geeks\n");

// using rewind()

rewind(fptr);

// reading from file


char buf[50];

fscanf(fptr, "%[^\n]s", buf);

printf("%s", buf);

return 0;

Output
Geeks for Geeks

More Functions for C File Operations


The following table lists some more functions that can be used to
perform file operations or assist in performing them.
Functions Description

fopen() It is used to create a file or to open a file.

fclose() It is used to close a file.

fgets() It is used to read a file.

fprintf() It is used to write blocks of data into a file.

fscanf() It is used to read blocks of data from a file.


Functions Description

getc() It is used to read a single character to a file.

putc() It is used to write a single character to a file.

fseek() It is used to set the position of a file pointer to a mentioned location.

ftell() It is used to return the current position of a file pointer.

rewind() It is used to set the file pointer to the beginning of a file.

putw() It is used to write an integer to a file.

getw() It is used to read an integer from a file.

You might also like