Professional Documents
Culture Documents
Definition : A Computer is an electronic device that can perform activities that involve Mathematical,
Logical and graphical manipulations. Generally, the term is used to describe a collection of devices that
function together as a system.
It performs the following three operations in sequence.
1. It receives data & instructions from the input device.
2. Processes the data as per instructions.
3. Provides the result (output) in a desired form.
Data : It is the collection of raw facts, figures & symbols.
Ex : Names of students and their marks in different subjects listed in random order.
Information : It is the data that is processed & presented in an organized manner.
Ex : When the names of students are arranged in alphabetical order, total and average marks are
calculated & presented in a tabular form, it is information.
Program : Set of instructions that enables a computer to perform a given task.
Advantages of computers :
1. High speed : Computers have the ability to perform routine tasks at a greater speed than human
beings. They can perform millions of calculations in seconds.
2. Accuracy : Computers are used to perform tasks in a way that ensures accuracy.
3. Storage : Computers can store large amount of information. Any item of data or any instruction
stored in the memory can be retrieved by the computer at lightning speeds.
4. Automation : Computers can be instructed to perform complex tasks automatically ( which
increases the productivity).
5. Diligence : Computers can perform the same task repeatedly & with the same accuracy without
getting tired.
6. Versatility : Computers are flexible to perform both simple and complex tasks.
7. Cost effectiveness : Computers reduce the amount of paper work and human effort, thereby
reducing costs.
Limitations of computers :
1. Computers need clear & complete instructions to perform a task accurately. If the instructions
are not clear & complete, the computer will not produce the required result.
2. Computers cannot think.
3. Computers cannot learn by experience.
Generations of computers :
Generation Component used
First Generation Vacuum tubes
(1946-1954 )
Second Generation Transistors
(1955-1965)
Third Generation Integrated Circuits (IC)
(1968-1975 )
Fourth Generation Very Large Scale Integrated Circuits
( 1976-1980) (VLSI)
Fifth Generation Ultra Scale Integrated Circuits (ULSI)
(1980 – till today ) Micro Processor (SILICON CHIP)
******
3
ANATOMY OF COMPUTERS
The computer system consists of three units:
1. Input device 2. Central Processing Unit (CPU) 3. Output device
Memory unit
Control Unit
Unit Function
1.Input device : Reads information from input media and enters to the
computer in a coded form
2.CPU
(a) Memory unit : Stores program and data
(b) Arithmetic Logic unit : Performs arithmetic and logical functions
(c) Control Unit : Interprets program instructions and controls the input and
output devices
3. Output device : decodes information and presents it to the user
Central Processing Unit: It is the part of the computer that carries out the instructions of a
computer program. It is the unit that reads and executes program instructions. Hence it is known as the
―brain‖ of the computer. The CPU consists of storage or memory unit, Arithmetic Logic Unit (ALU)
and control unit.
(a). Memory Unit: It is also known as the primary storage or main memory. It stores data, program
instructions, internal results and final output temporarily before it is sent to an appropriate output
device. It consists of thousands of cells called ―storage locations‖. These cells activate with ―off-on‖
or binary digits(0,1) mechanism. Thus a character either a letter or numerical digit is stored as a string
of (0,1) Binary digits ( BITS). These bits are used to store instructions and data by their combinations.
(b) Arithmetic and Logical Unit(ALU): It is the unit where all Arithmetic operations (addition,
subtraction etc.) and logical functions such as true or false, male or female are performed. Once data are
fed into the main memory from input devices, they are held and transferred as needed to ALU where
processing takes place. No process occurs in primary storage. Intermediate generated results in ALU
4
are temporarily placed in memory until needed at later time. Data may move from primary memory to
ALU and back again to storage many times before the process is finalized.
(c).Control Unit : It acts as a central nervous system and ensures that the information is stored
correctly and the program instructions are followed in proper sequence as well as the data are selected
from the memory as necessary. It also coordinates all the input and output devices of a system .
5
Input Devices
Devices used to provide data and instructions to the computer are called Input devices.
Some important input devices are
Key board, Mouse, Scanner, MICR, Web camera, Microphone etc.
1. Keyboard: The Key board is used for typing text into the computer. It is also known as standard
Input device. A computer keyboard is similar to that of a type writer with additional keys. The
most commonly available computer keyboard has 104 keys.
There are different types of keys on the keyboard. The keys are categorized as :
Punctuation keys, such as colon (:), semicolon (;) Question mark (?), Single & double
quotes (‗,‖)
Special keys such as arrow keys, control keys, function keys (F1 to F12), HOME, END etc.
2.. Mouse: It is a device that controls the movement of the cursor on a monitor. A mouse will have 2
buttons on its top. The left button is the most frequently used button. There will be a wheel between the
left and right buttons. This wheel enables us to smoothly scroll through screens of information. As we
move the mouse, the pointer on the monitor moves in the same direction. Optical mouse is another
advanced pointing device that uses a light emitting component instead of the mouse ball. Mouse cannot
be used for entering the data. It is only useful to select the options on the screen.
3. Scanner: : It is an input device that can read text or illustrations printed on paper and translate into
digital form. The main advantage of these scanners is that the data need not be entered separately
resulting in saving lot of time.
Output devices
Any device that is capable of representing information on a computer is called an Output device.
Output devices receive information from the CPU and present it to the user in the desired form.
1 .Terminal/Monitor: It is similar to TV screen- either a monochrome (black & white) or colour – and
it displays the output. It is also referred as Visual Display Unit(VDU). Several types of monitors are in
use. Some of them are Colour Graphic Adapter(CGA), Enhanced Graphics Adaptor(EGA) , Video
Graphics Adapter (VGA) and Super Video Graphics Adapter (SVGA).
The screen sizes differ from system to system. The standard size is 24 lines by 80 characters. Most
systems have provision for scrolling which helps in moving the text vertically or horizontally on the
screen.
2 . Printer: A printer is used to transfer data from a computer onto paper. The paper copy obtained
from a printer is often referred as ―printout‖. The different printers and their speeds are as follows:
S. No. Type Mode of Printing Speed
1 Dot – Matrix Prints the character in dotted pattern 200/300 to 700
printer through printer ribbon using either 24 CPS
pin or 9 pin
2 Ink Jet printer Work by spraying ionized ink Slow, 90 CPS
3 Laser printer Also called page printer. Uses laser 6 to 12 PPM
beam to produce an image.
4 Line printer Prints lines at a time instead of single 300 to 600 LPM
characters.
5 Plotter Produces drawings or graphs through
pens which are filled with different
colours.
( CPS: Characters Per Second; PPM: Pages Per Minutes; LPM : Lines Per Minute)
Laser printer
******
7
MEMORY OF THE COMPUTER
Memory or storage capacity is one of the important components of a computer. Any storage
unit of a computer system is classified on the basis of the following criteria:
1. Access time: This is the time required to locate and retrieve stored data from the storage unit in
response to program instructions.
2. Storage capacity: It is the amount of data that can be stored in the storage unit.
Units of memory: The computer stores a character in the storage cells with binary (0,1) mechanism.
Thus the basic unit of memory is a bit (binary digit – 0,1). To store a character, a computer requires 8
bits or 1 byte. This is called the ― word length‖ of the storage unit. Hence the storage capacity of the
computer is measured in the number of words it can store and is expressed in terms of bytes. The
different units of measurement are
8 Bits = 1 Byte
Conversion :
This code has given alphabets like some numbers which can be converted to Binary form.
A- 65 …….Z – 90 and a – 97 ………. z – 121
By using these codes the alphabets can be converted to digital & hence to Binary form.
Types of Memory : A computer memory is of two types
1. Primary Memory ( Internal storage) 2. Secondary Memory ( External storage)
Primary Memory : Primary memory is also called internal memory and is an important part of a
computer. It is the main area in a computer where the data is stored. The stored data can be recalled
instantly and correctly whenever desired. This memory can be quickly accessed by the CPU for reading
or storing information. Primary memory is further classified into two types:
8
ROM:
It is called Read-only memory as information can only be read from and not written or changed onto
ROM. ROM is the ‗built-in‘ memory of a computer. It stores some basic input – output instructions put
by the manufacturer to operate the computer. The storage of data and instructions in ROM is permanent.
It does not depend on the power supply. i.e it is non-volatile memory.
Secondary memory: The primary memory which is faster (and hence expensive) is generally not
sufficient for large storage of data. As a result, additional memory, called the ―auxiliary‖ or ―secondary
memory‖ is used. It is also referred as ―backup storage‖ as it is used to store large volume of data on a
permanent basis which can be transferred to the primary memory whenever required for processing.
Data are stored in secondary storage in the same binary codes as in the main (primary memory) storage.
Some of the devices of secondary storages are Floppy Disk, Hard Disk, CD-ROM, DVD and Flash
drive.
1. Floppy Disk: It is also referred as ―Diskette: and is made of flexible Vinyl material. It has a small
hole on one side called ―Right protect notch‖, Which protects accidental writing/deleting the
information from the disk. There is a hole in the centre through which the spindle of drive unit rotates
the disk. The disks are available in two sizes of 5.25 and 3.5 inches and these could be either low-
density or high-density floppies. Storage capacity of floppies are measured in kilobytes (KB) and
megabytes (MB). The details about the storage capacities of the floppies are presented below:
Floppy Disk Storage Capacity Size (Diameter)
Low Density 360 KB 5.25 inches
High Density 1.2 MB 5.25 inches
High Density 1.44 MB 3.5 inches
Extended 2.8 MB 3.5 inches
2. Hard Disk: The hard disk can hold more information than the floppy disk and the retrieval of
information from hard disk is faster when compared to floppies or tapes. A hard disk is fixed inside the
CPU and its capacity ranges from 20 MB onwards. The hard disk is made up of a collection of discs
(one below the other) known as platters on which the data is recorded. These platters are coated with
magnetic material. It is less sensitive to external environmental disorders and hence the storage in hard
disk is safe. A small hard disk might be as much as 25 times larger than a floppy disk. Storage Capacity
of hard disks varies from 20 MB to several Gega bytes like 80GB, 160GB.
9
3. CD-ROM: CD-ROM stands for Compact Disk–Read Only Memory. It is used to store a wide variety
of information. Its main advantage is that it is portable and can hold a large amount of data.. The storage
capacity of most CD-ROMs is approximately 650 MB or 700 MB.
CD-ROMs have the following variations:
(i) CD-R(Compact disc Recordable): Data can be written onto it just once. The stored data can be read.
Data once written onto it cannot be erased.
(ii) CD-RW(Compact disc Rewritable): It is also called erasable CD. Data once written onto it can be
erased to write or record new information many times.
To use a CD-ROM, a device called CD drive is needed.
4. DVD: DVD stands for Digital Versatile Disc. It is similar to a CD-ROM, except that it can store
larger amounts of data. The storage capacity of a DVD is at least 4.7MB. DVDs that can store up to
17GBs are also available. Because of their capacity, DVDs are generally used to store a very large
multimedia presentations and movies that combine high quality sound and graphics.
5. Flash Drive: It is a small, portable device that can be used to store, access and transfer data. Due to
its small size, it is commonly called Pen drive. It is also called USB drive. We can read, write, copy,
delete, and move data from computer to pen drive or pen drive to computer. It comes in various storage
capacities of 2GB, 4GB, 8GB etc. It is popular because it is easy to use and small enough to be carried
in a pocket. This device is plugged into the USB port of the computer and the computer automatically
detects this device.
******
10
HARDWARE and SOFTWARE
Hardware: The physical components of the computer are known as ―Hardware‖. It refers to the objects
that we can actually touch.
Ex: input and output devices, processors, circuits and the cables.
Software: Software is a program or set of instructions that causes the Hardware to function in a desired
way. The basic difference between the Hardware and Software is just the same as that exists between
TV and TV studio. Without TV studio (software) from where the programs are telecast, the TV
(Hardware) is a dead machine.
1. Operating System (OS) : The software that manages the resources of a computer system and
schedules its operation is called Operating system. The operating system acts as interface between
the hardware and the user programs and facilitates the execution of programs.
Generally the OS acts as an interface between the user and the Hardware of the computer.
i.e It is a bridge between the user and the Hardware.
The User interface provided by the OS can be character based or graphical.
CUI -- Character user Interface
GUI -- Graphical user Interface
CUI : It is operated with keyboard only. Ex: MS-DOS, UNIX
GUI : The system can be operated with mouse and keyboard. Ex: Windows 95, Windows XP etc
Disk Operating System (DOS): It was developed as early as 1980 by Bill Gates at the age of
19. It is suited for personal computers. Dos is a single user and single task operating system
WINDOWS : It works with DOS and it supports single user and multitask system. It
requires a powerful PC with a minimum RAM of 8 MB .
2. Translators : Computers can understand instructions only when they are written in their own
language – the machine language . Therefore, a program written in any other language should be
translated into machine language. The software that ―translates‖ the instructions of different
languages is known as translators .
There are two types of translators. They are compilers and Interpreters
A Compiler checks the entire user – written program (known as the source program) and if it is
error free, produces a complete program in machine language (known as object program). The source
program is retained for possible modifications and corrections and the object program is loaded into the
computer for execution. If the source program contains errors, the compilers produce a list of errors at
the end of the execution of the program. i.e a compiler translates the whole program before execution.
An interpreter does a similar job but in a different style. The interpreter translates one statement
at a time and if it is error – free, executes. This continues till the last statement. Thus an interpreter
11
translates or executes the first instruction before it goes to the second, while a compiler translates the
whole program before execution.
1. Error correction is very much simpler in the case of interpreter as it translates the
statements in stages. The compiler produces an error list of the entire program at the end.
2. Interpreter takes more time for the execution of the program compared to compilers as it
translates one statement at a time
1. Machine Languages: Computers respond only to machine language. This language is in terms of
binary codes (0,1). i.e. all programs should be written with these codes, which is difficult, time
consuming and leading to errors while writing the programs. There is no unique standard
machine language. Rather there are many machine languages. These are machine dependent.
These are referred as the first generation languages.
2. Assembly Languages : It uses mnemonic codes rather than numeric codes (as in machine
languages). Ex. Add or A is used as a symbol for addition. It requires translators to convert into
machine language. Like machine language, writing program in assembly language is also time
consuming. These are also machine dependent.
3. High Level Languages (HLL): These are referred as problem oriented languages (POL). These
are referred as third generation languages. The advantages of these languages are
The high level languages are convenient for writing programs as they can be written without
any codes. These languages follow rules like ―English‖ language.
Because of their English like nature, less time is required to write a program.
They are machine independent. A program written in any HLL can be run on computers of
different types without any modifications.
4. Application Programs: These are user written programs to do a specific job which can be changed to
meet the individual needs. These programs are written in different languages such as BASIC or C or by
using database packages like dBASE, Oracle.
i) Data Analysis ii) Word Processing iii) Spread Sheet iv) Graphics and v) Databases
Data Analysis
Ex: SPSS (Statistical Package for Social Science),
MSTAT, MICROSTAT, GENSTAT, SAS etc.
Word Processing
Ex: WORD PERFECT, WORDSTAR, MS-Word, CHIRATOR, NORTON EDITOR etc.
Spread Sheet
Ex: LOTUS, Qpro, VP-PLANNER, SYMPHONY, MS-Excel etc.
Graphics
Ex: LOTUS, STORY-BOARD, POWER-POINT etc.
Databases
Ex: dBASE, FOX-BASE, FOX-PRO, ORACLE, MS-Access etc.
2. Memory management : It manages the allocation of main memory and other storage areas to the
system programmes as well as user programmes and data.
3. Input / Output management : It manages the co-ordination and assignment of different Input and
Output devices while one or more programmes are executed.
4. File management : It allows all files to be easily changed and modified through the use of text
editors or some other file manipulation routines.
5. Establishment and enforcement of a priority system : It determines and maintains the order in
which jobs are to be executed in the computer system.
7. Facilitates easy communication between the computer system and the computer operator.
*******
13
Classification of Computers
Computers are classified according to the storage capacity, speed and the purpose for which they
are developed. These can be classified into three types:
2. Digital Computers: These computers operate by ―counting‖. All quantities are expressed as
discrete digits or numbers. These are useful for evaluating arithmetic expressions and
manipulations of data.
3. Hybrid Computers: Computers which combine the features of analog and digital computers are
known as Hybrid computers.
A majority of the computers that are in use are digital. These computers were essentially developed
for computations. Later, the developments in the computers led to the use of digital computers in
variety of applications. Depending on the use of applications, the digital computers are classified
into 1) Special Purpose Computers and 2) General Purpose Computers
1. Special Purpose Computers: These are developed with a specific purpose. Some of the areas
where these computers are being used are – soil testing, drip irrigation, medical scanning, traffic
signals, spacecraft, rocket technology etc.,
2. General Purpose Computers: These are developed to meet the requirements of several areas such
as simulation, solving mathematical equations, payroll and personnel database. These computers
are available in different sizes and capabilities and are further classified (based on memory,
speed, storage) as follows.
a) Super Computers: These have extremely large storage capacities and computing speeds
which are atleast 10 times faster than other computers. These are used for large scale
numerical problems in scientific and engineering disciplines such as electronics, weather
forecasting etc.,. The first super computer was developed in U.S.A. by CRAY
computers. In India the indigenous super computer was developed under the name
Param.
b) Mainframe Computers: They also have large storage and high computing speed (but
relatively lower than the super computers). They are used in applications like weather
forecasting, space applications etc., they support a large number of terminals for use by a
variety of users simultaneously, but are expensive
c) Mini Computers: It is a medium sized computer with moderate cost, available
indigenously and used for large volume applications. It can serve multi-users
simultaneously
14
d) Micro Computers: A micro computer is the smallest general purpose processing system.
Micro computers are also referred as ―personal computers‖(PC). These are self
contained units and usually developed for use by one person at a time but can be linked
to very large systems. They are cheap, easy to use even at homes and can be read for
variety of applications from small to medium range. These are available in three models:
1. PC : Personal Computer
2. PC-XT : PC with Extended Technology
3. PC-AT : PC with Advanced Technology
*****
15
Algorithm & Flowchart Manual
..
ALGORITHM:
The word “algorithm” relates to the name of the mathematician Al-khowarizmi, which means
a procedure or a technique. Software Engineer commonly uses an algorithm for planning
and solving the problems. An algorithm is a sequence of steps to solve a particular problem
or algorithm is an ordered set of unambiguous steps that produces a result and terminates in
a finite time
The algorithm and flowchart include following three types of control structures.
1. Sequence: In the sequence structure, statements are placed one after the other and
the execution takes place starting from up to down.
2. Branching (Selection): In branch control, there is a condition and according to a
condition, a decision of either TRUE or FALSE is achieved. In the case of TRUE, one
of the two branches is explored; but in the case of FALSE condition, the other
alternative is taken. Generally, the ‘IF-THEN’ is used to represent branch control.
3. Loop (Repetition): The Loop or Repetition allows a statement(s) to be executed
repeatedly based on certain loop condition e.g. WHILE, FOR loops.
Advantages of algorithm
3 CIC-UHF
Algorithm & Flowchart Manual
Step 1 Define your algorithms input: Many algorithms take in data to be processed, e.g.
to calculate the area of rectangle input may be the rectangle height and rectangle width.
Step 2 Define the variables: Algorithm's variables allow you to use it for more than one
place. We can define two variables for rectangle height and rectangle width as HEIGHT and
WIDTH (or H & W). We should use meaningful variable name e.g. instead of using H & W
use HEIGHT and WIDTH as variable name.
Step 3 Outline the algorithm's operations: Use input variable for computation purpose,
e.g. to find area of rectangle multiply the HEIGHT and WIDTH variable and store the value in
new variable (say) AREA. An algorithm's operations can take the form of multiple steps and
even branch, depending on the value of the input variables.
Step 4 Output the results of your algorithm's operations: In case of area of rectangle
output will be the value stored in variable AREA. if the input variables described a rectangle
with a HEIGHT of 2 and a WIDTH of 3, the algorithm would output the value of 6.
FLOWCHART:
The first design of flowchart goes back to 1945 which was designed by John Von Neumann.
Unlike an algorithm, Flowchart uses different symbols to design a solution to a problem. It is
another commonly used programming tool. By looking at a Flowchartone can understand the
operations and sequence of operations performed in a system. Flowchart is often considered
as a blueprint of a design used for solving a specific problem.
Advantages of flowchart:
4 CIC-UHF
Algorithm & Flowchart Manual
Predefined Process
/Function Used to represent
a group of statements
performing one processing
task.
Preprocessor
|--------------
--------- | Comments
|--------------
5 CIC-UHF
Algorithm & Flowchart Manual
The language used to write algorithm is simple and similar to day-to-day life language. The
variable names are used to store the values. The value store in variable can change in the
solution steps. In addition some special symbols are used as below
HEIGHT 5
or
HEIGHT = 5
The symbol ‘=’ is used in most of the programming language as an assignment symbol, the
same has been used in all the algorithms and flowcharts in the manual.
The statement C = A + B means that add the value stored in variable A and variable B
then assign/store the value in variable C.
The statement R = R + 1 means that add I to the value stored in variable R and then
assign/store the new value in variable R, in other words increase the value of variable R by 1
Mathematical Operators:
Relational Operators
6 CIC-UHF
Algorithm & Flowchart Manual
Logical Operators
Note: We can use keyword INPUT or READ or GET to accept input(s) /value(s) and
keywords PRINT or WRITE or DISPLAY to output the result(s).
7 CIC-UHF
Algorithm & Flowchart Manual
..
Algorithm
Step-1 Start
Step-4 SUM = A + B
Step-6 Stop
OR
Algorithm
Step-1 Start
Step-3 SUM = A + B
Step-5 Stop
8 CIC-UHF
Algorithm & Flowchart Manual
..
C : temperature in Celsius
F : temperature Fahrenheit
Algorithm
Step-1 Start
Step-3 F = (9.0/5.0 x C) + 32
Step-5 Stop
C : temperature in Celsius
F : temperature Fahrenheit
Algorithm
Step-1 Start
Step-3 C = 5.0/9.0 (F - 32 )
Step-5 Stop
9 CIC-UHF
Algorithm & Flowchart Manual
..
Algorithm
Step-1 Start
Step-3 Area = L x L
Step-4 PERIMETER = 4 x L
Step-6 Stop
L : Length of Rectangle
B : Breadth of Rectangle
AREA : Area of Rectangle
PERIMETER : Perimeter of Rectangle
Algorithm
Step-1 Start
Step-3 Area = L x B
Step-4 PERIMETER = 2 x ( L + B)
Step-6 Stop
10 CIC-UHF
Algorithm & Flowchart Manual
..
R : Radius of Circle
AREA : Area of Circle Start
Input Value
Algorithm of R
Step-1 Start
AREA = 22.0/7.0
Step-2 Input Radius of Circle say R xRx R
Stop
Algorithm
Step-1 Start
Step-5 PERIMETER = S1 + S2 + S3
Step-7 Stop
11 CIC-UHF
Algorithm & Flowchart Manual
..
P : Principle Amount
N : Time in Years
R : % Annual Rate of Interest
SI : Simple Interest
Algorithm
Step-1 Start
Step-3 SI = (P x N x R)/100.0
Step-4 Display SI F
Step-6 Stop
P : Principle Amount
N : Time in Years
R : % Annual Rate of Interest
CI : Compound Interest
Algorithm
Step-1 Start
Step-3 CI = P(1+R/100)N - P
Step-4 Display CI
Step-6 Stop
..
12 CIC-UHF
Algorithm & Flowchart Manual
..
Algorithm
Step-1 Start
Step-8 Stop
Algorithm
Step-1 Start
Step-4 A=A+B
Step-5 B=A-B
Step-6 A=A-B
Step-8 Stop
13 CIC-UHF
Algorithm & Flowchart Manual
..
Algorithm
Step-1 Start
NUM1,NUM2
ELSE
ENDIF
Step-4 Stop
Algorithm
Start
Step-1 Start
Step-4 Stop
Stop
14 CIC-UHF
Algorithm & Flowchart Manual
..
Algorithm
Step-1 Start
15 CIC-UHF
Algorithm & Flowchart Manual
..
Algorithm & Flowchart to find the largest of three numbers (an another way)
Algorithm
Step-1 Start
Step-3 BIG = A
BIG = B
ENDIF
BIG = C
ENDIF
Step-7 Stop
16 CIC-UHF
Algorithm & Flowchart Manual
..
Algorithm
Step-1 Start
Step-2 I=1
Step-6 GO TO Step--3
Step-7 Stop
Algorithm
Step-1 Start
Step-3 I=1
Step-7 GO TO Step-4
Step-8 Stop
17 CIC-UHF
Algorithm & Flowchart Manual
..
Algorithm
Step-1 Start
Step-3 I = 1, SUM=0
Step-6 I=I+1
Step-7 Go to step-4
Step-9 Stop
Algorithm
Step-1 Start
Step-3 I = 1, SUM=0
Step-6 I=I+2
Step-7 Go to step-4
Step-9 Stop
18 CIC-UHF
Algorithm & Flowchart Manual
..
Algorithm
Step-1 Start
Step-7 I=I+1
Step-8 Go to step-4
Step-10 Stop
Algorithm
Step-1 Start
Step-3 I=1
Step-7 I=I+1
Step-8 Go to step-4
Step-9 Stop
19 CIC-UHF
Algorithm & Flowchart Manual
..
Algorithm
Step-1 Start
Step-4 WRITE A, B
Step-6 NEXT= A + B
Step-8 A=B
Step-9 B=NEXT
Step-10 COUNT=COUNT + 1
Step-11 Go to step-4
Step-12 Stop
20 CIC-UHF
Algorithm & Flowchart Manual
..
Algorithm & Flowchart to find sum and average of given series of numbers
Algorithm
Step-1 Start
Step-2 COUNT=0
Step-3 SUM=0
Step-6 COUNT=COUNT+1
GOTO Step-4
ENDIF
Step-10 Stop
21 CIC-UHF
Algorithm & Flowchart Manual
..
Algorithm
Step-1 Start
Step-3 DISC= B2 – 4 A * C
Stop
ENDIF
22 CIC-UHF
Algorithm & Flowchart Manual
..
Algorithm
Step-1 Start
Step-3 R=SQRT(NUM)
Step-4 I=2
Step-8 Go to Step-5
23 CIC-UHF
Algorithm & Flowchart Manual
..
Algorithm
Step-1 Start
Step-5 WHILE (r != 0)
DO
N=D
D=r
r =N%D
DONE
Step-6 gcd=d
Step-7 lcm = (a*b)/gcd
Step-9 Stop
24 CIC-UHF
Algorithm & Flowchart Manual
…
Algorithm
Step-1 Start
Step-6 Stop
Algorithm
Step-1 Start
Step-3 D=1
Step-4 WHILE (D< N)
DO
IF ( N % D ==0) THEN
PRINT D
ENDIF
D=D+1
DONE
Step-5 Stop
25 CIC-UHF
UNIT-II:
Introduction to C Programming
Introduction:
C is a programming language developed at AT & T bell lab of USA
(California) in 1972, designed and written by "Dennis Ritchie".
C is a powerful general-purpose programming language. It is fast, portable
and available in all platforms.
The Unix operating system and virtually all Unix applications are written
in the C language. C has now become a widely used professional language for various
reasons.
Easy to learn
Structured language
It produces efficient programs.
It can handle low-level activities.
It can be compiled on a variety of computers.
It can be defined by following ways:
1. Mother language
2. System programming language
3. Procedure-oriented programming language
4. Structured programming language
5. Mid level programming language
C-Tokens:
Tokens:
The individual unit (or) a part which has a specific meaning is called as
token and smallest meaningful individual in “C” are called as “C” tokens.
Keywords:
The words which have a predefined meaning and this meaning doesn‟t have any
change these words are called as keywords.
Identifiers
Identifiers are distinct names given to program elements such as constants, variables,
etc.
An identifier is a sequence of letters, digits, and the special character "_"
(Underscore).
Rules:
1. It must start with either a letter or underscore. '_'
2. No commas or blanks are allowed within a variable name.
3. The upper case and lower case letters are treated as distinct, identifiers are case
sensitive.
4. An identifier can be of any length.
5.No special symbol can be used in a variable name
Constant:
Constant is a value give to a variable which can‟t be changed
through the execution of programme.
String:
String is a collection of characters (or) numbers (or) any special symbols which are
enclosed with in double quotation marks is called a string.
Ex: “ C programming ”
Identifiers
Identifiers are distinct names given to program elements such as constants, variables,
etc.
An identifier is a sequence of letters, digits, and the special character "_"
(Underscore).
Rules for Creating Identifiers
1. It must start with either a letter or underscore. '_'
2. No commas or blanks are allowed within a variable name.
3. The upper case and lower case letters are treated as distinct, identifiers are case
sensitive.
4. An identifier can be of any length.
5. No special symbol can be used in a variable name.
The main () Function,
All the c programs must have a main () function.
The starting point of the c programme and the execution starts from this function
followed by open parenthesis and ended by closed parenthesis.
It is the empty point of any c program.
It is required in every c program.
It contains instructions that tells the computer to carry out what ever task you
program is designed to do.
It is the point at which execution of program is started.
When a c program is executed the execution control goes directly to the main ()
function.
Syntax:
main ()
.........
.........
Ex:
#include<stdio.h>
main()
Output:
This is main function
Variable:
C variable is a named location in a memory where a program can manipulate the data. This
location is used to hold the value of the variable.
The value of the C variable may get change in the program.
C variable might be belonging to any of the data type like int, float, char etc.
A variable name may contain letters, digits and underscore symbol. The following are the rules to
specify a variable name...
Variable name should not start with digit.
Keywords should not be used as variable names.
Variable name should not contain any special symbols except underscore(_).
Variable name can be of any length but compiler considers only the first 31 characters of the
variable name.
Declaration of Variable
datatype variablename ;
Comments
Comments in C language are used to provide information about lines of code. It
is widely used for documenting code. There are 2 types of comments in C language.
1. Single Line Comments
2. Multi Line Comments
Single Line Comments
Single line comments are represented by double slash // .
EX:
#include <stdio.h>
main()
{
printf("Hello C"); //printing information
}
Output:
Hello C
Mult Line Comments
Multi line comments are represented by slash asterisk \* ... *\. It can
occupy many lines of code but it can't be nested.
Syntax:
/*
code
to be commented
*/
Ex:
#include <stdio.h>
main()
{
/*printing
information*/
printf("Hello C");
}
Output:
Hello C
Dataypes:
Data type is a keyword used to identify type of data. Data types are used
for storing the input of the program into the main memory (RAM) of the computer by
allocating sufficient amount of memory space in the main memory of the computer.
Operators:
An operator is a symbol that use to perform certain mathematical or logical
operations. Operator is used to manipulate data and variables.
Types of operators:
In C programming operator classified into various categories.
1. Arithmetic operator.
2. Relational operator.
3. Logical operator.
4. Assignment operator.
5. Unary operator (Increment and decrement operator).
6. Conditional operator.
7. Bitwise operator.
8. Special operators.
Arithmetic:
These are used to perform mathematical operations.
These are binary operators since they operate on two operands at a time.
They can be applied to any integers, floating-point number or characters.
C supports 5 arithmetic operators. They are +, -, *, /, %.
The modulo (%) operator can only be applied to integer operands and cannot be
used on float or double values.
Program:
#include<stdio.h>
main()
{
int a,b,c;
printf("Enter first Number : \n");
scanf("%d",&a);
printf("Enter second Number : \n");
scanf("%d",&b);
c=a+b;
printf("Addition value of C is %d\n",c);
c=a-b;
printf("Subtraction value of C is %d\n",c);
c=a*b;
printf("Multiplication value of C is %d\n",c);
c=a/b;
printf("Division value of C is %d\n",c);
Output:
Enter first Number : 6
Enter second Number : 6
Addition value of C is 12
Subtraction value of C is 0
Multiplication value of C is 36
Division value of C is 1
Relational Operator:
Relational operators checks relationship between two operands . If the relation is true, it
returns value 1 and if the relation is false, it return value 0 for example a>b.
Program:
#include <stdio.h>
main()
{
int a=21,b=10,c;
if(a<b)
{
printf("a is less than b \n");
}
else
{
printf("a is not less than b \n");
}
if(a>b)
{
printf("a is Greater than b \n");
}
else
{
printf("a is not Greater than b \n");
}
if(a<=b)
{
printf("a is less than or equal to b \n");
}
else
{
printf("a is not less than or equal to b \n");
}
if(a>=b)
{
printf("a is Greater than or equal to b \n");
}
else
{
printf("a is not Greater than or equal to b \n");
}
if(a==b)
{
printf("a is equal to b \n");
}
else
{
printf("a is not equal to b \n");
}
}
Output:
a is not less than b
a is Greater than b
a is not less than or equal to b
a is Greater than or equal to b
a is not equal to b
Logical operator:
A logical operator is used to compare or evaluate logical and relational expressions.
There are following logical operators.
Operators (&&, || and !) are used to perform logical operations on the given expressions.
&& operator – “if clause” becomes true only when both conditions is true. Else, it
becomes false.
|| Operator – “if clause” becomes true when any one of the condition is true. It
becomes false when none of the condition is true.
If the conditions (m>n && m!=0) is true, true (1) is returned. This value is inverted
by “!” operator.
So, “! (m>n and m! =0)” returns false (0).
Program:
#include <stdio.h>
main()
{
int a=5,b=20,c;
if(a&&b)
{
printf("Condition a&&b is true \n");
}
else
{
printr("Condition a&&b is not true\n");
}
if(a||b)
{
printf("Condition a||b is true \n");
}
else
{
printr("Condition a||b is not true\n");
}
if(!(a&&b))
{
printf("Condition !(a&&b) is true \n");
}
else
{
printf("Condition !(a&&b) is not true \n");
}
}
Output:
Condition a&&b is true
Condition a||b is true
Condition !(a&&b) is not true
Assignment operator:
An assignment operator is used to assign a constant or a value of one variable to
another.
= is a assignment operator.
You can use the assignment for multiple assignments as follow: X=Y=Z=20;
Program:
#include <stdio.h>
main()
{
int a,b,c;
printf("Enter any two numbers\n");
scanf("%d%d",&a,&b);
c=a+b;
printf("Addition of C value is %d\n",c);
}
Output:
Unary operator:
Unary operators act on single operands. C language supports three unary operators. They are:
1. Increment (++)
2. Decrement ( - - )
Output:
21
22
23
#include<stdio.h>
main()
{
int a=21,b;
b=a- -; // First use then change
printf("%d\n",b);
printf("%d\n",a);
b= - - a; // first change then use
printf("%d",b);
}
Output:
21
20
19
Bitwise Operators:
The output of bitwise AND is 1 if the corresponding bits of two operands is 1. If either bit of an operand
is 0, the result of corresponding bit is evaluated to 0.
Example:
The output of bitwise OR is 1 if at least one corresponding bit of two operands is 1. In C Programming,
bitwise OR operator is denoted by |.
The result of bitwise XOR operator is 1 if the corresponding bits of two operands are opposite. It is
denoted by ^.
Example for Bitwise :
#include <stdio.h>
main() {
c=a&b
c = a | b;
c = a ^ b;
c = ~a;
c = a << 2;
c = a >> 2;
Output:
The Value of c is 12
The Value of c is 61
The Value of c is 49
The Value of c is -61
The Value of c is 240
The Value of c is 15
Conditional (or) Ternary operator in C
Syntax:
Expression 1 ? Expression 2 : Expression 3
Where
Expression 1 is Condition
Expression 2 is statement followed of condition is true.
Expression 3 is statement followed of condition is false.
Flowchart:
Example Program:
#include <stdio.h>
main()
{
int num1,num2,large;
printf("Enter two numbers:\n");
scanf("%d%d",&num1,&num2);
large = (num1 > num2) ? num1 : num2;
printf("The large number is %d",large);
}
Output:
Special operator:
There are many special operators use in c programming.
Comma operator.
Size of operator.
Comma operator (,)
The comma operator can be used to link the related expression together. A comma operator
linked list of expression are evaluated left to right and the of right most expression is the value of
the combined expression.
Evaluate of comma operator left to right.
Uses of comma operator as following:
Multiples declaration
Multiples initialization
Multiples variation
Multiples statement
Example of comma operator.
X=12, y=10, z=18;
for(i=0,j=0;i<5,j<5;i++,j++)
Size of operator:
Sizeof operator syntax looks more like a function but it is considered as an operator in c
programming
Program:
#include<stdio.h>
main()
{
int x=10;
printf("Size of x is %d",sizeof(x));
}
Output:
Size of x is 4
1. formatted functions
2. Unformatted functions.
Formatted function:
It read and write all types of data values.
Requires format string to produce formatted result
Returns value after execution.
Formatted input function
Scanf() :
This is formatted i/p function which can read data from the standard i/p device into
the variable in different formats by the user.
The function is used to read data more than one variable at a time.
It reads all types of data values.
It is used for run time assignment of variables.
It requires conversion symbol to identify the data to be read by the program during
execution.
The Ampersand(&) symbol is used to indicate the memory location of the variable.
So that the value read would be placed at that location.
The control string may contain format code, escape sequence & width specifier.
The format code specifies the type of input data.
For each variable there must be a format code.
Syntax:
scanf(“control stirng”&arg1, &arg2, . . . ,&argn);
EX:
#include <stdio.h>
main()
{
int a,b,c;
printf("Enter any two numbers\n");
scanf("%d%d",&a,&b);
c=a+b;
printf("Addition of C value is %d\n",c);
}
Output:
#include<stdio.h>
main()
}
Output:
The fav color: black
First number: 1201
Float number: 77.410000
Unformatted function:
Works only with character data type
Do not require format conversion for formatted data type.
Unformatted input function:
getchar() function will read a single character from the standard input. The return
value of getchar() is the first character in the standard input.The input is read until
the Enter key is pressed, but only the first character in the input will be returned.
getch() reads a single character from the standard input. The input character is not
displayed (echoed) on the screen. Unlike the getchar()function, getch() returns
when the first character is entered and does not wait for the Enter key to be
pressed.
putchar() function will print a single character on standard output. The character
to be printed is passed to putchar() function as an argument. The return value
of putchar() is the character which was written to the output.
Format specifiers.
Format specifiers can be defined as the operators which are used in association
with printf() function for printing the data that is referred by any object or any
variable. When a value is stored within a particular variable then you cannot print
the value stored in the variable straightforwardly without using the format
specifiers. You can retrieve the data that are stored in the variables and can print
them onto the console screen by implementing these format specifiers in a printf()
function.
#include <stdio.h>
main()
{
int num1, num2, max;
return 0;
}
Output:
Enter two numbers: 10
20
Maximum between 10 and 20 is 20
Write a C program to swap (exchange) the values of two variables without using temporary
variable
#include <stdio.h>
main()
{
int x = 10, y = 5;
x = x + y; // x now becomes 15
y = x - y; // y becomes 10
x = x - y; // x becomes 5
return 0;
}
Output:
After Swapping: x = 5, y = 10
Expression Types,
Every expression consists of at least one operand and can have one or more
operators.
Operands are values and Operators are symbols that represent particular actions .
An expression is a combination of constant and operator.
Types:
Infix : Operator is in between operands a+b
Prefix : operator is written before operands +ab
Postfix : operator is written after operands ab+
Precedence of Operators in C
The precedence of operator species that which operator will be evaluated first and next.
The associativity specifies the operators direction to be evaluated, it may be left to right
or right to left. int value=10+20*10;
The value variable will contain 210 because * (multiplicative operator) is evaluated
before + (additive operator).
The precedence and associativity of C operators is given below:
Ex:
#include <stdio.h>
int main()
{
int a,b,c,d;
printf("Enter first number a: \n");
scanf("%d",&a);
printf("Enter second number b: \n");
scanf("%d",&b);
printf("Enter third number c: \n");
scanf("%d",&c);
d=a+b*c;
printf("The value of d =a+b*c is : %d",d);
}
Output:
Enter first number a= 5
Enter second number b= 3
Enter third number c= 4
The value of d=a+b*c is : 17
Explain pre- and post- decrement and increment operation on a variable with an example
Increment Operator in C Programming
Increment operator is used to increment the current value of variable by adding integer 1.
Increment operator can be applied to only variables.
Increment operator is denoted by ++.
Different Types of Increment Operation
In C Programming we have two types of increment operator i.e Pre-Increment and Post-Increment
Operator.
Pre Increment Operator
Pre-increment operator is used to increment the value of variable before using in the expression. In the
Pre-Increment value is first incremented and then used inside the expression.
b = ++y;
In this example suppose the value of variable „y‟ is 5 then value of variable „b‟ will be 6 because the value of
„y‟ gets modified before using it in a expression.
Post Increment Operator
Post-increment operator is used to increment the value of variable as soon as after executing expression
completely in which post increment is used. In the Post-Increment value is first used in a expression and then
incremented.
b = x++;
In this example suppose the value of variable „x‟ is 5 then value of variable „b‟ will be 5 because old value of
„x‟ is used.
Ex
#include<stdio.h>
main()
{
int a,b,x=10,y=10;
a = x++;
b = ++y;
printf("Value of a : %d",a);
printf("Value of b : %d",b);
}
Output :
Value of a : 10
Value of b : 11
Pre-decrement operator is used to decrement the value of variable before using in the expression. In the
Pre-decrement value is first decremented and then used inside the expression.
b = --var;
Suppose the value of variable var is 10 then we can say that value of variable „var‟ is firstly decremented
then updated value will be used in the expression.
Post Decrement Operator
Post-decrement operator is used to decrement the value of variable immediatly after executing expression
completely in which post decrement is used. In the Post-decrement old value is first used in a expression and
then old value will be decrement by 1.
b = var--;
Value of variable „var‟ is 5. Same value will be used in expression and after execution of expression new
value will be 4.
C Program
#include<stdio.h>
main()
{
int a,b,x=10,y=10;
a = x--;
b = --y;
printf("Value of a : %d",a);
printf("Value of b : %d",b);
}
Output :
Value of a : 10
Value of b : 9
An integer is divisible by 9 if the sum of its digits also divisible by 9 write a C program that
prompts the user to input an integer. The program should then output the number and a message
stating whether the number is divisible by 9 or not.
Program:
#include<stdio.h>
main()
{
int num,sum=0,a;
printf("Enter any integer =\n");
scanf("%d",&num);
while(num>10)
{
a=num%10;
sum=sum+a;
num=num/10;
}
if(sum%9==0)
{
printf("It is Divisible by 9\n");
}
else
{
printf("Not Divisible by 9\n");
}
}
Output:
What is meant by type conversion? Why is necessary ? Explain about implicit(coercion) and
explicit (type casting ) type conversion with examples.
Type Conversion in C
A type cast is basically a conversion from one type to another. There are two types of type conversion:
1. Implicit
2. Explicit
1. Implicit Type Conversion Also known as „automatic type conversion‟.
Done by the compiler on its own, without any external trigger from the user.
Generally takes place when in an expression more than one data type is present. In such
condition type conversion (type promotion) takes place to avoid lose of data.
All the data types of the variables are upgraded to the data type of the variable with
largest data type.
It is possible for implicit conversions to lose information, signs can be lost (when signed is
implicitly converted to unsigned), and overflow can occur (when long long is implicitly
converted to float).
Program:
#include<stdio.h>
main()
int x = 10;
char y = 'a';
x = x + y;
float z = x + 1.0;
}
Output:
x = 107, z = 108.000000
This process is also called type casting and it is user defined. Here the user can type cast the result to
make it of a particular data type.
Program:
#include<stdio.h>
main()
double x = 1.2;
Output:
sum = 2
expr1 && expr2 represents a logical AND operation that employs short-circuiting behavior. That
is, expr2 is not evaluated if expr1 is logical 0 (false). Each expression must evaluate to a scalar logical
result.
expr1 || expr2 represents a logical OR operation that employs short-circuiting behavior. That
is, expr2 is not evaluated if expr1 is logical 1 (true). Each expression must evaluate to a scalar logical
result.
Syntax
expr1 && expr2
expr1 || expr2
#include<stdio.h>
main()
{
int a=10,b= -1,i;
i=++a && ++b;
printf("a is %d b is %d i is %d",a,b,i);
}
Output:
a is 11 b is 0 i is 0
#include<stdio.h>
main()
{
int a=10,b=-1,i;
i=++a || ++b;
printf("a is %d b is %d i is %d",a,b,i);
}
Output:
a is 11 b is -1 i is 1
What do you mean by operator precedence and associativity? How one can override operator
precedence defined by c language dive illustrative examples.
Operator precedence determines which operator is performed first in an expression with more than one
operators with different precedence. For example 10 + 20 * 30 is calculated as 10 + (20 * 30) and not as
(10 + 20) * 30.
Associativity is used when two operators of same precedence appear in an expression. Associativity can
be either Left to Right or Right to Left. For example „*‟ and „/‟ have same precedence and their
associativity is Left to Right, so the expression “100 / 10 * 10” is treated as “(100 / 10) * 10”.
Example for override operator precedence
#include <stdio.h>
int main()
{
int a,b,c,d;
printf("Enter first number a: \n");
scanf("%d",&a);
printf("Enter second number b: \n");
scanf("%d",&b);
printf("Enter third number c: \n");
scanf("%d",&c);
d=(a+b)*c;
printf("The value of d =(a+b)*c is : %d",d);
}
Output:
Enter first number a: 5
Enter second number b: 3
Enter third number c: 2
The value of d =(a+b)*c is : 16
Write about statement types in C language.
A statement is a command given to the computer that instructs the computer to take a specific action,
such as display to the screen, or collect input. A computer program is made up of a series of statements
Types of Statements
1. Expression statement
2. Compound Statement
3. Selection statement
4. Iteration statement
5. Jump statement
6. Labeled statement
Mathematical Functions in C
The mathematical functions such as sin, cos, sqrt, log etc., are frequently used in analysis of real-life
problems. Most of the C compilers support these basic math functions.
The following Table lists some standard math functions
Program:
#include <stdio.h>
#include <math.h>
int main()
{
printf("sin 90 = %.0f\n",sin(90));
printf("cos 0= %.0f\n",cos(0));
printf("sqrt(9) = %.0f\n",sqrt(9));
printf("ceil(9.56) = %.2f\n",ceil(9.56));
printf("power(2,3) = %.0f\n",pow(2,3));
printf("Remainder of 9/3 = %.0f\n",fmod(9,3));
}
Output:
sin 90 = 1
cos 0= 1
sqrt(9) = 3
ceil(9.56) = 10.00
power(2,3) = 8
Remainder of 9/3 = 0
Unit-3
Write a C program to find the roots of a quadratic equation ax2+bx+c=0 for all possible
combination values a, b and c .
Program:
#include <stdio.h>
main
{
int a,b,c,d;
float root1,root2;
printf("Enter values for a,b,c=\n");
scanf("%d%d%d",&a,&b,&c);
d=(b*b)-(4*(a*c));
if(d>0)
{
root1=(-b+sqrt(d))/(2*a);
root2=(-b-sqrt(d))/(2*a);
printf("root1=%f\n",root1);
printf("root1=%f\n",root2);
}
else if(d==0)
{
root1=-b/(2*a);
printf("root1=%f",root1);
}
else
{
printf("There are no real roots\n");
}
}
Output 1 :
The Boolean expression are checked one after the other until the first true Boolean expression is
encountered, then the corresponding statement is executed. Program control is then passed to
the statement after the multiway if-else-statement.
if-else statement:
In else if, if the condition is true the statements between if and else if is executed , if the false the
condition in else if checked and if it is true if will be executed, if none of the condition is true the
statement under else is executed.
Flow chart:
Syntax:
if(condition1)
{
//code to be executed if condition1 is true
}else if(condition2)
{
//code to be executed if condition2 is true
}
else if(condition3)
{
//code to be executed if condition3 is true
}
...
Else
{
//code to be executed if all the conditions are false
}
Program:
#include <stdio.h>
main
{
int x,y;
printf("Enter two numbers\n");
scanf("%d%d",&x,&y);
if(x>y)
{
printf("X is big");
}
else if(y>x)
{
printf("Y is big");
}
else
{
printf("Both are equal");
}
}
Output:
Switch:
Switch statement can be matching case statement if matches the values in variable
(switch (variable)) with any of the case inside, the statement under the case that matches will be
executed.
Syntax:
switch(expression)
case 1 : statement(s);
break;
case 2 : statement(s);
break;
case 3 : statement(s);
break;
case 4 : statement(s);
break;
default : statement(s);
Program:
#include <stdio.h>
int main () {
int ch;
scanf("%d",&ch);
switch(ch)
case 1:
printf("A\n" );
break;
case 2 :
printf("B\n" );
break;
case 3 :
printf("C\n" );
break;
case 4 :
printf("D\n" );
break;
default :
printf("Wrong choice\n" );
Output:
#include <stdio.h>
#include<math.h>
long factorial(int p)
{
long f = 1;
for (p; p>=1; p--)
f *= p;
return f;
}
float series(float x)
{
float sum = 0;
int i, s = 1;
for (i = 1; i <= 9; i += 2)
{
sum += (pow((double) x, i) / factorial(i))*s;
s *= -1;
}
return sum;
}
int main( )
{
int x;
printf("Enter the value of x: \n");
scanf("%d", &x);
printf("sin(x) is : %f\n", series(x));
return 0;
}
Output:
Program:
#include<stdio.h>
#include<math.h>
void sine(float*);
float fact(float);
void sine(float *x)
{
float i,j=0;
float sum=0;
for(i=1;i<8;i=i+2)
{
sum=sum+pow(-1,j++)*(pow(*x,i)/fact(i));
}
printf("%f",sum);
}
float fact(float i)
{
float f=1;
while(i>=1)
{
f=f*i;
i--;
}
return f;
}
void main()
{
float x;
printf("Enter the value of x\n");
scanf("%f",&x);
sine(&x);
printf(“”);
}
Output:
Loops are the technique to repeat set of statements until given condition is true. C
programming language has three types of loops
1. For
2. While
3. Dowhile
For loop:
For loop allows code to be repeatedly executed.
The for loop is also used to iterate the statement or a part of the program several times.
For loop has three parts :
Flow chart:
Syntax:
for(initialization;condition;incr/decr)
{
Valid C Statement ;
}
Example for loop:
#include<stdio.h>
main()
{
int i=1;
for(i=1;i<=5;i++)
{
printf("%d\n",i);
}
}
Output:
1
2
3
4
5
While loop:
The while statement continually executes a block of statement while a particular condition is
true.
The while loop is used to iterate the part of program or statements many times.
In while loop, condition is given before the statement. So it is different from the do while loop. It
can execute the statements 0 or more times.
Flow Chart:
Syntax:
while(condition)
{
Valid C Statement ;
Iteration ;
}
Example for While loop :
#include<stdio.h>
main()
{
int i=1;
while(i<=5)
{
printf("%d\n",i);
i++;
}
}
Output:
1
2
3
4
5
do while loop
do while allow the code to be executed at least once based on a given Boolean condition.
To execute a part of program or code several times, we can use do-while loop of C language. The
code given between the do and while block will be executed until condition is true.
In do while loop, statement is given before the condition, so statement or code will be executed
at lease one time.
Flow chart:
Syntax:
do
{
Valid C Statement ;
}while(condition);
Example for do while loop
#include<stdio.h>
main()
{
int i=1;
do
{
printf("%d\n",i);
i++;
} while(i<=5);
}
Output:
1
2
3
4
5
Write a C program to sum of first and last digit of a number.
#include <stdio.h>
main()
{
int num, temp, firstDigit, lastDigit;
printf("Enter a Number\n");
scanf("%d", &num);
temp = num;
lastDigit = num %10;
while(num > 10){
num = num/10;
}
firstDigit = num;
printf("Sum of first and last digit of %d = %d", temp, firstDigit+lastDigit);
return 0;
}
Output:
Enter a Number 19
Sum of first and last digit of 19 = 10
Write the difference between entry controlled (called pretest) loop and exit controlled (called
posttest) Loops
Loops are the technique to repeat set of statements until given condition is true. C programming
language has three types of loops
1. for
2. while
3. dowhile
These loops controlled either at entry level or at exit level hence loops can be controlled two ways
Loop, where test condition is checked before entering the loop body, known as Entry Controlled
Loop.
Example: while loop, for loop
For loop:
For loop allows code to be repeatedly executed.
The for loop is also used to iterate the statement or a part of the program several times.
For loop has three parts :
#include<stdio.h>
main()
{
int i=1;
while(i<=5)
{
printf("%d\n",i);
i++;
}
}
Output:
1
2
3
4
5
Exit Controlled Loop
Loop, where test condition is checked after executing the loop body, known as Exit Controlled
Loop.
Example: do while loop
do while loop
do while allow the code to be executed at least once based on a given Boolean condition.
To execute a part of program or code several times, we can use do-while loop of C language. The
code given between the do and while block will be executed until condition is true.
In do while loop, statement is given before the condition, so statement or code will be executed
at lease one time.
Syntax:
do
{
Valid C Statement ;
}while(condition);
Test condition is checked first, and then loop Loop body will be executed first, and then
body will be executed. condition is checked.
If Test condition is false, loop body will not be If Test condition is false, loop body will be
executed. executed once.
for loop and while loop are the examples of do while loop is the example of Exit
Entry Controlled Loop. controlled loop.
Entry Controlled Loops are used when Exit Controlled Loop is used when checking
checking of test condition is mandatory before of test condition is mandatory after executing
executing loop body. the loop body.
#include<stdio.h>
main()
{
int count;
for( count=1; count<=10; count++)
{
printf("%d",count);
}
}
Output:
1 2 3 4 5 6 7 8 9 10
#include<stdio.h>
main()
int num,sum=0,a;
scanf("%d",&num);
while(num>10)
a=num%10;
sum=sum+a;
num=num/10;
if(sum%9==0)
else
Output:
o If statement
o If-else statement
o If else-if
o Nested if
If Statement
The single if statement in C language is used to execute the code if condition is true.
An expression which returns only two value either true or false is known as Boolean type
expression.
Flow chart:
Syntax:
if(condition)
{
Valid C statement ;
}
Program:
#include <stdio.h>
main()
{
int a=20,b=21;
if(a<b)
{
printf("a is less then b\n");
}
}
Output:
a is less then b
If-else Statement
The if-else statement in C language is used to execute the code if condition is true or false.
If the given condition is true then the true part is executed otherwise false part is executed.
Flow chart:
Syntax:
if(expression){
//code to be executed if condition is true
}else{
//code to be executed if condition is false
}
Program:
#include <stdio.h>
main()
{
int num;
printf("Enter any number\n");
scanf("%d",&num);
if(num%2==0)
{
printf("Even number\n");
}
else
{
printf("Odd number\n");
}
}
Output:
if-else if statement:
In else if, if the condition is true the statements between if and else if is executed , if the false the
condition in else if checked and if it is true if will be executed, if none of the condition is true the
statement under else is executed.
Flow chart:
Syntax:
if(condition1)
{
//code to be executed if condition1 is true
}else if(condition2)
{
//code to be executed if condition2 is true
}
else if(condition3)
{
//code to be executed if condition3 is true
}
...
Else
{
//code to be executed if all the conditions are false
}
Program:
#include <stdio.h>
main
{
int x,y;
printf("Enter two numbers\n");
scanf("%d%d",&x,&y);
if(x>y)
{
printf("X is big");
}
else if(y>x)
{
printf("Y is big");
}
else
{
printf("Both are equal");
}
}
Output:
Nested loop:
We many use loop statement inside another looping statement this type of looping is called nested
loop
Nested loop the inner loop is executed first and then other the nested loop must be used to input or
output multi dimensional array elements.
Syntax:
for(i=1;i<=5;i++)
Valid c statement ;
for(j=1;j<=i ;j++)
Valid c statement ;
Example :
#include <stdio.h>
main()
{
int n=5,i,j;
for(i=1;i<=n;i++)
for(j=1;j<=i;j++)
printf("%3d",j);
printf("\n");
Output:
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
#include<stdio.h>
main()
int n,coef=1,space,i,j;
printf("Enter no of rows\n");
scanf("%d",&n);
for(i=0;i<n;i++)
for(space=1;space<=n-i;space++)
printf(" ");
for(j=0;j<=i;j++)
{
if(j==0||i==0)
coef=1;
else
coef=coef*(i-j+1)/j;
printf("%4d",coef);
printf("\n");
Output:
Enter no of rows 5
1 1
1 2 1
1 3 3 1
1 4 6 4 1
#include<stdio.h>
main()
int n=5,i,j,k=1;
for(i=1;i<=n;i++)
for(j=1;j<=i;j++)
printf("%3d",k++);
printf("\n");
Output:
2 3
4 5 6
7 8 9 10
11 12 13 14 15
#include<stdio.h>
main()
int num,rem,sum=0,temp;
scanf("%d",&num);
temp=num;
while(num>0)
rem=num%10;
sum=sum+(rem*rem*rem);
num=num/10;
}
if(temp==sum)
printf("Arstrong number\n");
else
Output:
Arstrong number
#include<stdio.h>
main()
int n,i,count=0;
scanf("%d",&n);
for(i=1;i<=n;i++)
if(n%i==0)
count++;
}
if(count==2)
printf("prime number\n");
else
Output:
prime number
/*This program for displaying or printing the leap year or not a leap year */
#include<stdio.h>
main()
int year;
scanf("%d",&year);
if (year%4==0)
else
Output:
When break is executed the statement following break are skipped and cause the loop to be
terminated
Syntax:
jump-statement;
break;
Program:
#include <stdio.h>
main()
int i=1;
for(i=1;i<=10;i++)
if(i==5)
break;
printf("%d\n",i);
Output:
1
2
3
4
5
Continue statement:
When continue statement is executed, the statements following continue are skipped and cause
the loop to be continued with the next iteration
Syntax:
jump-statement;
continue;
Program:
#include <stdio.h>
main(){
int i=1;
for(i=1;i<=10;i++)
{
if(i==5)
{
continue;
}
printf("%d\n",i);
}
}
Output:
1
2
3
4
6
7
8
9
10
Difference between break and continue Statement.
Break Continue
When continue statement is executed, the
When break is executed the statement following statements following continue are skipped and
break are skipped and cause the loop to be terminated cause the loop to be continued with the next
iteration
It can be used in switch statement to transfer the It cannot be used inside a switch statement.
control outside switch It is used only with loops
Leave current block also used to leave case statement only used in loops to continue with next loop
in switch immediately
EX: EX:
for(i=1;i<=10;i++) for(i=1;i<=10;i++)
{ {
if(i==5) if(i==5)
break; {
printf("%d\n",i); continue;
} }
printf("%d\n",i);
goto Statement:
In C programming provides an unconditional jump from the goto to a labeled statement in the
same function.
The goto statement can be used to jump from anywhere to anywhere within a function.
The goto statement is used to alter the normal sequence of program execution by transferring control
to some other part of the program unconditionally.
Syntax:
goto label;
Program:
#include <stdio.h>
main ()
int a = 10;
LOOP:do {
if( a == 15) {
a = a + 1;
goto LOOP;
a++;
}while( a < 20 );
Output:
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 16
value of a: 17
value of a: 18
value of a: 19
Difference between while and dowhile loop
Introduction To Arrays:
In C programming, one of the frequently problem is to handle similar types of data. For example: if the
user wants to store marks of 500 students, this can be done by creating 500 variables individually but,
this is rather tedious and impracticable. These types of problem can be handled in C programming using
arrays.
An array in C Programing can be defined as number of memory locations, each of which can store the
same data type and which can be references through the same variable name. It is a collective name
given to a group of similar quantities. These similar quantities could be marks of 500 students, number
of chairs in university, salaries of 300 employees or ages of 250 students. Thus we can say array is a
sequence of data item of homogeneous values (same type). These values could be all integers, floats or
characters etc.
1. One-dimensional arrays.
2. Multidimensional arrays.
data_type array_name[array_size];
Here “data_type” is the type of the array we want to define, “array_name” is the name given to the
array and “array_size” is the size of the array that we want to assign to the array. The array size is always
mentioned inside the “[]”.
For example:
Int age[5];
Initializing Arrays
Initializing of array is very simple in c programming. The initializing values are enclosed within the curly
braces in the declaration and placed following an equal sign after the array name. Here is an example
which declares and initializes an array of five elements of type int. Array can also be initialized after
declaration. Look at the following code, which demonstrate the declaration and initialization of an array.
int age[5]={2,3,4,5,6};
int age[]={2,3,4,5,6};
In this case, the compiler determines the size of array by calculating the number of elements of an array.
For example:
scanf("%d",&age[2]);
//statement to insert value in the third element of array age[]
printf("%d",age[2]);
//statement to print third element of an array.
Arrays can be accessed and updated using its index.An array of n elements, has indices ranging from 0 to
n-1. An element can be updated simply by assigning
A[i] = x;
A great care must be taken in dealing with arrays. Unlike in Java, where array index out of bounds
exception is thrown when indices go out of the 0..n-1 range, C arrays may not display any warnings if out
of bounds indices are accessed. Instead,compiler may access the elements out of bounds, thus leading
to critical run time errors.
Example of array in C programming
#include <stdio.h>
int main(){
int i,n;
int marks[n];
int sum=0;
for(i=0;i<n;i++){
printf("Enter marks of student%d: ",i+1);
scanf("%d",&marks[i]); //saving the marks in array
sum+=marks[i];
}
return 0;
Output :
Sum of marks = 50
int smarks[3][4];
Here, smarks is an array of two dimension, which is an example of multidimensional array. This array has
3 rows and 4columns. For better understanding of multidimensional arrays, array elements of above
example can be as below:
Make sure that you remember to put each subscript in its own, correct pair of brackets. All three
examples below are wrong.
This program asks user to enter the size of the matrix (rows and column) then, it asks the user to enter
the elements of two matrices and finally it adds two matrix and displays the result.
int main(){
int r,c;
int a[r][c];
int b[r][c];
int sum[r][c;
for(int i=0;i<r;++i){
for(int j=0;j<c;++j){
printf("Enter element a%d%d: ",i+1,j+1);
scanf("%d",&a[i][j]);
}
}
for(int i=0;i<r;++i)
for(int j=0;j<c;++j)
sum[i][j]=a[i][j]+b[i][j];
return 0;
Program Output:
Enter number of rows (between 1 and 100): 3
Enter number of rows (between 1 and 100): 2
8 -11
17 6
5 5
Searching
Search is a process of finding a value in a list of values. In other words, searching is the
process of locating given value position in a list of values. Searching is a process of finding a
particular element among several given elements.
The searching of an element in a given array can be done in two ways-
Linear Search
Binary Search
Step 2 - Compare the search element with the first element in the list.
Step 3 - If both are matched, then display "Given element is found!!!" and terminate the
function.
Step 4 - If both are not matched, then compare search element with the next element in the list.
Step 5 - Repeat steps 3 and 4 until search element is compared with last element in the list.
Step 6 - If last element in the list also doesn't match, then display "Element is not found!!!" and
terminate the function.
Example
Consider the following list of elements and the element to be searched...
Program
Write a C program for searching element by using linear search.
#include <stdio.h>
int main()
{
int array[100], search,i,n;
printf("Enter number of elements in array\n");
scanf("%d", &n);
printf("Enter Array Elements”);
for (i = 0; i < n; i++)
scanf("%d", &array[i]);
printf("Enter a number to search\n");
scanf("%d", &search);
for (i = 0; i < n; i++)
{
if (array[i] == search
{
printf("%d is present at location %d.\n", search, i+1);
break;
}
}
if (i == n)
printf("%d isn't present in the array.\n", search);
return 0;
}
Output
Enter number of elements in array
10
Enter Array Elements
1 2 3 4 5 6 7 8 9 10
Enter a number to search
8
8 is present at location 8.
So we replace 14 with 10. After one iteration10, which happens to be the minimum value in the
list, appears in the first position of the sorted list.
For the second position, where 33 is residing, we start scanning the rest of the list in a linear
manner.
We find that 14 is the second lowest value in the list and it should appear at the second place. We
swap these values.
After two iterations, two least values are positioned at the beginning in a sorted manner.
The same process is applied to the rest of the items in the array.
Following is a pictorial depiction of the entire sorting process −
Write a C program to arrange elements in an asecending order using Selection Sort
Technique
#include <stdio.h>
int main()
{
int array[100], n, i, j, position, swap;
return 0;
}
OUT PUT
Enter number of elements
5
Enter integers
10 50 20 40 30
Sorted list in ascending order
10 20 30 40 50
BUBBLE SORT
Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping
the adjacent elements if they are in wrong order.
Example:
First Pass:
( 5 1 4 2 8 ) –> ( 1 5 4 2 8 ),
Here, algorithm compares the first two elements, and swaps since 5 > 1.
( 1 5 4 2 8 ) –> ( 1 4 5 2 8 ), Swap since 5 > 4
( 1 4 5 2 8 ) –> ( 1 4 2 5 8 ), Swap since 5 > 2
( 1 4 2 5 8 ) –> ( 1 4 2 5 8 ),
Now, since these elements are already in order (8 > 5), algorithm does not swap them.
Second Pass:
( 1 4 2 5 8 ) –> ( 1 4 2 5 8 )
( 1 4 2 5 8 ) –> ( 1 2 4 5 8 ), Swap since 4 > 2
( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )
( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )
Now, the array is already sorted, but our algorithm does not know if it is completed. The
algorithm needs one whole pass without any swap to know it is sorted.
Third Pass:
( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )
( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )
( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )
( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )
#include<stdio.h>
int main()
scanf("%d", &n);
scanf("%d", &a[i]);
if(a[j]>a[j+1])
{
temp=a[j];
a[j]=a[j+1];
a[j+1]=temp;
return 0;
Expected Output:
A
r
r
a
y
e
l
e
m
e
n
t