You are on page 1of 123

INTRODUCTION

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

Block diagram of a Computer :

CENTRAL PROCESSING UNIT

Memory unit

INPUT DEVICE ALU


OUT PUT DEVICE

Control Unit

The various functions of these units can be summarized as:

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 :

 Alphanumeric keys , including letters & numbers.

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

Scanners are of two types: i) optical scanners ii) MICR


i) Optical scanners:
a. Optical character Recognition(OCR): In this, characters are read with the help of a light. This is
used in office atomization, documentation in library etc.
b. Optical mark recognition(OMR): It is a technology where an OMR device senses the presence or
absence of a mark such as a pencil mark. OMR is used in tests such as aptitude tests.
c. Optical barcode recognition(OBCR): Barcode readers are photoelectric scanners that read the bar
codes or vertical zebra striped marks printed on product containers. This is used in super markets, book
shops etc.
ii. MICR: This is widely used in banks to process the cheques. This allows the computer to recognize
characters printed using magnetic ink.
6
4. Magnetic Ink Character Recognition(MICR): : It is a character recognition technology used
primarily by the banking industry to facilitate the processing of the cheques. MICR characters ( cheque
No., Acc.No.etc) are printed in special ink usually containing iron oxide. When a document that
contains the ink needs to be read, it passes through a machine which magnetizes the ink and there will
be a reader sorter unit which translates the magnetic information into characters. MICR provides a
secure, high speed of scanning and processing information. It scans about 2600 cheques/min.

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.

Some important Output devices are : Monitor, Printer

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.

3. Cost per bit of storage.

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

210 (or) 1024 Bytes = 1 Kilo Byte (KB)

210 (or)1024 KB = 1 Mega Byte (MB)

210 (or)1024 MB = 1 Gega Byte (GB)

Conversion :

ASCII – American Standard Code for Information Interchange.

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:

Random Access Memory (RAM) and Read- Only Memory (ROM )


RAM:
RAM is also known as read/write memory as information can be read from and written onto it. RAM is
a place in a computer that holds instructions for the computer, its programs and the data. The CPU can
directly access the data from RAM almost immediately. However, the storage of data and instructions in
RAM is temporary, till the time the computer is running. It disappears from RAM as soon as the power
to the computer is switched off. i.e it is volatile memory.

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.

There are five categories of software. They are:

1. Operating System 2. Translators 3. Utility programs 4. Application programs


5. General purpose programs

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 .

 UNIX AND XENIX: It is suited for multi-user and multi-task system

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.

The major difference between compiler and interpreter is

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

Programming Languages: There are three types of programming languages.

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.

Several High Level Languages which are in common use:


FORTRAN : FORmula TRANslation
COBOL : Common Business Oriented Language
BASIC : Beginner‘s All purpose Symbolic Instruction Code
PROLOG: PROgramming in LOGic
ALGOL : ALGOrithmic Language
3. Utility Programs: These are pre-written programs supplied by the manufacturer for maintaining day
to day activities of computer system.

Example: COPY, SORT, MAILING, virus scanning software etc.,

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.

Example: Payroll, Billing, Railway Reservation etc.


12
5. General Purpose Packages: These packages are developed to suit the needs of research workers /
scientists in different fields. These packages are categorized as :

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.

Functions of Operating System :


Today most operating systems perform the following important functions :

1. Processor management : It manages the assignment of processor to different tasks being


performed by the computer system.

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.

6. Interpretation of commands and instructions.

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:

1. Analog Computes 2. Digital Computers 3. Hybrid Computers


1. Analog computers: They operate by ―measuring‖ instead of ―counting‖. The name (derived
from greek word analog) denotes that the computer functions by establishing similarities between
the two quantities. They are powerful tools for solving differential equations.

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 b) Mainframe Computers c) Mini Computers d) Micro Computers

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

Algorithm has the following characteristics

• Input: An algorithm may or may not require input

• Output: Each algorithm is expected to produce at least one result

• Definiteness: Each instruction must be clear and unambiguous.

• Finiteness: If the instructions of an algorithm are executed, the algorithm


should terminate after finite number of steps

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

• It is a step-wise representation of a solution to a given problem, which makes it easy


to understand.
• An algorithm uses a definite procedure.
• It is not dependent on any programming language, so it is easy to understand for
anyone even without programming knowledge.
• Every step in an algorithm has its own logical sequence so it is easy to debug.

3 CIC-UHF
Algorithm & Flowchart Manual

HOW TO WRITE ALGORITHMS

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:

• Flowchart is an excellent way of communicating the logic of a program.


• Easy and efficient to analyze problem using flowchart.
• During program development cycle, the flowchart plays the role of a blueprint, which
makes program development process easier.
• After successful development of a program, it needs continuous timely maintenance
during the course of its operation. The flowchart makes program or system
maintenance easier.
• It is easy to convert the flowchart into any programming language code.

4 CIC-UHF
Algorithm & Flowchart Manual

Flowchart is diagrammatic /Graphical representation of sequence of steps to solve a


problem. To draw a flowchart following standard symbols are use

Symbol Name Symbol function

Used to represent start and


Oval end of flowchart

Used for input and output


Parallelogram
operation

Processing: Used for


Rectangle arithmetic operations and
data-manipulations

Decision making. Used to


represent the operation in
Diamond which there are two/three
alternatives, true and false
etc

Flow line Used to indicate


Arrows the flow of logic by
connecting symbols

Circle Page Connector

Off Page Connector

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

Assignment Symbol (  or =) is used to assign value to the variable.

e.g. to assign value 5 to the variable HEIGHT, statement is

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:

Operator Meaning Example


+ Addition A+B
- Subtraction A–B
* Multiplication A*B
/ Division A/ B
^ Power A^3 for A3
% Reminder A%B

Relational Operators

Operator Meaning Example


< Less than A<B
<= Less than or equal to A <= B
= or == Equal to A = B
# or != Not equal to A # B or A !=B
> Greater than A>B
>= Greater tha or equal to A >= B

6 CIC-UHF
Algorithm & Flowchart Manual

Logical Operators

Operator Example Meaning


AND A < B AND B < C Result is True if both A<B and
B<C are true else false
OR A< B OR B < C Result is True if either A<B or
B<C are true else false
NOT NOT (A >B) Result is True if A>B is false
else true

Selection control Statements

Selection Control Example Meaning


IF ( Condition ) Then IF ( X > 10 ) THEN If condition X>10 is True
… Y=Y+5 execute the statement
ENDIF ENDIF between THEN and ENDIF

IF ( Condition ) Then IF ( X > 10 ) THEN If condition X>10 is True


… Y=Y+5 execute the statement
ELSE ELSE between THEN and ELSE
….. Y=Y+8 otherwise execute the
Z=Z+3 statements between ELSE
ENDIF ENDIF and ENDIF

Loop control Statements

Selection Control Example Meaning


WHILE (Condition) WHILE ( X < 10) Execute the loop as long as
DO DO the condition is TRUE
.. print x
.. x=x+1
ENDDO ENDDO
DO DO Execute the loop as long as
…. print x the condition is false
… x=x+1
UNTILL (Condition) UNTILL ( X >10)

GO TO statement also called unconditional transfer of control statement is used to transfer


control of execution to another step/statement. . e.g. the statement GOTO n will transfer
control to step/statement n.

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 & Flowchart to find the sum of two numbers

Algorithm

Step-1 Start

Step-2 Input first numbers say A

Step-3 Input second number say B

Step-4 SUM = A + B

Step-5 Display SUM

Step-6 Stop

OR

Algorithm

Step-1 Start

Step-2 Input two numbers say A & B

Step-3 SUM = A + B

Step-4 Display SUM

Step-5 Stop

8 CIC-UHF
Algorithm & Flowchart Manual
..

Algorithm & Flowchart to convert temperature from Celsius to Fahrenheit

C : temperature in Celsius
F : temperature Fahrenheit

Algorithm

Step-1 Start

Step-2 Input temperature in Celsius say C

Step-3 F = (9.0/5.0 x C) + 32

Step-4 Display Temperature in Fahrenheit F

Step-5 Stop

Algorithm & Flowchart to convert temperature from Fahrenheit to Celsius

C : temperature in Celsius
F : temperature Fahrenheit

Algorithm

Step-1 Start

Step-2 Input temperature in Fahrenheit say F

Step-3 C = 5.0/9.0 (F - 32 )

Step-4 Display Temperature in Celsius C

Step-5 Stop

9 CIC-UHF
Algorithm & Flowchart Manual
..

Algorithm & Flowchart to find Area and Perimeter of Square

L : Side Length of Square


AREA : Area of Square
PERIMETER : Perimeter of Square

Algorithm

Step-1 Start

Step-2 Input Side Length of Square say L

Step-3 Area = L x L

Step-4 PERIMETER = 4 x L

Step-5 Display AREA, PERIMETER

Step-6 Stop

Algorithm & Flowchart to find Area and Perimeter of Rectangle

L : Length of Rectangle
B : Breadth of Rectangle
AREA : Area of Rectangle
PERIMETER : Perimeter of Rectangle

Algorithm

Step-1 Start

Step-2 Input Side Length & Breadth say L, B

Step-3 Area = L x B

Step-4 PERIMETER = 2 x ( L + B)

Step-5 Display AREA, PERIMETER

Step-6 Stop

10 CIC-UHF
Algorithm & Flowchart Manual
..

Algorithm & Flowchart to find Area and Perimeter of Circle

R : Radius of Circle
AREA : Area of Circle Start

PERIMETER : Perimeter of Circle

Input Value
Algorithm of R

Step-1 Start
AREA = 22.0/7.0
Step-2 Input Radius of Circle say R xRx R

Step-3 Area = 22.0/7.0 x R x R


PERIMTER = 2 X
22.0/7.0 x R
Step-4 PERIMETER = 2 x 22.0/7.0 x R

Step-5 Display AREA, PERIMETER


Pr int A REA,
Step-6 Stop PER I M T ER

Stop

Algorithm & Flowchart to find Area & Perimeter of Triangle


(when three sides are given)

A : First Side of Triangle


B : Second Side of Triangle
C : Third Side of Triangle
AREA : Area of Triangle
PERIMETER : Perimeter of Triangle

Algorithm

Step-1 Start

Step-2 Input Sides of Triangle A,B,C

Step-3 S= (A + B + C)/ 2.0

Step-4 AREA = SQRT(S x (S-A) x (S-B) x(S-C))

Step-5 PERIMETER = S1 + S2 + S3

Step-6 Display AREA, PERIMETER

Step-7 Stop

11 CIC-UHF
Algorithm & Flowchart Manual
..

Algorithm & Flowchart to find Simple Interest

P : Principle Amount
N : Time in Years
R : % Annual Rate of Interest
SI : Simple Interest

Algorithm

Step-1 Start

Step-2 Input value of P, N, R

Step-3 SI = (P x N x R)/100.0

Step-4 Display SI F

Step-6 Stop

Algorithm & Flowchart to find Compound Interest

P : Principle Amount
N : Time in Years
R : % Annual Rate of Interest
CI : Compound Interest

Algorithm

Step-1 Start

Step-2 Input value of P, N, R C

Step-3 CI = P(1+R/100)N - P

Step-4 Display CI

Step-6 Stop

..

12 CIC-UHF
Algorithm & Flowchart Manual
..

Algorithm & Flowchart to Swap Two Numbers using Temporary Variable

Algorithm

Step-1 Start

Step-2 Input Two Numbers Say NUM1,NUM2

Step-3 Display Before Swap Values NUM1, NUM2

Step-4 TEMP = NUM1

Step-5 NUM1 = NUM2

Step-6 NUM2 = NUM1

Step-7 Display After Swap Values NUM1,NUM

Step-8 Stop

Algorithm & Flowchart to Swap Two Numbers without using temporary


variable

Algorithm

Step-1 Start

Step-2 Input Two Numbers Say A,B

Step-3 Display Before Swap Values A, B

Step-4 A=A+B

Step-5 B=A-B

Step-6 A=A-B

Step-7 Display After Swap Values A, B

Step-8 Stop

13 CIC-UHF
Algorithm & Flowchart Manual
..

Algorithm & Flowchart to find the smallest of two numbers

Algorithm

Step-1 Start

Step-2 Input two numbers say

NUM1,NUM2

Step-3 IF NUM1 < NUM2 THEN

print smallest is NUM1

ELSE

print smallest is NUM2

ENDIF

Step-4 Stop

Algorithm & Flowchart to find the largest of two numbers

Algorithm
Start
Step-1 Start

Step-2 Input two numbers say


I nput V alue
NUM1,NUM2 of NUM1

Step-3 IF NUM1 > NUM2 THEN

print largest is NUM1 Input Value


of NUM2
ELSE

print largest is NUM2 Print Yes if No Print


Largest is NUM1 > NUM2
Largest is
NUM1 NUM2
ENDIF

Step-4 Stop

Stop

14 CIC-UHF
Algorithm & Flowchart Manual
..

Algorithm & Flowchart to find the largest of three numbers

Algorithm

Step-1 Start

Step-2 Read three numbers say num1,num2, num3

Step-3 if num1>num2 then go to step-5

Step-4 IF num2>num3 THEN


print num2 is largest
ELSE
print num3 is largest
ENDIF
GO TO Step-6
Step-5 IF num1>num3 THEN
print num1 is largest
ELSE
print num3 is largest
ENDIF
Step-6 Stop

15 CIC-UHF
Algorithm & Flowchart Manual
..

Algorithm & Flowchart to find the largest of three numbers (an another way)

Algorithm

Step-1 Start

Step-2 Read three numbers say A,B,C

Step-3 BIG = A

Step-4 IF B > BIG THEN

BIG = B

ENDIF

Step-5 IF C >BIG THEN

BIG = C

ENDIF

Step-6 Write BIG

Step-7 Stop

16 CIC-UHF
Algorithm & Flowchart Manual
..

Algorithm & Flowchart to find Even number between 1 to 50

Algorithm

Step-1 Start

Step-2 I=1

Step-3 IF (I >50) THEN


GO TO Step-7
ENDIF
Step-4 IF ( (I % 2) =0) THEN
Display I
ENDIF
Step-5 I=I+1

Step-6 GO TO Step--3

Step-7 Stop

Algorithm & Flowchart to find Odd numbers between 1 to n where n is a


positive Integer

Algorithm

Step-1 Start

Step-2 Input Value of N

Step-3 I=1

Step-4 IF (I >N) THEN


GO TO Step-8
ENDIF
Step-5 IF ( (I % 2)=1) THEN
Display I
ENDIF
Step-6 I=I+1

Step-7 GO TO Step-4

Step-8 Stop

17 CIC-UHF
Algorithm & Flowchart Manual

..

Algorithm & Flowchart to find sum of series 1+2+3+…..+N

Algorithm

Step-1 Start

Step-2 Input Value of N

Step-3 I = 1, SUM=0

Step-4 IF (I >N) THEN


GO TO Step-8
ENDIF
Step-5 SUM = SUM + I

Step-6 I=I+1

Step-7 Go to step-4

Step-8 Display value of SUM

Step-9 Stop

Algorithm & Flowchart to find sum of series 1+3+5+…..+N, Where N is positive


odd Integer
Algorithm

Algorithm

Step-1 Start

Step-2 Input Value of N

Step-3 I = 1, SUM=0

Step-4 IF (I >N) THEN


GO TO step 8
ENDIF
Step-5 SUM = SUM + I

Step-6 I=I+2

Step-7 Go to step-4

Step-8 Display value of SUM

Step-9 Stop

18 CIC-UHF
Algorithm & Flowchart Manual
..

Algorithm & Flowchart to find sum of series 1 – X + X2 –X3 ….XN

Algorithm

Step-1 Start

Step-2 Input Value of N, X

Step-3 I = 1, SUM=1, TERM=1

Step-4 IF (I >N) THEN


GO TO Step-9
ENDIF
Step-5 TERM = - TERM * X

Step-6 SUM = SUM + TERM

Step-7 I=I+1

Step-8 Go to step-4

Step-9 Display value of SUM

Step-10 Stop

Algorithm & Flowchart to print multiplication Table of a number

Algorithm

Step-1 Start

Step-2 Input Value of NUM

Step-3 I=1

Step-4 IF (I >10) THEN


GO TO Step 9
ENDIF
Step-5 PROD = NUM * I

Step-6 WRITE I “x” NUM “=” PROD

Step-7 I=I+1

Step-8 Go to step-4

Step-9 Stop

19 CIC-UHF
Algorithm & Flowchart Manual

..

Algorithm & Flowchart to generate first n Fibonacci terms 0,1,1,2,3,5…n (n>2)

Algorithm

Step-1 Start

Step-2 Input Value of N

Step-3 A=0, B=1, COUNT=2

Step-4 WRITE A, B

Step-5 IF (COUNT >N) then go to step 12

Step-6 NEXT= A + B

Step-7 WRITE NEXT

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-4 Input NUM (next number in series)

Step-5 SUM= SUM +NUM

Step-6 COUNT=COUNT+1

Step-7 IF More Number in Series then

GOTO Step-4

ENDIF

Step-8 AVERGAE=SUM / COUNT

Step-9 WRITE SUM, AVERAGE

Step-10 Stop

21 CIC-UHF
Algorithm & Flowchart Manual
..

Algorithm & Flowchart to find Roots of Quadratic Equations AX2+BX+C=0

Algorithm

Step-1 Start

Step-2 Input A,B,C

Step-3 DISC= B2 – 4 A * C

Step-4 IF (DISC < 0) THEN


Write Roots are Imaginary
Stop
ENDIF
Step-5 IF (DISC==0) THEN
Write Roots are Real and Equal
X1 = - B/(2*A)
Write Roots are X1,X1
Stop
ENDIF
Step-6 IF (DISC >0)

Write Roots are Real and Unequal

X1= (- B + SQRT(DISC)) / (2*A)

X2= (- B + SQRT(DISC)) / (2*A)

Write Roots are X1,X2

Stop

ENDIF

22 CIC-UHF
Algorithm & Flowchart Manual
..

Algorithm & Flowchart to find if a number is prime or not

Algorithm

Step-1 Start

Step-2 Input NUM

Step-3 R=SQRT(NUM)

Step-4 I=2

Step-5 IF ( I > R) THEN


Write NUM is Prime Number
Stop
ENDIF
Step 6 IF ( NUM % I ==0) THEN
Write NUM is Not Prime
Stop
ENDIF
Step-7 I=I+1

Step-8 Go to Step-5

23 CIC-UHF
Algorithm & Flowchart Manual
..

Algorithm & Flowchart to find GCD and LCM of two numbers

Algorithm

Step-1 Start

Step-2 Read two number A, B

Step-3 IF (A > B) THEN


N =A
D=B
ELSE
N=B
D=A
ENDIF
Step-4 r=N/D

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-8 Display gcd, lcm

Step-9 Stop

24 CIC-UHF
Algorithm & Flowchart Manual

Algorithm & Flowchart to find Factorial of number n ( n!=1x2x3x…n)

Algorithm

Step-1 Start

Step-2 Read number N

Step-3 FACT=1 CTRL=1


Step-4 WHILE (CTRL <= N)
DO
FACT=FACT*I
CTRL=CTRL+1
DONE
Step-5 Display FACT

Step-6 Stop

Algorithm & Flowchart to find all the divisor of a number

Algorithm

Step-1 Start

Step-2 Read number N

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

printf("This is main function");

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.

 ! Operator – It is used to reverses the state of the operand.

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

Enter any two numbers : 10


10
Addition of C value is 20

Unary operator:
Unary operators act on single operands. C language supports three unary operators. They are:
1. Increment (++)
2. Decrement ( - - )

Increment operator (++):


 Increment operators are increase the value of subsequent.
 Increment operator are two types as follows:
 Post increment (Ex: X=5; X++; X=5.)
 Pre increment (Ex: X=5; ++X; X=6.)
Program:
#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
22
23

Decrement operator (--).


 Decrement operators decrease the value to one, two and so on.
 Decrement operators are also two type as:
 Post increment (Ex: X=5; X--; X=5.)
 Pre increment (Ex: X=5; --X; X=4.)
Program:

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

 Bitwise operators operate on individual bits of integer(int and long) values.


 If an operand is shorter than an int, it is promoted to int before doing the operations.
Bitwise AND operator &

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:

bitwise AND operation of two integers 12 and 25.


Bitwise OR operator |

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

Bitwise XOR (exclusive OR) operator ^

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

int a = 60, b = 13,c ;

c=a&b

printf("The Value of c is %d\n", c );

c = a | b;

printf("The Value of c is %d\n", c );

c = a ^ b;

printf("The Value of c is %d\n", c );

c = ~a;

printf("The Value of c is %d\n", c );

c = a << 2;

printf("The Value of c is %d\n", c );

c = a >> 2;

printf("The Value of c is %d\n", c );

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

 Conditional operator in c is also known as ternary operators


 It is called ternary operator because it takes 3 arguments
 Main features of conditional operator as follows:
 There are three operand.
 It works from left to right.
 Example of ternary operator is conditional operator. Symbol of conditional operator
 Condition ? True_parts : False_parts

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:

/* Find the largest among two numbers using conditional operator */

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

Enter two numbers : 10


15
The large number is 15

 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 is used to calculate the size of data type or variables.

 Sizeof operator can be nested.

 Sizeof operator will return the size in integer format.

 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

 Formatted input/output Functions in C


Reading data from input device and displaying the result on
the screen are the two main tasks of any programming. In „C‟ language the input output
operations are carried out by using standard functions. The programs for these functions
are kept in the file . this file must be included in the program to use these functions using
the pre processor directive as: #include
The i/o functions are classified into 2 types :

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:

Enter any two numbers : 10


10
Addition of C value is 20
Formatted output function
Printf():–
Pritnf() function is used to print the data (or) more than one data item in
different formats on the standard o/p device.
Syntax:–
printf(“control string”, arg1, arg2,….,argn);

Control string consists of 3 types of items:


 Characters that will be printed on the screen as they appear .
 Format specifications that define the o/p format for display of each item.
 Escape sequence characters such as \n, \t & \b.
The control string indicates how many arguments follow & printed according
to the specifications of the control string.
The arguments should match in number, order and type with format
specifications.
EX:

#include<stdio.h>

main()

printf("The fav color: %s\n", "black");

printf("First number: %d\n",1201);

printf("Float number: %f\n",77.41);

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

 getche() is same as getch() except that it echoes the input character.

Unformatted ouptput function:

 putch() writes a character that is passed as an argument to the console.

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

 Format specifiers start with a percentage % operator and followed by a special


character for identifying the type of the data.
 There are mostly 6 types of format specifiers that are available in C
 Write a „C‟ program to find the largest among two numbers using Conditional Operator.

#include <stdio.h>

main()
{
int num1, num2, max;

printf("Enter two numbers: ");


scanf("%d %d", &num1, &num2);

max = (num1>num2) ? num1 : num2;

printf("Maximum between %d and %d is %d", 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

printf("After Swapping: x = %d, y = %d", x, y);

return 0;
}

Output:
After Swapping: x = 5, y = 10

 Expression Types,

 In programming, an expression is any legal combination of symbols that represents


a value.

 C Programming Provides its own rules of Expression, whether it is legal

 expression or illegal expression. For example, in the C language x+5 is a legal


expression.

 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

Decrement Operator in C Programming :


 Decrement operator is used to decrease the current value of variable by subtracting integer 1.
 Like Increment operator, decrement operator can be applied to only variables.
 Decrement operator is denoted by –.
Different Types of Decrement Operation :
When decrement operator used in C Programming then it can be used as pre-decrement or
post-decrement operator.

Pre Decrement Operator

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:

Enter any integer = 9


It is Divisible by 9

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;

printf("x = %d, z = %f", x, z);

}
Output:

x = 107, z = 108.000000

2. Explicit Type Conversion

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;

int sum = (int)x + 1;

printf("sum = %d", sum);

Output:

sum = 2

Advantages of Type Conversion


 This is done to take advantage of certain features of type hierarchies or type
representations.
 It helps us to compute expressions containing variables of different data types.
 Explain different short circuit evaluation operators called logical operators

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

Example for 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

Example for 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 -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

Write about mathematical library function in c language.

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 :

Enter values for a,b,c= 1


2
3
There are no real roots
Output 2 :
Enter values for a,b,c= 1
2
1
root1=-1.00000

Explain in details about multi way selection statements with examples.


Multi way selection statements

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:

Enter two numbers 20


21
Y is big

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;

printf("Enter the choice 1-4\n");

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

printf("Your grade is %d\n", ch);

Output:

Enter the choice 1-4= 2


B
Your grade is 2

 Write a C Program to evaluate the following series.

Sin(x) = x – x3/3! +x5/5! – x7/7! .. . …….. ∞

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

Enter the value of x: 2


sin(x) is : 0.909347

Write a C Program to evaluate the following series.

Sin(x) = x – x3/3! +x5/5! – x7/7! .. . …….. ∞

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:

Enter the value of x : 2


0.907937

What is a loop ? Explain different statement in C with examples.

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 :

 Initialization is executed as start of loop


 Loop condition is tested before iteration to decide whether to continue or terminate the loop.
 Increment is executed at the end of each loop iteration.

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

1. Entry controlled loop (Pre test)


2. Exit controlled loop (Post test)

Entry Controlled Loop

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 :

 Initialization is executed as start of loop


 Loop condition is tested before iteration to decide whether to continue or terminate the loop.
 Increment is executed at the end of each loop iteration.
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.
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
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);

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
Differences between Entry controlled and Exit Controlled loop

Entry Controlled Loop Exit Controlled Loop

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.

Difference between Sentinel and Counter controlled loops

Counter Controlled Loop


When we know how many times loop body will be executed known as Counter Controlled Loop,
for example - print natural numbers from 1 to 10, such kind of problem will be solved using counter
controlled loop.
EX:

#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

Sentinel Controlled Loop


When we don’t know exactly know how many times loop body will be executed known as Sentinel
Controlled Loop.
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:

Enter any integer = 9


It is Divisible by 9
Conditional statement :
Conditional statement are used to execute a statement or a group of
statement based on certain condition.

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.

 It is conditional statement which is used to execute a set of statement on some conditions

 The condition must be of Boolean type expression.

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

 It is known as double blocked conditional statement

 It means it has true parts as well as false part

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

Enter any number= 2


Even number

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:

Enter two numbers 20


21
Y is big

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

/ * Write a program to print the following series on the screen */

#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

 / *This program for pascal triangle * /

#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

/ * This program for Floyd triangle */

#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

/ * This program for displaying or printing the number is Amstrong or not * /

#include<stdio.h>

main()

int num,rem,sum=0,temp;

printf("Enter any number\n");

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

printf("Not armstrong number\n");

Output:

Enter any number 153

Arstrong number

 Write a C program to prime number.

#include<stdio.h>

main()

int n,i,count=0;

printf("Enter any number=\n");

scanf("%d",&n);

for(i=1;i<=n;i++)

if(n%i==0)

count++;

}
if(count==2)

printf("prime number\n");

else

printf("not prime number\n");

Output:

Enter any number= 5

prime number

/*This program for displaying or printing the leap year or not a leap year */

#include<stdio.h>

main()

int year;

printf("Enter any year=\n");

scanf("%d",&year);

if (year%4==0)

printf("The year is a leap year\n");

else

printf("The year is not a leap year\n");

Output:

Enter any year=2016

The year is a leap year


 Break Statement.

 Causes an immediate exit from the loop (for,while,dowhile).

 Break can be used in for,while,dowhile.

 Break can be used in switch statement.

 When break is executed the statement following break are skipped and cause the loop to be
terminated

 It breaks the iteration.

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

printf("Exited from the for loop\n");

Output:

1
2
3
4
5
Continue statement:

 Causes the next iteration of the loop.

 Continue can be used in for,while,dowhile.

 It cannot be used in switch statement.

 When continue statement is executed, the statements following continue are skipped and cause
the loop to be continued with the next iteration

 It skips the 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);

It breaks the iteration. It skips the iteration.

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;

printf("value of a: %d\n", a);

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.

We have two types of arrays:

1. One-dimensional arrays.
2. Multidimensional arrays.

One Dimensional Arrays:


A one-dimensional array is a structured collection of components (often called array elements) that can
be accessed individually by specifying the position of a component with a single index value. Arrays must
be declared before they can be used in the program. Here is the declaration syntax of one dimensional
array:

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];

int age [5];

Here int is Age is the [5] is the size of


the data name of the the array
type array
The following will be the result of the above declarations:

age[0] age[1] age[2] age[3] age[4]

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

It is not necessary to define the size of arrays during initialization e.g.

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.

age[0] age[1] age[2] age[3] age[4]


2 3 4 5 6

Accessing array elements


In C programming, arrays can be accessed and treated like variables in C.

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

/* C program to find the sum marks of n students using arrays */

#include <stdio.h>

int main(){

int i,n;
int marks[n];
int sum=0;

printf("Enter number of students: ");


scanf("%d",&n);

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

printf("Sum of marks = %d",sum);

return 0;

Output :

Enter number of students: (input by user)3


Enter marks of student1: (input by user) 10
Enter marks of student2: (input by user) 29
Enter marks of student3: (input by user) 11

Sum of marks = 50

Important thing to remember in C arrays


Suppose, you declared the array of 10 students. For example: students[10]. You can use array members
from student[0] to student[9]. But, what if you want to use element student[10], student[100] etc. In
this case the compiler may not show error using these elements but, may cause fatal error during
program execution.
Multidimensional Arrays:
C programming language allows the user to create arrays of arrays known as multidimensional arrays.
To access a particular element from the array we have to use two subscripts one for row number and
other for column number. The notation is of the form array [i] [j] where i stands for row subscripts and j
stands for column subscripts. The array holds i*j elements. Suppose there is a multidimensional array
array[i][j][k][m]. Then this array can hold i*j*k*m numbers of data. In the same way, the array of any
dimension can be initialized in C programming. For example :

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:

Col 1 Col 2 Col 3 Col 4


Row 1 smakrs[0][0] smarks[0][1] smarks[0][2] smarks[0][3]

Row 2 smarks[1][0] smarks[1][1] smarks[1][2] smarks[1][3]


Row 3 smarks[2][0] smarks[2][1] smarks[2][2] smarks[2][3]

Make sure that you remember to put each subscript in its own, correct pair of brackets. All three
examples below are wrong.

int a2[5, 7]; /* XXX WRONG */

a2[i, j] = 0; /* XXX WRONG */

a2[j][i] = 0; /* XXX WRONG */

would do anything remotely like what you wanted

Initialization of Multidimensional Arrays


In C, multidimensional arrays can be initialized in different number of ways.

int smarks[2][3]={{1,2,3}, {-1,-2,-3}};


OR
int smarks[][3]={{1,2,3}, {-1,-2,-3}};
OR
int smarks[2][3]={1,2,3,-1,-2,-3};
Coding example of Multidimensional Array:

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.

Source Code to Add Two Matrix in C programming


#include <stdio.h>

int main(){
int r,c;
int a[r][c];
int b[r][c];
int sum[r][c;

printf("Enter number of rows (between 1 and 100): ");


scanf("%d",&r);

printf("Enter number of columns (between 1 and 100): ");


scanf("%d",&c);

printf("\nEnter elements of 1st matrix:\n");

/* Storing elements of first matrix entered by user. */

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

/* Storing elements of second matrix entered by user. */

printf("Enter elements of 2nd matrix:\n");


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",&b[i][j]);
}
}

/*Adding Two matrices */

for(int i=0;i<r;++i)
for(int j=0;j<c;++j)
sum[i][j]=a[i][j]+b[i][j];

/* Displaying the resultant sum matrix. */


printf("\nSum of two matrix is: \n\n");
for(int i=0;i<r;++i){
for(int j=0;j<c;++j){
printf("%d ",sum[i][j]);
if(j==c-1)
printf("\n\n");
}

return 0;

Program Output:
Enter number of rows (between 1 and 100): 3
Enter number of rows (between 1 and 100): 2

Enter elements of 1st matrix:


Enter element a11: 4
Enter element a12: -4
Enter element a21: 8
Enter element a22: 5
Enter element a31: 1
Enter element a32: 0
Enter elements of 2nd matrix:
Enter element a11: 4
Enter element a12: -7
Enter element a21: 9
Enter element a22: 1
Enter element a31: 4
Enter element a32: 5

Sum of two matrix is:

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

Linear Search Algorithm (Sequential Search Algorithm)


Linear search algorithm finds a given element in a list of elements with O(n) time
complexity where n is total number of elements in the list. This search process starts comparing
search element with the first element in the list. If both are matched then result is element found
otherwise search element is compared with the next element in the list. Repeat the same until
search element is compared with the last element in the list, if that last element also doesn't
match, then the result is "Element not found in the list". That means, the search element is
compared with element by element in the list.
Linear search is implemented using following steps...
Step 1 - Read the search element from the user.

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.

Binary Search Algorithm


. The binary search algorithm can be used with only a sorted list of elements. That
means the binary search is used only with a list of elements that are already arranged in an
order. The binary search can not be used for a list of elements arranged in random order. This
search process starts comparing the search element with the middle element in the list. If both
are matched, then the result is "element found". Otherwise, we check whether the search
element is smaller or larger than the middle element in the list. If the search element is smaller,
then we repeat the same process for the left sublist of the middle element. If the search element
is larger, then we repeat the same process for the right sublist of the middle element. We repeat
this process until we find the search element in the list or until we left with a sublist of only one
element. And if that element also doesn't match with the search element, then the result is
"Element not found in the list". Search is implemented using following steps...
Step 1 - Read the search element from the user.
Step 2 - Find the middle element in the sorted list.
Step 3 - Compare the search element with the middle element in the sorted list.
Step 4 - If both are matched, then display "Given element is found!!!" and terminate the
function.
Step 5 - If both are not matched, then check whether the search element is smaller or larger
than the middle element.
Step 6 - If the search element is smaller than middle element, repeat steps 2, 3, 4 and 5 for the
left sublist of the middle element.
Step 7 - If the search element is larger than middle element, repeat steps 2, 3, 4 and 5 for the
right sublist of the middle element.
Step 8 - Repeat the same process until we find the search element in the list or until sublist
contains only one element.
Step 9 - If that element also doesn't match with the search element, then display "Element is not
found in the list!!!" 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 Binary search.
#include <stdio.h>
int main()
{
int i, first, last, middle, n, search, array[100];
printf("Enter number of elements\n");
scanf("%d",&n);
printf("Enter %d integers\n", n);
for (i = 0; i < n; i++)
scanf("%d",&array[i]);
printf("Enter value to find\n");
scanf("%d", &search);
first = 0;
last = n - 1;
middle = (first+last)/2;
while (first <= last)
{
if (array[middle] < search)
first = middle + 1;
else if (array[middle] == search)
{
printf("%d found at location %d.\n", search, middle+1);
break;
}
else
last = middle - 1;
middle = (first + last)/2;
}
if (first > last)
printf("Not found!”);
return 0;
}
Output:
Enter number of elements
10
Enter Array Elements
1 2 3 4 5 6 7 8 9 10
Enter value to find
20
Sorting
Sorting is a process which arranges individual elements of a list according to proper rank
either in ascending or descending order.

There are different sorting techniques available in C language are,


 Selection Sort
 Bubble Sort
 Selection sort
Selection sort is a simple sorting algorithm. This sorting algorithm is an in-place
comparison-based algorithm in which the list is divided into two parts, the sorted part at the left
end and the unsorted part at the right end. Initially, the sorted part is empty and the unsorted part
is the entire list.
The smallest element is selected from the unsorted array and swapped with the leftmost
element, and that element becomes a part of the sorted array. This process continues moving
unsorted array boundary by one element to the right.

How Selection Sort Works?

Consider the following depicted array as an example.


For the first position in the sorted list, the whole list is scanned sequentially. The first position
where 14 is stored presently, we search the whole list and find that 10 is the lowest value.

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;

printf("Enter number of elements\n");


scanf("%d", &n);
printf("Enter integers\n");

for (i = 0; i < n; i++)


scanf("%d", &array[i]);

for (i = 0; i < (n - 1); i++)


{
position = i;

for (j = i + 1; j < n; j++)


{
if (array[position] > array[j])
position = d;
}
if (position != i)
{
swap = array[i];
array[i] = array[position];
array[position] = swap;
}
}

printf("Sorted list in ascending order:\n");

for (i = 0; i < n; i++)


printf("%d\n", array[i]);

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 )

/*Write a C program to arrange elements in an asecending order using Bubble Sort


Technique*/

#include<stdio.h>

int main()

int a[50], n, i, j, temp;

printf("Enter the size of array: ");

scanf("%d", &n);

printf("Enter the array elements: ");

for(i=0; i<n; ++i)

scanf("%d", &a[i]);

for(i=1; i<n; ++i)

for(j=0; j<(n-i); ++j)

if(a[j]>a[j+1])
{

temp=a[j];

a[j]=a[j+1];

a[j+1]=temp;

printf("\nArray elements after sorting:");

for(i=0; i<n; ++i)

printf("%d ", a[i]);

return 0;

Expected Output:

Enter the size of an array: 6

Enter the array elements: 50 63 14 45 55 20

A
r
r
a
y

e
l
e
m
e
n
t

You might also like