0% found this document useful (0 votes)
12 views72 pages

Notes Chapater 1 and 2

The document provides an overview of operating systems, detailing their importance as essential software that manages computer hardware and software, enabling user interaction. It discusses the evolution of operating systems through four generations, from vacuum tubes to personal computers, and outlines various types of operating systems, including batch, time-sharing, distributed, network, real-time, and multiprogramming systems. Additionally, it highlights the services provided by operating systems, such as program execution, I/O operations, file system manipulation, and communication.

Uploaded by

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

Notes Chapater 1 and 2

The document provides an overview of operating systems, detailing their importance as essential software that manages computer hardware and software, enabling user interaction. It discusses the evolution of operating systems through four generations, from vacuum tubes to personal computers, and outlines various types of operating systems, including batch, time-sharing, distributed, network, real-time, and multiprogramming systems. Additionally, it highlights the services provided by operating systems, such as program execution, I/O operations, file system manipulation, and communication.

Uploaded by

itzlove957
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 72

LECTURE NOTES

on

PROGRAMMING for Problem Solving

Course Code : BTSC21101

Operating System
Chapter 1

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. An Operating System (OS) is a
software that acts as an interface between computer hardware components and the user.
Every computer system must have at least one operating system to run other programs.
Applications like Browsers, MS Office, Notepad Games, etc., need some environment to run and
perform its tasks.

The OS helps you to communicate with the computer without knowing how to speak the
computer’s language. It is not possible for the user to use any computer or mobile device
without having an operating system.
#Topic

Generations of Operating System

Operating Systems have evolved over the years. So, their evolution through the years can be
mapped using generations of operating systems. There are four generations of operating
systems. These can be described as follows −
The First Generation ( 1945 - 1955 ): Vacuum Tubes and Plugboards

Digital computers were not constructed until the second world war. Calculating engines with
mechanical relays were built at that time. However, the mechanical relays were very slow and
were later replaced with vacuum tubes. These machines were enormous but were still very
slow.

These early computers were designed, built and maintained by a single group of people.
Programming languages were unknown and there were no operating systems so all the
programming was done in machine language. All the problems were simple numerical
calculations.

By the 1950’s punch cards were introduced and this improved the computer system. Instead of
using plugboards, programs were written on cards and read into the system.

The Second Generation ( 1955 - 1965 ): Transistors and Batch Systems

Transistors led to the development of the computer systems that could be manufactured and
sold to paying customers. These machines were known as mainframes and were locked in air-
conditioned computer rooms with staff to operate them.

The Batch System was introduced to reduce the wasted time in the computer. A tray full of jobs
was collected in the input room and read into the magnetic tape. After that, the tape was
rewound and mounted on a tape drive. Then the batch operating system was loaded in which
read the first job from
the tape and ran it. The output was written on the second tape. After the whole batch was
done, the input and output tapes were removed and the output tape was printed.

The Third Generation ( 1965 - 1980 ): Integrated Circuits and Multiprogramming

Until the 1960’s, there were two types of computer systems i.e the scientific and the
commercial computers. These were combined by IBM in the System/360. This used integrated
circuits and provided a major price and performance advantage over the second generation
systems.

The third generation operating systems also introduced multiprogramming. This meant that the
processor was not idle while a job was completing its I/O operation. Another job was scheduled
on the processor so that its time would not be wasted.

The Fourth Generation ( 1980 - Present ): Personal Computers

Personal Computers were easy to create with the development of large-scale integrated circuits.
These were chips containing thousands of transistors on a square centimeter of silicon. Because
of these, microcomputers were much cheaper than minicomputers and that made it possible
for a single individual to own one of them.

The advent of personal computers also led to the growth of networks. This created network
operating systems and distributed operating systems. The users were aware of a network while
using a network operating system and could log in to remote machines and copy files from one
machine to another.

#Topic

Types of Operating Systems

An Operating System performs all the basic tasks like managing files, processes, and memory.
Thus operating system acts as the manager of all the resources, i.e. resource manager. Thus,
the operating system becomes an interface between user and machine.

Types of Operating Systems: Some widely used operating systems are as follows-

1. Batch Operating System –


This type of operating system does not interact with the computer directly. There is an
operator which takes similar jobs having the same requirement and group them into batches.
It is the responsibility of the operator to sort jobs with similar needs.
Advantages of Batch Operating System:

● It is very difficult to guess or know the time required for any job to complete. Processors
of the batch systems know how long the job would be when it is in queue

● Multiple users can share the batch systems

● The idle time for the batch system is very less

● It is easy to manage large work repeatedly in batch systems

Disadvantages of Batch Operating System:

● The computer operators should be well known with batch systems

● Batch systems are hard to debug

● It is sometimes costly

● The other jobs will have to wait for an unknown time if any job fails

Examples of Batch based Operating System: Payroll System, Bank Statements, etc.

2. Time-Sharing Operating Systems –


Each task is given some time to execute so that all the tasks work smoothly. Each user gets the
time of CPU as they use a single system. These systems are also known as Multitasking Systems.
The task can be from a single user or different users also. The time that each task gets to
execute is called quantum.
After this time interval is over OS switches over to the next task.
Advantages of Time-Sharing OS:

● Each task gets an equal opportunity

● Fewer chances of duplication of software

● CPU idle time can be reduced

Disadvantages of Time-Sharing OS:

● Reliability problem

● One must have to take care of the security and integrity of user programs and data

● Data communication problem

Examples of Time-Sharing OSs are: Multics, Unix, etc.

3. Distributed Operating System –


These types of the operating system is a recent advancement in the world of computer
technology and are being widely accepted all over the world and, that too, with a great pace.
Various autonomous interconnected computers communicate with each other using a shared
communication network.
Independent systems possess their own memory unit and CPU. These are referred to as loosely
coupled systems or distributed systems. These system’s processors differ in size and function.
The major benefit of working with these types of the operating system is that it is always
possible that one user can access the files or software which are not actually present on his
system but some other system connected within this network i.e., remote access is enabled
within the devices connected in that network.
Advantages of Distributed Operating System:

● Failure of one will not affect the other network communication, as all systems are
independent from each other

● Electronic mail increases the data exchange speed

● Since resources are being shared, computation is highly fast and durable

● Load on host computer reduces

● These systems are easily scalable as many systems can be easily added to the network

● Delay in data processing reduces

Disadvantages of Distributed Operating System:

● Failure of the main network will stop the entire communication

● To establish distributed systems the language which is used are not well defined yet

● These types of systems are not readily available as they are very expensive. Not only
that the underlying software is highly complex and not understood well yet

Examples of Distributed Operating System are- LOCUS, etc.


4. Network Operating System –
These systems run on a server and provide the capability to manage data, users, groups, security,
applications, and other networking functions. These types of operating systems allow shared
access of files, printers, security, applications, and other networking functions over a small
private network. One more important aspect of Network Operating Systems is that all the
users are well aware of the underlying configuration, of all other users within the network,
their individual connections, etc. and
that’s why these computers are popularly known as tightly coupled systems.

Advantages of Network Operating System:

● Highly stable centralized servers

● Security concerns are handled through servers

● New technologies and hardware up-gradation are easily integrated into the system

● Server access is possible remotely from different locations and types of systems

Disadvantages of Network Operating System:

● Servers are costly

● User has to depend on a central location for most operations

● Maintenance and updates are required regularly

Examples of Network Operating System are: Microsoft Windows Server 2003, Microsoft
Windows Server 2008, UNIX, Linux, Mac OS X, Novell NetWare, and BSD, etc.
5. Real-Time Operating System –
These types of OSs serve real-time systems. The time interval required to process and respond
to inputs is very small. This time interval is called response time.
Real-time systems are used when there are time requirements that are very strict like missile
systems, air traffic control systems, robots, etc.

Two types of Real-Time Operating System which are as follows:

● Hard Real-Time Systems:


These OSs are meant for applications where time constraints are very strict and even
the shortest possible delay is not acceptable. These systems are built for saving life like
automatic parachutes or airbags which are required to be readily available in case of
any accident. Virtual memory is rarely found in these systems.

● Soft Real-Time Systems:


These OSs are for applications where for time-constraint is less strict.

Advantages of RTOS:

● Maximum Consumption: Maximum utilization of devices and system, thus more output
from all the resources

● Task Shifting: The time assigned for shifting tasks in these systems are very less. For
example, in older systems, it takes about 10 microseconds in shifting one task to
another, and in the latest systems, it takes 3 microseconds.

● Focus on Application: Focus on running applications and less importance to applications


which are in the queue.

● Real-time operating system in the embedded system: Since the size of programs are
small, RTOS can also be used in embedded systems like in transport and others.
● Error Free: These types of systems are error-free.
● Memory Allocation: Memory allocation is best managed in these types of systems.

Disadvantages of RTOS:

● Limited Tasks: Very few tasks run at the same time and their concentration is very less on
few applications to avoid errors.

● Use heavy system resources: Sometimes the system resources are not so good and they are
expensive as well.

● Complex Algorithms: The algorithms are very complex and difficult for the designer to write on.

● Device driver and interrupt signals: It needs specific device drivers and interrupts signals to
respond earliest to interrupts.

● Thread Priority: It is not good to set thread priority as these systems are very less prone to
switching tasks.

Examples of Real-Time Operating Systems are: Scientific experiments, medical imaging systems,
industrial control systems, weapon systems, robots, air traffic control systems, etc.

6. Multiprogramming - in an operating system as the name suggests multi means more than one
and programming means the execution of the program. when more than one program can execute
in an operating system then this is termed a multiprogramming operating system.Before the
concept of Multiprogramming, computing takes place in other way which does not use the CPU
efficiently.Earlier, CPU executes only one program at a time. In earlier day’s computing ,the problem
is that when a program undergoes in waiting state for an input/output operation, the CPU remains
idle which leads to underutilization of CPU and thus poor performance . Multiprogramming
addresses this issue and solve this issue.Multiprogramming was developed in 1950s. It was first used
in mainframe computing.The major task of multiprogramming is to maximize the utilization of
resources.
Multiprogramming is broadly classified into two types namely

1. Multi-user operating system

2. Multitasking operating system

Multiuser and Multitasking both are different in every aspect and multitasking is an operating
system that allows you to run more than one program simultaneously. The operating system does
this by moving each program in and out of memory one at a time. When a program runs out of
memory, it is temporarily stored on disk until it is needed again.A multi-user operating system allows
many users to share processing time on a powerful central computer on different terminals. The
operating system does this by quickly switching between terminals, each receiving a limited amount
of CPU time on the central computer. Operating systems change so rapidly between terminals that
each user appears to have constant access to the central computer. If there are many users on such
a system, the time it takes for the central computer to respond may become more apparent.

Multi-Processing Operating System is a type of Operating System in which more than one CPU is
used for the execution of resources. It betters the throughput of the System.
Advantages of Multi-Processing Operating System
It increases the throughput of the system.As it has several processors, so, if one processor fails, we can proceed
with another processor.
Disadvantages of Multi-Processing Operating System
Due to the multiple CPU, it can be more complex and somehow difficult to understand.

4. Multi-Tasking Operating System Multitasking Operating System is simply a multiprogramming Operating


System with having facility of a Round-Robin Scheduling Algorithm. It can run multiple programs simultaneously.
1. Preemptive Multi-Tasking
In preemptive multitasking, the operating system can initiate a context switching from the running
process to another process. In other words, the operating system allows stopping the execution of the
currently running process and allocating the CPU to some other process. The OS uses some criteria to
decide for how long a process should execute before allowing another process to use the operating
system. The mechanism of taking control of the operating system from one process and giving it to
another process is called preempting or preemption.
2. Cooperative Multi-Tasking- In cooperative multitasking, the operating system never initiates context
switching from the running process to another process. A context switch occurs only when the
processes voluntarily yield control periodically or when idle or logically blocked to allow multiple
applications to execute simultaneously. Also, in this multitasking, all the processes cooperate for the
scheduling scheme to work.
Advantages of Multi-Tasking Operating System
Multiple Programs can be executed simultaneously in Multi-Tasking Operating System.It comes with
proper memory management.
Disadvantages of Multi-Tasking Operating System
The system gets heated in case of heavy programs multiple times.

#Topic

Operating System Services

Following are a few common services provided by an operating system −

● Program execution

● I/O operations

● File System manipulation

● Communication

● Error Detection

● Resource Allocation

● Protection

Program execution
Operating systems handle many kinds of activities from user programs to system programs like
printer spooler, name servers, file server, etc. Each of these activities is encapsulated as a process.
A process includes the complete execution context (code to execute, data to manipulate, registers,
OS resources in use). Following are the major activities of an operating system with respect to
program management −

● Loads a program into memory.

● Executes the program.

● Handles program's execution.

● Provides a mechanism for process synchronization.

● Provides a mechanism for process communication.

● Provides a mechanism for deadlock handling.

I/O Operation

An I/O subsystem comprises of I/O devices and their corresponding driver software. Drivers hide the
peculiarities of specific hardware devices from the users.

An Operating System manages the communication between user and device drivers.

● I/O operation means read or write operation with any file or any specific I/O device.

● Operating system provides the access to the required I/O device when required.

File system manipulation

A file represents a collection of related information. Computers can store files on the disk (secondary
storage), for long-term storage purpose. Examples of storage media include magnetic tape, magnetic
disk and optical disk drives like CD, DVD. Each of these media has its own properties like speed,
capacity, data transfer rate and data access methods.

A file system is normally organized into directories for easy navigation and usage. These directories
may contain files and other directions. Following are the major activities of an operating system with
respect to file management −

● Program needs to read a file or write a file.


● The operating system gives the permission to the program for operation on file.

● Permission varies from read-only, read-write, denied and so on.

● Operating System provides an interface to the user to create/delete files.

● Operating System provides an interface to the user to create/delete directories.

● Operating System provides an interface to create the backup of file system.


Communication

In case of distributed systems which are a collection of processors that do not share memory,
peripheral devices, or a clock, the operating system manages communications between all the
processes. Multiple processes communicate with one another through communication lines in the
network.

The OS handles routing and connection strategies, and the problems of contention and security.
Following are the major activities of an operating system with respect to communication −

● Two processes often require data to be transferred between them

● Both the processes can be on one computer or on different computers, but are connected
through a computer network.

● Communication may be implemented by two methods, either by Shared Memory or by


Message Passing.

Error handling

Errors can occur anytime and anywhere. An error may occur in CPU, in I/O devices or in the memory
hardware. Following are the major activities of an operating system with respect to error handling −

● The OS constantly checks for possible errors.

● The OS takes an appropriate action to ensure correct and consistent computing.

Resource Management
In case of multi-user or multi-tasking environment, resources such as main memory, CPU cycles and
files storage are to be allocated to each user or job. Following are the major activities of an operating
system with respect to resource management −

● The OS manages all kinds of resources using schedulers.

● CPU scheduling algorithms are used for better utilization of CPU.

Protection

Considering a computer system having multiple users and concurrent execution of multiple
processes, the various processes must be protected from each other's activities.

Protection refers to a mechanism or a way to control the access of programs, processes, or users to
the resources defined by a computer system. Following are the major activities of an operating
system with respect to protection −

● The OS ensures that all access to system resources is controlled.

● The OS ensures that external I/O devices are protected from invalid access attempts.
● The OS provides authentication features for each user by means of passwords.

INTRODUCTION TO COMPUTERS

Any programming language is implemented on a computer. Right form its


inception, to the present day, all computer system (irrespective of their shape & size)
perform the following 5 basic operations. It converts the raw input data into information,
which is useful to the users.

Inputting: It is the process of entering data & instructions to the computer


system.
Storing: The data & instructions are stored for either initial or additional
processing, as & when required.
Processing: It requires performing arithmetic or logical operation on the saved
data to convert it into useful information.
Outputting: It is the process of producing the output data to the end user.
Controlling: The above operations have to be directed in a particular sequence
to be completed.
Based on these 5 operations, we can sketch the block diagram of a computer.

Fig 1: Block Diagram of a Computer


Input Unit: We need to first enter the data & instruction in the computer system,
before any computation begins. This task is accomplished by the input devices.
(Eg: keyboard, mouse, scanner, digital camera etc). This device is responsible
for linking the system with the external environment. The data accepted is in a
human readable form. The input device converts it into a computer readable
form.

Storage Unit: The data & instruction that are entered have to be stored in the
computer. Similarly, the end results & the intermediate results also have to be
stored somewhere before being passed to the output unit. The storage unit
provides solution to all these issues. This storage unit is designed to save the
initial data, the intermediate result & the final result. This storage unit has 2
units: Primary storage & Secondary storage.

Primary Storage: The primary storage, also called as the main memory, holds the
data when the computer is currently on. As soon as the system is switched off or
restarted, the information held in primary storage disappears (i.e. it is volatile
in nature). Moreover, the primary storage normally has a limited storage
capacity, because it is very expensive as it is made up of semiconductor devices.

Secondary Storage: The secondary storage, also called as the auxiliary storage,
handles the storage limitation & the volatile nature of the primary memory. It
can retain information even when the system is off. It is basically used for
holding the program instructions & data on which the computer is not working
on currently, but needs to process them later.

Central Processing Unit: Together the Control Unit & the Arithmetic Logic Unit
are called as the Central Processing Unit (CPU). The CPU is the brain of the
computer. Like in humans, the major decisions are taken by the brain itself &
other body parts function as directed by the brain. Similarly in a computer
system, all the major calculations & comparisons are made inside the CPU. The
CPU is responsible for activating & controlling the operation of other units of
the computer system.

Arithmetic Logic Unit: The actual execution of the instructions (arithmetic or


logical operations) takes place over here. The data & instructions stored in the
primary storage are transferred as & when required. No processing is done in
the primary storage. Intermediate results that are generated in ALU are
temporarily transferred back to the primary storage, until needed later. Hence,
data may move from the primary storage to ALU & back again to storage, many
times, before the processing is done. Control Unit: This unit controls the
operations of all parts of the computer but does not carry out any actual data
processing.It is responsible for the transfer of data and instructions among
other units of the computer.It manages and coordinates all the units of the
system.It also communicates with Input/Output devices for transfer of data or
results from the storage units.
Output Unit: The job of an output unit is just the opposite of an input unit. It
accepts the results produced by the computer in coded form. It converts these
coded results to human readable form. Finally, it displays the converted results
to the outside world with the help of output devices ( Eg :monitors, printers,
projectors etc..).

So when we talk about a computer, we actually mean 2 things:

Hardware- This hardware is responsible for all the physical work of the
computer. Software- This software commands the hardware what to do & how
to do it.

Together, the hardware & software form the computer system.

This software is further classified as system software & application software.


System Software- System software are a set of programs, responsible for running
the computer, controlling various operations of computer systems and
management of computer resources. They act as an interface between the
hardware of the computer & the application software. E.g.: Operating System

Application Software- Application software is a set of programs designed to solve


a particular problem for users. It allows the end user to do something besides
simply running the hardware. E.g.: Web Browser, Gaming Software, etc.
INTRODUCTION TO PROGRAMMING

A language that is acceptable to a computer system is called a computer language or


programming language and the process of creating a sequence of instructions in such a
language is called programming or coding. A program is a set of instructions, written to
perform a specific task by the computer. A set of large program is called software. To
develop software, one must have knowledge of a programming language.

Before moving on to any programming language, it is important to know about the various
types of languages used by the computer. Let us first know what the basic requirements of
the programmers were & what difficulties they faced while programming in that language.

COMPUTER LANGUAGES

Languages are a means of communication. Normally people interact with each other through
a language. On the same pattern, communication with computers is carried out through a
language. This language is understood both by the user and the machine. Just as every
language like English, Hindi has its own grammatical rules; every computer language is also
bounded by rules known as syntax of that language. The user is bound by that syntax while
communicating with the computer system.
Computer languages are broadly classified as:

Low Level Language: The term low level highlights the fact that it is closer to a
language which the machine understands.
The low level languages are classified as:

o Machine Language: This is the language (in the form of 0’s and 1’s, called
binary numbers) understood directly by the computer. It is machine
dependent. It is difficult to learn and even more difficult to write programs.

o Assembly Language: This is the language where the machine codes


comprising of 0’sand 1’s are substituted by symbolic codes (called mnemonics)
to improve their understanding. It is the first step to improve programming
structure. Assembly language programming is simpler and less time
consuming than machine level programming, it is easier to locate and correct
errors in assembly language than in machine language programs. It is also
machine dependent. Programmers must have knowledge of the machine on
which the program will run.
High Level Language: Low level language requires extensive knowledge of the
hardware since it is machine dependent. To overcome this limitation, high level
language has been evolved which uses normal English, which is easy to understand to
solve any problem. High level languages are computer independent and
programming becomes quite easy and simple. Various high level languages are given
below:

o BASIC (Beginners All Purpose Symbolic Instruction Code): It is widely used,


easy to learn general purpose language. Mainly used in microcomputers in
earlier days. o COBOL (Common Business Oriented language): A standardized
language used for commercial applications. o FORTRAN (Formula
Translation): Developed for solving mathematical and scientific problems. One
of the most popular languages among scientific community. o C: Structured
Programming Language used for all purpose such as scientific application,
commercial application, developing games etc.
o C++: Popular object oriented programming language, used for general
purpose.

PROGRAMMING LANGUAGE TRANSLATORS

As you know that high level language is machine independent and assembly language
though it is machine dependent yet mnemonics that are being used to represent instructions
are not directly understandable by the machine. Hence to make the machine understand the
instructions provided by both the languages, programming language instructors are used. They
transform the instruction prepared by programmers into a form which can be interpreted &
executed by the computer. Flowing are the various tools to achieve this purpose:
Compiler: The software that reads a program written in high level language and
translates it into an equivalent program in machine language is called as compiler.
The program written by the programmer in high level language is called source
program and the program generated by the compiler after translation is called as
object program.

Interpreter: it also executes instructions written in a high level language. Both


complier & interpreter have the same goal i.e. to convert high level language into
binary instructions,
but their method of execution is different. The complier converts the entire source
code into machine level program, while the interpreter takes 1 statement, translates
it, executes it & then again takes the next statement.

Assembler: The software that reads a program written in assembly language and
translates it into an equivalent program in machine language is called as assembler.
Linker: A linker or link editor is a computer program that takes one or more object
files generated by a compiler and combines them into a single executable file, library
file, or another object file.
Brief History of C

The C programming language is a structure oriented programming language,


developed at Bell Laboratories in 1972 by Dennis Ritchie.

C programming language features were derived from an earlier language called “B”
(Basic Combined Programming Language – BCPL)

C language was invented for implementing UNIX operating system.

In 1978, Dennis Ritchie and Brian Kernighan published the first edition “The C
Programming Language” and is commonly known as K&R C.

In 1983, the American National Standards Institute (ANSI) established a committee


to provide a modern, comprehensive definition of C. The resulting definition, the
ANSI standard, or “ANSI C”, was completed late 1988.

Many of C’s ideas & principles were derived from the earlier language B, thereby
naming this new language “C”.
Taxonomy of C Language
WHY IS C POPULAR

It is reliable, simple and easy to use.


C is a small, block-structured programming language.
C is a portable language, which means that C programs written on one system can be
run on other systems with little or no modification.
C has one of the largest assortments of operators, such as those used for calculations
and data comparisons.
Although the programmer has more freedom with data storage, the languages do not
check data type accuracy for the programmer.

WHY TO STUDY C

By the early 1980s, C was already a dominant language in the minicomputer world of
Unix systems. Since then, it has spread to personal computers (microcomputers) and
to mainframes.
Many software houses use C as the preferred language for producing word
processing programs, spreadsheets, compilers, and other products.
C is an extremely flexible language—particularly if it is to be used to write operating
systems.
Unlike most other languages that have only four or five levels of precedence, C has 15.

CHARECTERESTICS OF A C PROGRAM

Middle level language.

High Level Middle Level Low Level


High level languages Middle level languages don’t Low level languages
provide almost provide all the built-in functions provides
everything that the found in high level languages, nothing other
programmer might need but provides all building blocks than access to the
to do as already built that we need to produce the machines basic
into the language result we want instruction set
Examples: C, C++ Assembler
Java, Python

Small size – has only 32 keywords


Extensive use of function calls- enables the end user to add their own functions to the
C library.
Supports loose typing – a character can be treated as an integer & vice versa.
Structured language
Structure oriented Object oriented Non structure
In this type of language, large In this type of language, There is no specific
programs are divided into programs are divided structure for
small programs called into objects programming this
functions language
Prime focus is on functions and Prime focus is in the data that N/A
procedures that operate on the is being operated and not on
data the functions or procedures
Data moves freely around the Data is hidden and cannot be N/A
systems from one function to accessed by external functions
another
Program structure follows “Top Program structure follows N/A
Down Approach” “Bottom UP Approach”
Examples: C++, JAVA and C# (C sharp) BASIC, COBOL,
C, Pascal, ALGOL and Modula-2 FORTRAN

Low level (Bit Wise) programming readily available


Pointer implementation - extensive use of pointers for memory, array, structures and
functions.
It has high-level constructs.
It can handle low-level activities.
It produces efficient programs. It can be compiled on a variety of computers.

USES

The C programming language is used for developing system applications that forms a major
portion of operating systems such as Windows, UNIX and Linux. Below are some examples of
C being used:
Database systems

Graphics packages

Word processors

Spreadsheets

Operating system development

Compilers and Assemblers

Network drivers

Interpreters
STRUCTURE OF A C PROGRAM

The structure of a C program is a protocol (rules) to the programmer, which he has to follow
while writing a C program. The general basic structure of C program is shown in the figure
below.
Based on this structure, we can sketch a C program.

Example:

/* This program accepts a number & displays it to the user*/

#include <stdio.h>
void main(void)
{ int number;
printf( "Please enter a number: " ); scanf(
"%d", &number ); printf( "You
entered %d", number ); return 0;}
Stepwise explanation:

#include

The part of the compiler which actually gets your program from the source file is
called the preprocessor.
▪ #include <stdio.h>
#include is a pre-processor directive. It is not really part of our program, but instead
it is an instruction to the compiler to make it do something. It tells the C compiler to
include the contents of a file (in this case the system file called stdio.h).
The compiler knows it is a system file, and therefore must be looked for in a special
place, by the fact that the filename is enclosed in <> characters

<stdio.h>

stdio.h is the name of the standard library definition file for all STanDard Input and
Output functions.
Your program will almost certainly want to send information to the screen and read
things from the keyboard, and stdio.h is the name of the file in which the functions
that we want to use are defined.
The function we want to use is called printf. The actual code of printf will be tied in
later by the linker.
The ".h" portion of the filename is the language extension, which denotes an include
file.

void

This literally means that this means nothing. In this case, it is referring to the function
whose name follows.
Void tells to C compiler that a given entity has no meaning, and produces no error.

main

In this particular example, the only function in the program is called main.
A C program is typically made up of large number of functions. Each of these is given
a name by the programmer and they refer to each other as the program runs.
C regards the name main as a special case and will run this function first i.e. the
program execution starts from main.

(void)
This is a pair of brackets enclosing the keyword void.
It tells the compiler that the function main has no parameters.
A parameter to a function gives the function something to work on.
{ (Brace)

This is a brace (or curly bracket). As the name implies, braces come in packs of two -
for every open brace there must be a matching close one.
Braces allow us to group pieces of program together, often called a block.
A block can contain the declaration of variable used within it, followed by a sequence
of program statements.
In this case the braces enclose the working parts of the function main.

; (semicolon)

The semicolon marks the end of the list of variable names, and also the end of that
declaration statement.
All statements in C programs are separated by ";" (semicolon) characters.
The ";" character is actually very important. It tells the compiler where a given
statement ends.
If the compiler does not find one of these characters where it expects to see one, then
it will produce an error.

scanf

In other programming languages, the printing and reading functions are a part of the
language.
In C this is not the case; instead they are defined as standard functions which are part
of the language specification, but are not a part of the language itself.
The standard input/output library contains a number of functions for formatted data
transfer; the two we are going to use are scanf (scan formatted) and printf (print
formatted).
printf

The printf function is the opposite of scanf.


It takes text and values from within the program and sends it out onto the screen.
Just like scanf, it is common to all versions of C and just like scanf, it is described in
the system file stdio.h.
The first parameter to a printf is the format string, which contains text, value
descriptions and formatting instructions.

FILES USED IN A C PROGRAM

Source File- This file contains the source code of the program. The file extension of
any c file is .c. The file contains C source code that defines the main function & maybe
other functions.
Header File- A header file is a file with extension .h which contains the C function
declarations and macro definitions and to be shared between several source files.
Object File- An object file is a file containing object code, with an extension .o,
meaning relocatable format machine code that is usually not directly executable.
Object files are produced by an assembler, compiler, or other language translator,
and used as input to the linker, which in turn typically generates an executable or
library by combining parts of object files.
Executable File- The binary executable file is generated by the linker. The linker links
the various object files to produce a binary file that can be directly executed.

COMPLIATION & EXECUTION OF A C PROGRAM


LECTURE NOTE -4

ELEMENTS OF C

Every language has some basic elements & grammatical rules. Before starting with
programming, we should be acquainted with the basic elements that build the language.

Character Set
Communicating with a computer involves speaking the language the computer understands.
In C, various characters have been given to communicate.

Character set in C consists of;

Types Character Set


Lower case a-z
Upper case A-Z
Digits 0-9
Special Character !@#$%^&*
White space Tab or new lines or space

Keywords

Keywords are the words whose meaning has already been explained to the C compiler. The
keywords cannot be used as variable names because if we do so we are trying to assign a
new meaning to the keyword, which is not allowed by the computer.

There are only 32 keywords available in C. Below figure gives a list of these keywords for
your ready reference.

Identifier

In the programming language C, an identifier is a combination of alphanumeric characters,


the first being a letter of the alphabet or an underline, and the remaining being any letter of
the alphabet, any numeric digit, or the underline.

Two rules must be kept in mind when naming identifiers.

1. The case of alphabetic characters is significant. Using "INDEX" for a variable is not the
same as using "index" and neither of them is the same as using "InDeX" for a variable.
All three refer to different variables.
2. As C is defined, up to 32 significant characters can be used and will be considered
significant by most compilers. If more than 32 are used, they will be ignored by the
compiler.

Data Type

In the C programming language, data types refer to a domain of allowed values & the
operations that can be performed on those values. The type of a variable determines how
much space it occupies in storage and how the bit pattern stored is interpreted. There are 4
fundamental data types in C, which are- char, int, float &, double. Char is used to store any
single character; int is used to store any integer value, float is used to store any single
precision floating point number & double is used to store any double precision floating point
number. We can use 2 qualifiers with these basic types to get more types.

There are 2 types of qualifiers-

Sign qualifier- signed & unsigned


Size qualifier- short & long

The data types in C can be classified as follows:

Type Storage size Value range

char 1 byte -128 to 127

unsigned char 1 byte 0 to 255

int 2 or 4 bytes -32,768 to 32,767 or -2,147,483,648 to 2,147,483,647

unsigned int 2 or 4 bytes 0 to 65,535 or 0 to 4,294,967,295

short 2 bytes -32,768 to 32,767

unsigned short 2 bytes 0 to 65,535

long 4 bytes -2,147,483,648 to 2,147,483,647

unsigned long 4 bytes 0 to 4,294,967,295


Type Storage size Value range Precision

float 4 bytes 1.2E-38 to 3.4E+38 6 decimal places

double 8 bytes 2.3E-308 to 1.7E+308 15 decimal places

long double 10 bytes 3.4E-4932 to 1.1E+4932 19 decimal places

Constants

A constant is an entity that doesn’t change whereas a variable is an entity that may change.

C constants can be divided into two major categories:


• Primary Constants
• Secondary Constants

Here our only focus is on primary constant. For constructing these different types of
constants certain rules have been laid down.

Rules for Constructing Integer Constants:

An integer constant must have at least one digit.

a) It must not have a decimal point.


b) It can be either positive or negative.
c) If no sign precedes an integer constant it is assumed to be positive.

d) No commas or blanks are allowed within an integer constant.


e) The allowable range for integer constants is -32768to 32767.

Ex.: 426, +782,-8000, -7605

Rules for Constructing Real Constants:

Real constants are often called Floating Point constants. The real constants could be written
in two forms—Fractional form and Exponential form.

Rules for constructing real constants expressed in fractional form:

a) A real constant must have at least one digit.

b) It must have a decimal point.

c) It could be either positive or negative.

d) Default sign is positive.

e) No commas or blanks are allowed within a real constant.

Ex. +325.34, 426.0, -32.76, -48.5792

Rules for constructing real constants expressed in exponential form:

a) The mantissa part and the exponential part should be separated by a letter e.

b) The mantissa part may have a positive or negative sign.

c) Default sign of mantissa part is positive.

d) The exponent must have at least one digit, which must be a positive or negative
integer. Default sign is positive.

e) Range of real constants expressed in exponential form is -3.4e38 to 3.4e38. Ex. +3.2e-
5,

4.1e8, -0.2e+3, -3.2e-5

Rules for Constructing Character Constants:


a) A character constant is a single alphabet, a single digit or a single special symbol
enclosed within single inverted commas.

b) The maximum length of a character constant can be 1 character.

Ex.: ‘M’, ‘6’, ‘+’


VARIABLES

Variables are names that are used to store values. It can take different values but one at a
time. A data type is associated with each variable & it decides what values the variable can
take. When you decide your program needs another variable, you simply declare (or define)
a new variable and C makes sure you get it. You declare all C variables at the top of whatever
blocks of code need them. Variable declaration requires that you inform C of the variable's
name and data type. Syntax – datatype variablename;

Eg:
int page_no;

char grade;

float salary;

long y;

Declaring Variables:

There are two places where you can declare a variable:

• After the opening brace of a block of code (usually at the top of a function)

• Before a function name (such as before main() in the program) Consider various
examples:

Suppose you had to keep track of a person's first, middle, and last initials. Because
an initial is obviously a character, it would be prudent to declare three character
variables to hold the three initials. In C, you could do that with the following
statement:
1. main()

{
char first, middle, last;

// Rest of program follows

}
2. main()

{ char first; char middle;

char last;

// Rest of program follows

Initialization of Variables

When a variable is declared, it contains undefined value commonly known as garbage


value. If we want we can assign some initial value to the variables during the
declaration itself. This is called initialization of the variable.

Eg- int pageno=10;

char grade=’A’;

float salary= 20000.50;

Expressions

An expression consists of a combination of operators, operands, variables & function calls.


An expression can be arithmetic, logical or relational. Here are some expressions:

a+b – arithmetic

operation a>b- relational


operation a == b - logical

operation func (a,b) –

function call

4+21

a*(b + c/d)/20

q = 5*2 x =

++q % 3

q>3
As you can see, the operands can be constants, variables, or combinations of the two. Some
expressions are combinations of smaller expressions, called subexpressions. For example,
c/d is a subexpression of the sixth example.

An important property of C is that every C expression has a value. To find the value, you
perform the operations in the order dictated by operator precedence.

Statements
Statements are the primary building blocks of a program. A program is a series of statements
with some necessary punctuation. A statement is a complete instruction to the computer. In
C, statements are indicated by a semicolon at the end. Therefore

legs = 4

is just an expression (which could be part of a larger expression), but

legs = 4;

is a statement.

What makes a complete instruction? First, C considers any expression to be a statement if


you append a semicolon. (These are called expression statements.) Therefore, C won't object
to lines such as the following:
8;

3 + 4;

However, these statements do nothing for your program and can't really be considered
sensible statements. More typically, statements change values and call functions:

x = 25;

++x; y =

sqrt(x);

Although a statement (or, at least, a sensible statement) is a complete instruction, not all
complete instructions are statements. Consider the following statement:

x = 6 + (y = 5);

In it, the subexpression y = 5 is a complete instruction, but it is only part of the statement.
Because a complete instruction is not necessarily a statement, a semicolon is needed to
identify instructions that truly are statements.
Compound Statements (Blocks)

A compound statement is two or more statements grouped together by enclosing them in


braces; it is also called a block. The following while statement contains an example:

while (years < 100)

wisdom = wisdom * 1.05;

printf("%d %d\n", years, wisdom);

years

= years + 1;

}
If any variable is declared inside the block then it can be declared only at the beginning of
the block. The variables that are declared inside a block can be used only within the block.
INPUT-OUTPUT IN C

When we are saying Input that means we feed some data into program. This can be given in
the form of file or from command line. C programming language provides a set of built-in
functions to read given input and feed it to the program as per requirement.

When we are saying Output that means to display some data on screen, printer or in any file.
C programming language provides a set of built-in functions to output the data on the computer
screen. Functions printf() and scanf() are the most commonly used to display out and take
input respectively. Let us consider an example:

#include <stdio.h> //This is needed to run printf() function. int


main()
{
printf("C Programming"); //displays the content inside quotation
return 0;
}
Output:
C Programming

Explanation:

Every program starts from main() function.


printf() is a library function to display output which only works if #include<stdio.h>is
included at the beginning.
Here, stdio.h is a header file (standard input output header file) and #include is
command to paste the code from the header file when necessary. When compiler
encounters printf()function and doesn't find stdio.h header file, compiler shows error.
return 0; indicates the successful execution of the program.

Input- Output of integers in C

#include<stdio.h>
int main()
{ int
c=5;
printf("
Number
=%d",c
);
return
0;
}
Output Number=5

Inside quotation of printf() there, is a conversion format string "%d" (for integer). If this
conversion format string matches with remaining argument, i.e, c in this case, value of c is
displayed.

#include<stdio.h>
int main()
{ int c; printf("Enter
a number\n");
scanf("%d",&c);
printf("Number=%d",c);
return 0; }

Output Enter
a number
4
Number=4

The scanf() function is used to take input from user. In this program, the user is asked an
input and value is stored in variable c. Note the '&' sign before c. &c denotes the address of c
and value is stored in that address.

Input- Output of floats in C

#include <stdio.h> int main()


{ float a; printf("Enter value: "); scanf("%f",&a);
printf("Value=%f",a); //%f is used for floats instead of %d return 0; }
Output

Enter value: 23.45


Value=23.450000
Conversion format string "%f" is used for floats to take input and to display floating value of
a variable.

Input - Output of characters and ASCII code


#include <stdio.h> int
main()
{
char var1;
printf("Enter character: ");
scanf("%c",&var1); printf("You
entered %c.",var1);
return 0;
}
Output
Enter character: g You
entered g.

Conversion format string "%c" is used in case of characters.

ASCII code
When character is typed in the above program, the character itself is not recorded a numeric
value (ASCII value) is stored. And when we displayed that value by using "%c", that
character is displayed.

#include <stdio.h> int


main()
{
char var1; printf("Enter
character: ");
scanf("%c",&var1); printf("You
entered %c.\n",var1);
/* \n prints the next line(performs work of enter). */
printf("ASCII value of %d",var1);
return 0; }
Output:
Enter character:
g
103
When, 'g' is entered, ASCII value 103 is stored instead of g.

You can display character if you know ASCII code only. This is shown by following example.

#include <stdio.h> int main()


{
int var1=69; printf("Character of ASCII value
69: %c",var1); return 0;
}

Output
Character of ASCII value 69: E

The ASCII value of 'A' is 65, 'B' is 66 and so on to 'Z' is 90. Similarly ASCII value of 'a' is 97, 'b'
is 98 and so on to 'z' is 122.
FORMATTED INPUT-OUTPUT

Data can be entered & displayed in a particular format. Through format specifications, better
presentation of results can be obtained.

Variations in Output for integer & floats:


#include<stdio.h> int main()
{
printf("Case 1:%6d\n",9876);
/* Prints the number right justified within 6 columns */
printf("Case 2:%3d\n",9876);
/* Prints the number to be right justified to 3 columns but, there are 4 digits so number is not
right justified */ printf("Case 3:%.2f\n",987.6543);
/* Prints the number rounded to two decimal places */
printf("Case 4:%.f\n",987.6543);
/* Prints the number rounded to 0 decimal place, i.e, rounded to integer */ printf("Case
5:%e\n",987.6543);
/* Prints the number in exponential notation (scientific notation) */
return 0;
}
Output
Case 1: 9876
Case 2:9876
Case 3:987.65
Case 4:988
Case 5:9.876543e+002

Variations in Input for integer and floats:


#include <stdio.h> int main()
{ int a,b;
float c,d;
printf("Enter two intgers: ");
/*Two integers can be taken from user at once as below*/
scanf("%d%d",&a,&b); printf("Enter intger and
floating point numbers: ");
/*Integer and floating point number can be taken at once from user as
below*/ scanf("%d%f",&a,&c); return 0;
}
Similarly, any number of inputs can be taken at once from user.

EXERCISE:

1. To print out a and b given below, which of the following printf() statement will you use?

#include<stdio.h>
float a=3.14;
double b=3.14;
A. printf("%f %lf", a, b);
B. printf("%Lf %f", a, b);
C. printf("%Lf %Lf", a, b);
D. printf("%f %Lf", a, b);

2. To scan a and b given below, which of the following scanf() statement will you use?
#include<stdio.h> float a;
double b;
A. scanf("%f %f", &a, &b);
B. scanf("%Lf %Lf", &a, &b);
C. scanf("%f %Lf", &a, &b);
D. scanf("%f %lf", &a, &b);

3. For a typical program, the input is taken using.


A. scanf
B. Files
C. Command-line
D. None of the mentioned 4. What is the output of this C code?

#include <stdio.h> int main()


{ int i = 10, j = 2; printf("%d\n",
printf("%d %d ", i, j));
}
A. Compile time error
B. 10 2 4 C. 10 2 2
D. 10 2 5

5. What is the output of this C code?

#include <stdio.h> int


main()
{
int i = 10, j = 3; printf("%d %d %d",
i, j);
}

A. Compile time error


B. 10 3
C. 10 3 some garbage value
D. Undefined behavior
6. What is the output of this C code?

#include <stdio.h> int main()


{ int i = 10, j = 3, k = 3; printf("%d
%d ", i, j, k);
}

A. Compile time error


B. 10 3 3
C. 10 3
D. 10 3 somegarbage value
7. The syntax to print a % using printf statement can be done by.
A. %
B. %
C. ‘%’
D. %%

8. What is the output of this C code?

#include <stdio.h> int


main()
{ int n; scanf("%d", n);
printf("%d\n",
n); return 0;
}
A. Compilation error
B. Undefined behavior
C. Whatever user types
D. Depends on the standard

9. What is the output of this C code?


#include <stdio.h> int
main()
{ short int i;
scanf("%hd", &i); printf("%hd",
i);
return 0;
}
A. Compilation error
B. Undefined behavior
C. Whatever user types
D. None of the mentioned

10. In a call to printf() function the format specifier %b can be used to print binary
equivalent of an integer.
A. True
B. False
11. Point out the error in the program?

#include<stdio.h>
int main()
{ char ch;
int i;
scanf("%c", &i);
scanf("%d", &ch); printf("%c
%d", ch, i); return
0;
}
A. Error: suspicious char to in conversion in scanf()
B. Error: we may not get input for second scanf() statement
C. No error
D. None of above

12. Which of the following is NOT a delimiter for an input in scanf?


A. Enter
B. Space
C. Tab
D. None of the mentioned
OPERATORS

An operator is a symbol that tells the compiler to perform specific mathematical or logical
manipulations. C language is rich in built-in operators and provides the following types of
operators:

• Arithmetic Operators

• Relational Operators

• Logical Operators

• Bitwise Operators

• Assignment Operators

• Increment and decrement operators

• Conditional operators

• Misc Operators

Arithmetic operator:

These are used to perform mathematical calculations like addition, subtraction,


multiplication, division and modulus.

Following table shows all the arithmetic operators supported by C language. Assume
variable A holds 10 and variable B holds 20 then:

Operator Description Example


+ Adds two operands A + B will give 30

- Subtracts second operand from the first A – B will give -10

* Multiplies both operands A * B will give 200

/ Divides numerator by de-numerator B / A will give 2

Modulus Operator and remainder of after an


% B % A will give 0
integer Division
Increments operator increases integer value by
++ A++ will give 11
one
Decrements operator decreases integer value by
-- A–will give 9
one

Relational Operators:

These operators are used to compare the value of two variables.

Following table shows all the relational operators supported by C language. Assume variable
A holds 10 and variable B holds 20, then:

Operator Description Example

== Checks if the values of two operands are equal or not, if (A == B) is not


yes then condition becomes true. true.

!= Checks if the values of two operands are equal or not, if (A != B) is true.


values are not equal then condition becomes true.

> Checks if the value of left operand is greater than the value (A > B) is not
of right operand, if yes then condition becomes true. true.

< Checks if the value of left operand is less than the value of (A < B) is true.
right operand, if yes then condition becomes true.
>= Checks if the value of left operand is greater than or equal (A >= B) is not
to the value of right operand, if yes then condition true.
becomes true.

<= Checks if the value of left operand is less than or equal to (A <= B) is true.
the value of right operand, if yes then condition becomes
true.

Logical Operators:

These operators are used to perform logical operations on the given two variables.

Following table shows all the logical operators supported by C language. Assume variable A
holds 1 and variable B holds 0, then:
Operator Description Example

&& Called Logical AND operator. If both the operands are


(A && B) is false.
nonzero, then condition becomes true.

Called Logical OR Operator. If any of the two operands is


|| non-zero, then condition becomes true. (A || B) is true.

Called Logical NOT Operator. Use to reverses the logical


! state of its operand. If a condition is true then Logical !(A && B) is true.
NOT operator will make false.

Bitwise Operators

Bitwise operator works on bits and performs bit-by-bit operation. Bitwise operators are
used in bit level programming. These operators can operate upon int and char but not on
float and double.

Showbits( ) function can be used to display the binary representation of any integer or
character value.

Bit wise operators in C language are; & (bitwise AND), | (bitwise OR), ~ (bitwise OR), ^
(XOR), << (left shift) and >> (right shift).
The truth tables for &, |, and ^ are as follows:

P q p&q p|q p^q

0 0 0 0 0

0 1 0 1 1

1 1 1 1 0

1 0 0 1 1

The Bitwise operators supported by C language are explained in the following table. Assume
variable A holds 60 (00111100) and variable B holds 13 (00001101), then:

Operator Description Example

& Binary AND Operator copies a bit to the result if it (A & B) will give 12,
exists in both operands. which is 0000 1100

| Binary OR Operator copies a bit if it exists in (A | B) will give 61, which


either operand. is 0011 1101

^ Binary XOR Operator copies the bit if it is set in (A ^ B) will give 49,
one operand but not both. which is 0011 0001

~ Binary Ones Complement Operator is unary and (~A ) will give -61,
has the effect of ‘flipping’ bits. which is 1100 0011 in
2’s complement form.

<< Binary Left Shift Operator. The left operands A << 2 will give 240
value is moved left by the number of bits which is 1111 0000
specified by the right operand.

>> Binary Right Shift Operator. The left operands A >> 2 will give 15 which
value is moved right by the number of bits is 0000 1111
specified by the right operand.

Assignment Operators:
In C programs, values for the variables are assigned using assignment operators.

There are following assignment operators supported by C language:


Operato Description Example
r
= Simple assignment operator, Assigns values from right C = A + B will
side operands to left side operand assign value of A
+ B into C

+= Add AND assignment operator, It adds right operand to C += A is


the left operand and assign the result to left operand equivalent to C = C
+A

-= Subtract AND assignment operator, It subtracts right C -= A is equivalent


operand from the left operand and assign the result to to C = C – A
left operand

*= Multiply AND assignment operator, It multiplies right C *= A is


operand with the left operand and assign the result equivalent to C = C
to left operand *A

/= Divide AND assignment operator, It divides left operand C /= A is


with the right operand and assign the result to left equivalent to C = C
operand /A

%= Modulus AND assignment operator, It takes modulus C %= A is


using two operands and assign the result to left operand equivalent to C =
C%A

<<= Left shift AND assignment operator C <<= 2 is same as


C
= C << 2
>>= Right shift AND assignment operator C >>= 2 is same as
C
= C >> 2
&= Bitwise AND assignment operator C &= 2 is same as C
=C&2
^= bitwise exclusive OR and assignment operator C ^= 2 is same as C
=C^2

|= bitwise inclusive OR and assignment operator C |= 2 is same as C


=C|2

INCREMENT AND DECREMENT OPERATOR

In C, ++ and – are called increment and decrement operators respectively. Both of these
operators are unary operators, i.e, used on single operand. ++ adds 1 to operand and –
subtracts 1 to operand respectively. For example:

Let a=5 and b=10

a++; //a becomes 6

a--; //a becomes 5

++a; //a becomes 6

--a; //a becomes 5

When i++ is used as prefix(like: ++var), ++var will increment the value of var and then
return it but, if ++ is used as postfix(like: var++), operator will return the value of operand
first and then only increment it. This can be demonstrated by an example:

#include <stdio.h> int main()

int c=2,d=2;

printf(“%d\n”,c++); //this statement displays 2 then, only c incremented by 1 to 3.

Printf(“%d”,++c); //this statement increments 1 to c then, only c is displayed.

Return 0;
}

Output

4
Conditional Operators (? :)

Conditional operators are used in decision making in C programming, i.e, executes different
statements according to test condition whether it is either true or false.

Syntax of conditional operators;


conditional_expression?expression1:expression2

If the test condition is true (that is, if its value is non-zero), expression1 is returned and if
false expression2 is returned.

Let us understand this with the help of a few examples:


int x, y ;
scanf ( “%d”, &x ) ;

y = ( x> 5 ? 3 : 4 ) ;

This statement will store 3 in y if x is greater than 5, otherwise it will store 4 in y.

The equivalent if statement will be, if ( x > 5 )

y=3;

else
y=4;

Misc Operators:

There are few other operators supported by c language.


Operator Description Example

sizeof() It is a unary operator which is used in sizeof(a), where a is integer,


finding the size of data type, constant, will return 4.
arrays, structure etc.

& Returns the address of a variable. &a; will give actual address of
the variable.

* Pointer to a variable. *a; will pointer to a variable.

Operators Precedence in C

Operator precedence determines the grouping of terms in an expression. This affects how an
expression is evaluated. Certain operators have higher precedence than others; for example,
the multiplication operator has higher precedence than the addition operator.

For example x = 7 + 3 * 2; here, x is assigned 13, not 20 because operator * has higher
precedence than +, so it first gets multiplied with 3*2 and then adds into 7.

Here, operators with the highest precedence appear at the top of the table, those with the
lowest appear at the bottom. Within an expression, higher precedence operators will be
evaluated first.

Category Operator Associativity

Postfix () [] -> . ++ - - Left to right

Unary + - ! ~ ++ - - (type)* &sizeof Right to left

Multiplicative */% Left to right

Additive +- Left to right


Shift <<>> Left to right

Relational <<= >>= Left to right

Equality == != Left to right

Bitwise AND & Left to right

Bitwise XOR ^ Left to right

Bitwise OR | Left to right

Logical OR || Left to right

Conditional ?: Right to left

Assignment = += -= *= /= %=>>= <<= &= ^= |= Right to left

Comma , Left to right

What is a Flowchart?

Flowchart is a graphical representation of an algorithm. Programmers often use it as a


program-planning tool to solve a problem. It makes use of symbols which are connected
among them to indicate the flow of information and processing.
The process of drawing a flowchart for an algorithm is known as “flowcharting”.
Basic Symbols used in Flowchart Designs

Terminal: The oval symbol indicates Start, Stop and Halt in a program’s logic flow. A pause/halt is
generally used in a program logic under some error conditions. Terminal is the first and last symbols in
the flowchart.
1. Check each element in the list by comparing it to the key.
● Input/Output: A parallelogram denotes any function of input/output type. Program instructions
that take input from input devices and display output on output devices are indicated with
parallelogram in a flowchart.

If any elem
ent is equal to the key, return its index.

Processing: A box represents arithmetic instructions. All arithmetic processes such as adding, subtracting,
multiplication and division are indicated by action or process symbol.

Decision Diamond symbol represents a decision point. Decision based operations such as yes/no question or
true/false are indicated by diamond in flowchart.

Connectors: Whenever flowchart becomes complex or it spreads over more than one page, it is useful to use
connectors to avoid any confusions. It is represented by a circle.

● Flow lines: Flow lines indicate the exact sequence in which instructions are executed. Arrows represent
the direction of flow of control and relationship among different symbols of flowchart.
Rules For Creating Flowchart :
A flowchart is a graphical representation of an algorithm.it should follow some rules while creating a flowchart
Rule 1: Flowchart opening statement must be ‘start’ keyword.
Rule 2: Flowchart ending statement must be ‘end’ keyword.
Rule 3: All symbols in the flowchart must be connected with an arrow line.
Rule 4: The decision symbol in the flowchart is associated with the arrow line.

Advantages of Flowchart:
● Flowcharts are a better way of communicating the logic of the system.
● Flowcharts act as a guide for blueprint during program designed.
● Flowcharts help in debugging process.
● With the help of flowcharts programs can be easily analyzed.
● It provides better documentation.
● Flowcharts serve as a good proper documentation.
● Easy to trace errors in the software.
● Easy to understand.
● The flowchart can be reused for inconvenience in the future.
● It helps to provide correct logic.

Disadvantages of Flowchart:
● It is difficult to draw flowcharts for large and complex programs.
● There is no standard to determine the amount of detail.
● Difficult to reproduce the flowcharts.
● It is very difficult to modify the Flowchart.
● Making a flowchart is costly.
● Some developer thinks that it is waste of time.
● It makes software processes low.
● If changes are done in software, then the flowchart must be redrawn

Example : Draw a flowchart to input two numbers from the user and display the largest of two numbers
Introduction to Algorithms

The word Algorithm means ” A set of finite rules or instructions to be followed in calculations or other problem-
solving operations ”
Or
” A procedure for solving a mathematical problem in a finite number of steps that frequently involves recursive
operations”.
Therefore Algorithm refers to a sequence of finite steps to solve a particular problem.

Use of the Algorithms:


Algorithms play a crucial role in various fields and have many applications. Some of the key areas where
algorithms are used include:
1. Computer Science: Algorithms form the basis of computer programming and are used to solve problems
ranging from simple sorting and searching to complex tasks such as artificial intelligence and machine
learning.
2. Mathematics: Algorithms are used to solve mathematical problems, such as finding the optimal solution to
a system of linear equations or finding the shortest path in a graph.
3. Operations Research: Algorithms are used to optimize and make decisions in fields such as
transportation, logistics, and resource allocation.
4. Artificial Intelligence: Algorithms are the foundation of artificial intelligence and machine learning, and
are used to develop intelligent systems that can perform tasks such as image recognition, natural language
processing, and decision-making.
5. Data Science: Algorithms are used to analyze, process, and extract insights from large amounts of data in
fields such as marketing, finance, and healthcare.
These are just a few examples of the many applications of algorithms. The use of algorithms is continually
expanding as new technologies and fields emerge, making it a vital component of modern society.
Algorithms can be simple and complex depending on what you want to achieve.
It can be understood by taking the example of cooking a new recipe. To cook a new recipe, one reads the
instructions and steps and executes them one by one, in the given sequence. The result thus obtained is the new
dish is cooked perfectly. Every time you use your phone, computer, laptop, or calculator you are using Algorithms.
Similarly, algorithms help to do a task in programming to get the expected output.
The Algorithm designed are language-independent, i.e. they are just plain instructions that can be implemented in
any language, and yet the output will be the same, as expected.
What is the need for algorithms?
1. Algorithms are necessary for solving complex problems efficiently and effectively.
2. They help to automate processes and make them more reliable, faster, and easier to perform.
3. Algorithms also enable computers to perform tasks that would be difficult or impossible for humans to do
manually.
4. They are used in various fields such as mathematics, computer science, engineering, finance, and many
others to optimize processes, analyze data, make predictions, and provide solutions to problems.

What are the Characteristics of an Algorithm?


As one would not follow any written instructions to cook the recipe, but only the standard one. Similarly,
not all written instructions for programming are an algorithm. For some instructions to be an algorithm, it
must have the following characteristics:
● Clear and Unambiguous: The algorithm should be unambiguous. Each of its steps should be clear in all
aspects and must lead to only one meaning.
● Well-Defined Inputs: If an algorithm says to take inputs, it should be well-defined inputs. It may or may not
take input.
● Well-Defined Outputs: The algorithm must clearly define what output will be yielded and it should be well-
defined as well. It should produce at least 1 output.
● Finite-ness: The algorithm must be finite, i.e. it should terminate after a finite time.
● Feasible: The algorithm must be simple, generic, and practical, such that it can be executed with the
available resources. It must not contain some future technology or anything.
● Language Independent: The Algorithm designed must be language-independent, i.e. it must be just plain
instructions that can be implemented in any language, and yet the output will be the same, as expected.
● Input: An algorithm has zero or more inputs. Each that contains a fundamental operator must accept zero
or more inputs.
● Output: An algorithm produces at least one output. Every instruction that contains a fundamental operator
must accept zero or more inputs.
● Definiteness: All instructions in an algorithm must be unambiguous, precise, and easy to interpret. By
referring to any of the instructions in an algorithm one can clearly understand what is to be done. Every
fundamental operator in instruction must be defined without any ambiguity.
● Finiteness: An algorithm must terminate after a finite number of steps in all test cases. Every instruction
which contains a fundamental operator must be terminated within a finite amount of time. Infinite loops or
recursive functions without base conditions do not possess finiteness.
● Effectiveness: An algorithm must be developed by using very basic, simple, and feasible operations so that
one can trace it out by using just paper and pencil.
Properties of Algorithm:
● It should terminate after a finite time.
● It should produce at least one output.
● It should take zero or more input.
● It should be deterministic means giving the same output for the same input case.
● Every step in the algorithm must be effective i.e. every step should do some work
How to Design an Algorithm?
To write an algorithm, the following things are needed as a pre-requisite:
1. The problem that is to be solved by this algorithm i.e. clear problem definition.
2. The constraints of the problem must be considered while solving the problem.
3. The input to be taken to solve the problem.
4. The output is to be expected when the problem is solved.
5. The solution to this problem is within the given constraints.
Then the algorithm is written with the help of the above parameters such that it solves the problem.
Example: Consider the example to add three numbers and print the sum.
Step 1: Fulfilling the pre-requisites
As discussed above, to write an algorithm, its prerequisites must be fulfilled.
1. The problem that is to be solved by this algorithm: Add 3 numbers and print their sum.
2. The constraints of the problem that must be considered while solving the problem: The numbers
must contain only digits and no other characters.
3. The input to be taken to solve the problem: The three numbers to be added.
4. The output to be expected when the problem is solved: The sum of the three numbers taken as the
input i.e. a single integer value.
5. The solution to this problem, in the given constraints: The solution consists of adding the 3 numbers. It
can be done with the help of the ‘+’ operator, or bit-wise, or any other method.

Step 2: Designing the algorithm


Now let’s design the algorithm with the help of the above pre-requisites:
Algorithm to add 3 numbers and print their sum:
1. START
2. Declare 3 integer variables num1, num2, and num3.
3. Take the three numbers, to be added, as inputs in variables num1, num2, and num3 respectively.
4. Declare an integer variable sum to store the resultant sum of the 3 numbers.
5. Add the 3 numbers and store the result in the variable sum.
6. Print the value of the variable sum
7. END

Step 3: Testing the algorithm by implementing it.


To test the algorithm, let’s implement it in C 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.

How to write Pseudocode?


Before writing the pseudocode of any algorithm the following points must be kept in mind.
Organize the sequence of tasks and write the pseudocode accordingly.
At first, establishes the main goal or the aim. Example:
This program will print first N numbers of Fibonacci series.

Use standard programming structures such as if-else, for, while, and cases the way we use them in
programming. Indent the statements if-else, for, while loops as they are indented in a program, it helps to
comprehend the decision control and execution mechanism. It also improves readability to a great extent.
Example:

IF “1”
print response
“I AM CASE 1”

IF “2”
print response
“I AM CASE 2”

Use appropriate naming conventions. The human tendency follows the approach of following what we see.
If a programmer goes through a pseudo code, his approach will be the same as per that, so the naming
must be simple and distinct.
Reserved commands or keywords must be represented in capital letters. Example: if you are writing
IF…ELSE statements then make sure IF and ELSE be in capital letters.
Check whether all the sections of a pseudo code are complete, finite, and clear to understand and
comprehend. Also, explain everything that is going to happen in the actual code.
Don’t write the pseudocode in a programming language. It is necessary that the pseudocode is simple and
easy to understand even for a layman or client, minimizing the use of technical terms.

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:
1. Documentation
2. Preprocessor Section
3. Definition
4. Global Declaration
5. Main() Function
6. Sub Programs
1. Documentation
This section consists of the description of the program, the name of the program, and the creation date and
time of the program. It is specified at the start of the program in the form of comments. Documentation can
be represented as:
// description, name of the program, programmer name, date, time etc.
or
/*
description, name of the program, programmer name, date, time etc.
*/
Anything written as comments will be treated as documentation of the program and this will not interfere
with the given code. Basically, it gives an overview to the reader of the program.
2. Preprocessor Section
All the header files of the program will be declared in the preprocessor section of the program. Header files
help us to access other’s improved code into our code. A copy of these multiple files is inserted into our
program before the process of compilation.
Example:
#include<stdio.h>
#include<math.h>
3. Definition
Preprocessors are the programs that process our source code before the process of compilation. There are
multiple steps which are involved in the writing and execution of the program. Preprocessor directives
start with the ‘#’ symbol. The #define preprocessor is used to create a constant throughout the program.
Whenever this name is encountered by the compiler, it is replaced by the actual piece of defined code.
Example:
#define long long ll
4. Global Declaration
The global declaration section contains global variables, function declaration, and static variables.
Variables and functions which are declared in this scope can be used anywhere in the program.
Example:
int num = 18;
5. Main() Function
Every C program must have a main function. The main() function of the program is written in this section.
Operations like declaration and execution are performed inside the curly braces of the main program. The
return type of the main() function can be int as well as void too. void() main tells the compiler that the
program will not return any value. The int main() tells the compiler that the program will return an integer
value.
Example:
void main()
or
int main()
6. Sub Programs
User-defined functions are called in this section of the program. The control of the program is shifted to the
called function whenever they are called from the main or outside the main() function. These are specified
as per the requirements of the programmer.
Example:
int sum(int x, int y)
{
return x+y;
}
Structure of C Program with example
Example: Below C program to find the sum of 2 numbers:
C

// Documentation
/**
* file: sum.c
* author: you
* description: program to find sum.
*/

// Link
#include <stdio.h>

// Definition
#define X 20

// Global Declaration
int sum(int y);

// Main() Function
int main(void)
{
int y = 55;
printf("Sum: %d", sum(y));
return 0;
}

// Subprogram
int sum(int y)
{
return y + X;
}

Output
Sum: 75
Explanation of the above Program
Below is the explanation of the above program. With a description explaining the program’s meaning and
use.
Sections Description

/**
* file: sum.c
* author: you
It is the comment section and is part of the description section of the
* description: program to
code.
find
sum.
*/

Header file which is used for standard input-output. This is the preprocessor
#include<stdio.h> section.

#define X 20 This is the definition section. It allows the use of constant X in the code.

This is the Global declaration section includes the function declaration


int sum(int y) that can be used anywhere in the program.

int main() main() is the first function that is executed in the C program.
Sections Description

{…} These curly braces mark the beginning and end of the main function.

printf(“Sum: %d”, sum(y)); printf() function is used to print the sum on the screen.

We have used int as the return type so we have to return 0


which states that the given program is free from the error and it can be exited
return 0; successfully.

int sum(int y)
{ This is the subprogram section. It includes the user-defined functions
return y + X; that are called in the main() function.
}

Steps involved in the Compilation and execution of a C program:


● Program Creation
● Compilation of the program
● Execution of the program
● The output of the program

Note: If the compiler performs tail call optimization, then Auxiliary Space for recursive
approach can be reduced to O(1).

Bat works by repeatedly swapping the adjacent elements if they are in the wrong order.
This algorithm is not suitable for large data sets as its average and worst-case time
complexity is quite high.
Bubble Sort Algorithm
In this algorithm,
• traverse from left and compare adjacent elements and the higher one is placed at right
side.
• In this way, the largest element is moved to the rightmost end at first.
• This process is then continued to find the second largest and place it and so on until
the data is sorted.
elements at their correct positions
• Total no. of passes: n-1
• Total no. of comparisons: n*(n-1)/2
Implementation of Bubble Sort
Below is the implementation of the bubble sort. It can be optimized by stopping the algorithm
if the inner loop didn’t cause any swap.

• C
• Java
• Python3
• C#
• Javascript
• PHP

You might also like