0% found this document useful (0 votes)
11 views76 pages

Unit1 & Unit2

Computer science engineering semester 1

Uploaded by

tbot1738
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)
11 views76 pages

Unit1 & Unit2

Computer science engineering semester 1

Uploaded by

tbot1738
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
You are on page 1/ 76

Programming for Problem Solving Notes

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.

Types of System Software

It has subtypes which are:

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.

Types of Application Software


There are different types of application software and those are:

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.

Need of an operating System:

User-Friendly Interface:
Provides a user-friendly interface for people to interact with computers and devices.

Abstracts complex hardware details, making it easier to use the system.

Facilitates tasks like file management, application execution, and device control.

Effective Resource Allocation:


Manages and distributes system resources such as memory, processing power, and storage.

Prevents conflicts and maximizes performance, enabling smooth multitasking.

Improves overall responsiveness of the computer.

Ensuring Security:
Prioritizes security by protecting critical data and system integrity.

Enforces user permissions and controls resource access.

Guards against malicious applications to enhance system stability.

Bridging Human-Machine Gap:


Acts as a bridge between human interaction and machine execution.
Allows users to tap into their devices' full potential.

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.

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

Access Methods: Memory can be accessed through four modes of memory.

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.

Performance: The performance of memory is majorly divided into three parts.

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

The following figure represents the classification of memory:


There are two types of RAM:

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

It requires continuously refreshed to retain the data.

It is slower than SRAM

It holds a large amount of data


It is the combination of capacitor and transistor

It is less expensive as compared to SRAM

Less power consumption

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.

Characteristics of Static Ram

It does not require to refresh.

It is faster than DRAM

It is expensive.

High power consumption

Longer life

Large size

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 preserve the It requires periodically refreshing to preserve the
information. 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

It is a faster type of memory in a computer.

It requires less power to operate.

Program loads much faster

More RAM increases the performance of a system and can multitask.

Perform read and write operations.

The processor can read information faster than a hard disc, floppy,
USB, etc.

Disadvantages of RAM

Less RAM reduces the speed and performance of a computer.

Due to volatile, it requires electricity to preserve the data.

It is expensive than ROM

It is unreliable as compared to ROM

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 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 or Main Memory

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.

The primary memory is further divided into two parts:

RAM (Random Access Memory)

ROM (Read Only Memory)

Random Access Memory (RAM)

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

There are five types of Read Only Memory:

MROM (Masked Read Only Memory):

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.

EPROM (Erasable and Programmable Read Only Memory):

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.

EEPROM (Electrically Erasable and Programmable Read Only Memory):

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.

It is static, so it does not require refreshing the content every time.

Data can be stored permanently.

It is easy to test and store large data as compared to RAM.

These cannot be changed accidentally

It is cheaper than RAM.

It is simple and reliable as compared to RAM.

It helps to start the computer and loads the OS.

Disadvantages of ROM

Store data cannot be updated or modified except to read the existing data.

It is a slower memory than RAM to access the stored data.

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

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

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.

Features of Secondary Memory

Its speed is slower than the primary/ main memory.

Store data cannot be lost due to non-volatile nature.

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.

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 stores data, programs, and files, and
cannot store data when the computer's power source is switched
off. Typically, it is located internally on a computer's motherboard
that stores and retrieves data using 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, text documentation, videos, operating system, and
data until the user does not delete.
Floppy 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)

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

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.

CD-RW (Compact Disc Rewritable): It is a rewritable CD disc, often used


to write or delete the stored data.

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

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:

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 does not
have any moveable part to store the data; it uses an integrated circuit
chip that stores the data. It allows the users to store and transfer data
like audio, videos, images, etc. from one computer to any 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 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.

Advantages of Cache Memory


Cache memory is the faster memory as compared to the main memory.

It stores all data and instructions that are repeatedly used by the CPU for improving the performance of a
computer.

The access time of data is less than the main memory.

Disadvantage of Cache Memory

It is very costly as compared to the Main memory and the Secondary memory.

It has limited storage capacity.

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.

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

An identifier can include letters (a-z or A-Z), and digits (0-9).

An identifier cannot include special characters except the ‘_’ underscore.

Spaces are not allowed while naming an identifier.


An identifier can only begin with an underscore or letters.

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.

The identifier must be unique in its namespace.

C language is case-sensitive so, ‘name’ and ‘NAME’ are different identifiers.

Keywords in C:

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

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:

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

Main function with no arguments and void return type

Example:

Void main()

// statements

Main function with no arguments and int return type

Example:

intmain()

// statements

return 0;

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

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.

The data types in C can be classified as follows:

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.

User Defined Data


The user-defined data types are defined by the user himself.
Types

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.

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:

Global Variable: Outside of all the functions

Local Variable: Within a function block:

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.

It can be accessed by any function present in the 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>

int a=50, b=40; // global variable

void main()

printf("a = %d and b=%d",a,b);

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

int x=50, y=40; //local variable

printf("x = %d and y=%d",x, y);

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

1.Automatic 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;

2.Static 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.

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

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 program


Globa
extern External RAM Zero Maybe declared anywhere in the
l
program

Till the end of the main program,


static Static RAM Zero Local 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 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.

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 “constant =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.

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.

Syntax for constant variable is:-

const data type constantName = value ;

OR

const data type constantName ;

Example: Const int a = 10 ;

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

The variables are stored inside a data


The constants are generally stored in the text segment as
segment, heap, or stack depending on the
they are read-only
environment it is declared in.

We can only assign a value to the constant while


We can assign value to the variable anytime.
defining it.

A constant can be defined by A variable can only be defined using the


using #define or const keyword. standard variable definition syntax.

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

constint pi = 3.14; var = 10;

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.

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

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

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:

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.

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

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.

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 representation of An algorithm is a procedure or set of rules


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

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.

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


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

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

Solution In a flowchart, the solution is represented in In an algorithm, the solution is presented


a graphical format. in non non-computer language.
What is Pseudocode?

Pseudocode: A Pseudocode is defined as a step-by-step description of an algorithm. Pseudocode does not


use any programming language in its representation instead it uses the simple English language text as it
is intended for human understanding rather than machine reading. Pseudocode is the intermediate state
between an idea and its implementation (code) in a high-level language.

What is the need for Pseudocode

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.

Pseudocode is an intermediate state between algorithm and program

Five important rules for writing pseudocode are:


Write one statement per line.

Initial keywords should be represented in capital case(READ, WRITE, IF, WHILE, UNTIL).

Indentation of pseudocode should be similar to the actual program to show hierarchy.

Ending the multiline structure is necessary.

Keep statements in simple language(English).

Algorithm Pseudocode

An Algorithm is used to provide a solution to a A Pseudocode is a step-by-step description of


particular problem in form of a well-defined step- an algorithm in code-like structure using plain
based form. English text.

Pseudocode also uses reserved keywords like


An algorithm only uses simple English words
if-else, for, while, etc.
Algorithm Pseudocode

These are fake codes as the word pseudo


These are a sequence of steps of a solution to a
means fake, using code like structure and plain
problem
English text

There are no rules to writing algorithms There are certain rules for writing pseudocode

Pseudocode cannot be considered an


Algorithms can be considered pseudocode
algorithm

It is difficult to understand and interpret It is easy to understand and interpret

Difference between Flowchart and Pseudocode

Flowchart Pseudocode

A Pseudocode is a step-by-step description of


A Flowchart is pictorial representation of flow of
an algorithm in code like structure using plain
an algorithm.
English text.

A Flowchart uses standard symbols for input,


Pseudocode uses reserved keywords like if-
output decisions and start stop statements. Only
else, for, while, etc.
uses different shapes like box, circle and arrow.

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

Pseudocode is better suited for the purpose of


Flowcharts are good for documentation
understanding.
Operators in C

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.

It subtracts the value of the second


− C − D = -10
operand from the first one.

This operator multiplies the two


* C * D = 200
operands.

Divides the operand in the numerator


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

The modulus operator gives out the


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

The increment operator increases the


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

The decrement operator decreases the


-- C-- = 9
integer value 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 Operator Sample Operator Expression Description/ Explanation

Here, q increases the initial value by 1,


Prefix Increment
++q after which the program uses the value
Operator
of q.
The program uses the current value of q
Postfix Increment
q++ and later on increases the value of q by
Operator
1.

Here, q decreases the value by 1 first,


Prefix Decrement
–q and then the program uses the value of
Operator
q.

Postfix Decrement The program uses the current value of q


q–
Operator and then decreases 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:

Example
Operator
Operator Name (Say we have two operands, i.e., 6 and Result
Notation
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 equal


>= 6 >= 5 is evaluated to 1 True
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.

Operator Name/ Description Example Result

Logical AND operator


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

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.

Logical NOT operator


If c = 6 then, expression !(c==6)
! It returns true only if the False
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.

Operator Description Example

sizeof(x), where x is an integer,


will return 4.
sizeof(y), where y is float, will
A unary operator called sizeof returns the
return 4.
sizeof() number of bytes of data (for example, int,
sizeof(z), where z is double,
char, float, double, etc.).
will return 8.
sizeof(t), where t is an integer,
will return 1.

&x; returns the actual address


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

If Condition is true ? then value


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

The star or asterisk operator acts as a


* *a, it points to the variable a
pointer to a variable.

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:

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

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.

What are the types of C operators?


The different types of operators in C are as follows:

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.

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

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.

Control statements in C are classified into following:

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:

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

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

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 –

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

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.

In C, what is the difference between a for loop and a while?


Difference between if else and switch:-

Difference between break and continue:

You might also like