Unit1 & Unit2
Unit1 & Unit2
Unit -1
Introduction to 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 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, our programs and
data remain in the secondary storage, ready for the next time we need them.
Computer Software
Computer software is divided into 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.
Types of software :
We have two types of software :
System Software:
Application software
1.System software :- System software is software that directly operates the computer hardware and
provides the basic functionality to the users as well as to the other software to operate smoothly. Or in
other words, system software basically controls a computer’s internal functioning and also controls
hardware devices such as monitors, printers, and storage devices, etc. It is like an interface between
hardware and user applications, it helps them to communicate with each other because hardware
understands machine language(i.e. 1 or 0) whereas user applications are work in human-readable
languages like English, Hindi, German, etc. so system software converts the human-readable language
into machine language and vice versa.
Operating System: It is the main program of a computer system. When the computer system ON it is the
first software that loads into the computer’s memory. Basically, it manages all the resources such as
computer memory, CPU, printer, hard disk, etc., and provides an interface to the user, which helps the
user to interact with the computer system. It also provides various services to other computer software.
Examples of operating systems are Linux, Apple macOS, Microsoft Windows, etc.
Language Processor: As we know that system software converts the human-readable language into a
machine language and vice versa. So, the conversion is done by the language processor. It converts
programs written in high-level programming languages like Java, C, C++, Python, etc(known as source
code), into sets of instructions that are easily readable by machines(known as object code or machine
code).
Device Driver: A device driver is a program or software that controls a device and helps that device to
perform its functions. Every device like a printer, mouse, modem, etc. needs a driver to connect with the
computer system eternally. So, when you connect a new device with your computer system, first you need
to install the driver of that device so that your operating system knows how to control or manage that
device.
2.Application Software :- Software that performs special functions or provides functions that are much
more than the basic operation of the computer is known as application software. Or in other words,
application software is designed to perform a specific task for end-users. It is a product or a program that
is designed only to fulfill end-users’ requirements. It includes word processors, spreadsheets, database
management, inventory, payroll programs, etc.
General Purpose Software: This type of application software is used for a variety of tasks and it is not
limited to performing a specific task only. For example, MS-Word, MS-Excel, PowerPoint, etc.
Customized Software: This type of application software is used or designed to perform specific tasks or
functions or designed for specific organizations. For example, railway reservation system, airline
reservation system, invoice management system, etc.
Utility Software: This type of application software is used to support the computer infrastructure. It is
designed to analyze, configure, optimize and maintains the system, and take care of its requirements as
well. For example, antivirus, disk fragmenter, memory tester, disk repair, disk cleaners, registry cleaners,
disk space analyzer, etc.
Operating system
An operating system is the most important software that runs on a computer. It manages the computer's
memory and processes, as well as all of its software and hardware. It also allows you to communicate
with the computer without knowing how to speak the computer's language. Without an operating system,
a computer is useless.
User-Friendly Interface:
Provides a user-friendly interface for people to interact with computers and devices.
Facilitates tasks like file management, application execution, and device control.
Ensuring Security:
Prioritizes security by protecting critical data and system integrity.
Shields users from complex underlying technology by offering an organized, secure, and efficient environment.
What is computer memory?
Computer memory is any physical device, used to store data, information or instruction temporarily or
permanently. It is the collection of storage units that stores binary information in the form of bits. The
memory block is split into a small number of components, called cells. Each cell has a unique address to
store the data in memory, ranging from zero to memory size minus one. For example, if the size of
computer memory is 64k words, the memory units have 64 * 1024 = 65536 locations or cells. The address
of the memory's cells varies from 0 to 65535.
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 write and
execute any computer program, it is initially stored in primary memory. If the processor does not need
particular items for a longer time, the program or data is automatically saved into the permanent or
secondary memory. Then the data is called from secondary memory to main memory and performs the
execution of codes.
Features of Memory
Following are the different features of the memory system that includes:
Location: It represents the internal or external location of the memory in a computer. The
internal memory is inbuilt in computer memory. It is also known as primary memory. the
example of primary memory are registers, cache and main memory. Whereas, external memory is
the separate storage device from the computer, such as disk, tape, USB pen drive.
Capacity: It is the most important feature of computer memory. Storage capacity can vary in
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 can vary
in bits, such as 8, 16 or 32 bits.
DMA: As the name specifies, Direct Memory Address (DMA) is a method that allows
input/output (I/O) devices to access or retrieve data directly or from the main memory.
Sequential Access Method: The sequential access method is used in a data storage device to
read stored data sequentially from the computer memory. Whereas, the data received from
random access memory (RAM) can be in any order.
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 all
intervening from A to Z to reach at the particular memory location.
Associative Access Method: It is a special type of memory that optimizes search performance
through defined data to directly access the stored information based on a memory address.
Unit of transfer: As the name suggests, a unit of transfer measures the transfer rate of bits that
can be read or write in or out of the memory devices. The transfer rate of data can be different in
external and internal memory.
Internal memory: The transfer rate of bits is mostly equal to the word size.
External memory: The transfer rate of bit or unit is not equal to the word length. It is always
greater than a word or may be referred to as blocks.
Access Time: In random access memory, it represents the total time taken by memory devices to
perform a read or write operation that an address is sent to memory.
Memory Cycle Time: Total time required to access memory block and additional required time
before starting second access.
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 external and internal devices.
Volatile memory. Volatile memory is known as RAM, which requires power to 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 erased after the manufactured
like ROM because at the time of manufactured ROM are programmed.
Classification of Memory
DRAM
SRAM
DRAM: DRAM (Dynamic Random-Access Memory) is a type of RAM that is used for the dynamic
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, requiring
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 information because
DRAM is volatile. If the power is switched off, the data store in memory is lost.
Characteristics of DRAM
SRAM: SRMA (Static Random-Access Memory) is a type of RAM used to store static data in the
memory. It means to store data in SRAM remains active as long as the computer system has a power
supply. However, data is lost in SRAM when power failures have occurred.
It is expensive.
Longer life
Large size
SRAM DRAM
The access time of SRAM is slow. The access time of DRAM is high.
It uses flip-flops to store each bit of information. It uses a capacitor to store each bit of information.
It does not require periodic refreshing to preserve the It requires periodically refreshing to preserve the
information. information.
It uses in cache memory. It is used in the main memory.
Advantages of RAM
The processor can read information faster than a hard disc, floppy,
USB, etc.
Disadvantages of RAM
ROM is a memory device or storage medium that is used to permanently store information inside a chip.
It is a read-only memory that can only read stored information, data or programs, but we cannot write or
modify anything. A ROM contains some important instructions or program data that are required to start
or boot a computer. It is a non-volatile memory; it means that the stored information cannot be lost even
when the power is turned off or the system is shut down.
Primary memory is also known as the computer system's main memory that communicates directly within
the CPU, Auxiliary memory and the Cache memory. Main memory is used to kept programs or 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 the processor starts
execution. Accessing or executing of data from primary memory is faster because it has a cache or
register memory that provides faster response, and it is located closer to the CPU. The 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 as compared to secondary
memory.
Random Access Memory (RAM) is one of the faster types of main memory accessed directly by the CPU.
It is the hardware in a computer device to temporarily store data, programs or program results. It is used
to read/write data in memory until the machine is working. It is volatile, which means if a power failure
occurs or the computer is turned off, the information stored in RAM will be lost. All data stored in
computer memory can be read or accessed randomly at any time.
Types of ROM
MROM is the oldest type of read-only memory whose program or data is pre-configured by the integrated
circuit manufacturer at the time of manufacturing. Therefore, a program or instruction stored within the
MROM chip cannot be changed by the user.
PROM (Programmable Read Only Memory):
It is a type of digital read-only memory, in which the user can write any type of information or
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;
after that, the data or instruction cannot be changed or erased.
It is the type of read only memory in which stored data can be erased and reprogrammed only once in the
EPROM memory. It is a non-volatile memory chip that holds data when there is no power supply and can
also store data for a minimum of 10 to 20 years. In EPROM, if we want to erase any stored data and re-
programmed it, first, we need to pass the ultraviolet light for 40 minutes to erase the data; after that, the
data is re-created in EPROM.
The EEPROM is an electrically erasable and programmable read only memory used to erase stored data
using a high voltage electrical charge and re-programmed it. It is also a non-volatile memory whose data
cannot be erased or lost; even the power is turned off. In EEPROM, the stored data can be erased and
reprogrammed up to 10 thousand times, and the data erased one byte at a time.
Flash ROM:
Flash memory is a non-volatile storage memory chip that can be written or programmed in small
units called Block or Sector. Flash Memory is an EEPROM form of computer memory, and the
contents or data cannot be lost when the power source is turned off. It is also used to transfer data
between the computer and digital devices.
Advantages of ROM
It is a non-volatile memory in which stored information can be lost even if power is turned off.
Disadvantages of ROM
Store data cannot be updated or modified except to read the existing data.
It takes around 40 minutes to destroy the existing data using the high charge of ultraviolet light.
RAM ROM
Read and write operations can be performed. Only Read operation can be performed.
Data can be lost in volatile memory when the Data cannot be lost in non-volatile memory when the
power supply is turned off. power supply is turned off.
Storage data requires to be refreshed in RAM. Storage data does not need to be refreshed in ROM.
The size of the chip is bigger than the ROM chip The size of the chip is smaller than the RAM chip to
to store the data. 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. Secondary memory is
also known as external memory that represents 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 is 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, an optical disk such as CDs and
CDROMs, and magnetic tapes.
It can store large collections of different types, such as audio, video, pictures, text, software, etc.
All the stored data in a secondary memory cannot be lost because it is a permanent storage area; even the
power is turned off.
Hard Disk
A floppy disk is a secondary storage system that consists of thin, flexible magnetic
coating disks for holding electronic data such as computer files. It is also known
as Floppy Diskette that comes in three 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 or backup of the information. However, it is the oldest type of portable
storage device, which can store data up to 1.44 MB. Since most programs were
larger, that required multiple floppy diskettes to store large amounts of data.
Therefore, it is not used due to very low memory storage.
CD (Compact Disc)
Types of CDs
CD-ROM (Compact Disc Read Only Memory): It is mainly used for bulk size mass like audio
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 burn it.
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.
DVD Drive/Disc
DVD is an optical disc storage device, stands for Digital Video Display or Digital
Versatile Disc. It has the same size as a CD but can store a larger amount of data
than a compact disc. It was developed in 1995 by Sony, Panasonic, Toshiba and
Philips four electronics companies. DVD drives are divided 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 storage capacity of data in DVD
is 4.7 GB to 17 GB.
Blu Ray is an Optical disc storage device used to store a large amount of data or high definition video
recording and playing other media files. It uses laser technology to read the stored data of the 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 storage capacity, while Blu-ray
Discs provide 28 GB of space to store data.
Pen Drive:
Cache Memory
It is a small-sized chip-based computer memory that lies between the CPU and the
main memory. It is a faster, high performance and temporary memory to enhance the
performance of the CPU. It stores all the data and instructions that are often used by computer CPUs. It
also reduces the access time of data 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.
It stores all data and instructions that are repeatedly used by the CPU for improving the performance of a
computer.
It is very costly as compared to the Main memory and the Secondary memory.
Register Memory
The register memory is a temporary storage area for storing and transferring the data and the instructions
to a computer. It is the smallest and fastest memory of a computer. It is a part of computer 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 to provide
faster response to the CPU.
Data can be accessed directly by the processor Data cannot be accessed directly by the I/O
or CPU. processor or CPU.
Stored data can be a volatile or non-volatile The nature of secondary memory is always non-
memory. volatile.
It is more costly than secondary memory. It is less costly than primary memory.
It required the power to retain the data in It does not require power to retain the data in
primary memory. secondary memory.
Examples of primary memory are RAM, ROM, Examples of secondary memory are CD, DVD,
Registers, EPROM, PROM and cache memory. HDD, magnetic tapes, flash disks, pen drive, etc.
UNIT -1 PART 2
What is C?
C 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 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.
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
// Link
#include <stdio.h>
// Definition
#define X 20
// Global Declaration
intsum(int y);
// Main() Function
int main(void)
int y = 55;
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.
A programmer has to follow certain rules while naming variables. For the valid identifier, we must follow
the given below set of rules.
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.
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 is mentioned below:
// Statement 1;
// Statement 2;
// and so on..
return;
Example:
Void main()
// statements
Example:
intmain()
// statements
return 0;
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.
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 them.List 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.
Types Description
Primitive Data Primitive data types are the most basic data types that are used for representing
Types simple values such as integers, float, characters, etc.
The data types that are derived from the primitive or built-in datatypes are
Derived Types
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 times.They 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.
Here,
Example
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.
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:
Global Variable:-
Global variables are those variables which are declared outside of all the functions or block and can be
accessed globally in a program.
Once we declare a global variable, its value can be varied as used with different functions.
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.
Global variables are mostly used in programming and useful for cases where all the functions need to
access the same data.
Example:
#include<stdio.h>
void main()
Local Variable:-
Variables that are declared within or inside a function block are known as Local variables.
These variables can only be accessed within the function in which they are declared.
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.
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.
But by making the variable static with "static" keyword, we can retain the value of local variable.
Example:
#include<stdio.h>
void main()
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;
return0;
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()
}
3.Register 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>
int main()
Register int a; // variable a is allocated memory in the CPU register. The initial default value of a is 0.
printf("%d",a);
#include<stdio.h>
int a;
intmain()
printf("%d",a);
}
Overview of storage classes in C
Garbage
auto Automatic RAM Local Within function
Value
Garbage
register Register Register Local Within function
Value
Difference between Global Variable and Local Variable
Global Variable Local Variable
Global variables are declared outside all the Local Variables are declared within a function block.
function blocks.
The scope remains throughout the program. The scope is limited and remains within the function only in
which they are declared.
Any change in global variable affects the Any change in the local variable does not affect other
whole program, wherever it is being used. functions of the program.
A global variable exists in the program for the A local variable is created when the function is executed, and
entire time the program is executed. once the execution is finished, the variable is destroyed.
It can be accessed throughout the program by It can only be accessed by the function statements in which it
all the functions present in the program. is declared and not by the other functions.
If the global variable is not initialized, it takes If the local variable is not initialized, it takes the garbage
zero by default. value by default.
Global variables are stored in the data segment Local variables are stored in a stack in memory.
of memory.
We cannot declare many variables with the We can declare various variables with the same name but in
same name. 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.
const keyword
#define preprocessor
Use of Const Keyword:-The ‘const’ keyword is used to create a constant of any given data type in a
program. For creating a constant, we have to prefix the declaration of the variable with the ‘const’
keyword.
OR
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 ;
scanf(“%d”, &a) ;
area = PI * (a * a) ;
Types of Constants:
A constant is a variable or value that cannot be altered A variable is a name associated with some
once defined. memory location.
A constant is used to hold the fixed values which we can A variable is used to hold some value that can
retrieve later but cannot change. be changed according to the requirement.
Language translators:
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.
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.
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.
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.
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.
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 operations.According to its formal definition, an algorithm is a finite set of instructions
carried out in a specific order to perform a particular task.
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.
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.
Simplicity: Keeping the algorithm as simple as possible while meeting its requirements, avoiding
unnecessary complexity.
1. 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:
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.
Analysis: I don't have a card. I prefer to buy a card rather than make one myself.
High-level algorithm:
3.Coding: Write the code to convert the steps followed by an algorithm to solve the problem.
4.Testing and debugging:- check the program that is working well or not according to the requirements.
Examples:
Ex. 1. Write an algorithm to find the sum and product of two given numbers.
Step 1:Start
Step 2: Read A , B
Step 6:Stop
Step 1: START
Step 5: STOP
factorial = 1
i =1
factorial = factorial*i
i = i+1
Step 7: Stop
Step 1: Start
Else if b > c
Else
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:
Limitations: Complex and detailed charts can be laborious to plan and draw and the actions to be taken in
specified situations can be difficult when many decision paths are involved
Complexity It is easy to design and also very user It is comparatively difficult to create and
friendly. also a bit challenging to be understood by
a layman.
Geometrical It utilizes different types of geometrical An algorithm does not include any sort of
diagrams shapes, symbols, and patterns. 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.
Debugging It is easy to debug the errors in flowcharts. It is difficult to debug the errors in
algorithms.
Implementation In flowcharts, no rules are used. In algorithms, predefined rules are used.
Branching and Simple to display branching and looping. Hard to display branching and looping.
Looping
Pseudocode is an important part of designing an algorithm, it helps the programmer in planning the
solution to the problem as well as the reader in understanding the approach to the problem. Pseudocode is
an intermediate state between algorithm and program that plays supports the transition of the algorithm
into the program.
Initial keywords should be represented in capital case(READ, WRITE, IF, WHILE, UNTIL).
Algorithm Pseudocode
There are no rules to writing algorithms There are certain rules for writing pseudocode
Flowchart Pseudocode
This is a way of visually representing data, these These are fake codes as the word pseudo
are nothing but the graphical representation of the means fake, using code like structure but plain
algorithm for a better understanding of the code English text instead of programming 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:
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.
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 operands
+ C + D = 30
given as input.
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:
Example
Operator
Operator Name (Say we have two operands, i.e., 6 and Result
Notation
5)
Logical OR operator
If c = 6 and d = 5 then, expression
|| It returns true if either one of True
((c==6) || (d>5)) equals 1.
the conditions is true.
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 OR
^ Bitwise exclusive OR
~ Bitwise complement
Assignment Operators
An assignment operator is a symbol used in programming to assign a value to a variable or constant. It is
frequently indicated by the equals sign (=) or another symbol suited for the computer language being
used.
The variable or constant on the left side of the assignment operator receives the value on the right side
when the operator is used. This enables programmers to change and store data in their code.
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
Syntax
Special Operators
Special operators are operators that are intended to carry out particular operations or have a distinct
syntax that isolates them from ordinary operators. Programming requires the usage of special operators
because they enable developers to carry out particular operations and change data in particular ways.
Size-of operator in C (sizeof): The sizeof operator is used to determine the size of a variable or data type
in bytes. It is often used when allocating memory or when dealing with structures or arrays.
Address-of Operator (&):The memory address of a variable can be determined with the address-of
operator (&). It is commonly used when working with pointers or when passing variables by reference.
Shift Operators
The shift operators are binary operations that move a binary number's bits to a certain number of
locations, either to the left or to the right. In both C and C++, the left shift operator (<<) fills the empty
locations with zeros and moves the bits of the left operand to the left by the number of positions indicated
by the right-hand operand. The right shift operator (>>) moves the bits of the left operand to the right by
the number of positions indicated by the right-hand operand. Depending on the sign of the left-hand
operand, the vacant positions are filled with either zeros or ones.
The ternary operator (?:) performs a boolean expression evaluation and, depending on the outcome,
returns one of two results.
The comma operator (,) enables the sequential evaluation of several expressions with the result of the last
expression being returned.
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 (&).
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.
Arithmetic operators: These operators are used to execute addition, subtraction, multiplication, division,
and modulus operations in mathematics.
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.
Logical Operators: These operators are used to apply logical operations to Boolean values, such as AND,
OR, and NOT.
Bitwise operators are used to perform operations on the operands' binary values.
Conditional Operators: These are used for making judgments based on conditions given to be assessed.
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++;
‘=’ 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.
Sequential
Decision or branching
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.
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:
If Statement.
If..else statement.
if..else-if ladder
Nested if statement.
Switch statement.
Syntax
if(Boolean expr)
Expr;
...
if...else statement
The if – else statement offers an alternative path when the condition isn't met.
Syntax
if(Boolean expr)
Expr;
...
else
Expr;
...
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:
if(condition) {
else if(condition) {
}
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;
// condition true
if(n > 0) {
printf("Positive");
// condition true
elseif(n < 0) {
printf("Negative");
else{
printf("Zero");
return0;
Output
Zero
#include <stdio.h>
intmain()
intmarks = 91;
printf("A+ Grade");
printf("A Grade");
printf("B Grade");
printf("C Grade");
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 */
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:
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
execute.When 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 –
While Loop in C
A while loop is the most straightforward looping structure. While loop syntax in C programming
language is as follows:
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.
#include<stdio.h>
#include<conio.h>
intmain()
{ intnum=1; //initializing the variable
printf("%d\n",num);
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.
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()
do //do-while loop
{
printf("%d\n",2*num);
}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 −
statement(s);
The initialization step is executed first, and only once. This step allows you to declare and initialize any
loop control variables. You are not required to put a statement here, as long as a semicolon appears.
Next, the condition is evaluated. If it is true, the body of the loop is executed. If it is false, the body of the
loop does not execute and the flow of control jumps to the next statement just after the 'for' loop.
After the body of the 'for' loop executes, the flow of control jumps back up to the increment statement.
This statement allows you to update any loop control variables. This statement can be left blank, as long
as a semicolon appears after the condition.
The condition is now evaluated again. If it is true, the loop executes and the process repeats itself (body of
loop, then increment step, and then again condition). After the condition becomes false, the 'for' loop
terminates.
Flow Diagram
Example
Live Demo
#include<stdio.h>
int a;
return0;
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.
In the While loop, the condition is tested before In Do while-loop, the statement is executed at least
any statement is executed. once even if the condition is false
Syntax: Syntax:
while(condition){ do{
// statements //statements
} }while(expression);
In While loop, no semicolon is needed after the In Do-while loop, semicolon needed after the end of
end of the condition. the condition
While loop may or may not be executed at all. Do-while loop will execute at least once.
While loop can lead to errors if the condition is Do-while loop help prevents error as it runs at least
always false. 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.