0% found this document useful (0 votes)
29 views200 pages

Unit 1

Uploaded by

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

Unit 1

Uploaded by

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

Contents

• Unit-1
– History of Computers
– Basic organization of a Computer: ALU, Input-Output units,
memory, Program Counter.
– Introduction to Programming Languages
– Basics of a Computer Program
• Algorithms
• Flowcharts
• Pseudo code
– Introduction to Compilation and Execution
– Primitive Data Types
– Variables and Constants
– Basic input and Output
– Operators
– Type conversion and Casting
Contents
• Unit-1 contd..

– Problem solving techniques


• Algorithmic approach
• Characteristics of Algorithm
– Problem solving strategies
• Top-down approach
• Bottom-up Approach
– Time-space complexities of algorithms
Introduction
• Computer
– A computer can be defined as an electronic device
that is designed to accept data, perform the
required mathematical and logical operations at
high speed and output the result.
Data Process Information

• For ex:
– date of birth of a student ---- data
– Process this data ---- subtract it from the present date
– Information ---- age of the student
– Computers solve problems quickly and accurately.
Introduction
Computer
System

Computer Computer
Hardware Software

System Application
Software Software

Computer
Operating Utility
BIOS and Translators
System Software
Device Drivers

Compilers Interpreter Linker Loader


Contents
• Unit-1
– History of Computers
– Basic organization of a Computer: ALU, Input-Output units,
memory, Program Counter.
– Introduction to Programming Languages
– Basics of a Computer Program
• Algorithms
• Flowcharts
• Pseudo code
– Introduction to Compilation and Execution
– Primitive Data Types
– Variables and Constants
– Basic input and Output
– Operators
– Type conversion and Casting
History of Computers

• The history of computer development is often


discussed in terms of different generation of
computers
– First generation computers
– Second generation computers
– Third generation computers
– Fourth generation computers
– Fifth generation computers
History of Computers
• First generation computers
– Uses vacuum tubes technology for calculation as well as for
storage purposes.
– Ex: ENIAC, EVAC, EDSAC, UNIVAC.
– Advantages:
• Fastest computing devices of their time
• Able to execute complex mathematical problems in an efficient manner.
– Disadvantages:
• Not very easy to program being machine dependent
• Not flexible in running different types of applications designed for
special purposes
• The use of vacuum tube technology made these computers very large
and bulky and also required to be placed in cool places
• They could execute only one program at a time, were not very
productive
• The generate huge amount of heat and hence were prone to hardware
faults
History of Computers
• First generation computers
History of Computers
• Second generation computers
– Uses Transistors in place of vacuum tubes in building the basic logic
circuits.
– A transistor is a semi conductor device that is used to increase the
power of the incoming signals by preserving the shape of the original
signal.
– PDP-8, IBM 1401 and IBMN 7090.
– Advantages:
• Fastest computing devices of their time.
• Easy to program because of the use of assembly language.
• Small and light weight computing devices.
• Required very less power in carrying out operations.
– Disadvantages:
• Input and Output media for these computers were not improved to a
considerable extent.
• Required to be placed in air-conditioned places
• Very expensive and beyond the reach of home users
• Being special-purpose computers they could execute only specific applications
History of Computers
• Second generation computers
History of Computers
• Third generation computers
– The major characteristics feature of third generation computer systems
was the use of Integrated Circuits (ICs).
– ICs are the circuits that combine various electronics components, such as
transistors, resistors, capacitors, etc, onto a single small silicon chip.
– NCR 395, B6500, IBM 370, PDP11 and CDC 7600.
– Advantages:
• Computational time for these computers was usually in nanoseconds hence were
the fastest computing devices.
• Easily transportable because of their small size.
• They used high-level languages which is machine independent hence very easy to
use.
• Easily installed and required less space.
• Being able to execute any type of application these were considered as general-
purpose computers.
– Disadvantages:
• Very less storage capacity.
• Degraded performance while executing complex computations because of the
small storage capacity.
History of Computers
• Third generation computers
History of Computers
• Fourth generation computers
– The progress in LSI and VLSI technologies led to the
development of microprocessor, which became the
major characteristic feature of fourth generation
computers.
– The LSI and VLSI technology allowed thousands of
transistors to be fitted onto one small silicon chip.
– A microprocessor incorporates various components
of a computer– such as CPU, memory and
Input/Output (I/O) controls – onto a single chip.
– Popular later microprocessors include Intel 386, Intel
486 and Pentium.
– IBM PC, IBM PC/AT, Apple and CRAY-1.
History of Computers
• Fourth generation computers
History of Computers
• Fourth generation computers
– Advantages:
• LSI and VLSI technologies made them small, cheap, compact and
powerful
• High storage capacity
• Highly reliable and required very less maintenance
• Provided a user-friendly environment with the development of
GUIs and interactive I/O devices.
• Programs written on these computers were highly portable
because of the use of high-level languages.
• Very versatile and suitable for every type of applications.
• Required very less power to operate.
– Disadvantages:
• The soldering of LSI and VLSI chips on the wiring board was
complicated.
• Still dependent on the instructions given by the programmer.
History of Computers
• Fifth generation computers
– Fifth generation computers are based on the Ultra Large Scale
Integration (ULSI) technology that allows almost ten million
electronic components to be fabricated on one small chip.
– Advantages:
• Faster, cheaper and most efficient computers till date.
• They are able to execute a large number of applications at the same
time and that too at a very high speed.
• The use of ULSI technology helps in decreasing the size of these
computers to a large extent.
• Very comfortable to use because of the several additional multimedia
features.
• Versatile for communications and resource sharing.
– Disadvantages:
• They are not provided with an intelligent program that could guide
them in performing different operations.
History of Computers

Sl.No. Generation Period Components


1 First 1946-1959 Vacuum tube based
2 Second 1959-1965 Transistor based
3 Third 1965-1971 Integrated Circuit (IC) based
4 Fourth 1971-1980 VLSI microprocessor based
5 Fifth 1980 onwards ULSI technology
Contents
• Unit-1
– History of Computers
– Basic organization of a Computer: ALU, Input-Output units,
memory, Program Counter.
– Introduction to Programming Languages
– Basics of a Computer Program
• Algorithms
• Flowcharts
• Pseudo code
– Introduction to Compilation and Execution
– Primitive Data Types
– Variables and Constants
– Basic input and Output
– Operators
– Type conversion and Casting
Basic organization of a Computer: ALU, Input-Output units,
memory, Program Counter
• Basic organization of a computer
Basic organization of a Computer: ALU, Input-Output units,
memory, Program Counter
• Basic organization of a computer
– Input devices
• They are used for accepting the data on which the operations are to be
performed.
• Examples: keyboard, mouse and track ball
– Processor
• Also known as CPU, it is used perform the calculations and information
processing on the data that is entered through the input device.
– Output devices
• They are used for providing the output of a program that is obtained after
performing the operations specified in a program.
• Examples: monitor and printer.
– Memory
• It is used for storing the input data as well as the output of a program that is
obtained after performing the operations specified in a program. Memory can
be primary memory as well as secondary memory.
• Primary memory includes Random Access Memory (RAM) and secondary
memory includes hard disks and floppy disks.
Basic organization of a Computer: ALU, Input-Output units,
memory, Program Counter

• Basic organization of a computer


– Input devices
• They are electromechanical devices that are used to
provide data to a computer for storing and further
processing.
• Input devices may belong to one of the following categories
– Keyboard
– Mouse
– Scanning Device
Basic organization of a Computer: ALU, Input-Output units,
memory, Program Counter
• Input device
– Keyboard:
• Keyboard is used to type data and text and execute
commands.
• It consists of following groups of keys
– Alphanumeric keys: include the number keys and alphabet keys
arranged in QWERTY layout
– Function keys: help perform specific tasks, such as searching a file
or refreshing a web page.
– Central keys: include arrow keys ( for moving cursor) and modifier
keys such as SHIFT, ALT and CTRL (for modifying the input);
– Numeric keys: looks like a calculator’s keyboard with its 10 digits
and mathematical operators.
– Special Purpose keys: it help perform a certain kind of operation,
like exiting a program (Escape) or deleting some characters
(Delete) in a document, etc.
Basic organization of a Computer: ALU, Input-Output units,
memory, Program Counter
• Input device
– Keyboard:
Basic organization of a Computer: ALU, Input-Output units,
memory, Program Counter

• Input device
– Mouse:
• Mouse is small hand-held pointing device that basically
controls the two-dimensional movement of the cursor on
the displayed screen.
• It is an important part of the Graphical User Interface
(GUI) based Operating Systems(OS) as it helps in selecting
a portion of the screen and copying and pasting the text.
• The mouse, on moving, also moves the pointer appearing
on the display device.
Basic organization of a Computer: ALU, Input-Output units,
memory, Program Counter

• Input device
– Mouse:
Basic organization of a Computer: ALU, Input-Output units,
memory, Program Counter
• Input device
– Scanning Device:
• Scanning devices are the input devices that can electronically
capture text and images, and convert them into computer
readable form.
• Following types of scanners that can be used to produce
digitized images:
– Flatted scanner: it contains a scanner head that moves across a page
from top to bottom to read the page and converts the image or text
available on the page in digital form. The flatbed scanner is used to scan
graphics, oversized documents and pages from books.
– Drum scanner: a fixed type of scanner head is used and the image to be
scanned is moved across the head. The drum scanners are used for
scanning prepress materials.
– Slide scanner: it can scan photographic slides directly to produce files
understandable by the computer.
– Handheld scanner: it is moved by the end user across the page to be
scanned. This type of scanner is inexpensive and small in size.
Basic organization of a Computer: ALU, Input-Output units,
memory, Program Counter

• Input device
– Scanning Device:
Basic organization of a Computer: ALU, Input-Output units,
memory, Program Counter

• Basic organization of a computer


– Processor
• The CPU consists of Control Unit (CU) and ALU.
• Cu stores the instruction set, which specifies the operations
to be performed by the computer.
• CU transfers the data and the instructions to the ALU for an
arithmetic operation.
• ALU performs arithmetical or logical operations on the data
received.
• The CPU registers store the data to be processed by the
CPU and the Processed data also.
Basic organization of a Computer: ALU, Input-Output units,
memory, Program Counter
• Basic organization of a computer
– Output devices
• Display Monitors:
– A monitor produces visual displays generated by the computer.
– A monitor is connected to the video card placed in the
expansion slot of the motherboard.
– The monitors can be classified as
» cathode ray tube (CRT) monitors :
• these are large, occupy more space in the computer.
» liquid crystal display (LCD) monitors:
• these are thin, light weighted and occupy lesser space.
Both monitors are available as monochrome, gray scale and
color models.
Basic organization of a Computer: ALU, Input-Output units,
memory, Program Counter

• Basic organization of a computer


– Output devices
• Display Monitors:
– A monitor can be characterized by its monitor size and
resolution.
– The monitor size is the length of the screen that is measured
diagonally.
– The resolution of the screen is expressed as the number of
picture elements or pixels of the screen.
– The resolution of the monitor is also called the dot pitch.
– The monitor with a higher resolution produces a clearer image.
Basic organization of a Computer: ALU, Input-Output units,
memory, Program Counter

• Basic organization of a computer


– Output devices
• Display Monitors:
Basic organization of a Computer: ALU, Input-Output units,
memory, Program Counter
• Basic organization of a computer
– Output devices
• printer:
– It transfers the text displayed on the screen, onto the paper sheets that can
be used by the end user.
– Printers can be classified based on the technology they use to print the text
and images.
» Dot matrix printers:
• Dot matrix printers are impact printers that use perforated sheet to
print the text.
• These are used to produce multiple copies of a print out.
» Inkjet printers:
• These are slower than dot matrix printers and are used to generate
high quality photographic prints
» Laser Printers:
• It may or may not be connected to a computer, to generate an
output.
• These printers consists of microprocessor, ROM and RAM, which
can be used to store textual information.
Basic organization of a Computer: ALU, Input-Output units,
memory, Program Counter
• Basic organization of a computer
– Output devices
• Voice Output Systems:
– These systems record the simple messages in human speech from
and then combine all these simple messages to form a single
message.
– The voice response system is of two types- one uses a
reproduction of human voice and other sounds, and the other
ises speech synthesis.
– The basic application of a voice output system is in Interactive
Voice Response (IVR) systems, which are used by the customer
care or customer support departments of an organization, such as
telecommunication companies, etc.
Basic organization of a Computer: ALU, Input-Output units,
memory, Program Counter
• Basic organization of a computer
– Output devices
• Projectors
– It is a device that is connected to a computer or a video device
for projecting an image from the computer or video device onto
the big white screen.
– The images projected by a projector are larger in size as
compared to the original images.
– A projector consists of an optic system, a light source and
displays, which contain the original images. Projectors were
initially used for showing films but now they are used on a large
scale for displaying presentations in business organizations and
for viewing movies at home.
Basic organization of a Computer: ALU, Input-Output units,
memory, Program Counter
• Basic organization of a computer
– Output devices
• Projectors
Basic organization of a Computer: ALU, Input-Output units,
memory, Program Counter

• Basic organization of a computer


– Memory
• The memory unit of a computer is used to store data,
instructions for processing data, intermediate results of
processing and the final processed information.
• The memory units of a computer are classified as
– primary memory
– secondary memory
– Internal process memory
» This memory is placed either the CPU or near the CPU.
Basic organization of a Computer: ALU, Input-Output units,
memory, Program Counter

• Basic organization of a computer


– Memory
Basic organization of a Computer: ALU, Input-Output units,
memory, Program Counter

• Basic organization of a computer


– Memory
• Primary memory:
– It is available in the computer as a built-in unit of the computer.
– The primary memory is represented as a set of locations with each
location occupying 8 bits.
– Each bit in the memory is identified by a unique address.
– The data is stored in the machine-understandable binary form in
these memory locations.
– The commonly used memories are
» ROM
» RAM
» Cache memory
Basic organization of a Computer: ALU, Input-Output units,
memory, Program Counter

• Basic organization of a computer


– Memory
• Primary memory:
– ROM
» It represents Read Only Memory that stores data and
instructions, even when the computer is turned off.
» It is the permanent memory of the computer where the
contents cannot be modified by an end user
» ROM is a chip that is inserted into the motherboard.
» It is generally used to store the Basic Input/Output system
(BIOS), which performs the Power On Self Test (POST).
Basic organization of a Computer: ALU, Input-Output units,
memory, Program Counter

• Basic organization of a computer


– Memory
• Primary memory:
– RAM
» It is the read/write memory unit in which the information is
retained only as long as there is a regular power supply.
» When power supply is interrupted or switched off, the
information stored in the RAM is lost. RAM is volatile
memory that temporarily stores data and applications as
long as they are in use.
» When the use of data or the application is over, the content
in RAM is erased.
Basic organization of a Computer: ALU, Input-Output units,
memory, Program Counter

• Basic organization of a computer


– Memory
• Primary memory:
– Cache Memory
» Cache memory is used to store the data and the related
application that was last processed by the CPU.
» When the processor performs processing, it first searches
the cache memory and then the RAM, for an instruction.
Basic organization of a Computer: ALU, Input-Output units,
memory, Program Counter

• Basic organization of a computer


– Memory
• Secondary memory:
– It represents the external storage devices that are connected
to the computer. They provide a non-volatile memory source
used to store information that is not in use currently.
– A storage device is either located in the CPU causing of the
computer or is connected externally to the computer.
– The secondary storage can be classified as:
» Magnetic storage device
» Optical storage device
» Magneto-optical storage device
Basic organization of a Computer: ALU, Input-Output units,
memory, Program Counter
• Basic organization of a computer
– Memory
• Secondary memory:
– Magnetic storage device
» It store information that can be read, erased and rewritten a number of
times
» Ex: Floppy disk, hard disk and magnetic tapes.
– Optical storage device
» It use laser beams to read the stored data.
» Ex: CD-ROM, rewritable compact disk ( CD-RW ), digital video disks with
read only memory ( DVD-Rom ), etc.
– Magneto-optical storage device
» It is used to store large information such as large programs, files and
back-up data.
» The end user can modify the information stored in magneto-optical
storage devices multiple times.
» Higher storage capacity as they use laser beams and magnets for
reading and writing data to the device.
» Ex: Sony miniDisc.
Contents
• Unit-1
– History of Computers
– Basic organization of a Computer: ALU, Input-Output units,
memory, Program Counter.
– Introduction to Programming Languages
– Basics of a Computer Program
• Algorithms
• Flowcharts
• Pseudo code
– Introduction to Compilation and Execution
– Primitive Data Types
– Variables and Constants
– Basic input and Output
– Operators
– Type conversion and Casting
Introduction
• Programming Languages:
– A programming language is a language specifically
designed to express computations that can be
performed by the computer.
– Programming languages are used to create programs
that control the behavior of a system, to express
algorithms, or as a mode of human-computer
communication.
– it have a vocabulary of syntax and semantics for
instructing a computer to perform specific tasks.
Introduction
• Programming Languages:
– High-level language
• Are easy for humans to read and understand.
– Machine language
• The computer understands the machine language that
consists of numbers only.
• Each type of CPU has its own unique machine language.
– Assembly language
• Assembly languages are similar to machine languages, but
they are much easier to program because they allow a
programmer to substitute names for numbers.
Introduction
• Programming Languages:
– Irrespective of what language the programmer uses,
the program written using any programming
language has to be converted into machine language
so that the computer can understand it.
– The question of which language on which the
program has to be the following factors:
• The type of computer on which the program has to be
executed
• The type of program
• The expertise of the programmer
Introduction
• Programming Languages:
– For example:
• FORTRAN is a particularly good language for processing
numerical data, but it does not lend itself very well to
organizing large programs.
• Pascal can be used for writing well-structured and
readable programs, but it is not as flexible as the C
programming language.
• C++ goes one step ahead of C by incorporating powerful
object-oriented features, but it is complex and difficult to
learn.
Contents
• Unit-1
– History of Computers
– Basic organization of a Computer: ALU, Input-Output units,
memory, Program Counter.
– Introduction to Programming Languages
– Basics of a Computer Program
• Algorithms
• Flowcharts
• Pseudo code
– Introduction to Compilation and Execution
– Primitive Data Types
– Variables and Constants
– Basic input and Output
– Operators
– Type conversion and Casting
Algorithms

• Definition:
– An algorithm is a finite set of steps defining the solution
of a particular problem.
– It is expected that one could translate each pseudo-code
statement or a small number of lines of actual code,
easily and mechanically.
– An efficient algorithm is one which is capable of giving
the solution to the problem by using minimum resources
of the system such as memory and processor’s time.
– Algorithm is a language independent, well structured
and detailed.
– It will enable the programmer to translate onto a
computer program using any high-level language.
Algorithms

• Features :
– Proper understanding of the problem
– Use of procedures/functions to emphasize
modularity
– Choice of variable names
– Documentation of the program
Algorithms

• Features :
– Proper understanding of the problem
• For designing an efficient algorithm, the expectations from
the algorithm should be clearly defined so that the person
developing the algorithm can understand the expectations
from it.
– Use of procedures/ functions to emphasize modularity
• To assist the development, implementation and readability of
the program, it is usually helpful to modularize the program.
• Independent functions perform specific and well defined
tasks.
• The program that can be implemented as calls to the various
procedures that will be needed in the final implementations.
Algorithms

• Features :
– Choice of variable names
• Proper variable names and constant names can make the program
more meaningful and easier to understand.
• It make the program more self documenting.
• For Ex: variable ‘day’ is used for the day of the weeks, instead of the
variable a or something else.
– Documentation of the program
• Brief information about the segment of the code can be included in
the program to facilitate debugging and providing information.
• A related part of the documentation is the information that the
programmer presents to the user during the execution of the
program.
• Since, the program is often to be used by persons who are unfamiliar
with the working and input requirements of the program, proper
documentation must be provided.
• The program must specify, what responses are required from the
user.
Algorithms

• Criteria :
– Input:
• There should be zero or more values which are to be supplied.
– Ouput:
• At least one result is to be produced.
– Definiteness:
• Each step must be clear and unambiguous
– Finiteness:
• If we trace the steps of an algorithm, then for all cases, the
algorithm must terminate after a finite number of steps.
– Effectiveness:
• Each step must be sufficiently basic that a person using only
paper and pencil can in principle carry it out.
• Not only each step is definite, it must also be feasible.
Algorithm

• Advantages:
– It is step by step solution to a given problem which is very easier to
understand.
– It has got a definite procedure.
– It is easy to first develop an algorithm, then convert it into a flow
chart and then into a computer program.
– It is easy to debug as every step has got its own logical sequence.
– It is independent of programming languages.
• Disadvantages:
– It is time consuming. (First we have to write algorithm then, convert
it into flowchart and then computer program).
– Algorithm lacks visual representation hence understanding the logic
becomes difficult.
Algorithms

• Examples :
– Sum of two numbers
1. Start
2. Read two numbers a and b
3. Calculate the sum of a and b and store it in sum
4. Display the value of sum
5. Stop.
Algorithms

• Examples :
– Average of a set of data values
1. Start
2. Set the sum of the data values and the count to zero
3. As long as the data values exist, add the next data
value to the sum and add 1 to the count
4. To complete the average, divide the sum be the count.
5. Display the average.
6. Stop
Algorithms

• Examples :
– Factorial of a given number
1. Start
2. Read the number n
3. [Initialize]
i ← 1, fact ← 1
4. Repeat steps 4 through 6 until i = n
5. fact ← fact * i
6. i ← i + 1
7. Print fact
8. Stop
Algorithms

• Examples :
– Whether the given number is prime or not
1. Start
2. Read the number n
3. [Initialize]
i ← 2, flag ← 1
4. Repeat steps 4 through 6 until i < n or flag = 0
5. rem ← num mod i
6. if rem =0 then
flag ← 0
else
i← i+1
7. if flag = 0 then
print number is not prime
Else
print number is prime
8. Stop
Flowcharts

• The next step after the algorithm development is the


flowcharting.
• Flowcharts are used in programming to diagram the path in
which information is processed through a computer to
obtain the desired results.
• Flowchart is a graphical representation of an algorithm.
• It makes use of symbols which are connected among them
to indicate the flow of information and processing.
• It will show the general outline of how to solve a problem or
perform a task.
• It is prepared for better understanding of the algorithm.
Flowcharts

• Basic Symbols used in flowchart design:

Start / Stop

Question, Decision
(Use in Branching)

Input / Output

Lines or arrows represent


the direction of flow of control
Flowcharts

• Basic Symbols used in flowchart design:

Connector (connect one part


of the flowchart to another)

Process, Instruction

Comments, Explanations,
Definitions
Flowcharts

• Additional Symbols Related to more advance programming:

Preparation (may be used


with “ do Loops”)

Refers to separate flowchart


Flowchart

• Advantages:
– It clarifies the program logic
– Before coding begins, the flowchart assists the
programmer in determining the type of logic control
to be used in a program.
– The flowchart gives pictorial representation.
– Serves as documentation.
– Serves as guide for program writing
– Ensure that all possible conditions are accounted for
– Help to detect deficiencies in the problem statement.
Flowchart

• Disadvantages:
– When the program logic is complex, the flowchart
quickly becomes complex and clumsy and lacks the
clarity of decision table.
– It alternations and modifications are required the
flowchart may require redrawing completely.
– As the flow chart symbols cannot be typed
reproduction of flowcharts often a problem.
– It is sometimes difficult for a business person (or)
user to understand the logic depicted in a flowchart.
Flowcharts Examples

• Adding of two numbers

Start

Read a,b

Sum = a+b

Print sum

stop
Flowcharts Examples

• largest of two numbers

Start

Read a,b

Is
a>b No

Yes
Print a Print b

stop
comparison between Algorithm and Flowchart

Algorithm Flowchart
An algorithm is a finite set of step by step Flowchart is a pictorial (or) symbolic
instructions that solve a problem representation of an algorithm
Algorithm gives verbal which is almost Gives pictorial representation
similar to English language
Suitable for large and modular programs Suitable for small programs
Easier to understand To understand flowcharts one has to familiar
with symbols
Drawing tools are not required Drawing tools are required
Algorithm can be typed, so reproduction is They cannot be typed, so reproduction is a
easy problem
It is independent of programming languages We have to use predefined standard
symbols only.
Pseudo codes

• Pseudocode
– Like step-form, pseudo-code is a written statement of
an algorithm using a restricted and well-defined
vocabulary.
– It is similar to a 3GL, and for many programmers and
program designers it is the preferred way to state
algorithms and program specifications.
– There is no standard for pseudo-code, it is generally
quite easy to read and use.
– For ex:
dowhile kettle_empty
Add_Water_To_Kettle
end dowhile
• As can be seen, it is a precise statement of a while loop.
Contents
• Unit-1
– History of Computers
– Basic organization of a Computer: ALU, Input-Output units,
memory, Program Counter.
– Introduction to Programming Languages
– Basics of a Computer Program
• Algorithms
• Flowcharts
• Pseudo code
– Introduction to Compilation and Execution
– Primitive Data Types
– Variables and Constants
– Basic input and Output
– Operators
– Type conversion and Casting
Introduction to Compilation and Execution

• C is a compiled language. So once a C program is written, you


must run it through a C compiler that can create an executable file
to be run by the computer.
• A running a C program begins with one or more program source
files, and ends with an executable file, which can be run a
computer.
• The source file usually contains ASCII characters and can be
produced with a text editor, such as windows notepad, or in an
Integrated Design Environment.
• The source file is then processed by a special program called a
compiler.
• The compiler translates the source code into an object code. The
object code contains the machine instructions for the CPU, and
calls to the operating system API (Application Programming
Interface).
Introduction to Compilation and Execution

• Even the object file is not an executable file. The


object file is processed with another special
program called linker. The output of the linker is
an executable or runnable file.
Introduction to Compilation and Execution

• In C language programs, there are two kinds of


source files.
• In addition to the main (.c) source file, which
contains executable statements there are also
header (.h) source files.
• All input and output in C programs is done
through library functions, every C program
therefore uses standard header files.
• Every C program therefore uses standard header
files.
Introduction to Compilation and Execution

• The compilation process is done in two steps.


1. The preprocessor program reads the source file as
text, and produces another text file as output.
Source code lines which begin with the # symbol
are actually not written in C but in the preprocessor
language. The output of the preprocessor is a text
file which does not contain any preprocessor
statements. This file is ready to be processed by the
compiler. The linker combines the object file with
library routines to produce the final executable file.
Introduction to Compilation and Execution
Introduction to Compilation and Execution

• The compilation process is done in two steps.


2. In modular programming the source code is divided
into two or more source files. All these source files
are compiled separately thereby producing multiple
object files. These object files are combined by the
linker to produce an executable file.
Structure of C Program
Structure of C Program
• A C Program is composed of preprocessor
commands, a global declaration section, and one
or more functions.
– Preprocessor directives
• It contain special instructions that indicate how to prepare
the program for compilation.
• One important and commonly used preprocessor is “include”,
which tells the compiler that to execute the program, some
information is needed from the specified header file.
– Global declarations
• Scope of these variables or functions is valid through out the
program
– Functions
Structure of C Program
• Functions:
– C Program contains one or more functions.
– It is defined as a group of C statements that are executed
together. These statements are written in a logical
sequence to perform a specific task.
– The main() function is the most important function and is a
part of every C program. The execution of a C program
begins at this function.
– All functions are divided into two parts
• The declaration section
– Is used to declare data that will be used in the function.
– Data declared within function are known as local declaration as that data
will be visible only within that function.
• Statement section
– It contains the code that manipulates the data to perform a specified task.
C Tokens

• Tokens are basic building blocks in C language.


• Token is a smallest individual unit in a C program.
Program is constructed using a combination of
these tokens.
C Tokens
Tokens in C

Keywords

Variables

Constants

Strings

Special
Characters

Operators
Keywords
• C has set of reserved words often known as
keywords that cannot be used as an identifier.
• All keywords are basically a sequence of
characters that have a fixed meaning.
• All keywords must be written in lowercase
letters.
• Keywords in C language are:
– Auto, break, case, char, continue, double, else, float,
for, goto, int, long, while, do, static, union, void, if,
enum, return, struct, typedef,…..etc
Identifiers

• Identifiers help us to identify data and other


objects in the program.
• Identifiers are basically the names given to
program elements such as variables, arrays and
functions.
• Identifiers may consist of sequence of letters,
numerals, or underscore.
Identifiers
• Rules for forming identifier Names:
– Identifiers cannot include any special characters (like
#, $, ?) or punctuation marks except the underscore
’_’.
– They cannot be two successive underscores.
– Keywords cannot be used as identifiers.
– The case of alphabetic characters that form the
identifier name is significant.
Ex: first is different from First and FIRST.
– Identifiers must begin with a letter or an underscore.
– Identifiers can be of any reasonable length.
Identifiers
• Good identifiers are descriptive but short.
• C allows identifiers to be up to 63 characters long. If a
name is longer than 63 characters, then only the first
31 characters are used.
• If the identifier is a little long then you may use an
underscore to separate the parts of the name or you
may use capital letters for each part.
• Examples of valid identifiers:
 roll_number, marks, names, emp_number,basic_pay, HRA,
DA, dept_code, RollNo….etc.
• Examples of invalid identifiers:
 23_student, #marks, @name, #emp_number, basic.pay, -
NBA, (DA), &dept_code, auto.
Contents
• Unit-1
– History of Computers
– Basic organization of a Computer: ALU, Input-Output units,
memory, Program Counter.
– Introduction to Programming Languages
– Basics of a Computer Program
• Algorithms
• Flowcharts
• Pseudo code
– Introduction to Compilation and Execution
– Primitive Data Types
– Variables and Constants
– Basic input and Output
– Operators
– Type conversion and Casting
Basic Data Types and Sizes
Data type Keyword Size in Range Use
used bytes
Character Char 1 -128 to 127 To store characters
Integer Int 2 -32768 to 32767 To store integer
numbers
Floating point Float 4 3.4E-38 to 3.4E+38 To store floating point
numbers
Double double 8 1.7E-308 to 1.7E+308 To store big floating
point numbers
Valueless Void 0 Valueless ----

Range equation is -2n-1 to 2n-1-1 where n is data type size in no of bits

For Ex: for char, size = 1 byte=8 bits


Range= -27 to 27-1 i.e. -128 to 127
Basic Data Types and Sizes
Data type Size in bytes Range
Char 1 -128 to 127
unsigned char 1 0 to 255
signed char 1 -128 to 127
Int 2 -32768 to 32767
unsigned int 2 0 to 65535
signed int 2 -32768 to 32767
short int 2 -32768 to 32767
unsigned short int 2 0 to 65535
signed short int 2 -32768 to 32767
long int 4 -2147483648 to 2147483648
unsigned long int 4 0 to 4294967295
signed long int 4 -2147483648 to 2147483648
float 4 3.4E-38 to 3.4E+38
double 8 1.7E-308 to 1.7E+308
long double 10 3.4E-4932 to 1.1E+4932
Contents
• Unit-1
– History of Computers
– Basic organization of a Computer: ALU, Input-Output units,
memory, Program Counter.
– Introduction to Programming Languages
– Basics of a Computer Program
• Algorithms
• Flowcharts
• Pseudo code
– Introduction to Compilation and Execution
– Primitive Data Types
– Variables and Constants
– Basic input and Output
– Operators
– Type conversion and Casting
Constants

• Constants are identifiers whose values do not


change.
• It is a explicit data value specified by the
programmer.
• The value of the constant is known to the
compiler at the compile time.
Constants

Constants in
a c Program

Floating Character
Integer type String type
point type type
Constants
Integer constants

• It consists of a sequence of digits.


1, 34, 567,…etc. Integer type
• long integers is declared by ‘l’
1234567l long integer
• unsigned int literal is written by ‘U’ or ‘u’
1234U unsigned int
1234ul unsigned long int
• While writing integer constants, embedded spaces, commas,
and non-digit characters are not allowed.
Invalid Integer constants: 123 456
12,34,567
$123
Constants
Integer constants

• Integer literals can be expressed in decimal, octal or


hexadecimal notation.
Octal integers:
– Octal integers consists of set of digits, 0 through 7.
– Integer constants are preceded by 0 are octal integers
Ex: 012, 01234
Hexadecimal Integers:
– Hexadecimal integers contain digits from 0-9 and letters A
through F.
– Integer constants are preceded by 0x or 0X are hexadecimal
integers
Ex: 0x12, 0X12, 0XABCD, 0xA3D
Constants
Floating point constants
• It consists of an integer part, decimal point, a fractional part and
an exponent field containing e or E followed by an integer.
• It is not necessary that every floating point numbers must
contain all these parts.
Examples:
0.01, -0.23, 123.456, +0.34, 123, …etc.
• A literal like 0.07 treated as of type double by default. To make it
as float, we have to specify it using ‘f’ or ‘F’.
0.02F, 0.34f, 3.1415L (long double) // l for long int
• A Floating point number may be expressed in scientific notation.
0.5e2, 14E-2, 1.2e+3, 2.1E-3, -5.6e-2, …etc.
• These numbers represented using scientific notations are very
small or very large.
120000000=1.2E8 -0.000000025=-2.5E-8
Constants
Character constants

• A Character constant consists of a single


character enclosed in single quotes.
ex: ‘a’ , ‘A’ etc…
• All escape characters are character constants.
White Space Meaning
Character
\b Blank space
\t Horizontal tab
\v Vertical return
\r Carriage return
\f Form feed
\n New line
Constants
String constants

• A string constant is a sequence of characters


enclosed in double quotes
Ex: “a”, “f”, ….etc.
• In a string constant, characters are stored in
successive memory location.
• In C program, the compiler records the address of
the first character and appends a null character(‘\0’)
to the string to mark the end of the string.
• The length of the string is number of characters in
the string.
Ex: “hello” is 5.
Constants
Declaring Constants
• To declare a constant can be done by two ways
– precede the normal variable declaration with const keyword and
assign it a value.
ex: const float pi = 3.14;
– Using pre-processor command, define is preceded with a # symbol.
ex: #define pi 3.14159
• Some rules for defining the #define statement.
Rule 1: Constant names are written in Capital letters. It is just a
convention and not a rule.
Rule 2: No blank spaces are permitted between the # symbol and
define keyword.
Rule 3: Blank space must be used between #define and constant
name and between constant name and constant value.
Rule 4: #define is a pre-processor compiler directive and not a
statement. So, it does not end with a semi-colon.
Variables
• A Variable is defined as a meaningful name given to a data
storage location in computer memory.
• When using a variable, we actually refer to address of the
memory where the data is stored.
• C language supports two basic kinds of variables
– numeric
• These can be used to store either integer values or floating point values.
• These are associated with modifiers like short, long, signed and unsigned.
– Character
• These are single characters enclosed within single quotes.
• These characters could be any characters from the ASCII character set—
letters(‘a’, ’A’), numerals (‘2’), or special characters (‘&’).
• In C, a number that is given in single quote is not the same as a number.
2 is considered as number. Whereas, ‘2’ is considered as character not an
integer.
Variables
• Declaring Variables:
– Variables to be used in the program must be declared.
– To declare a variable, specify the data type of variable followed by
its name.
– A variable cannot be of type void.
– The data type indicates the kind of values that the variable will
store.
– Memory location is important to compiler. Whereas, the
programmers must be concerned with accessing data through
their symbolic names.
– In C, variable declaration always ends with a semicolon, for
example:
int emp_num;
float salary;
char grade;
Variables
• Declaring Variables:
– Variables can be declared at any place in the program. But
two things should be remembered in mind.
• Variables should be declared before using them.
• Variables should be declared closest to their first point of use to
make the source code easier to maintain
– C allows multiple variables of the same type to be declared in
one statement.
• Float temp1, temp2, temp3;
– In C variables are declared at three basic places:
when the variable is declared
• Inside a function parameters it is known as local variable.
• In the definition of function parameters it is known as formal
parameter.
• Outside all functions, it is known as global variable.
Variables
• Declaring Variables:
– Initializing Variables
• While declaring the variables, we can also initialize them
with some value.
For ex:
int emp_num = 7;
float salary = 2156.35;
char grade = ‘A’;
int count, flag = 1; #initializes the flag and not count.
int count = 0, flag = 1;

• when variables are declared but not initialized they usually


contain garbage values.
Contents
• Unit-1
– History of Computers
– Basic organization of a Computer: ALU, Input-Output units,
memory, Program Counter.
– Introduction to Programming Languages
– Basics of a Computer Program
• Algorithms
• Flowcharts
• Pseudo code
– Introduction to Compilation and Execution
– Primitive Data Types
– Variables and Constants
– Basic input and Output
– Operators
– Type conversion and Casting
Input / Output Statements
• There are two ways to accept the data.
– Using assignment statement
– Using functions (input/output functions)
• There are two types of I/O functions, based on the data
type.
– Formatted functions
• Input or output is formatted as per our requirement.
• Input devices such as keyboard, a disc drive or network connection
to main memory.
• Output devices such as monitor, printer, disc drive, network
connection.
– Unformatted functions
• Input/output functions work only with character data type.
• There is no need of formatting because they work only with
character data type.
Input / Output Statements

Input / Output
Functions

Formatted Unformatted
Functions Functions

getch() putch()
prinf()
getche() putche()
scanf()
getchar() putchar()
Formatted Output Statement: printf()

• The syntax of output function for outputting the


data such as printf() is as follows:
printf(“Control String”, var1, var2,..varn);
Ex: printf(“%d %d”, x, y);
• The Control String can be
% [Flag] [width] [.precision] [length modifier] type specifier
each control string begin with %
Formatted Output Statement: printf()

– Flag is an optional argument which specifies output justification


such as numerical sign, trailing zeros or octal, decimal, or
hexadecimal prefixes.

Flags Description
- Left-justify within the given field width
+ Displays the data with its numeric sign ( + or - )
# Used to provide additional specifiers like o, x, X,0, 0x, or 0X
for octal and hexadecimal values.
0 The number is left-padded with zeros instead of spaces
Formatted Output Statement: printf()
• Width: It is an optional argument which specifies the
minimum number of positions in the output. Width can
be specified through a decimal point(.) or using an
asterisk(*).
• Precision: it is an optional argument which specifies the
maximum number of characters to print.
– for integer specifiers (d, i, o, u, x, X): specify the minimum
number of digits to be written.
– For character strings: Specify the maximum number of
characters to be printed.
– For floating point numbers: Specifies the number of decimal
places to be printed.
If no precision modifier is specified, printf prints six decimal
positions.
Formatted Output Statement: printf()
• Length Modifiers:
Length Description

h When the argument is a short int or


unsigned short int
l When the argument is a long int or
unsigned long int for integer specifiers

L When the argument is a long double (used


for floating point specifiers)
Formatted Output Statement: printf()
• Type Specifiers: are used to define the type and the
interpretation of the value of the corresponding argument.
Length Description
c For Single characters
d For integer values
f For Floating point numbers
E, e Floating point numbers in exponent format
g Floating point numbers in the shorter of e format
o For octal numbers
s For a sequence of characters (string)
u For unsigned integer values
x, X For hexadecimal values
hx Displays hexadecimals in lower case
p Displays hexadecimals in upper case
n Aborts program with error
Formatted Output Statement: printf()
Simple printf example:
printf(“ C Language”);
printf function Output
printf(“\n Result: %d%c%f”, 12, ‘a’, 2.3); Result: 12a2.3
printf(“\n Result: %d %c %f”, 12, ‘a’, 2.3); Result: 12 a 2.3
printf(“\n Result: %d\t%c\t%f”, 12, ‘a’, 2.3); Result: 12 a 2.3
printf(“\n Result: %d\t %c\t6.2%f”, 12, ‘a’, 245.37154); Result: 12 a 245.37
printf(“\n Result: %5d \t %x \t %#x”, 234, 234, 234); Result: 234 EA 0xEA
printf(“\n The number is %6d”, 12); The number is 12
printf(“\n The number is %-6d”, 12); The number is 12____
//__ indicate white spaces
printf(“\n The number is %06d”, 1234); The number is 001234
printf(“\n This is \“so\” beautiful”); This is “so” beautiful
Formatted Output Statement: printf()
Examples of width specifiers:
printf function Output
printf(“\n 0.2s”, adcde); ad

printf(“\n 0.3s”, adcde); adc

char str[]=“good morning”;


printf(“\n %s”, str); Good Morning
printf(“\n %20s”, str); Good Morning
printf(“\n %-20s”, str); Good Morning
printf(“\n %20.10s”, str); Good Morni
printf(“\n %-7s”, str); Good Mo
Formatted Input Statement: scanf()
• The scanf() function takes a text stream from the keyboard,
extracts and formats data from the stream according to a format
control string and then stores the data in specified program
variables.
• The scanf function ignores any blank spaces, tabs and newlines
entered by the user.
• The syntax of input function for inputting the data such as scanf()
is as follows:
scanf(“Control String”, arg1, arg2, …);
Ex: scanf(“%d”, &x);
• The Control String can be
% [*] [width] [modifier] type
– each control string begin with %
– * is an optional argument that suppresses assignment of the input field,
i.e., it indicates that data should be read from the stream but ignored.
Formatted Input Statement: scanf()

• The Control String can be


% [*] [width] [modifier] type
– Width is an optional argument that specifies the
maximum number of characters to be read.
– Modifier is an optional argument that can be h, l, or L for
the data pointed by corresponding additional arguments.
• h short int or unsigned short int
• l long int or unsigned long int
• L long double
– Type specifies the type of data that has to be read. It also
indicates how this data is expected to be read from the
user. These are same as printf() type specifiers.
Formatted Input Statement: scanf()
Rules of scanf function:
1. The scanf function works until:
a) The maximum number of characters has been processed
b) A white space character (‘\t’, ‘\n’, ‘\r’, ’\f’…etc) is encountered, or
c) An error is detected
2. Every variable that has to be processed must have a conversion specification
associated with it.
scanf(“%d %d”, &num1, &num2, &num3); //invalid
3. There must be a variable address for each conversion specification.
scanf(“%d %d %d”, &num1, &num2); //invalid
4. An error would be generated if the format string is ended with a white space
character.
5. The data entered by the user must match the character specified in the control
string
scanf(“%d / %d”, &num1, &num2); //valid
6. Input data values must be separated by spaces.
7. Any unread data value will be considered as a part of the data input in the next
call to scanf.
8. When the field width specifier is used, it should be large enough to contain the
input data size.
Formatted Input Statement: scanf()
• Examples for scanf() function:

Example scanf function


1 int num;
float fnum;
char ch;
char str[10];
scanf(“%d %f %c %s”, &num, &fnum, &ch, str);

2 scanf(“%2d %5d”, &num1, &num2);

3 double dnum;
short int snum;
long int lnum;
scanf(“%lf %hd %ld”, &dnum, &snum, &lnum);
Programs related to Input/Output Statements
1. Find out the output of the following program
#include <stdio.h>
int main()
{
int a, b;
printf(“\n Enter two four digit numbers:”);
scanf(“%2d %2d”, &a, &b);
printf(“\n The two numbers are: %d and %d”, a, b);
return 0;
}

Ouput:
Enter two four digit numbers : 1234 5678
The two numbers are : 12 and 34

/* a accepts first two digits only and rest of the number will be assigned to b. The
value 5678 that is unread will be assigned to the first variable in the next call to the
scanf function. */
Programs related to Input/Output Statements
2. Write a program to demonstrate the use of printf statement to print values of variables of different
data types.
#include <stdio.h>
int main()
{
int num = 7;
float amt = 123.45;
char code = ‘A’;
double pi = 3.1415926536;
long int population_of_india = 10000000000;
char msg[] = “Hi”;
printf(“\n NUM=%d \n AMT= %f \n CODE= %c \n PI = %e \n POPULATION INDIA = %ld \n
MESSAGE = %s”, num, amt, code, pi, population_of-india, msg);
return 0;
}

Ouput:
NUM = 7
AMT = 123.450000
CODE = A
PI = 3.141590e+00
POPULATION OF INDIA = 10000000000
MESSAGE = Hi
Programs related to Input/Output Statements
2. Write a program to demonstrate the printf(“\n Enter the value of code:”);
use of scanf and printf statement to scanf(“%c”, &code);
print values of variables of different printf(“\n Enter the value of pi:”);
data types.
scanf(“%e”, &pi);
#include <stdio.h>
printf(“\n Enter the value of population
int main() of india:”);
{ scanf(“%ld”, &population_of_india);
int num; printf(“\n Enter messgae:”);
float amt; scanf(“%s”, &msg);
char code;
double pi ; printf(“\n NUM=%d \n AMT= %f \n
long int population_of_india; CODE= %c \n PI = %e \n POPULATION
char msg[] ; INDIA = %ld \n MESSAGE = %s”, num,
amt, code, pi, population_of-india, msg);
printf(“\n Enter the value of num:”);
scanf(“%d”, &num); return 0;
printf(“\n Enter the value of }
amount:”);
scanf(“%f”, &amt);
Programs related to Input/Output Statements
Ouput:
Enter the value of num : 5
Enter the value of amount: 123.45
Enter the value of code: c
Enter the value of pi : 3.14159
Enter the value of Population of India: 12345
Enter the Message: Hello

NUM = 5
AMT = 123.450000
CODE = c
PI = 3.141590e+00
POPULATION OF INDIA = 12345
Programs related to Input/Output Statements
#include <stdio.h>
void main()
{
char a;
clrscr();
printf(“Enter value of ‘A’ : “);
scanf(“%d”, &a);
printf(“A=%d”,a);
}

Ouput:
Enter the value of ‘A’ : 255
A=255
Enter the value of ‘A’ : 256
Programs related to Input/Output Statements
#include <stdio.h>
void main()
{
char nm[20];
int l;
clrscr();
printf(“Enter string“);
scanf(“%s”, nm);
l=printf(nm);
printf(“\nLength = %d”,l);
}

Ouput:
Enter string : HELLO
Length = 5
Write a program to find the addition and square of two numbers
#include <stdio.h>
void main()
{
int a, b, c;
clrscr();
printf(“Enter two values\n“);
scanf(“%d %d”, &a, &b);
c=a+b;
printf(“\n Sum = %d”, c);
c=a*a;
printf(“\n square of a is %d“, c);
}

Ouput:
Enter two values
35
Sum = 8
Square of a is 9
Write a program to swap two variables without use of third variable
#include <stdio.h>
void main()
{
int a=7, b=4;
clrscr();
printf(“\n A = %d B = %d“, a, b);
a=a+b;
b=a-b;
a=a-b;
printf(“\nAfter Swapping A = %d B = %d“, a, b);
}

Ouput:
A=7B=4
After Swapping A=4 B = 7
Write a program to calculate the area of a triangle using Hero’s formula
#include <stdio.h>
#include <conio.h>
#include <math.h>
void main()
{
float a, b, c, area, S;
clrscr();
printf(“Enter the lengths of the three sides of the triangle:”);
scanf(“%f %f %f“, &a, &b, &c);
S = (a+b+c)/2 ;
area = sqrt (S* (S-a) * (S-b) * (S-c));
printf(“\n Area = %f“, area);
return 0;
}

Ouput:
Enter the lengths of the three sides of the triangle : 12 16 20
Area = 96
Write a program to calculate the distance between two points
#include <stdio.h>
#include <conio.h>
#include <math.h>
void main()
{
int x1, x2, y1, y2;
float distance;
clrscr();
printf(“Enter the x and y coordinates of the first point :”);
scanf(“%d %d“, &x1, &y1);
printf(“Enter the x and y coordinates of the second point :”);
scanf(“%d %d“, &x2, &y2);
distance = sqrt(pow((x2-x1), 2) + pow((y2-y1), 2));
printf(“\n Distance = %f“, distance);
return 0;
}

Ouput:
Enter the x and y coordinates of the first point : 2 5
Enter the x and y coordinates of the first point : 3 7
Unformatted Functions

• C has three types of unformatted I/O functions.


– Character I / O
• For reading / writing single character.
• Functions: getchar(), putchar(), getch(), getche(), putch().
– String I /O
• For reading/writing set of characters.
• Functions: gets(), puts(), cgets(), cputs()
– File I /O
• For reading/ writing files.
• Functions: fread(), fwrite(), fscanf(), fprintf(),fgets(),
fputs(), fgetc(), fputc().
Unformatted Functions
• Character I / O
– getchar()
• This function reads a character-type data from standard input. It reads one
character at a time till the user presses the enter key.
Syntax:
variable name = getchar();
Example:
#include<stdio.h>
void main()
{
char c;
printf(“\nEnter a char :”);
c=getchar();
printf(“a=%c”, c);
}
Output:
Enter a char : g
a=g
Unformatted Functions
• Character I / O
– putchar()
• This function prints one character on the screen at a time, read
by the standard input.
Syntax:
putchar(variable name);
Example:
#include<stdio.h>
void main()
{
char c=‘C’;
putchar(c);
}
Output:
C
Unformatted Functions
• Character I / O
– getch() & getche()
• These functions read any alphanumeric character from the standard input
device and return immediately without even waiting for enter key. The
character entered is not displayed by the getch(), getche();
Syntax:
getch(); getche();
Example:
#include<stdio.h>
void main()
{
printf(“enter any two alphabetic”);
getch();
getche();
}
Output:
Enter any two alphabetic
Unformatted Functions
• Character I / O
– putch()
• This function prints any alphanumeric character from the standard input device.
Syntax:
putch(variable name);
Example:
#include<stdio.h>
void main()
{
char ch;
printf(“press any key to continue”);
ch=getch();
printf(“\n You pressed”);
putch(ch);
}
Output:
Press any key to continue
You pressed: 9
Unformatted Functions
• String I / O
– gets()
• This function is used for accepting any string through stdin(keyboard) until enter
key is pressed.
Syntax:
char str[length of string in number];
gets(str);
Example:
#include<stdio.h>
void main()
{
char ch[30];
printf(“enter the string:”);
gets(ch);
printf(“\n Entered String : %s”, ch);
}
Output:
Enter the String : Hello
Entered String : Hello
Unformatted Functions
• String I / O
– puts()
• This function prints the string or character array. It is opposite to gets().
Syntax:
char str[length of string in number];
gets(str);
puts(str);
Example:
#include<stdio.h>
void main()
{
char ch[30];
printf(“enter the string:”);
gets(ch);
printf(“\n Entered String : “);
puts(ch);
}
Output:
Enter the String : Hello
Entered String : Hello
Contents
• Unit-1
– History of Computers
– Basic organization of a Computer: ALU, Input-Output units,
memory, Program Counter.
– Introduction to Programming Languages
– Basics of a Computer Program
• Algorithms
• Flowcharts
• Pseudo code
– Introduction to Compilation and Execution
– Primitive Data Types
– Variables and Constants
– Basic input and Output
– Operators
– Type conversion and Casting
Operators
• An operator is a symbol that specifies the mathematical,
logical, or relational operation to be performed.
• C language supports different types of operator, which can
be used with variables and constants to form expressions.
• These operators can be categorized into the following major
groups:
– Arithmetic Operators
– Relational Operators
– Equality Operators
– Logical Operators
– Assignment Operators
– Comma Operator
– Unary Operators
– Ternary Operators
Operators
• Unary Operators
– Unary minus(-)
– Increment(++)
– decrement(--)
– Logical NOT(!)
– Bitwise NOT(~) or one’s compliment (~)
– Address of operator(&)
– sizeof()
• Binary Operators or Bitwise operators
– Logical AND(&&)
– Logical OR(||)
– Binary AND(&)
– Binary OR(|)
– Binary XOR(^)
– Binary Left Shift(<<)
– Binary Right Shift(>>)
• Ternary Operators
– Conditional operator (?:)
Arithmetic Operators
• Arithmetic Operators can be applied to any integer or
floating-point number.
• The addition, subtraction, multiplication, and division
operators perform the usual arithmetic operations in C
programs.
• Modulus operator (%) finds the remainder of an
integer division and this can be applied only on integer
operands and cannot be on float or double operands.
• While performing the modulus division, the sign of the
result is always the sign of the first operand.
16 % 3 =1 -16 % 3 = -1
16 % -3 = 1 -16 % -3 = -1
Arithmetic Operators
• Given
int a=9, b=3, result;
Operation Operator Syntax Comment Result

Multiply * a*b Result = a * b 27

Divide / a/b Result = a / b 3

Addition + a+b Result = a + b 12

Subtraction - a–b Result = a – b 6

Modulus % a%b Result = a % b 0


Arithmetic Operators
• Write a program to perform Arithmetic Operations (addition, subtraction, division,
multiplication and modulo division on two integer numbers).
#include<stdio.h>
#include<conio.h>
int main()
{
int num1, num2;
int add_res=0, sub_res=0, mul_res=0, idiv_res=0, modiv_res=0;
float fdiv_res=0.0;
clrscr();
printf(“Enter first number”);
scanf(“%d”, &num1);
printf(“\n Enter the second number”);
scanf(“%d”, &num2);
add_res=num1 + num2;
sub_res = num1 - num2;
mul_res = num1 * num2;
idiv_res = num1 / num2;
modiv_res = num1 % num2;
Arithmetic Operators
printf(“\n %d + %d = %d”, num1, num2, add_res);
printf(“\n %d - %d = %d”, num1, num2, sub_res);
printf(“\n %d * %d = %d”, num1, num2, mul_res);
printf(“\n %d / %d = %d (Integer Division)”, num1, num2, idiv_res);
printf(“\n %d % %d = %d (Moduluo Division)”, num1, num2, modi_res);
printf(“\n %d / %d = %.2f (Normal Division)”, num1, num2, fdiv_res);
return 0;
}
Output:
Enter the first number : 9
Enter the second number:7
9 + 7 = 16
9-7 =2
9 * 7 = 63
9 / 7 = 1 (Integer Division)
9 % 7 = 2 (Moduluo Division)
Relational Operators
• A relational operator also known as comparison
operator, is an operator that compares two
values.
• Expressions contain relational operators are
called relational expressions.
• Relational operators return true or false value,
depending on whether the conditional
relationship between the two operands holds or
not.
• Relational operators can be used to determine
the relationships between the operands.
Relational Operators
Operator Meaning Example
< Less than 3 < 5 gives 1
> Greater than 7 > 9 gives 0
<= Less than or equal to 100 <= 100 gives 1
>= Greater than equal to 50 >= 100 gives 0

• The relational operator are evaluated from left to right.


• The operands of a relational operator must evaluate to
a number.
• Characters are considered valid operands since they are
represented by numeric values in the computer system.
Ex: ‘A’ < ‘B’, where A is 65 and B is 66 then the result
would be 1 as 65 < 66.
Relational Operators
• When arithmetic expressions are used on either
side of a relational operator, then first the
arithmetic expression will be evaluated and
then the result will be compared. This is
because arithmetic operators have a higher
priority over relational operators.
• Relational operators should not be used for
comparing strings as this will result in
comparing the address of the string and not
their contents.
Relational Operators
• Write a program to show the use of relational operators.
#include<stdio.h>
main()
{
int x=10, y=20;
printf(“ \n %d < %d = %d”, x, y, x<y);
printf(“ \n %d == %d = %d”, x, y, x==y);
printf(“ \n %d != %d = %d”, x, y, x!=y);
printf(“ \n %d > %d = %d”, x, y, x>y);
printf(“ \n %d >= %d = %d”, x, y, x>=y);
printf(“ \n %d <= %d = %d”, x, y, x<=y);
return 0;
}

Output:
10 < 20 = 1
10 == 20 = 0
10 != 20 =1
10 > 20 = 0
10 >= 20 = 0
Equality Operators
• C language supports two kinds of equality
operators to compare their operands for strict
equality or inequality. They are equal to (==) and
not equal to (!=) operators.
• The equality operators have lower precedence
than the relational operators.

Operator Meaning

== returns 1 if both operands are equal, 0 otherwise.

!= returns 1 if the operands do not have the same value; 0 otherwise.


Unary Operators
• Unary Operators
– A unary operator operates on only one operand.
Syntax: operator operand
Ex: -a
– Some of the unary operators are:
• unary minus(-)
• Increment(++)
• decrement(--)
• Address of operator(&)
• sizeof()
• Logical NOT(!)
• Bitwise NOT(~) or one’s compliment (~)
Unary Operators
• Unary minus(-)
– Unary minus operator is used for indicating or
changing the algebraic sign of a value.
– Ex: int a, b =10;
a = -(b);
The result of this expression is a = -10, because variable b
has a positive value. After unary minus operator (-) on the
operand b, the value becomes -10, which indicates it as a
negative value.
Unary Operators
• Increment Operators(++) or Decrement Operators(--)
– The operator(++) adds one to its operand, where as the
operator – subtracts one from its operand.
x= x+1 => x++ or ++x
x=x-1 => x-- or --x
++x (Pre-increment) and x++ (Post-increment)
– In case of pre-increment or post-increment, there is not
change in the increment of value of a variable. The change
comes to that variable, which is assigned to this post-
increment or pre-increment variable.
Ex: x=10 x=10
y=++x y=x++
printf(%d %d”,x, y) printf(%d %d”, x,y);
Output: 11 11 11 10
Unary Operators
• sizeof and ‘&’ Operator:

– The sizeof operator gives the bytes occupied by a


variable, i.e. the size in terms of bytes required in
memory to store the value.
– The number of bytes occupied varies from variable to
variable depending upon its data types.
– The ‘&’ operator prints address of the variable in the
memory.
Unary Operators
• Program to show the use of sizeof and ‘&’ Operator:

#include<stdio.h>
void main()
{
int x=2;
float y = 2;
clrscr();
printf(“\n sizeof(x)=%d bytes”, sizeof(x));
printf(“\n sizeof(y)=%d bytes”, sizeof(y));
printf(“\n Address of x=%u and y=%u”, &x, &y);
}
Output:
sizeof(x) = 2
sizeof(y) =4
Address of x=4066 and y=25096
Unary Operators
• Logical not(!):
– It takes a single expression and negates the value of the
expression.
– It produces a zero if the expression evaluates to a non-
zero value and produces a 1 if the expression produces a
zero. i.e. provides 0 if the condition is true, otherwise 1.
A !A
0 1
1 0

– Ex: int a=10, b;


b= !a;
Output: b=0;
Unary Operators

• Bitwise not(~) or one’s compliment:


– The bitwise not or compliment is unary operator that
performs logical negation on each bit of the operand.
– Bitwise NOT operator sets the bit to 1 if it was initially
0 and sets it to 0 if it was initially 1.
– Example:
1) ~10101011 = 01010100
2) unsigned int v=0;
~v = 65535
Binary Operators
• Binary Operators or Bitwise operators
– A binary operator operates on two operands.
Syntax: operand1 operator operand2
Ex: a && b
– The following are the some of the Binary operators
• Logical AND(&&)
• Logical OR(||)
• Bitwise AND(&)
• Bitwise OR(|)
• Bitwise XOR(^)
• Left Shift(<<)
• Right Shift(>>)
Binary Operators
• Logical AND(&&)
– It evaluates two values or relational expressions. If both
the operands are true, then the whole expression
evaluates to true. If both or one of the operands is
false, then the whole expression evaluates to false.
A B A && B
0 0 0
0 1 0
1 0 0
1 1 1

– Example: int a = 10, b= 20, c=30;


(a<b) && (b>c) => false
(a<b) && (b<c) => true
Binary Operators
• Logical OR(||)
– It evaluates two values or relational expressions. If both
the operands are false, then the whole expression
evaluates to false. If both or one of the operands is
true, then the whole expression evaluates to true.
A B A || B
0 0 0
0 1 1
1 0 1
1 1 1

– Example: int a = 10, b= 20, c=30;


(a<b) || (b>c) => true
(a<b) || (b<c) => true
Binary Operators
• Bitwise AND(&)
– It performs operation on bits.
– The bit in the first operand is ANDed with the corresponding
bit in the second operand. If both bits are 1, the
corresponding bit in the result is 1 and 0 otherwise.
A B A&B
0 0 0
0 1 0
1 0 0
1 1 1

– Example: int a = 10, b= 20, c;


c= a&b;
printf(“ %d”, c);
Output: c=0
Binary Operators
• Bitwise OR(|)
– It performs operation on bits.
– The bit in the first operand is ORed with the corresponding
bit in the second operand. If one or both bits are 1, the
corresponding bit in the result is 1 and 0 otherwise
A B A|B
0 0 0
0 1 1
1 0 1
1 1 1

– Example: int a = 10, b= 20, c;


c= a|b;
printf(“ %d”, c);
Output: c = 30
Binary Operators
• Bitwise XOR(^)
– It performs operation on bits.
– The bit in the first operand is XORed with the corresponding
bit in the second operand. if one of the bits is 1, the
corresponding bit in the result is 1 and 0 otherwise.
A B A^B
0 0 0
0 1 1
1 0 1
1 1 0

– Example: int a = 10, b= 20, c;


c= a ^ b;
printf(“ %d”, c);
Output: c = 30
Binary Operators
• Shift Left (<<) and shift Right (>>):
– These operators are simple and are responsible for shifting
bits either to the left or to the right.
– Syntax:
operator op num
Ex: x << 1 , y >> 4
– If x= 0001 1101 then, x << 1 produces 0011 1010
x << 4 produces 1101 0000
x >> 4 produces 0000 0001
– Shifting once to the left multiplies the number by 2. Hence,
multiple shifts of 1 to the left, results in multiplying the
number by 2 over and over again
– Shifting once to the right divides the number by 2. Hence,
multiple shifts of 1 to the right, results in dividing the number
Write a program to use bitwise operators
#include<stdio.h>
void main() output:
{
int a=8, b=2, c;
clrscr();
c=a & b;
printf(“ a & b = %d”, c); a & b =0
c=a | b;
printf(“ a | b = %d”, c); a | b = 10
c=a ^ b;
printf(“ a ^ b = %d”, c); a ^ b = 10
c=a<<3;
printf(“ a left shift 3 = %d”, c); a left shift 3 =64
c=b >> 2;
printf(“ a right shift 2 = %d”, c); a right shift 2 =0
}
Logical Operators and Bitwise Operators
• C language supports three logical operators –
logical AND (&&), logical OR (||), and logical
NOT (!).
• Logical expressions are evaluated from left to
right.
• Bitwise operators are those operators that
perform operations at bit level. These include
bitwise AND, bitwise OR, bitwise XOR, and shift
operators.
Ternary Operator or Conditional Operator(?:)
– This operator is just like if-else statement that can be
used within expressions.
Syntax:
expr1 ? expr2 : expr3
expr1 is evaluated first, if it is true then expr2 is evaluated
and becomes the result of the expression, otherwise expr3
is evaluated and becomes the result of the expression
Example:
large = (a > b ) ? a : b
if a >b then large = a else large =b.
Hence, large is equal to either a or b but not
both.
Write a program to find the largest of three numbers
#include<stdio.h>
#include<conio.h>
int main()
{
int num1, num2, num3, large;
clrscr();
printf(“enter the three numbers”);
scanf(“%d %d %d”, &num1, &num2, &num3);
large = num1 > num2 ? (num1> num3 ? num1 : num3) :
(num2 > num3) > num2 : num3);
printf(“ \n The largest number is : %d”, large);
return 0;
}
Output:
Enter the three numbers 12 34 11
Assignment Operators

• It is responsible for assigning values to the


variables.
• Equal sign (=) is the fundamental assignment
operator.
• Assignment operator has right-to-left
associativity.
a=b=c=10; is evaluated as (a = (b = (c = 10)));
Other assignment operators
• Shorthand assignment operators of the form
variable op = expression

Operator Syntax Equivalent to Meaning Example

/= Variable/ Variable= Divides the value of a float a = 9.0


=expressio Variable/ expression variable by the value of float b = 3.0
n the expression and assigns a/=b;
the result to the variable
\= Variable\ Variable= Divides the value of a int a = 9
=expressio Variable\ expression variable by the value of int b = 3
n the expression and assigns a\=b;
the integer result to the
variable
*= Variable*= Variable= Multiplies the value of a int a = 9
expression Variable *expression variable by the value of int b = 3
the expression and assigns a*=b;
the result to the variable
Other assignment operators
Operator Syntax Equivalent to Meaning Example

+= Variable+= Variable= Adds the value of a int a = 9


expression Variable +expression variable by the value of int b = 3
the expression and assigns a+=b;
the result to the variable
-= Variable-= Variable= Subtracts the value of a int a = 9
expression Variable –expression variable by the value of int b = 3
the expression and assigns a-=b;
the result to the variable
&= Variable&= Variable= Performs the bitwise AND int a = 9
expression Variable&expression between the value of a int b = 3
variable by the value of a&=b;
the expression and assigns
the result to the variable
^= Variable^= Variable= Performs the bitwise XOR int a = 9
expression Variable*expression between the value of a int b = 3
variable by the value of a^=b;
the expression and assigns
the result to the variable
Other assignment operators
Operator Syntax Equivalent to Meaning Example

<<= Variable<<= Variable= Performs an arithmetic int a = 9


amount Variable<<amount left shift (amount times) int b = 3
on the value of a variable a<<=b;
and assigns the result
back to the variable.
>>= Variable>>= Variable= Performs an arithmetic int a = 9
amount Variable>> amount right shift (amount times) int b = 3
on the value of a variable a>>=b;
and assigns the result
back to the variable.
Comma Operators
• The comma operator in C takes two operands.
• It works by evaluating the first and discarding its
value, and then evaluates the second and returns
the value as the result of the expression.
• It evaluates in left-to-right sequence with the right
most value yielding the result of the expression.
• Among the all operators, the comma operator has
the lowest precedence.
• Ex: int a=2, b=3, x=0;
x= (++a, b+=a);
output: value of x is 6.
Write a program to calculate the area of a circle
#include<stdio.h>
#include<conio.h>
int main()
{
float radius;
double area, circumference;
clrscr();
printf(“\n Enter the radius of the circle: “);
scanf(“%f”, &radius);
area = 3.14 * radius * radius;
printf(“Area = %.2e”, area);
Circumference=2 * 3.14 * radius;
prinft(“\n circumference =%.2e”, circumference);
return 0;
}

Output:
Enter the radius of the circle: 7
Area = 15.39e+01
Write a program to print ASCII value of a character
#include<stdio.h>
#include<conio.h>
int main()
{
char ch;
clrscr();
printf(“\n Enter any character: “);
scanf(“%c”, &ch);
prinft(“\n The ASCII value of %c is: %d”, ch, ch);
return 0;
}

Output:
Enter any character: A
The ASCII value of A is: 65
Write a program to read a character in upper case and then print it
in lower case

#include<stdio.h>
#include<conio.h>
int main()
{
char ch;
clrscr();
printf(“\n Enter any character in upper case: “);
scanf(“%c”, &ch);
prinft(“\n The character in lower case is: %c”, ch+32);
return 0;
}

Output:
Enter any character in upper case: A
The ASCII value of A is: a
Write a program to print the digit at ones place of a number

#include<stdio.h>
#include<conio.h>
int main()
{
Int num, digit_at_ones_place;
clrscr();
printf(“\n Enter any number: “);
scanf(“%d”, &num);
digit_at_ones_place = num % 10;
prinft(“\n The digit at ones place of %d is %d”, num, digit_at_ones_place);
return 0;
}

Output:
Enter any number: 123
Write a program to swap two numbers using a temporary variable

#include<stdio.h>
#include<conio.h>
int main()
{
Int num1, num2, temp;
clrscr();
printf(“\n Enter the first number: “);
scanf(“%d”, &num1);
printf(“\n Enter the second number: “);
scanf(“%d”, &num2);

temp= num1;
num1=num2;
num2=temp;;
printf(“\n The first number is: %d“, num1);
Printf(“\n the second number is: %d”, num2)
return 0;
}

Output:
Enter first number: 123
Enter second number: 45
The first number is : 45
The second number is: 123
Precedence chart
Precedence Operator Name of Operator Category -ary of Associat
Level operator ivity
Level –I () Function call
(Highest) [] Array subscript
-> Indirect member access
. Direct member access
Level-II ! Logical NOT Unary Unary R->L
~ Bitwise NOT operators
+ Unary plus
- Unary minus
++ Increment
-- Decrement
& Address-of
* Defence
sizeof Sizeof
Level-III * Multiplication Multiplicative Binary L->R
/ Division operators
% Modulus
Precedence chart
Precedence Operator Name of Operator Category -ary of Associat
Level operator ivity
Level –IV + Addition Additive Binary L->R
- Subtraction operators
Level-V << Left Shift Shift operators Binary L->R
>> Right Shift
Level-VI < Less than Relational Binary L->R
> Greater than operators
<= Less than or equal to
>= Greater than or equal to
Level-VII == Equal to Equality Binary L->R
!= Not equal to operators
Level-VIII & Bitwise AND Bitwise operator Binary L->R
Level-IX ^ Bitwise X-OR Bitwise operator Binary L->R
Level-X | Bitwise OR Bitwise operator Binary L->R
Level-XI && Logical AND Logical operator Binary L->R
Level-XII || Logical OR Logical operator Binary L->R
Precedence chart
Precedence Operator Name of Operator Category -ary of Associat
Level operator ivity
Level –XIII ?: Conditional operator Conditional Ternary R->L

Level-XIV = Simple assignment Assignment & Binary R->L


*= Assign product shorthand
/= Assign quotient assignment
%= Assign modulus operators
+= Assign sum
-= Assign difference
&= Assign bitwise AND
|= Assign bitwise OR
^= Assign bitwise XOR
<<= Assign left shift
>>= Assign right shift
Level-XV , Comma operator Comma Binary L->R
Contents
• Unit-1
– History of Computers
– Basic organization of a Computer: ALU, Input-Output units,
memory, Program Counter.
– Introduction to Programming Languages
– Basics of a Computer Program
• Algorithms
• Flowcharts
• Pseudo code
– Introduction to Compilation and Execution
– Primitive Data Types
– Variables and Constants
– Basic input and Output
– Operators
– Type conversion and Casting
Type Conversion
• In C, it is possible to convert one data type to
another. This process can be done either explicitly
or implicitly.
– Explicit type conversion
• For ex: The result of 5/2 = 2. It gives the integer result.
Because both the arguments are of integer data type.
• If you want the actual value of 5/2. Then, Explicit type casting
is used.
(float) 5/2 = 2.5.
– Implicit type conversion
• In C automatically ‘lower’ data type is promoted to ‘upper’
data type.
• For example, data type char or short is converted to int.
• This type of conversion is called as automatic unary
Type Conversion
• Some of the example of automatic type
conversions:

Expression operator Operand1 operand2 Outcome

a Unary Short - int

a/b Binary Int float float

(a/b)-c Binary float long int float

(a/b-c)*c Binary float double double


Type Conversion
• If programmer needs certain data type, then
programmer has to mention it explicitly.
• For ex: 1) int a = 500, b = 70;
float res;
res = (float) a/b;
2) r = (int) 9.5;
3) r1 = (int) 12.3 / (int) 4.2;
4) r2 = (double) total / n;
5) r3 = (int) (c+d);
6) r4 = (int) a1 + b1;
7) r5 = cos ( (double)x);
Type Conversion programs
#include<stdio.h>
#include<conio.h>
int main()
{
short a=5;
long int b=123456;
float c=234.56;
double d=234567.78695;
clrscr();
printf(“%lf”, ((a+b)*c)/d);
return 0;
}
Output:
Type Conversion programs
#include<stdio.h>
#include<conio.h>
int main()
{
clrscr();
Printf(“\n Division operation Result”);
printf(“\n Two integers (5 & 2) : %d”, 5/2);
printf(“\n One int & one float (5.5 & 2) : %g”, 5.5/2);
printf(“\n Two integers (5 & 2) : %g”, (float)5/2);
return 0;
}
Output:
Division operation
Two integers (5 & 2): 2
One int & one float (5.5 & 2): 2.75
Two integers (5 & 2): 2.5
Contents
• Unit-1 contd..

– Problem solving techniques


• Algorithmic approach
• Characteristics of Algorithm
– Problem solving strategies
• Top-down approach
• Bottom-up Approach
– Time-space complexities
Problem solving techniques
• Problem solving techniques
A computer is used to solve various types of problems because it
takes very less time as compared to a human being. The following
steps are performed while solving a problem.
1. Analyze the given problem
2. Divide the process used to solve the problem in a series of
elementary tasks
3. Formulate the algorithm to solve the problem
4. Express the algorithm as a precise notation, which is known as a
computer program.
5. Feed the computer program in the computer. CPU interprets
the given program, processes the data accordingly, and
generates the result.
6. Send the generated result to the output unit, which displays it.
Algorithms and flowcharts are two important techniques that help
users in solving problems or accomplishing tasks using a computer.
Algorithmic approach

• Definition:
– An algorithm is a finite set of steps defining the solution
of a particular problem.
– It is expected that one could translate each pseudo-code
statement or a small number of lines of actual code,
easily and mechanically.
– An efficient algorithm is one which is capable of giving
the solution to the problem by using minimum resources
of the system such as memory and processor’s time.
– Algorithm is a language independent, well structured
and detailed.
– It will enable the programmer to translate onto a
computer program using any high-level language.
Algorithmic approach

• Features :
– Proper understanding of the problem
– Use of procedures/functions to emphasize
modularity
– Choice of variable names
– Documentation of the program
Algorithmic approach

• Features :
– Proper understanding of the problem
• For designing an efficient algorithm, the expectations from
the algorithm should be clearly defined so that the person
developing the algorithm can understand the expectations
from it.
– Use of procedures/ functions to emphasize modularity
• To assist the development, implementation and readability of
the program, it is usually helpful to modularize the program.
• Independent functions perform specific and well defined
tasks.
• The program that can be implemented as calls to the various
procedures that will be needed in the final implementations.
Algorithmic approach

• Features :
– Choice of variable names
• Proper variable names and constant names can make the program
more meaningful and easier to understand.
• It make the program more self documenting.
• For Ex: variable ‘day’ is used for the day of the weeks, instead of the
variable a or something else.
– Documentation of the program
• Brief information about the segment of the code can be included in
the program to facilitate debugging and providing information.
• A related part of the documentation is the information that the
programmer presents to the user during the execution of the
program.
• Since, the program is often to be used by persons who are unfamiliar
with the working and input requirements of the program, proper
documentation must be provided.
• The program must specify, what responses are required from the
user.
Characteristics of Algorithms

• Criteria’s or characteristics of Algorithms:


– Input:
• There should be zero or more values which are to be supplied.
– Ouput:
• At least one result is to be produced.
– Definiteness:
• Each step must be clear and unambiguous
– Finiteness:
• If we trace the steps of an algorithm, then for all cases, the
algorithm must terminate after a finite number of steps.
– Effectiveness:
• Each step must be sufficiently basic that a person using only
paper and pencil can in principle carry it out.
• Not only each step is definite, it must also be feasible.
Algorithm

• Advantages:
– It is step by step solution to a given problem which is very easier to
understand.
– It has got a definite procedure.
– It is easy to first develop an algorithm, then convert it into a flow
chart and then into a computer program.
– It is easy to debug as every step has got its own logical sequence.
– It is independent of programming languages.
• Disadvantages:
– It is time consuming. (First we have to write algorithm then, convert
it into flowchart and then computer program).
– Algorithm lacks visual representation hence understanding the logic
becomes difficult.
Algorithms

• Examples :
– Sum of two numbers
1. Start
2. Read two numbers a and b
3. Calculate the sum of a and b and store it in sum
4. Display the value of sum
5. Stop.
Algorithms

• Examples :
– Average of a set of data values
1. Start
2. Set the sum of the data values and the count to zero
3. As long as the data values exist, add the next data
value to the sum and add 1 to the count
4. To complete the average, divide the sum be the count.
5. Display the average.
6. Stop
Algorithms

• Examples :
– Factorial of a given number
1. Start
2. Read the number n
3. [Initialize]
i ← 1, fact ← 1
4. Repeat steps 4 through 6 until i = n
5. fact ← fact * i
6. i ← i + 1
7. Print fact
8. Stop
Algorithms

• Examples :
– Whether the given number is prime or not
1. Start
2. Read the number n
3. [Initialize]
i ← 2, flag ← 1
4. Repeat steps 4 through 6 until i < n or flag = 0
5. rem ← num mod i
6. if rem =0 then
flag ← 0
else
i← i+1
7. if flag = 0 then
print number is not prime
Else
print number is prime
8. Stop
Contents
• Unit-1 contd..

– Problem solving techniques


• Algorithmic approach
• Characteristics of Algorithm
– Problem solving strategies
• Top-down approach
• Bottom-up Approach
– Time-space complexities
Problem solving Strategies
• Top-down approach
– It is a method of problem solving and problem
analysis.
– The essential idea is to subdivide a large problem into
several smaller tasks or parts for ease of analysis.
– It simplifies or reduce the complexity of the process
of problem solving.
– There are two essential ideas in top-down analysis:
• Subdivision of a problem
• Hierarchy of tasks
Problem solving Strategies
• Top-down approach
– Subdivision of a problem
• Braking a big problem into two or more smaller problems.
• To solve the big problem, first these smaller problems
have to be solved.
• Top-down analysis does not simple divide a problem into
two or more smaller problems
– Hierarchy of tasks
• Each of these smaller problems is further subdivided.
• This process continues downwards, creating a hierarchy of
tasks, from one level to the next, until no further break up
is possible.
Problem solving Strategies
• Top-down approach
The four basic steps to top-down analysis are as follows:
1. Define the complete scope of the problem to determine the basic
requirement for its solution. Three factors must be considered in
the definition of a programming problem.
• Input: What data is required to be processed by the program?
• Process: What must be done with the input data? What type of
processing is required?
• Output: What information should the program produce? In what form
should it be presented?
2. Based on the definition of the problem, divide the problem into
two or more separate parts.
3. Carefully define the scope of each of these separate tasks and
subdivide them further, if necessary, into two or more smaller
tasks.
4. Repeat step 3, every step at the lowest level describes a simple
task, which cannot be broken further.
Problem solving Strategies
• Bottom-Up approach
– It is
Contents
• Unit-1 contd..

– Problem solving techniques


• Algorithmic approach
• Characteristics of Algorithm
– Problem solving strategies
• Top-down approach
• Bottom-up Approach
– Time-space complexities
Time and Space Complexities
• Efficiency of an algorithm means how fast it can
produce the correct result for the given problem.
• Efficiency of an algorithm depends upon its
– time complexity
• Refers to the amount of computer time required by an algorithm
for its execution.
• It includes both compile and run time.
• The compile time does not depend on the instance characteristics
of the algorithm.
• The run time is estimated by determining the number of various
operations such as addition, subtraction, multiplication, division,
load, and store, executed by it.
– space complexity.
• Refers to the amount of memory required by the algorithm for its
execution and generation of the final output.

You might also like