0% found this document useful (0 votes)
106 views309 pages

Pec Cse Pps Course File (5units)

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

Pec Cse Pps Course File (5units)

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

Department of Computer Science Engineering

PROGRAMMING FOR PROBLEM SOLVING


COURSE FILE
I B Tech – II Semester [Branch: CSE, CSC, CSD & EEE]

Mr. B. NARESH
Assistant Professor

Pallavi Engineering College


Kuntloor(v), Abdullapurmet(M),Hyderabad,R.R.Dist
PROGRAMMING FOR PROBLEM SOLVING (CS203ES)

COURSE PLANNER

I. COURSE OVERVIEW:
This course emphasizes solving problems using the language, and introduces
standard programming techniques like alternation, iteration and recursion. It
will briefly glimpse the basics of software engineering practices like
modularization, commenting, and naming conventions which help in
collaborating and programming in teams. This course is enabled the students
to formulate algorithms for arithmetic and logical problems, convert these
algorithms to C language programs. It also aims on using arrays, pointers and
structures to formulate algorithms and programs. In addition to that, apply
programming to solve matrix addition and multiplication problems and
searching and sorting problems.

II. PREREQUISITE(S):
 Mathematics knowledge, Analytical and Logical skills.

III. COURSE OBJECTIVES:


 To learn the fundamentals of computers.
 To understand the various steps in program development.
 To learn the syntax and semantics of C programming language.
 To learn the usage of structured programming approach in solving problems.

IV. COURSE OUTCOMES: The student will learn

Sno Course Outcomes Knowledge Level


(CO) (Blooms Level)
CO1 To write algorithms and to draw flowcharts for solving L5: Evaluate
problems.
CO2 To convert the algorithms/flowcharts to C programs L6: Create, L2:Understand
CO3 To code and test a given logic in C programming language L6: Create, L4: Analyze
CO4 To decompose a problem into functions and to develop modular L5: Evaluate, L3:Apply
reusable code
CO5 To use arrays, pointers, strings and structures to write C L5: Evaluate
programs
CO6 Searching and sorting problems L3:Apply
V. SYLLABUS:
UNIT – I :
Introduction to components of a computer system: disks, primary and
secondary memory, processor, operating system, compilers, creating,
compiling and executing a program etc., Number systems Introduction to
Algorithms: steps to solve logical and numerical problems. Representation
of Algorithm, Flowchart/Pseudo code with examples, Program design and
structured programming
Introduction to C Programming Language: variables (with data types and
space requirements), Syntax and Logical Errors in compilation, object and
executable code , Operators, expressions and precedence, Expression
evaluation, Storage classes (auto, extern, static and register), type
conversion, The main method and command line arguments Bitwise
operations: Bitwise AND, OR, XOR and NOT operators Conditional
Branching and Loops: Writing and evaluation of conditionals and
consequent branching with if, if-else, switch-case, ternary operator, goto,
Iteration with for, while, do-while loops

I/O: Simple input and output with scanf and printf, formatted I/O,
Introduction to stdin, stdout and stderr. Command line arguments

UNIT—II:
Arrays: one and two dimensional arrays, creating, accessing and
manipulating elements of arrays Strings: Introduction to strings, handling
strings as array of characters, basic string functions available in C (strlen,
strcat, strcpy, strstr etc.), arrays of strings
Structures: Defining structures, initializing structures, unions, Array of structures
Pointers: Idea of pointers, Defining pointers, Pointers to Arrays and
Structures, Use of Pointers in self- referential structures, usage of self
referential structures in linked list (no implementation) Enumeration data
type

UNIT- III:
Preprocessor: Commonly used Preprocessor commands like include, define, undef, if,
ifdef, ifndef
Files: Text and Binary files, Creating and Reading and writing text and
binary files, Appending data to existing files, Writing and reading structures
using binary files, Random access using fseek, ftell and rewind functions.

UNIT- IV:
Functions: Designing structured programs, Declaring a function, Signature
of a function, Parameters and return type of a function, passing parameters
to functions, call by value, Passing arrays to functions, passing pointers to
functions, idea of call by reference, Some C standard functions and libraries
Recursion: Simple programs, such as Finding Factorial, Fibonacci series
etc., Limitations of Recursive functions Dynamic memory allocation:
Allocating and freeing memory, Allocating memory for arrays of different
data types

UNIT V:
Algorithms for finding roots of a quadratic equations, finding minimum and
maximum numbers of a given set, finding if a number is prime number,
etc.Basic searching in an array of elements (linear and binary search
techniques), Basic algorithms to sort array of elements (Bubble, Insertion
and Selection sort algorithms), Basic concept of order of complexity through
the example programs

SUGGESTED BOOKS:

TEXT BOOKS:

1. T1. Byron Gottfried, Schaum’s Outline of Programming with C, McGraw-Hill.

2. T2. B.A. Forouzan and R.F. Gilberg C Programming and Data


Structures, Cengage Learning, (3rd Edition).

REFERENCE BOOKS:

1. R1. Brian W. Kernighan and Dennis M. Ritchie, The C


Programming Language, Prentice Hall of India
2. R2. R.G. Dromey, How to solve it by Computer, Pearson (16th Impression)
3. R3. Programming in C, Stephen G. Kochan, Fourth Edition, Pearson Education.
4. R4. Herbert Schildt, C: The Complete Reference, Mc Graw Hill, 4 th Edition
COURSE PLAN:

Course Learning Referen


Lecture Week Topics to be covered Outcomes ces
UNIT-I
Introduction to components of a computer system: disks, Illustrates
1. primary and secondary memory, processor, operating different
system, components
2. 1 compilers, creating, compiling and executing a program
3. Number systems Identify the steps
Introduction to Algorithms: steps to solve logical and in algorithm
4.
numerical problems. Representation of Algorithm
Flowchart/Pseudo code with examples, Program design Discuss the types T1
5. and structured programming of flowcharts and
Understand the
Introduction to C Programming Language: variables (with
programming
6. data types and space requirements), Syntax and Logical
design
2 Errors in compilation, object and executable code ,
7. Operators Describes about
operators and
8. expressions and precedence, Expression evaluation expressions
Mock Test #1
Describes various
Storage classes (auto, extern, static and register), type
9. storage classes
conversion
The main method and command line arguments Bitwise Compute various
10. operations: Bitwise AND, OR, XOR and NOT operators methods
Conditional Branching and Loops: Writing and evaluation
11. of conditionals and consequent branching with if, if-else,
3
switch-case, ternary operator,
Creating different T2
goto, Iteration with for, while, do-while loops branching
12. statements and
loops

I/O: Simple input and output with scanf and printf, Apply I/O
13. 4 formatted I/O, Introduction to stdin, stdout and stderr. operations
Command line arguments
UNIT-II
Course Learning Referen
Lecture Week Topics to be covered Outcomes ces
Arrays: one dimensional arrays, creating, accessing and Applying the T2
14. manipulating elements of arrays accessing
techniques
15. 4 two dimensional arrays
Defining strings
Strings: Introduction to strings, handling strings as array of and its
16.
characters characteristics
basic string functions available in C (strlen, strcat, strcpy, Describes various
17. string methods
strstr etc.),
18. arrays of strings
19. 5 Structures: Defining structures, initializing structures Define a structure
and its
20. unions, declaration
21. Array of structures
Pointers: Idea of pointers, Understand the
22. use of pointers
6
23. Defining pointers, Defines a pointer
24. Pointers to Arrays and Structures Types in it..
Use of Pointers in self-referential structures, Examine in
25. various methods
usage of self referential structures in linked list (no Analyses the
26. implementation)
7 usages
Understanding the
27. Enumeration data type data types
T2
UNIT-III
Preprocessor: Commonly used Preprocessor commands Demonstrate the
28. like include, define, undef, preprocessor
29. if, ifdef, ifndef Define the Loops
Understand the
30. 8 Files: Text and Binary files, files
Evaluate text and
31. Creating and Reading and writing text and binary files binary files

I-MID EXAMINATION (WEEK-9)


32. Appending data to existing files, Evaluate the files

Create the types


33. Writing and reading structures using binary files in it T2
10
Discuss about
Random access using fseek, ftell and rewind functions. Random
34.
functions
Programming for Problem Solving
Unit – 1(Syllabus)
Introduction to Programming

Introduction to components of a computer system: disks, primary and secondary memory,


processor, operating system, compilers, creating, compiling and executing a program etc.,
Number systems

Introduction to Algorithms: steps to solve logical and numerical problems. Representation of


Algorithm, Flowchart/Pseudo code with examples, Program design and structured programming

Introduction to C Programming Language: variables (with data types and space


requirements), Syntax and Logical Errors in compilation, object and executable code , Operators,
expressions and precedence, Expression evaluation, Storage classes (auto, extern, static and
register), type conversion, The main method and command line arguments,Bitwise operations:
Bitwise AND, OR, XOR and NOT operators

Conditional Branching and Loops: Writing and evaluation of conditionals and consequent
branching with if, if-else, switch-case, ternary operator, goto, Iteration with for, while, do-while
loops

I/O: Simple input and output with scanf and printf, formatted I/O, Introduction to stdin, stdout
and stderr. Command line arguments
Introduction to Programming
Introduction to components of a computer system

Computer:
A computer is an electronic device which takes information from the user as input
data, processes it and gives results as output data.
Input data: User given data to the computer.
Output data: Computer given data to the user.
BLOCK DIAGRAM OF A COMPUTER

Block diagram of a computer gives you the pictorial representation of a computer that how it
works inside.

In the above diagram, both control (control unit or CU) and arithmetic & logic unit
(ALU) combinely called as Central Processing Unit (CPU).
Let's describe about all the parts as included in the above diagram one by one.
The Processor Unit (CPU):
 It is the brain of a computer system.
 All major calculation and comparisons are made inside the CPU and it is also
responsible for activation and controlling the operation of other unit.
 This unit consists of two major components that are arithmetic logic unit (ALU) and
control unit (CU).
Arithmetic Logic Unit (ALU):
Here arithmetic logic unit performs all arithmetic operations such as addition,
subtraction, multiplication and division. It also uses logic operation for comparison.
Control Unit (CU):
 Control unit of a CPU controls the entire operation of a computer. It also controls
all devices such as memory, input/output devices connected to the CPU.
 As name indicates, this part of CPU extracts instructions, performs execution,
maintains and directs operations of entire system.
Functions of Control Unit
 It controls all activities of computer
 Supervises flow of data within CPU
 Directs flow of data within CPU
 Transfers data to Arithmetic and Logic Unit
 Transfers results to memory
 Fetches results from memory to output devices

Memory Unit
This is unit in which data and instructions given to computer as well as results given by
computer are stored. Unit of memory is "Byte". 1 Byte = 8 Bits

Input Unit
An input device is essentially a piece of instrument or hardware that allows users to
provide data, information, or control instructions to a computer used for interaction and
control. Data is entered into a computer in a raw format, which is converted into computer
understandable language by input devices and processed by a central processing unit (CPU)
to produce output.
In simple terms, an input device is a kind of peripheral device that helps communicate with
processing units of the computer.
Some of the major or popular input devices are given below:
 Keyboard
 Mouse
 Scanner
 Optical Mark
rk Reader (OMR)
 Light Pen
 Trackball
 Magnetic Ink Character Recognition (MICR)
 Bar code reader (BCR)
 Optical Character Recognition (OCR)
 Voice Input Systems
 Digital Camera

BCR
OMR MICR

Output unit
An output device is essentially a piece of instrument or compu
computer
ter hardware that retrieves
data from a computer system and further translates the received data into a form
understandable to humans. The most common human
human-understandable
understandable forms typically
include text, visual, audio, or a hard copy (printed on a paper).
In simple words, an output device is a type of peripheral device that helps us to get data
processed from a computer, usually in the form of audio, visual, and xerox.
The most common output devices that are in use as follows:
1. Monitors
2. Printers
3. Plotters
4. Projectors
5. Speakers

Memory unit or Storage devices


A storage unit is a part of the computer system which is employed to store the information
and instructions to be processed. A storage device is an integral part of the computer
hardware which stores information/data to process the result of any computational work.
Without a storage device, a computer would not be able to run or even boot up. Or in other
words, we can say that a storage device is hardware that is used for storing, porting, or
extracting data files. It can also store information/data both temporarily and permanently.
Computer storage is of two types:
 Primary Storage (Internal) Devices: It is also known as internal memory and main
memory. This is a section of the CPU that holds program instructions, input data, and
intermediate results. It is generally smaller in size. RAM (Random Access Memory) and
ROM (Read Only Memory) are examples of primary storage.

(i) RAM: It stands for Random Access Memory. It is used to store information
that is used immediately or we can say that it is a temporary memory.
Computers bring the software installed on a hard disk to RAM to process it
and to be used by the user. Once, the computer is turned off, the data is
deleted. With the help of RAM, computers can perform multiple tasks like
loading applications, browsing the web, editing a spreadsheet, experiencing
the newest game, etc. It allows you to modify quickly among these tasks,
remembering where you’re in one task once you switch to a different task. It
is also used to load and run applications
(ii) ROM: It stands for Read-Only Memory. The data written or stored in these
devices are non-volatile, i.e, once the data is stored in the memory cannot be
modified or deleted. The memory from which will only read but cannot
write it. This type of memory is non-volatile. The information is stored
permanently during manufacture only once. ROM stores instructions that are
used to start a computer. This operation is referred to as bootstrap. It is also
used in other electronic items like washers and microwaves. ROM chips can
only store few megabytes (MB) of data, which ranges between 4 and 8 MB
per ROM chip

 Secondary Storage (External) Devices: Secondary storage is a memory that is stored


external to the computer. It is mainly used for the permanent and long-term storage of
programs and data. Hard Disk, CD, DVD, Pen/Flash drive, SSD, etc, are examples of
secondary storage.
i. Magnetic Tape memory:
In magnetic tape only one side of the ribbon is used for storing data. It is
sequential memory which contains thin plastic ribbon to store data and coated by
magnetic oxide. Data read/write speed is slower because of sequential access. It is
highly reliable which requires magnetic tape drive writing and reading data.
Ex: cassette tape
ii. Magnetic storage Discs
There are several different ways of storing information on the computer. One of
the longest used systems for storing information have been with magnetic storage
devices.
a. Floppy Disk: It is also known as a floppy diskette. It is generally
used on a personal computer to store data externally. A Floppy
disk is made up of a plastic cartridge and secures with a protective
case. Nowadays floppy disk is replaced by new and effective
storage devices like USB, etc.
b. Hard Disk: It is a storage device (HDD) that stores and retrieves
data using magnetic storage. It is a non-volatile storage device that
can be modified or deleted n number of times without any
problem. Most of the computers and laptops have HDDs as their
secondary storage device. It is actually a set of stacked disks, just
like phonograph records. In every hard disk, the data is recorded
electromagnetically in the concentric circles or we can say track
present on the hard disk, and with the help of a head just like a
phonograph arm(but fixed in a position) to read the information
present on the track. The read-write speed of HDDs is not so fast
but decent. It ranges from a few GBs to a few and more TB.
c. Magnetic Card: It is a card in which data is stored by modifying
or rearranging the magnetism of tiny iron-based magnetic particles
present on the band of the card. It is also known as a swipe card. It
is used like a passcode(to enter into house or hotel room), credit
card, identity card, etc.
iii. Optical storage Discs
Optical Storage Devices is also a secondary storage device. It is a removable
storage device. Following are some optical storage devices:

(i) CD: It is known as Compact Disc. It contains tracks and sectors on its
surface to store data. It is made up of polycarbonate plastic and is circular in
shape. CD can store data up to 700MB.
(ii) DVD: It is known as Digital Versatile Disc. DVDs are circular flat optical
discs used to store data. It comes in two different sizes one is 4.7GB single-
layer discs and another one is 8.5GB double-layer discs. DVDs look like
CDs but the storage capacity of DVDs is more than as compared to CDs.
(iii) Blu-ray Disc: It is just like CD and DVD but the storage capacity of blu ray
is up to 25GB. To run a Blu-ray disc you need a separate Blu-ray reader.
This Blu-ray technology is used to read a disc from a blue-violet laser due to
which the information is stored in greater density with a longer wavelength.
iv. Flash Memory devices:
It is a cheaper and portable storage device. It is the most commonly used device
to store data because is more reliable and efficient as compare to other storage
devices. Some of the commonly used flash memory devices are:
(i) Pen Drive: It is also known as a USB flash drive that includes flash memory
with an integrated USB interface. We can directly connect these devices to our
computers and laptops and read/write data into them in a much faster and
efficient way. These devices are very portable. It ranges from 1GB to 256GB
generally.
(ii) SSD: It stands for Solid State Drive, a mass storage device like HDDs. It is
more durable because it does not contain optical disks inside like hard disks. It
needs less power as compared to hard disks, is lightweight, and has 10x faster
read and write speed as compared to hard disks. But, these are costly as well.
While SSDs serve an equivalent function as hard drives, their internal
components are much different. Unlike hard drives, SSDs don’t have any
moving parts and thus they’re called solid-state drives. Instead of storing data on
magnetic platters, SSDs store data using non-volatile storage. Since SSDs
haven’t any moving parts, they do not need to “spin up”. It ranges from 150GB
to a few and more TB.
(iii) SD Card: It is known as a Secure Digital Card. It is generally used with
electronic devices like phones, digital cameras, etc. to store larger data. It is
portable and the size of the SD card is also small so that it can easily fit into
electronic devices. It is available in different sizes like 2GB, 4GB, 8GB, etc.
(iv)Memory Card: It is generally used in digital cameras. printers, game
consoles, etc. It is also used to store large amounts of data and is available in
different sizes. To run a memory card on a computer you require a separate
memory card reader.
(v) Multimedia Card: It is also known as MMC. It is an integrated circuit that
is generally used in-car radios, digital cameras, etc. It is an external device to
store data/information.

Processor
A processor is an integrated electronic circuit that performs the calculations that run a computer.
A processor performs arithmetical, logical, input/output (I/O) and other basic instructions that are
passed from an operating system (OS). Most other processes are dependent on the operations of a

Processors are found in many modern electronic devices, including PCs, smartphones, tablets,
and other handheld devices. Their purpose is to receive input in the form of program instructions
and execute trillions of calculations to provide the output that the user will interface with.
A processor includes an arithmetical logic and control unit (CU), which measures capability
in terms of the following:
 Ability to process instructions at a given time.
 Maximum number of bits/instructions.
 Relative clock speed.
Every time that an operation is performed on a computer, such as when a file is changed or
an application is open, the processor must interpret the operating system or software’s
instructions. Depending on its capabilities, the processing operations can be quicker or
slower, and have a big impact on what is called the “processing speed” of the CPU.
Each processor is constituted of one or more individual processing units called “cores”.
Each core processes instructions from a single computing task at a certain speed, defined as
“clock speed” and measured in gigahertz (GHz). Since increasing clock speed beyond a
certain point became technically too difficult, modern computers now have several
processor cores (dual-core, quad-core, etc.). They work together to process instructions and
complete multiple tasks at the same time.
The CPU carries out his operations through the three main steps of the instruction cycle:
fetch, decode, and execute.
 Fetch: the CPU retrieves instructions, usually from a RAM.
 Decode: a decoder converts the instruction into signals to the other components of the
computer.
 Execute: the now decoded instructions are sent to each component so that the desired
operation can be performed.
Operating system:
Definition
An operating system is a program that acts as an interface between the user and the
computer hardware and controls the execution of all kinds of programs.
An operating system is a software which performs all the basic tasks like file management,
memory management, process management, handling input and output, and controlling
peripheral devices such as disk drives and printers.
Some popular Operating Systems include Linux Operating System, Windows Operating
System.
The process operating system as User Interface:
1. User
2. System and application programs
3. Operating system
4. Hardware
Every general-purpose computer consists of the hardware, operating system, system
programs, and application programs. The hardware consists of memory, CPU, ALU, and I/O
devices, peripheral devices, and storage devices. System program consists of compilers,
loaders, editors, OS, etc. The application program consists of business programs, database
programs.
Following are some types of operating systems

Batch Operating System


Some computer processes are very lengthy and time-consuming. To speed the same process, a
job with a similar type of needs are batched together and run as a group.

The user of a batch operating system never directly interacts with the computer. In this type of
OS, every user prepares his or her job on an offline device like a punch card and submit it to the
computer operator.

Multi-Tasking/Time-sharing Operating systems


Time-sharing operating system enables people located at a different terminal(shell) to use a
single computer system at the same time. The processor time (CPU) which is shared among
multiple users is termed as time sharing.

Real time OS
A real time operating system time interval to process and respond to inputs is very small.
Examples: Military Software Systems, Space Software Systems are the Real time OS example.
Distributed Operating System
Distributed systems use many processors located in different machines to provide very fast
computation to its users.

Network Operating System


Network Operating System runs on a server. It provides the capability to serve to manage data,
user, groups, security, application, and other networking functions.

Mobile OS
Mobile operating systems are those OS which is especially that are designed to power
smartphones, tablets, and wearables devices.

Computer Languages

What is Computer Language?


Generally, we use languages like English, Hindi, etc., to make communication between two
persons. That means when we want to make communication between two persons we need a
language through which persons can express their feelings. Similarly, when we want to make
communication between user and computer or between two or more computers we need a
language through which user can give information to the computer and vice versa?

When a user wants to give any instruction to the computer the user needs a specific language and
that Language is known as a computer language.

The user interacts with the computer using programs and that programs are created using
computer programming languages like C, C++, Java, etc.,
Computer languages are the languages through which the user can communicate with the
computer by writing program instructions.

Every computer programming language contains a set of predefined words and a set of rules
(syntax) that are used to create instructions of a program.

Computer Languages Classification


Over the years, computer languages have been evolved from Low-Level to High-Level
Languages. In the earliest days of computers, only Binary Language was used to write programs.
The computer languages are classified as follows...
Low level language
A low-level language is a type of programming language that contains basic instructions
recognized by a computer. Low-level
level code is often cryptic and not human
human-readable.
readable. Two
common types of low-level programming languages are assembly language and machine
language.

Machine Language

The only language which the computer itself can understand is the machine language.

We can use different languages to program a computer, it is translated to machine language


before running that program.

A machine language is the set of instructions which are coded as a series of 1s and 0s. These
1s and 0s are directly understood by the computer without the help of a translating program. A
program written in the form of 0s and 1s is called a machine language program. Each type of
computer has its own machine language. That is, the machine lan
language
guage is machine dependent
and the machine language is different from one type of computer to another
another.

Advantages:

1) High speed execution

2) The computer can understood instruction immediately


3) No translation is needed.

Disadvantages:

1) Machine dependent

2) Programming is very difficult

3) Difficult to understand

4) Difficult to write bug free programs

5) Difficult to isolate an error

Example Addition of two numbers

2 =0010

+3 = 0 0 1 1

5 =0101

Assembly Language (middle level language)

These early programming languages simply mirrored the machine languages using symbols or
mnemonics to represent the various language instructions. These languages were known as
symbolic languages. Because a computer does not understand symbolic language it must be
translated into the machine language. A special program called an Assembler translates
symbolic code into the machine language. Hence they are called as Assembly language.

Advantages:

1) Easy to understand and use

2) Easy to modify and isolate error

3) High efficiency

4) More control on hardware


Disadvantages:

1) Machine Dependent Language

2) Requires translator

3) Difficult to learn and write programs

4) Slow development time

5) Less efficient

Example:

2 PUSH2,A

3 PUSH3,B

+ ADDA,B

5 PRINTC

High level Language

A high-level language is a computer language which can be understood by the users. The high-
level language is very similar to human languages and has a set of grammar rules that are used to
make instructions more easily. Every high-level language has a set of predefined words known
as Keywords and a set of rules known as Syntax to create instructions.

The high-level language is easier to understand for the users but the computer can not understand
it. High-level language needs to be converted into the low-level language to make it
understandable by the computer.

We use Compiler or interpreter to convert high-level language to low-level language.

Languages like COBOL, FORTRAN, BASIC, C, C++, JAVA, etc., are examples

of high-level languages.
All these programming languages use human-understandable language like English to write
program instructions. These instructions are converted to low-level language by the compiler so
that it can be understood by the computer.

Advantages
1. Writing instructions in a high-level language is easier.
2. A high-level language is more readable and understandable.
3. The programs created using high-level language runs on different machines with little
change or no change.
4. Easy to understand, create programs, find errors and modify.
Disadvantages
1. High-level language needs to be translated into low-level language.
2. High-level language executes slower compared to middle and low-level languages.

Example:
#include<stdio.h>
int main()
{
printf(“Hello World”);
return 0;
} Output: Hello World
Differences between Machine Language and High Level Language
Machine Language

• It is a low level language containing binary digits 0 and 1.


• There is no need to translate it, since it is the only language which the computer itself
can understand.
• It is machine dependent and varies from computer to computer.
• It is very difficult to write a program in a machine language.
• Not closer to any natural languages.
• Relatively less efficient.
• Different to modify or understand
• Debugging is difficult.
High Level Language

• It is a programming language containing meaningful words.


• Compiler or interpreter is used to translate the high-level language into machine
language.
• It is machine independent and can be used in different types of computers.
• It is easy to write a program in a highlevel language.
• It is closer to natural language.
• More efficient.
• Easy to learn and understand.
• Easy to debug
Source Programs

Programs written in a high level language or low level language are called source
programs.

Object Programs

The source programs after getting translated into machine language are known as object
programs.

Language Translators

1. Translators
A Computer understands only machine language. To run the programs written in other
languages, we need to convert them into the machine language. Such translation is done
by system software programs called translators.
2. Assembler
A program which translates an assembly language program into a machine
language program is called an assembler. The assembler reads all instructions written
using mnemonics into binary codes and symbolic memory addressing into equivalent
binary addresses. Because each CPU has its own machine language, you require different
assemblers for different cpus.
3. Compilers
It is a translator which takes input i.e., High-Level Language, and produces an
output of low-level language i.e. machine or assembly language.
 A compiler is more intelligent than an assembler it checks all kinds of limits, ranges,
errors, etc.
 But its program run time is more and occupies a larger part of memory. It has slow speed
because a compiler goes through the entire program and then translates the entire
program into machine codes.

 The original high-level language program is called the source program. The compiled
program i.e., the machine language program generated by the compiler after translation is
called the object program.

Each high-level language uses different instructions to do the same job. Therefore, a separate
compiler is required for each high-level language. i.e., to execute both FORTRAN and COBAL
programs, you must have both FORTRAN compiler and COBOL compiler.

4. Interpreters
An interpreter is a program which translates one statement of a high-level language
program into machine codes and executes it. In this way it proceeds further till all the statements
of the program are translated and executed.

 It reads the first instruction written in the program and converts that into equivalent
machine language instructions. The the CPU executes those machine language
instructions. The interpreter reads and translates the next instructions, and so on.
Difference between Compiler and Interpreters.

Compiler

 Compiler scans the whole program and it converts it into object code.
 As it scans the code in one go, the errors(if any) are shown at the end together.
 Main advantage of compilers is its execution time.
 It converts the source code into object code.
 It does not require source code for later execution.
 C, C++, C# etc

Interpreters

 Translates program one statement at a time.


 Considering it scans code one line at a time, errors are shown line by line.
 Due to interpreters being slow in executing the object code, it is preferred less.
 It does not convert source code into object code instead it scans it line by line.
 It requires source code for later execution.
 Python, Ruby, Perl, SNOBOL, MATLAB, etc.

Creating, compiling and executing a program

Generally, the programs created using programming languages like C, C++, Java, etc., are
written using a high-level language like English. But, the computer cannot understand the high-
level language. It can understand only low-level language. So, the program written in the high-
level language needs to be converted into the low-level language to make it understandable for
the computer. This conversion is performed using either Interpreter or Compiler.
Popular programming languages like C, C++, Java, etc., use the compiler to convert high-level
language instructions into low-level language instructions. A compiler is a program that converts
high-level language instructions into low-level language instructions. Generally, the compiler
performs two things, first it verifies the program errors, if errors are found, it returns a list of
errors otherwise it converts
rts the complete code into the low
low-level language.

To create and execute C programs in the Windows Operating System, we need to install
Turbo C software. We use the following steps to create and execute C programs in Windows
OS…

Step 1: Creating a Sourcee Code/


Code/Writing and Editing Programs

The software used to write programs is known as a text editor. A text editor helps us enter,
change and store character data. Once we write the program in the text editor we save it using
a filename stored with an extens
extension
ion of .C. This file is referred as source code file.

Step 2: Compile Source Code (Alt + F9)

The compilation is the process of converting high


high-level
level language instructions into low-level
low
language instructions.

The entire high level program is converted into the executable machine code file. The
Compiler which executes C programs is called as C Compiler. Example Turbo C
Whenever we press Alt + F9, the source file is going to be submitted to the Compiler. On
receiving a source file, the compiler first checks for the Errors. If there are any Errors then
compiler returns List of Errors, if there are no errors then the source code is converted
into object code and stores it as a file with .obj extension. Then the object code is given to
the Linker. The Linker combines both the object code and specified header file code and
generates an Executable file with a .exe extension

Linking Programs

The Linker assembles all functions, the programs functions and system functions into one
executable program.

Step 3: Executing / Running Executable File (Ctrl + F9)

After completing compilation successfully, an executable file is created with


a .exe extension. The processor can understand this .exe file content so that it can perform the
task specified in the source file. We use a shortcut key Ctrl + F9 to run a C program.
Whenever we press Ctrl + F9, the .exe file is submitted to the CPU. On
receiving .exe file, CPU performs the task according to the instruction written in the file. The
result generated from the execution is placed in a window called User Screen.

Step 4: Check Result (Alt + F5)

After running the program, the result is placed into User Screen. Just we need to open the
User Screen to check the result of the program execution. We use the shortcut key Alt +
F5 to open the User Screen and check the result.

Execution Process of a C Program

When we execute a C program it undergoes with the following process…


Creating a program: Type the program and edit it in standard ‘C’ editor and save the
program with .c as an extensi
extension.
on. This is the source program .The file should be saved as '*.c'
extension only.

Compiling (Alt + F9) the Program:

• This is the process of converting the high level language program to Machine level
Language (Equivalent machine instruction).

• Errors will be reported if there is any, after the compilation

• Otherwise the program will be converted into an object file (.obj file) as a result of the
compilation

• After error correction the program has to be compiled again

Linking a program to library


library: The object code of a program is linked with libraries that are
needed for execution of a program. The linker is used to link the program with libraries. It
creates a file with '*.exe' extension.
Execution of program: This is the process of running (Ctrl + F9) and testing the program
with sample data. If there are any run time errors, then they will be reported.

Then we press Alt + F5 to open UserScreen and check the result of the program.

Number System

The number system or the numeral system is the system of naming or representing
numbers. We know that a number is a mathematical value that helps to count or measure
objects and it helps in performing various mathematical calculations. The technique to
represent and work with numbers is called number system. Decimal number system is the
most common number system. Other popular number systems include binary number system,
octal number system, hexadecimal number system, etc.

A digital system can understand positional number system only where there are a few symbols
called digits and these symbols represent different values depending on the position they occupy
in the number.

A value of each digit in a number can be determined using


 The digit
 The position of the digit in the number
 The base of the number system (where base is defined as the total number of digits
available in the number system).
Binary Number System
The easiest way to vary instructions through electric signals is two-state system – on and off. On
is represented as 1 and off as 0, though 0 is not actually no signal but signal at a lower voltage.
The number system having just these two digits – 0 and 1 – is called binary number system.

Each binary digit is also called a bit. Binary number system is also positional value system,
where each digit has a value expressed in powers of 2, as displayed here.

In any binary number, the rightmost digit is called least significant bit (LSB) and leftmost digit
is called most significant bit (MSB). Ex: 110102

Octal Number System

Octal number system has eight digits – 0, 1, 2, 3, 4, 5, 6 and 7. Octal number system is also
a positional value system with where each digit has its value expressed in powers of 8

Ex: 7268

Decimal Number System

Decimal number system is a base 10 number system having 10 digits from 0 to 9. This
means that any numerical quantity can be represented using these 10 digits. Decimal number
system is also a positional value system. This means that the value of digits will depend on
its position.
Ex: 2610

Hexadecimal Number System

Hexadecimal number system has 16 symbols – 0 to 9 and A to F where A is equal to 10, B


is equal to 11 and so on till F. Hexadecimal number system is also a positional value system
with where each digit has its value expressed in powers of 16, as shown here −

Ex: 27FB16

Conversion Types

Decimal number to Binary Number Conversion

Decimal to binary conversion is done through various methods. One of the methods to convert
decimal to binary is by dividing the given decimal number recursively by 2. Then, the
remainders are noted down till we get 0 as the final quotient. After this step, these remainders are
written in reverse order to get the binary value of the given decimal number.
Final Answer of decimal number (25) 10 is (11001)2

Decimal to Octal Number Conversion

The decimal number is divided by 8, each time a reminder is obtained from the previous digit.
The first remainder
ainder obtained is the least significant digit(LSD) and the last remainder is the most
significant digit(MSD). Once the quotient is less than 8, we obtain the octal number by writing
the remainder in reverse order.

Step 1: Check if the decimal number is le


less
ss than 8. If yes, the octal number is the same. If no,
then proceed forward. In this case, 350 is more than 8 so let's go to step 2.

Step 2: Divide 350 by 8 (octal base number). Note down the quotient and the remainder in the
quotient-remainder form. Repeat
at this process (dividing the quotient again by 8) until we get the
quotient to be less than 8.

Final answer of (350)10 is (536)8

Decimal to Hexadecimal Number Conversion

In order to convert decimal to hexadecimal, we need to do some basic mathematical calculations


using the following steps.

 Step 1: Divide the given decimal number system value by 16 and note the remainder.
 Step 2: Divide the quotient
otient by 16. Repeat this until you get a quotient equal to zero.
 Step 3: Use the characters A, B, C, D, E, F in place of 10, 11, 12, 13, 14, 15 in the
remainders respectively, wherever needed.
 Step 4: Follow the reverse order pattern to arrange all the vvalues
alues of the remainder.
 Step 5: The obtained number is the required hexadecimal number
number.
Binary to Decimal Number System

The positional notation method is one in which the value of a digit in a number is
determined by a weight based on its position. This is achieved by multiplying each digit by
the base (2) raised to the respective power depending upon the position of that digit in the
number. The sum of all these values obtained for each digit gives the equivalent value of the
given binary number in the decimal system.

Observe the following steps to understand the binary to decimal conversion. Let us consider
the binary number (101101)2(101101)2. In any binary number, the rightmost digit is called
the 'Least Significant Bit' (LSB) and the left-most digit is called the 'Most Significant Bit'
(MSB). For a binary number with 'n' digits, the least significant bit has a weight of 2 0 and the
most significant bit has a weight of 2n-1.

 Step 1: List out the powers of 2 for all the digits starting from the rightmost position. The
first power would be 20 and as we move on it will be 21, 22, 23, 24, 25,... In the given
example, there are 6 digits, therefore, starting from the rightmost digit, the weight of each
position from the right is 20,21,22,23,24,25.

Step 2: Now multiply each digit in the binary number starting from the right with its
respective weight based on its position and evaluate the product.
Step 3: Now, express the binary number as a decimal number: (101101)2 = (45)10

Binary to Octal Number Conver


Conversion

 Step 1: Identify the binary number i.e. the digits should be either 0 or 1 with base 2.
 Step 2: Group all the 0 to 1 in a set of three starting from the right side.
 Step 3: Add 0's to the left if it does not form a group of three. Each group must have three
digits.
 Step 4: Look at the binary to octal conversion table to get the accurate numbers.
 Step 5: Once obtained, that number is the octal numbe
number

Binary to Hexadecimal number Conversion

One of the simplest and easiest methods to convert from binar


binaryy to hexadecimal is by using the
conversion table. Since binary numbers only have 0 and 1 that are called bits and hexadecimal
numbers are also positional number system, every 4 bits or numbers is equivalent to 1
hexadecimal number that includes the alphab
alphabets A - F as well.
Final answer of (101100110101)2 is (B35)16

Octal to Binary Number conversion

 Take Octal number as input


 Convert each digit of octal into binary.
 That will be output as binary number.
Observe the octal to binary table given below which will help you to convert octal numbers to
binary numbers. The octal to binary table shows the equivalent number of each octal digit to
binary, for example, 0 in octal is equivalent to 000 in binary, 1 in octal is equivalent to 001 in
binary, 28 is the same as 0102, and so on.
Final conversion of (172)8 is (001111010)2

Octal to Decimal Number conversion

Octal to decimal conversion occurs when an octal number with the base of 8 has to be converted
to a decimal number with the base of 10.

 Step 1: Since an octal number only uses digits from 0 to 7, we first arrange the octal
number with the power of 8.
 Step 2: We evaluate all the power of 8 values such as 8 0 is 1, 81 is 8, etc., and write down
the value of each octal number.
 Step 3: Once the value is obt
obtained, we multiply each number.
 Step 4: Final step is to add the product of all the numbers to obtain the decimal number.

Octal to Hexadecimal Number Conversion

Hexadecimal numbers include binary digits; therefore, we can club these binary numbers into a
pair so that we can relate it with the octal numbers. Let us check the method with steps and
example:
 For each given hexadecimal number digit, write the equivalent binary number. If any of
the binary equivalents are less than 4 digits, add 0’s to the left side.
 Combine and make the groups of binary digits from right to left, each containing 3 digits.
Add 0’s to the left if there are less than 3 digits in the last group.
 Find the octal equivalent of each binary group.

Hexadecimal to Decimal number conversion

The conversion of hexadecimal to decimal is done by using the base number 16. The
hexadecimal digit is expanded to multiply each digit with the power of 16. The power starts at 0
from the right moving forward towards the right with the increase in power. For the conversion
to complete, the multiplied numbers are added.

The steps to convert hexadecimal to decimal are:

 Obtain the decimal equivalent of hexadecimal from the conversion table. (table
mentioned above)
 Multiply each digit with the power of 16 starting at 0 from the right.
 Add all the numbers together.
Hexadecimal to binary number conversion

This method is a direct procedure by just looking at the conversation table we can convert
hexadecimal to binary. The steps are fairly simple, lets loo
look at them:

 Step 1: Write the hexadecimal


 Step 2: Find the equivalent decimal of each of the digits by looking at the conversion
table.
 Step 2: Once the decimal number is obtained, looking at the same table we can convert it
to a binary.
 Step 3: Combine all the binary numbers together to obtain the final binary number.
number

Hexadecimal to Octal Number Conversion


Hexadecimal numbers include binary digits; therefore, we can club these binary numbers into a
pair so that we can relate it with the octal numbers. Let us check the method with steps and
example:

 For each given hexadecimal number digit, write the equivalent binary number. If any of
the binary equivalents are less than 4 digits, add 0’s to the left side.
 Combine and make the groups of binary digits from right to left, each containing 3 digits.
Add 0’s to the left if there are less than 3 digits in the last group.
 Find the octal equivalent of each binary group.

Steps to solve logical problems

The general strategy can be summarized in terms of five steps:

(1) Comprehend the problem: In this step you develop a qualitative description of the problem.
First, visualize the events described in the problem using a sketch. Write down a simple
statement of what you want to find out.

(2) Represent the problem in formal terms: Represent the problems in terms of formal
concepts and principals such as to which specific area the problem is related. It is useful in
simplifying the complexity of the problem.

(3) Plan a solution: plan a logical solution that is mostly depicted as mathematics. The solution
will involve a set of equations. Finally a logical chain of equations will be created to produce
effective logical solution.

(4) Execute the plan: Determine a solution by executing the logical steps. These steps are
nothing but the solution planned in the previous step. Execution must be done by applying all the
appropriate methods and techniques.
(5) Interpret and evaluate the solution: In this step the solution is checked and verified. The
solution should directly answer the problem and must not contain any unnecessary things.

Steps for solving numerical problems

The techniques used in computer to solve numeric problems are conveniently organized into a
three-step, problem-solving approach. This approach has been shown to be very helpful and
effective. So we recommend that you follow this approach when working on numeric problems
in this textbook. The steps for solving a numeric word problem are analyze, calculate, and
evaluate.

Analyze:

Initially determine the starting point and ending point i.e., the inputs, outputs and the
units of the output. Develop a plan to solve the problem and get relevant answer. Draw a table or
graph to visualize the problem and its data.

Calculate:

Calculations can be done easily if the planning is done effectively.

Evaluate:

Once the result is calculated, it should also be evaluated. It involves verifying the problem
solution whether the data correctly, whether appropriate equations are used, whether the numbers
are correctly rounded off, whether the units and figures are correct, finally the calculations and
checked.

1.1 Algorithms
History
Algorithms have a long history and the word can be traced back to the 9th century. At this
time the Persian scientist, astronomer and mathematician Abdullah Muhammad bin Musa al-
Khwarizmi, often cited as “The father of Algebra”, was indirect responsible for the creation
of the term “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.
Definition:
An algorithm is a step-by-step procedure/method for solving a problem or making
decisions.
Or
An algorithm is a finite sequence of well defined steps for solving a problem.

Characteristics of Algorithm

An algorithm has five important characteristics:

 Inputs: An algorithm may specify the quantities which are to be read.

 Outputs: An algorithm must specify the quantities which are to be displayed or printed.

 Definiteness: Each instruction must be clear and unambiguous.

 Finiteness: An algorithm should be terminated after finite number of steps.

 Effectiveness: An algorithm must be effective which means that all operations are
executable.

 Language Independent: The Algorithm designed must be language-independent, i.e. it


must be just plain instructions that can be implemented in any language, and yet the
output will be same, as expected.
Algorithm Development

To solve a problem on a computer. We need to identify the inputs and outputs to state the
problem in a precise manner,

The steps involved in developing algorithm are:

1. Identification of the nature of the problem and requirements.

2. Identification of the variables that are involved.

3. Identification of the relationship between the variables.

4. Problem formulation and analysis.


5. Identification of method of solving the problem.

6. Checking the results.

In solving a problem or computer programs we used to follow a systematic approach. There


may be much number of algorithms in solving a problem, but we can select a particular
algorithm, which we can follow it with ease, just as selecting an easy way to reach a wanted
destination.

Advantages of Algorithms:

 It is easy to understand.

 Algorithm is a step-wise representation of a solution to a given problem.

 In Algorithm the problem is broken down into smaller pieces or steps hence, it is easier
for the programmer to convert it into an actual program.

Disadvantages of Algorithms:

 Writing an algorithm takes a long time so it is time-consuming.

 Branching and looping statements are difficult to show in Algorithms.

Algorithms for simple problems

Write an algorithm to find the sum of four given numbers?

Ans:

Step 1: Start

Step 2: Read values of A, B, C, D

Step 3: Compute sum = A+B+C+D

Step 4: Print the values of sum

Step 5: Stop

 Write an algorithm to find the average of four given numbers?


Ans:
Step 1: Start

Step 2: Read values of A, B, C, D


Step 3: Compute average = (A+B+C+D)/4

Step 4: Print the values of average

Step 5: Stop

 Write an algorithm for calculating the simple interest.

Ans:

Formula of Interest=PTR/100, where P is the Principle amount, R is the rate of interest and T
is the time.

Step 1: Start

Step 2: Read values of P, T, R

Step 3: Compute I = P*T*R/100

Step 4: Print the values of P,T,R,I

Step 5: Stop

 Write an algorithm to convert centigrade temperature into Fahrenheit temperature.

Ans:

Step 1: Start

Step 2: Read values C

Step 3: Compute F = 1.8*C+32

Step 4: Print the values of C,F

Step 5: Stop

 Write an algorithm to find the area of a triangle, if the lengths of the sides are given.

Ans:

Step 1: Start

Step 2: Read values a, b, c


Step 3: Compute s = (a+b+c)/2

Step 4: Compute area = sqr root*(s(s-a)(s-b)(s-c)

Step 5: print the value of area

Step 6: Stop

 Write an algorithm to find the largest of 3 given numbers

Ans:

Step 1: Start

Step 2: Read values A, B, C

Step 3: Let BIG = A

Step 4: If B > BIG, then BIG = B

Step 5: If C > BIG, then BIG = C

Step 6: print BIG

Step 7: Stop

 Write an algorithm to find the sum of the first n natural numbers.

Ans:

Step 1: Start

Step 2: Read the value of n

Step 3: sum = 0

Step 4: I = 1

Step 5: sum = sum + I

Step 6: I = I +1

Step 7: if I < n

Step 8: print the value of sum

Step 9: Stop
Flowchart

History

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 Flowchart one can understand
the operations and sequence of operations performed in a system. Flowchart is often considered
as a blue print of a design used for solving a specific problem.

Definition:

A flowchart is a diagrammatic representation that shows the sequence of operations to be


performed to get the solution of a problem.

A flowchart is the graphical or pictorial representation of an algorithm with the help of different
symbols, shapes, and arrows to demonstrate a process or a program. With algorithms, we can
easily understand a program. The main purpose of using a flowchart is to analyze different
methods. Several standard symbols are applied in a flowchart.

Flowchart Symbols

1. Oval

 It is called as Terminal sybol


 It is used for beginning and ending point of the program.
 Examples:

Start Stop
2. Parallelogram

 It is called as input/output symbol


 It indicates an input or output operation
 Examples:

Read A, B,C Print sum


3. Rectangle

 It is called as process symbol.


 It used for representing any processing, computation and arithmetic
operations.
 Examples:
Sum = A+B+C+D

4. Diamond

 It is called as Decision symbol


 It is used for representing decisions that is to be taken and the subsequent
branches are to be followed depending upon the result of the decisions.
 Examples:

If A > B

5. Arrows

 It is called as flow lines


 It indicates the direction of the flow chart and to connect various flowchart
symbols.
6. Circle

 It is called as connecter symbol


 It is used to join various parts of a flowchart.

Advantages of Flowchart

1. It is a convenient method of communication.


2. It indicates very clearly just what is being done, where a program has logical
complexities.

3. A key to correct programming.

4. It is an important tool for planning and designing a new system.

5. It clearly indicates the role-played at each level.

6. It saves the inconveniences in future and serves the purpose of documentation for a
system.

7. It provides an overview of the system and also demonstrates the relationship between
various steps.

Disadvantages of Flowchart

1. The flowchart is a waste of time and slows down the process of software development.

2. Sometimes the Complex logic of the program logic is quite complicated to draw out on
by using different defined shapes. In that case, flowchart becomes complex and clumsy.

3. A correction in the logic of the given problem can require redrawing the entire flowchart.

Differences between a Flowchart and an Algorithm

Flowchart
• A flowchart is a graphical diagram of the solution to a problem.
• The process is shown in block-by-block information diagram
• It is intuitive and easy to understand.
• It is hard to debug errors.
• The solution is showcased in pictorial format.
• It costs less time to create a flowchart.
Algorithm
• An algorithm is a procedure for solving a problem.
• The process is shown in step-by-step instruction.
• It is complex and difficult to understand.
• It is convenient to debug errors.
• This solution is showcased in natural language.
• It costs more time to create an algorithm.
Flowcharts for simple problems

1. Draw a flowchart to calculate the circumference and area of a circle.

2. Draw a flowchart to find the largest of 3 given numbers

3. Draw a flow chart for finding whether the given number is odd or even?
4. A flowchart to convert temperature from Fahrenheit to Celsius

5. A Flowchart to find Area and Perimeter of Rectangle


6. Algorithm & Flowchart to Swap Two Numbers using Temporary Variable
7. Algorithm & Flowchart to find Even number between 1 to 50
Pseudo code

Definition: Pseudo code is way of describing the general structure of a program in simple
English language. Or

Pseudo code is defined as a method of describing a process or writing programming code and
algorithms using a natural language such as English.

It is not the code itself, but rather a description of what the code should do. In other
words, it is used as a detailed yet understandable step-by-step plan or blueprint from which a
program can be written. It is like a rough draft of a program or an algorithm before it is
implemented in a programming language. It can also be referred to as 'false code' or
'representation of code'. The purpose of using pseudocode is to provide a clear and concise
description of the steps that will be taken in a process or algorithm without the need for specific
syntax or code. Pseudocode is not compiled or executed on computers, it is only meant to be
read and understood by humans.

Advantages of Pseudocode
 Improves the readability of any approach. It’s one of the best approaches to start
implementation of an algorithm.
 Acts as a bridge between the program and the algorithm or flowchart. The main goal of a
pseudo code is to explain what exactly each line of a program should do, hence making
the code construction phase easier for the programmer.
Pseudo code examples
1 Write a pseudo code for addition of two numbers
 BEGIN
 NUMBER s1, s2, sum
 OUTPUT("Input number1:")
 INPUT s1
 OUTPUT("Input number2:")
 INPUT s2
 sum=s1+s2
 OUTPUT sum
 END
2 write a pseudo code for Area and Perimeter of Rectangle
 BEGIN
 NUMBER b1,b2,area,perimeter
 INPUT b1
 INPUT b2
 area=b1*b2
 perimeter=2*(b1+b2)
 OUTPUT area
 OUTPUT perimeter
 END

3 write a pseudo code to find the Area Of Circle using Radius


 BEGIN
 NUMBER r, area
 INPUT r
 area=3.14*r*r
 OUTPUT area
 END

4 write a pseudo code to find a Number is Positive or Negative


 BEGIN
 NUMBER num
OUTPUT "Enter a Number"
 INPUT num
 IF num>0 THEN
 OUTPUT "Entered number is positive"
 ELSE IF num <0 THEN
 OUTPUT "Entered number is negative"
 ELSE
 OUTPUT "Entered number is zero"
 ENDIF
 END
5 Write a pseudo code and flow chart for quadratic equation(ax2+bx+c = 0)

 Begin
 Input a, b, c.
 D ← sqrt (b × b – 4 × a × c).
 X1 ← (-b + d) / (2 × a).
 X2 ← (-b - d) / (2 × a).
 OUTPUT x1, x2.
 End

Program design and structured programming

Program Design
Computers play a major role in solving a problem. This is because of the good
communication that exists bet computers and their corresponding users. In order to write a
program, a process called programming' is required. But, before writing this, the problem to
be solved should be analyzed and need to be prepared by generating a step-by-step
procedure. The sufficient details about the problem are obtained. This process is referred to
as problem analysis while developing a program the following steps are required.
1. Problem Specification
The problem should be studied and understood well. The programmer should
have the knowledge about, what should be done in order to begin the first step. A
careful examination about the following is required to determine what has to be
done next.
2. Outlining the Solution In this step the problem to be solved is identified using solution
method. The chosen method is a path that defines, what is given and what is required to
solve the problem. There may be many solution methods available, but the following
conditions need to be considered before selecting a correct/appropriate solution method.
(a) The time needed to solve the problem
(b) Vulnerability to errors.

3. Programming or Coding the Algorithm

In this step, the algorithm written is converted into a program. Programs can be written in any
programming languages depending on the problems behavior and also on the availability of
those languages.

4 Removing Errors

In this step, the errors generated while developing a program are detected and then corrected.
Program verification is a process that assures the correctness of a program and debugging is a
mechanism that detect and removes the errors.

a. Syntax errors – the statements are not written according to the syntax or
grammatical rules of language
b. Runtime errors – these errors are generated when the program is being
executed.(which is fee from syntax errors)
c. Logical errors – these errors are generated when there are logically incorrect
statements in the program. Such errors are very difficult to be detected, because
they are found after examining the output.
5 Testing and validation
The programs must be tested and validated it should always produce correct and
appropriate results.
a. Valid cases – these king of test cases represent the data sets which are
logically related to the program
b. Invalid cases – these type of cases represent some situations which do not
provide any meaning and which deny the program statement.
6 Documentation and maintenance

The entire information of the program is collected, organized and maintained though a
process called documentation. Any changes in the program should be done according to the
requirements. This process is known as program maintenance. The programs must be written in a
clear and easy way, so that other users will identify the program very easy.

Structured Programming

Structured programming follows modular programming rapidly. This programming is built-on


the modularity principles. The procedure oriented approach is followed by programmers before
the development of object-oriented programming. Earlier, spaghetti code was used frequently in
the languages where the flow of control is usually decided by goto statement. This statement
alters the program execution. Hence, to avoid it, the structured programming was introduced.
The three basic structures used to express the code is instructed by the structured programming
principles. They are as follows,

1. Sequence of Operations
This principle states that the operations should be performed one after the other in a sequential
manner.
2. Loops
This principle states that a sequence is repeatedly executed until the condition becomes true. 3.
3. Selections
This principle states that a Boolean expression is used to decide a sequence that should be
executed among the given two sequences.

Introduction to C Programming Language

C Programming Language is a very popular computer programming language through which


users and computers can communicate.

What is C?
C is a computer programming language used to design computer software and applications.

Why do we use C?

We use the C programming language to design computer software and applications.


Who invented C?
C Programming Language was invented in the year 1972 by Dennis Ritchie (Dennis
MacAlistair Ritchie). He was an American Computer Scientist worked at Bell Labs as a
researcher along with Ken Thompson. He was born on 9th September 1941 and lived till 12th
October 2011. He is said to be the Father of C.
History of C Language

 C is a general-purpose programming language developed at AT & T Bell laboratories of


USA in 1972.
 It was designed by Dennis Ritchie.
 The earlier version of “C” was written by Ken Thompson who adopted it from BCPL
(Basic Combined Programming Language) called “B”.
 Dennis Ritchie studied it, improved and named as “C”.
 Much later, American National Standards Institute(ANSI) Published the “C” language as
a standard, The ANSI C standard was approved in 1989 and was updated in 1999.
 C language was developed to be used in UNIX operating system.
 C is often called a “Middle level language” since it stands in between High level and low
level languages.

Importance of C language
 C has a rich set of built-in functions and operators and these can be used to write any
complex programs.
 The c compiler combines the capabilities of an assembly language with the features of a
high-level language and therefore it is well suited for writing both system software and
business packages.
 Program written in C are efficient due to several variety of data types and powerful
operators.
 There are only 32 keywords; several standard functions are available which can be used
for developing program.
 C is portable language; this means that C programs written for one computer system can
be run on another system, with little or no modification.
 C language is well suited for structured programming, this requires user to think of a
problems in terms of function or modules or block. A collection of these modules make a
program debugging and testing easier.
 C language has its ability to extend itself. A c program is basically a collection of
functions that are supported by the C library. We can continuously add our own functions
to the library with the availability of the large number of functions.
C Language Uses
 C is used for writing Operating systems.
 It is used in language translators (compilers, Interpreters and Assemblers).
 It is used in Editors.
 It is used in Worksheets.
 Database Management systems.
Characteristics / Features of C Language
1. Portability
C programs are very portable means that C programs can be run easily on different machines or
PCs with little change or no change. Compiler and Preprocessor make it possible to run on
different PCs.

2. Powerful Programming Language


C programming language is a very fast and efficient programming language because it uses Data
Types, Function, and Control Statements.
3. Simple Programming Language
C language has commands like English, which makes it very easy for programmers to
understand the code and write programs.
4. Structured Oriented Language
C Language is a structured oriented programming language. Structured Oriented Programming
Language reduces the complexity of the code which leads to a lot of clarity in the programs.
5. Compiler Based
C language is a compiler based programming language. Programs of C language cannot be
executed or run without compiling.
6. Syntax Based Language
C language is a Syntax based programming language. Syntax Based Programming Language is
the language which treats rules and regulation strictly like C, C ++, Java, etc. If a programming
language does not strictly follow rules and regulations, then such programming language is
loosely called Syntax-based programming language such as HTML.
7. Middle Level Language
C language is a Middle Level Programming Language, using that low level programming can be
done and high level programming can also be done due to which both application software and
system software can be made easily with the help of C language.
8. Case Sensitive
C language is a Case Sensitive Programming Language. We understand the meaning of Case
Sensitive by an example, if we write such printf in C language and write PRINTF in another
place, then in C language, both are different things. This is a special feature of C Language.
9. Modularity/ Structured Programming
In C language, we can divide our code into blocks so that it is easier to read and write the code. It
is a technique to design software in which a whole program is divided into several functions or
blocks.

Structure of C Program (Basics)

C is a structured programming language. Every c program and its statements must be in a


particular structure. Every c program has the following general structure...
Line 1: Comments - They are ignored by the compiler

This section is used to provide a small description of the program. The comment lines are simply
ignored by the compiler that means they are not executed. In C, there are two types of comments.

1. Single Line Comments: Single line comment begins with // symbol. We can write any
number of single line comments.

2. Multiple Lines Comments: Multiple lines comment begins with /* symbol and ends
with */. We can write any number of multiple lines comments in a program.

In a C program, the comment lines are optional. Based on the requirement, we write comments.
All the comment lines in a C program just provide the guidelines to understand the program and
its code.

Line 2: Pre-processing
processing Commands

Preprocessing commands are used to include header files and to define constants. We use
the #include statement to include the header file into our program. We use a #define statement
to define a constant. The preprocessing
cessing statements are used according to the requirements. If we
don't need any header file, then no need to write #include statement? If we don't need any
constant, then no need to write a #define statement.

Line 3: Global Declaration


The global declaration is used to define the global variables, which are common for all the
functions after its declaration. We also use the global declaration to declare functions. This
global declaration is used based on the requirement.

Line 4: int main()

Every C program must write this statement. This statement (main) specifies the starting point of
the C program execution. Here, main is a user-defined method which tells the compiler that this
is the starting point of the program execution. Here, int is a data type of a value that is going to
return to the Operating System after completing the main method execution. If we don't want to
return any value, we can use it as void.

Line 5: Open Brace ( { )

The open brace indicates the beginning of the block which belongs to the main method. In C
program, every block begins with a '{' symbol.

Line 6: Local Declaration

In this section, we declare the variables and functions that are local to the function or block in
which they are declared. The variables which are declared in this section are valid only within
the function or block in which they are declared.

Line 7: Executable statements

In this section, we write the statements which perform tasks like reading data, displaying the
result, calculations, etc., All the statements in this section are written according to the
requirements.

Line 9: Closing Brace ( } )

The close brace indicates the end of the block which belongs to the main method. In C program
every block ends with a '}' symbol.

Line 10, 11, 12.,: User-defined function()

This is the place where we implement the user-defined functions. The user-defined function
implementation can also be performed before the main method. In this case, the user-defined
function need not be declared. Directly it can be implemented, but it must be before the main
method. In a program, we can define as many user-defined functions as we want. Every user-
defined function needs a function call to execute its statements.

C character set

A character denotes any alphabet, digit or special symbol used to represent information. Valid
alphabets, numbers and special symbols are used in C. The characters that are used to form basic
program elements (e.g., constants, variables, operators, expressions) in c programming language
called its character set. C language supports a total of 256 characters.

The characters used in C are grouped into the following categories:

1. Letters/Alphabets: C language supports all the alphabets from English language.

Lower and upper case letters together supports 52 alphabets.

 Lower case letters - a to z

 UPPER CASE LETTERS - A to Z

2. Digits: C language supports 10 digits which are used to construct numerical


values in C language.

 Digits - 0, 1, 2, 3, 4, 5, 6, 7, 8, 9

3. Special Symbols/Characters: C language supports rich set of special symbols


that include symbols to perform mathematical operations
4. White Space Characters: The compiler ignores white spaces unless they are a
part of a string constant. White spaces may be used to separate words in strings.
scanf() uses whitespace to separate consecutive input items from each other.

1. Blank Space 2. Horizontal Tab 3. Carriage Return 4. New Line 5. Form


Feed

Only these characters are allowed to construct statements in C. A single instruction is called a
statement.
Every character in C language
anguage has its equivalent ASCII (American Standard Code for
Information Interchange) value.

#Write a C program to print all the ASCII Values of a C Character set

#include <stdio.h>
#include<conio.h>
int main()
{
int i;
printf("ASCII VALUES\n");n");
for(i=-128;i<=127;i++)
printf("%d===> %c\n", i, i);
getch();
return 0;
}
C Tokens

A token is a sequence of one or more characters that have a uniform meaning. So the
smallest individual elements in a program are called tokens. Each token should be separated
from the other by a white space. The C tokens can be divided into the following:

1. Variables
2. Identifiers
3. Keywords/reserved words
4. Constants
5. Special symbols
6. Operators
7. Strings

Variables
A variable is a named memory location that can hold various values. The name of the
location (an identifier) is the called the variable name. A variable is identified by a unique name.
The value stored in the location is called the value of the variable. We can visualize variables as
a box, each of which have a name and contains a value.
A variable is a quantity whose value can varied during program execution.

Syntax: Datatypes variablenames;

Rules for constructing variable names

 A variable name consists of any sequence of letters, digits, and underscores (_).
 Except underscore no special character is permitted in a variable.
 The first character of the variable name must be a letter.
 A variable name can be of any length but compiler considers only the first 31 characters
of the variable name.
 Uppercase and lowercase letters are distinct. So the names sum, Sum, SUM are three
different variables.
 No commas or blanks are allowed within a variable name
 A variable name cannot be a keyword. However, keyword may be part of variable

Examples

Root1 sum g_salary num student_name code2 area roll_no a


1
Invalid variables 2

2root student add double x*y Hyderabad$ int_types 3


Scope of Variable in C/ space requirements of a variable in c
When we declare a variable in a program, it cannot be accessed against the scope rules. Variables
can be accessed based on their scope. The scope of a variable decides the portion of a program in
which the variable can be accessed. The scope of the variable is defined as follows...
Scope of a variable is the portion of the program where a defined variable can be accessed. It is
categorized into two types
Before the function definition (Global Declaration)
Declaring a variable before the function definition (outside the function definition) is
called global declaration. The variable declared using global declaration is called global variable.
Tha global variable can be accessed by all the functions that are defined after the global
declaration. That means the global variable can be accessed anywhere in the program after its
declaration. The global variable scope is said to be file scope.
Example program
#include<stdio.h>
#include<conio.h>
int num1, num2 ;
void main()
{
void addition() ;
void subtraction() ;
void multiplication() ;
num1 = 10 ;
num2 = 20 ;
printf("num1 = %d, num2 = %d", num1, num2) ;
addition() ;
subtraction() ;
multiplication() ;
getch() ;
}
void addition()
{
int result ;
result = num1 + num2 ;
printf("\naddition = %d", result) ;
}
void subtraction()
{
int result ;
result = num1 - num2 ;
printf("\nsubtraction = %d", result) ;
}
void multiplication()
{
int result ;
result = num1 * num2 ;
printf("\nmultiplication = %d", result) ;
}
Output:
num1 = 10, num2 = 20
addition = 30
subtraction = -10
multiplication = 200
In the above example program, the variables num1 and num2 are declared as global variables.
They are declared before the main() function. So, they can be accessed by function main() and
other functions that are defined after main(). In the above example, the functions main(),
addition(), subtraction() and multiplication() can access the variables num1 and num2.
Inside the function or block (Local Declaration)
Declaring a variable inside the function or block is called local declaration. The variable
declared using local declaration is called local variable. The local variable can be accessed only
by the function or block in which it is declared. That means the local variable can be accessed
only inside the function or block in which it is declared.
Example Program
#include<stdio.h>
#include<conio.h>
void main(){
void addition() ;
int num1, num2 ;
num1 = 10 ;
num2 = 20 ;
printf("num1 = %d, num2 = %d", num1, num2) ;
addition() ;
getch() ;
}
void addition()
{
int sumResult ;
sumResult = num1 + num2 ;
printf("\naddition = %d", sumResult) ;
}
Output: Error
The above example program shows an error because, the variables num1 and num2 are declared
inside the function main(). So, they can be used only inside main() function and not in addition()
function.
Identifiers

The identifier is a user-defined name of an entity to identify it uniquely during the program
execution

The names of variables, functions, labels and various other user-defined objects are called
Identifiers. Identifiers are used for defining variable names, function names etc. An identifier is a
collection of characters which acts as the name of variable, function, array, pointer, structure,
etc... In other words, an identifier can be defined as the user-defined name to identify an entity
uniquely in the c programming language that name may be of the variable name, function name,
array name, pointer name, structure name or a label.

Example

int marks;
char studentName[30];

Here, marks and studentName are identifiers.


Rules for Creating Identifiers
1. An identifier can contain letters (UPPERCASE and lowercase),
numerics & underscore symbol only.

2. An identifier should not start with a numerical value. It can start with a letter or an
underscore.

3. We should not use any special symbols in between the identifier even whitespace.
However, the only underscore symbol is allowed.

4. Keywords should not be used as identifiers.


5. There is no limit for the length of an identifier. However, the compiler considers the first
31 characters only. Hence sum, Sum and SUM are three separate identifiers.

6. An identifier must be unique in its scope.

Some examples of valid identifiers:

K1 Root1 sum temperature

Name stud_add area tax_rate

C programs are written using these tokens and the syntax of the language.
Keywords
At the time of designing a computer program or language, some words are reserved to do
specific tasks. Such words are called as keywords or reserved words.

The keywords are also identifiers but cannot be user defined since they have a specific
meaning to the compiler. These names cannot be used as names of identifiers or variables. For
example, ‘long’ is a keyword and cannot be used as an ordinary variable. All keywords must be
reserved words.

In the C programming language, there are 32 keywords. All the 32 keywords have their
meaning which is already known to the compiler.

Properties of Keywords

1. All the keywords in C programming language are defined as lowercase letters so they
must be used only in lowercase letters

2. Every keyword has a specific meaning; users can not change that meaning.

3. Keywords cannot be used as user-defined names like variable, functions, arrays, pointers,
etc...

4. Every keyword in C programming language represents something or specifies some kind


of action to be performed by the compiler.

The following table specifies all the 32 keywords with their meaning.
Constants

A constant is a named memory location which holds only one value throughout the program
execution. Constants in C refer to fixed values that do not cha
change
nge during the execution of a
program. C has four types of constants.
In C programming language, a constant can be of any data type like integer, floating-point,
character, string and double, etc.,

Integer constants

An integer constant can be a decimal integer or octal integer or hexadecimal integer. A


decimal integer value is specified as direct integer value whereas octal integer value is prefixed
with '0' and hexadecimal value is prefixed with 'OX'.

An integer constant can also be unsigned type of integer constant or long type of integer
constant. Unsigned integer constant value is suffixed with 'u' and long integer constant value is
suffixed with 'l' whereas unsigned long integer constant value is suffixed with 'ul'.

Example

125 -----> Decimal Integer Constant


O76 -----> Octal Integer Constant
OX3A -----> Hexa Decimal Integer Constant
50u -----> Unsigned Integer Constant
30l -----> Long Integer Constant
100ul -----> Unsigned Long Integer Constant

Floating point / Real constants

 A sequence of numeric digits with either a decimal point or an exponent or both is called
a floating-point constant. These are either positive or negative. No commas or blanks are
permitted with in a constant. These constants are also known as real constants.
 These constants could be written in two forms, fractional and exponential form. These are
stored in 32 bits with 6 digits of precision.
 The exponential form is useful for representing numbers that are either two small or too
large. In exponential form of representation, the floating point constant is represented in
two parts. The part appearing before ‘e’ is called mantissa, where as the part following
‘e’ is called exponent.
 The letter ‘e’ can be written in either lowercase or uppercase. The exponent must have
atleast one digit which must be a positive or negative integer. Ex. The floating-point
value 3.14 is represented as 3E-14 in exponent form
 The floating point constants cab be declared as ‘float’ in C.
Examples
0.1245---floating point constant
4567.78 floating point constant
2E_8--- floating point constant
23456.78e5L floating point constant
Character Constants
A character constant is a symbol enclosed in single quotation. A character constant has a
maximum length of one character. A character constants differs from a numeric constant in the
way that arithmetic operations can be performed on numeric constants while the character
constant is just simple text and is not used in arithmetic expressions.

Example

'A'
'2'
'+'
‘a’
‘,’

Escape sequences / Backslash character constants


Escape sequence are used in formatting input and output. An escape sequence always
begins with a backward slash and is followed by a character.
For example, a line feed which is referred to as a new line, can be represented as \n. This
is frequently used in the print statement to move to the next line. When the computer comes
across \n. the cursor automatically goes to the first position in the next line and the next character
to be printed appears at the beginning of the next line down. It is called an escape sequence,
since the backslash causes an “escape” from the normal way characters are interpreted.
In the C programming language, there are some predefined character constants called escape
sequences. Every escape sequence has its own special functionality and every escape sequence is
prefixed with '\' symbol. These escape sequences are used in output function called 'printf()'.

Backslash Characters
The backslash characters are as follows −
Character Meaning
‘\a’ Alert
‘\b’ Backspace
‘\f’ form feed
‘\n’ Newline
‘\t’ horizontal tab
‘\r’ carriage return
‘\v’ vertical tab
‘\\’ Backslash
‘\’ ’ single quote
Character Meaning
‘\" ’ double quote
‘\?’ Question mark
‘\0’ Null character

String Constants
A string constant is a collection of characters, digits, special symbols and escape sequences that
are enclosed in double quotations.

We define string constant in a single line as follows...


"This is Programming for problem solving class"
We can also define string constant by separating it with white space as follows...
"This" "is" "Programmingclass"
All the above three defines the same string constant
Examples: “C” “ “ “pec” “678” “=”

Every string constant terminates with a special character called as null character or simply null
represented as ‘\0’. The compiler automatically places the null character \0 at the end of string to
identify its end.

Creating constants in C

In a c programming language, constants can be created using two concepts...

1. Using the 'const' keyword

2. Using '#define' preprocessor

Using the 'const' keyword

We create a constant of any datatype using 'const' keyword. To create a constant, we prefix the
variable declaration with 'const' keyword.
The general syntax for creating constant using 'const' keyword is as follows...

const datatype constantName ;

OR

const datatype constantName = value ;

Example

const int x = 10 ;
Here, 'x' is a integer constant with fixed value 10.

Example Program
#include<stdio.h>
#include<conio.h>
void main()
{
int i = 9 ;
const int x = 10 ;
i = 15 ;
x = 100 ; // creates an error
printf("i = %d\nx = %d", i, x ) ;
}
The above program gives an error because we are trying to change the constant variable value (x
= 100).
Using '#define' preprocessor

We can also create constants using '#define' preprocessor directive. When we create
constant using this preprocessor directive it must be defined at the beginning of the program
(because all the preprocessor directives must be written before the global declaration).
We use the following syntax to create constant using '#define' preprocessor directive...

#define CONSTANTNAME value


Example
#define PI 3.14
Here, PI is a constant with value 3.14
Example Program
#include<stdio.h>
#include<conio.h>
#defiene PI 3.14
void main()
{
int r, area ;
clrscr();
printf("Please enter the radius of circle : ") ;
scanf("%d", &r) ;
area = PI * (r * r) ;
printf("Area of the circle = %d", area) ;
}
C Expressions
An expression is a collection of operators and operands that represents a specific value.
v In the
above definition, an operator is a symbol that performs tasks like arithmetic operations, logical
operations, and conditional operations, etc.
In any programming language, if we want to perform any calculation or to frame any condition
etc., wee use a set of symbols to perform the task. These set of symbols makes an expression.
In the above definition, an operator is a symbol that performs tasks like arithmetic operations,
logical operations, and conditional operations, etc.
Operands are the values
ues on which the operators perform the task. Here operand can be a direct
value or variable or address of memory location.
Expression Types in C
In the C programming language, expressions are divided into THREE types. They are as
follows...
1. Infix Expression
2. Postfix Expression
3. Prefix Expression
The above classification is based on the operator position in the expression.
Infix Expression
The expression in which the operator is used between operands is called infix expression.
The infix expression has the following
lowing general structure.
Operand1 Operator Operand2
Example

Postfix Expression
The expression in which the operator is used after operands is called postfix expression.
The postfix expression has the following general structure.
Operand1 Operand2 Operator or
Example

Prefix Expression
The expression in which the operator is used before operands is called a prefix expression.
The prefix expression has the following general structure.
Operator Operand1 Operand2
Example

C Operators

An operator is a symbol used to perform arithmetic and logical operations in a program. That
means an operator is a special symbol that tells the compiler to perform mathematical or logical
operations. C programming language supports a rich set of operators that are classified as
follows.

1. Arithmetic Operators

2. Relational Operators

3. Logical Operators

4. Increment & Decrement Operators

5. Assignment Operators

6. Bitwise Operators

7. Conditional Operator

8. Special Operators

Arithmetic Operators (+, -,, *, /, %)

The arithmetic operators are the symbo


symbolsls that are used to perform basic mathematical operations
like addition, subtraction, multiplication, division and percentage modulo. The following table
provides information about arithmetic operators.

Operator Meaning Example

+ Addition 10 + 5 = 15

- Subtraction
ubtraction 10 - 5 = 5
Operator Meaning Example

* Multiplication 10 * 5 = 50

/ Division 10 / 5 = 2

% Remainder of the Division 5%2=1

 The addition operator can be used with numerical data types and character data type.
When it is used with numerical values, it performs mathematical addition and when it is
used with character data type values, it performs concatenation (appending).
 The remainder of the division operator is used with integer data type only.

Assignment Operators (=, +=, -=, *=, /=, %=)


The assignment operators are used to assign right-hand side value (Rvalue) to the left-hand side
variable (Lvalue). The assignment operator is used in different variants along with arithmetic
operators. The following table describes all the assignment operators in the C programming
language.

Operator Meaning Example

= Assign the right-hand side value to left-hand side variable A = 15

+= Add both left and right-hand side values and store the A += 10
result into left-hand side variable ⇒ A = A+10

-= Subtract right-hand side value from left-hand side A -= B


variable value and store the result ⇒ A = A-B
into left-hand side variable

*= Multiply right-hand side value with left-hand side A *= B


variable value and store the result ⇒ A = A*B
into left-hand side variable

/= Divide left-hand side variable value with right-hand side A /= B


variable value and store the result ⇒ A = A/B
into the left-hand side variable

%= Divide left-hand side variable value with right-hand side A %= B


variable value and store the remainder ⇒ A = A%B
Operator Meaning Example

into the left-hand side variable

Increment & Decrement Operators (++ & --)

The increment and decrement operators are called unary operators because both need only one
operand. The increment operator adds one to the existing value of the operand and the decrement
operator subtracts one from the existing value of the operand. The following table provides
information about increment and decrement operators.

Operator Meaning Example

++ Increment - Adds one to existing value int a = 5;


a++; ⇒ a = 6
-- Decrement - Subtracts one from existing value int a = 5;
a--; ⇒ a = 4
The increment and decrement operators are used infront of the operand (++a) or after the
operand (a++). If it is used infront of the operand, we call it as pre-increment or pre-
decrement and if it is used after the operand, we call it as post-increment or post-decrement.
Pre-Increment or Pre-Decrement
In the case of pre-increment, the value of the variable is increased by one before the expression
evaluation. In the case of pre-decrement, the value of the variable is decreased by one before the
expression evaluation. That means, when we use pre-increment or pre-decrement, first the value
of the variable is incremented or decremented by one, then the modified value is used in the
expression evaluation.
Example Program
#include<stdio.h>
#include<conio.h>
void main(){
int i = 5,j;
j = ++i; // Pre-Increment
printf("i = %d, j = %d",i,j);
}
Output
i=6, j=6
Post-Increment or Post-Decrement
In the case of post-increment, the value of the variable is increased by one after the expression
evaluation. In the case of post-decrement, the value of the variable is decreased by one after the
expression evaluation. That means, when we use post-increment or post-decrement, first the
expression is evaluated with existing value, then the value of the variable is incremented or
decremented by one.
Example Program
#include<stdio.h>
#include<conio.h>
void main(){
int i = 5,j;
j = i++; // Post-Increment
printf("i = %d, j = %d",i,j);
}

Output i=6, j=5

Relational Operators (<, >, <=, >=, ==, !=)

The relational operators are the symbols that are used to compare two values. That means the
relational operators are used to check the relationship between two values. Every relational
operator has two results TRUE or FALSE. In simple words, the relational operators are used to
define conditions in a program. The following table provides information about relational
operators.

Operator Meaning Example

< Returns TRUE if the first value is smaller than 10 < 5 is FALSE
second value otherwise returns FALSE

> Returns TRUE if the first value is larger than second 10 > 5 is TRUE
value otherwise returns FALSE

<= Returns TRUE if the first value is smaller than or 10 <= 5 is FALSE
equal to second value otherwise returns FALSE

>= Returns TRUE if the first value is larger than or 10 >= 5 is TRUE
equal to second value otherwise returns FALSE

== Returns TRUE if both values are equal otherwise 10 == 5 is FALSE


returns FALSE

!= Returns TRUE if both values are not equal 10 != 5 is TRUE


otherwise returns FALSE

Logical Operators (&&, ||, !)


The logical operators are the symbols that are used to combine multiple conditions into one
condition. The following table provides information about logical operators.

Operator Meaning Example

&& Logical AND - Returns TRUE if all conditions 10 < 5 && 12 > 10 is
are TRUE otherwise returns FALSE FALSE

|| Logical OR - Returns FALSE if all conditions 10 < 5 || 12 > 10 is


are FALSE otherwise returns TRUE TRUE

! Logical NOT - Returns TRUE if condition is !(10 < 5 && 12 >


FLASE and returns FALSE if it is TRUE 10) is TRUE

 Logical AND - Returns TRUE only if all conditions are TRUE, if any of the conditions is
FALSE then complete condition becomes FALSE.
 Logical OR - Returns FALSE only if all conditions are FALSE, if any of the conditions
is TRUE then complete condition becomes TRUE.

Bitwise Operators (&, |, ^, ~, >>, <<)

The bitwise operators are used to perform bit-level operations in the c programming language.
When we use the bitwise operators, the operations are performed based on the binary values. The
following table describes all the bitwise operators in the C programming language.
Let us consider two variables A and B as A = 25 (11001) and B = 20 (10100).

Operator Meaning Example

& the result of Bitwise AND is 1 if all the bits are 1 A&B
otherwise it is 0 ⇒ 16 (10000)

| the result of Bitwise OR is 0 if all the bits are 0 A|B


otherwise it is 1 ⇒ 29 (11101)

^ the result of Bitwise XOR is 0 if all the bits are same A^B
otherwise it is 1 ⇒ 13 (01101)
Operator Meaning Example

~ the result of Bitwise once complement is negation of ~A


the bit (Flipping) ⇒ 6 (00110)

<< the Bitwise left shift operator shifts all the bits to the A << 2
left by the specified number of positions ⇒ 100
(1100100)

>> the Bitwise right shift operator shifts all the bits to the A >> 2
right by the specified number of positions ⇒ 6 (00110)

Write a C Program to demonstrate use of bitwise operators

#include <stdio.h>
int main()
{
// a = 5(00000101), b = 9(00001001)
int a = 5, b = 9;
// The result is 00000001
printf("a = %d, b = %d\n", a, b);
printf("a&b = %d\n", a & b);

// The result is 00001101


printf("a|b = %d\n", a | b);

// The result is 00001100


printf("a^b = %d\n", a ^ b);

// The result is 11111010


printf("~a = %d\n", a = ~a);

// The result is 00010010


printf("b<<1 = %d\n", b << 1);

// The result is 00000100


printf("b>>1 = %d\n", b >> 1);

return 0;

}
Ouput: a = 5, b = 9
a&b = 1
a|b = 13
a^b = 12
~a = -6
b<<1 = 18
b>>1 = 4
Conditional Operator (?:)
The conditional operator is also called a ternary operator because it requires three operands.
This operator is used for decision making. In this operator, first we verify a condition, then we
perform one operation out of the two operations based on the condition result. If the condition is
TRUE the first option is performed, if the condition is FALSE the second option is performed.
The conditional operator is used with the following syntax.

Condition ? TRUE Part : FALSE Part;

Example

A = (10<15)?100:200; ⇒ A value is 100

Special Operators (sizeof, pointer, comma, dot, etc.)

The following are the special operators in c programming language.

sizeof operator

This operator is used to find the size of the memory (in bytes) allocated for a variable. This
operator is used with the following syntax.

sizeof(variableName);

Example

sizeof(A); ⇒ the result is 2 if A is an integer

Pointer operator (*)


This operator is used to define pointer variables in c programming language.

Syntax: data_type pointer_variable;

Ex: int *ptr;

Comma operator (,)

This operator is used to separate variables while they are declaring, separate the expressions in
function calls, etc.

Syntax: data_type var1, var2…;

Ex: int a, b, c;

Dot operator (.)

This operator is used to access members of structure or union.

Precedence and Associatively of operators

Operator precedence determines which operator is performed first in an expression with more
than one operators with different precedence.
For example: Solve

10 + 20 * 30

10 + 20 * 30 is calculated as 10 + (20 * 30)=610

and not as (10 + 20) * 30

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

1) Associativity is only used when there are two or more operators of same precedence.
The point to note is associativity doesn’t define the order in which operands of a single operator
are evaluated.
2) All operators with the same precedence have same associativity
This is necessary, otherwise, there won’t be any way for the compiler to decide evaluation order
of expressions which have two operators of same precedence and different associativity. For
example + and – have the same associativity.

3) Precedence and associativity of postfix ++ and prefix ++ are different


Precedence of postfix ++ is more than prefix ++, their associativity is also different.
Associativity of postfix ++ is left to right and associativity of prefix ++ is right to left.

4) Comma has the least precedence among all operators and should be used carefully For
example consider the following program, the output is 1. See this and this for more details.

#include <stdio.h>
int main()
{
int a;
a = 1, 2, 3; // Evaluated as (a = 1), 2, 3
printf("%d", a);
return 0;
} Output: 1

C Expression Evaluation
An expression is evaluated based on the precedence and associativity of the operators in that
expression.
In the C programming language, an expression is evaluated based on the operator precedence
and associativity. When there are multiple operators in an expression, they are evaluated
according to their precedence and associativity. The operator with higher precedence is evaluated
first and the operator with the least precedence is evaluated last.
To understand expression evaluation in c, let us consider the following simple example
expression...
10 + 4 * 3 / 2
In the above expression, there are three operators +, * and /. Among these three operators, both
multiplication and division have the same higher precedence and addition has lower precedence.
So, according to the operator precedence both multiplication and division are evaluated first and
then the addition is evaluated. As multiplication and division have the same precedence they are
evaluated based on the associativity. Here, the associativity of multiplication and division is left
to right. So, multiplication is performed first, then division and finally addition. So, the above
expression is evaluated in the order of * / and +. It is evaluated as follows...
4 * 3 ====> 12
12 / 2 ===> 6
10 + 6 ===> 16
The expression is evaluated to 16.

Syntax and Logical Errors in compilation, object and executable code

Error: Error is an illegal operation performed by the user which results in abnormal working of
the program. or
An error in the C language is an issue that arises in a program, making the program not work in
the way it was supposed to work or may stop from compiling as well. If an error appears in a
program, the program can do one of the following three things: the code will not compile, the
program will stop working during execution, or the program will generate garbage values or an
incorrect output. There are five different types of errors in C Programming like Syntax
Error, Run Time Error, Logical Error, Semantic Error, and Linker Error.
Syntax error
Syntax errors are also known as the compilation errors as they occurred at the compilation time.
These errors are mainly occurred due to the mistakes while typing when programmer does not
follow the grammar rule of the programming language. These errors can be easily corrected.
Commonly occurred syntax errors are: using variable without its declaration, missing the
semicolon (;) at the end of the statement.

Run-time error / Execution Error


The errors exist during the execution-time even after the successful compilation known as run-
time errors. When the program is running, and it is not able to perform the operation is the main
cause of the run-time error. The division by zero is the common example of the run-time error.
These errors are very difficult to find, as the compiler does not point out to these errors.
Linker error
Linker errors are mainly generated when the executable file of the program is not created. This
can be happened either due to the wrong function prototyping or usage of the wrong header file.

Logical error
The logical error is an error that leads to an undesired output. These errors produce the incorrect
output, but they are error-free, known as logical errors. The occurrence of these errors mainly
depends upon the logical thinking of the developer.

Semantic error
Semantic errors are the errors that occurred when the statements are not understandable by the
compiler. The following can be the cases for the semantic error:

Data Types

C data types

Data used in c program is classified into different types based on its properties. In the C
programming language, a data type can be defined as a set of values with similar characteristics.
All the values in a data type have the same properties.
Data types in the c programming language are used to specify what kind of value can be stored in
a variable. The memory size and type of the value of a variable are determined by the variable
data type. In a c program, each variable or constant or array must have a data type and this data
type specifies how much memory is to be allocated and what type of values are to be stored in
that variable or constant or array. The formal definition of a data type is as follows...

The Data type is a set of value with predefined characteristics. data types are used to declare
variable, constants, arrays, pointers, and functions.

In the c programming language, data types are classified as follows...

3. Primary data types (Basic data types OR Predefined data types)


4. Derived data types (Secondary data types OR User-defined data types)
5. Enumeration data types
6. Void data type
1. Primary data types

The primary data types in the C programming language are the basic data types. All the
primary data types are already defined in the system. Primary data types are also called as Built-
In data types. The following are the primary data types in c programming language...

1. Integer data type – written as int


2. Floating Point data type – written as float / Double data type – written as double
3. Character data type – written as char

Primary data types in c – block diagram


Primary data type declaration

In memory of the computer, the data types are stored differently. So you have to tell the
computer whether your variable will be integer, float/real, or character variable. Each type is
represented in a different way inside the machine and needs space of a different size. For this
reason, it is necessary to declare the type of all variable before they can appear in executable
statements.

Datatype
To declare variables syntax is type v1,….,vn;
v1, v2, v2,
…, vn;
Where type is a C data type and v1, v2. vn are the names of the variables. In C programming, a
variable declaration is a statement and it must end with a semicolon (;).

1. Integer Data type

The integer data type is a set of whole numbers. Every integer value does not have the decimal
value. We use the keyword "int" to represent integer data type in c. We use the keyword int to
declare the variables and to specify the return type of a function. The integer data type is used
with different type modifiers like short, long, signed and unsigned. The following table provides
complete details about the integer data type.

Declaration of the Integer variable

the following declaration statements declares a, b, c to integer variables

int a;

int b;

int c;
C allows the declaration of variables that have the same type in a single declaration by separating
the variable names with commas. Thus a, b, c can also be declared by

int a, b, c;

if we need to store integer values less than -32768 or greater than 32,767, it should use long int.
or short int. to declare the variables a and b as a short int and c as a long int, it would be

short int a, b;

long int c;

whereas an unsigned short int has a range from 0 to 65535, to declare an integer variable as
being non-negative only, use the unsigned qualifier, as follows:

unsigned int step;

unsigned short int p;

unsigned long int q;

2. Floating Point data types / double data types

Floating-point data types are a set of numbers with the decimal value. Every floating-point
value must contain the decimal value. The floating-point data type has two variants...

 float

 double

We use the keyword "float" to represent floating-point data type and "double" to represent
double data type in c. Both float and double are similar but they differ in the number of decimal
places. The float value contains 6 decimal places whereas double value contains 15 or 19
decimal places.

The following table provides complete details about floating-point data types.

Declaration of the Floating-point and double variables


To declare a variable capable of holding real values, we use the keyword float or double.

float roo1, root2;

Double area;

The word double stands for double-precision. It is capable of representing a value which is about
twice as much precision as that of a float. The precision refers to the number of decimal places
that can be represented.

3. Character data type

The character data type is a set of characters enclosed in single quotations. The following table
provides complete details about the character data type.

Declaration of the character variables

To declare the variable capable of holding character constants, we use the keyword char.

Char x, y;

Char c;

A variable of type char is 8 bits long and is used to store a single character of information.
void data type

The void data type means nothing or no value. Generally, the void is used to specify a function
which does not return any value. We also use the void data type to specify empty parameters of a
function.

Enumerated data type

An enumerated data type is a user-defined data type that consists of integer constants and each
integer constant is given a name. The keyword "enum" is used to define the enumerated data
type.

Derived data types

Derived data types are user-defined data types. The derived data types are also called as user-
defined data types or secondary data types. In the c programming language, the derived data
types are created using the following concepts...

 Arrays

 Structures

 Unions

 Enumeration

Type Casting and Conversion in C

In a programming language, the expression contains data values of the same datatype or different
data types. When the expression contains similar datatype values then it is evaluated without any
problem. But if the expression contains two or more different datatype values then they must be
converted to the single datatype of destination datatype. Here, the destination is the location
where the final result of that expression is stored. For example, the multiplication of an integer
data value with the float data value and storing the result into a float variable. In this case, the
integer value must be converted to float value so that the final result is a float datatype value.
In a c programming language, the data conversion is performed in two different methods as
follows...

1. Type Conversion

2. Type Casting

Type Conversion

The type conversion is the process of converting a data value from one data type to another data
type automatically by the compiler. Sometimes type conversion is also called implicit type
conversion. The implicit type conversion is automatically performed by the compiler.
For example, in c programming language, when we assign an integer value to a float variable the
integer value automatically gets converted to float value by adding decimal value 0. And when a
float value is assigned to an integer variable the float value automatically gets converted to an
integer value by removing the decimal value. To understand more about type conversion observe
the following...

int i = 10 ;
float x = 15.5 ;
char ch = 'A' ;

i = x ; =======> x value 15.5 is converted as 15 and assigned to variable i

x = i ; =======> Here i value 10 is converted as 10.000000 and assigned to variable x

i = ch ; =======> Here the ASCII value of A (65) is assigned to i

Write a C program to print values by using type conversion

#include<stdio.h>
#include<conio.h>

void main(){
int i = 95 ;
float x = 90.99 ;
char ch = 'A' ;

i=x;
printf("i value is %d\n",i);
x=i;
printf("x value is %f\n",x);
i = ch ;
printf("i value is %d\n",i);

}
Output: i value is 90
x value is 90.000000
i value is 65
In the above program, we assign i = x, i.e., float variable value is assigned to the integer variable.
Here, the compiler automatically converts the float value (90.99) into integer value (90) by
removing the decimal part of the float value (90.99) and then it is assigned to variable i.
Similarly, when we assign x = i, the integer value (90) gets converted to float value (90.000000)
by adding zero as the decimal part.

Typecasting
Converting one datatype into another is known as type casting or, type-conversion. Typecasting
is also called an explicit type conversion. Compiler converts data from one data type to another
data type implicitly. When compiler converts implicitly, there may be a data loss. In such a case,
we convert the data from one data type to another data type using explicit type conversion. To
perform this we use the unary cast operator. To convert data from one type to another type we
specify the target data type in parenthesis as a prefix to the data value that has to be converted.
The general syntax of typecasting is as follows.
(TargetDatatype) DataValue
Consider the following example where the cast operator causes the division of one integer
variable by another to be performed as a floating-point operation
#include <stdio.h>
main()
{
int sum = 17, count = 5;
double mean;

mean = (double) sum / count;


printf("Value of mean : %f\n", mean );
}
Output: 3.400000

When the above code is compiled and executed, it produces the following result −
Value of mean: 3.400000
It should be noted here that the cast operator has precedence over division, so the value of sum is
first converted to type double and finally it gets divided by count yielding a double value.
Type conversions can be implicit which is performed by the compiler automatically, or it can be
specified explicitly through the use of the cast operator. It is considered good programming
practice to use the cast operator whenever type conversions are necessary.

C Storage Classes (auto, extern, static and register)


Storage classes
Storage Classes are used to describe the features of a variable/function. These features basically
include the scope, visibility and life-time which help us to trace the existence of a particular
variable during the runtime of a program.
In C programming language, storage classes are used to define things like storage
location (whether RAM or REGISTER), scope, lifetime and the default value of a variable.
The allocation of memory depends on storage classes.
In C programming language, there are FOUR storage classes and they are as follows...
1. auto storage class
2. extern storage class
3. static storage class
4. register storage class
auto storage class
The default storage class of all local variables (variables declared inside block or function) is
auto storage class. They are declared using keyword auto.
Syntax: auto data_type variable;
Variable of auto storage class has the following properties...
Property Description

Keyword auto

Storage Computer Memory (RAM)

Default Value Garbage Value

Scope Local to the block in which the variable is defined

Life time Till the control remains within the block in which variable is defined

Example Program 1
#include <stdio.h>
int main()
{
auto int a, b;
printf("\n %d\t%d",a,b);
return 0;
}
Output: 0 23445
The above example prints the garbage values since the variables a and b are not assigned any
values.
Example Program 2
#include<stdio.h>
#include<conio.h>
int main(){
int i;
auto char c;
float f;
printf("i = %d\tc = %c\tf = %f",i,c,f);
return 0;
}
Output: i = 0 c = f = 0.000000
Example Program 3
#include<stdio.h>
#include<conio.h>
int main(){
int a=10;
{ int a=20;
printf("%d",a);
}
printf(" %d",a);
return 0;
}
Output: 20 10

External storage class


The external storage class variables are declared outside all functions using keyword extern
The default storage class of all global varibles (variables declared outside function) is external
storage class is zero.
Syntax: extern data_type variable;
Variable of external storage class has the following properties...
Property Description

Keyword Extern

Storage Computer Memory (RAM)

Default Value Zero

Scope Global to the program (i.e., Throughout the program)

Life time As long as the program’s execution does not comes to end
Example Program 1
#include<stdio.h>
#include<conio.h>
int i; //By default it is extern variable
int main(){
printf("%d",i);
return 0;
}Output: 0
Example Program 2
#include<stdio.h>
#include<conio.h>
extern int i; //extern variable
int main(){
printf("%d",i);
return 0;
}
Output: 0
Static storage class
The static storage class is used to create variables that hold value beyond its scope until the end
of the program. The static variable allows to initialize only once and can be modified any
number of times. The static storage class variables are declared using the keyword static.
Syntax: static data_type variable;
Variable of static storage class has the following properties...
Property Description

Keyword static

Storage Computer Memory (RAM)

Default Value Zero

Scope Local to the block in which the variable is defined

Life time The value of the persists between different function calls (i.e., Initialization is done only once)
Example Program 1
#include<stdio.h>
#include<conio.h>
static int a;
int main(){
printf("%d",a);
return 0;
}
output: 0
Example Program 2
#include<stdio.h>
#include<conio.h>
static int i=10;
int main(){
i=25; //Assignment statement
printf("%d",i);
return 0;
}output: 25
Register storage class
The register storage class is used to specify the memory of the variable that has to be allocated in
CPU Registers. The memory of the register variable is allocated in CPU Register but not in
Computer memory (RAM). The register variables enable faster accessibility compared to other
storage class variables. As the number of registers inside the CPU is very less we can use very
less number of register variables. The register storage class keyword is register.
Syntax: register data_type variable:
Variable of register storage class has the following properties...
Property Description

Keyword register

Storage CPU Register

Default Value Garbage Value

Scope Local to the block in which the variable is defined

Life time Till the control remains within the block in which variable is defined
Example Program 1
#include<stdio.h>
#include<conio.h>
int main(){
register int a,b;
scanf("%d%d",&a,&b);
printf("%d %d",a,b);
}
output: 4,5
Void Functions
If a function does not return a value, then a special "TYPE" is used to tell the computer this. The
return type is "void" (all lower case).
Void functions are mostly used in two classes of functions.
The first is a function that prints information for the user to read. For example (for our purposes),
the printf function is treated as a void function. (In actuality, printf returns an integer which is the
number of characters printed... but we almost always ignore this value.)
Thus any change made to a reference parameter is in fact made to the original variable!.
Main method
main() is user-defined function which is called by compiler to execute the program The
execution of a c program starts and ends with main(). The main() can call other functions to
perform special task. Therefore, every c program must include main(). A c program can not run
without a main() function. It provides a platform to call the initial user-defined functions in a
program.

I/O (input/output) Operations


C language is a function oriented language and many tasks are done through functions only.
Functions are subprograms written to do subtasks of a program. the input and output operations
also facilitate interactions between the computer and user. The collection of functions is usually
referred to as the C standard library. It contains functions to perform input/output, string
manipulations, mathematics, and much more. A program using the input/output functions must
include the standard header file <stdio.h>. Reading, processing and writing of data are the three
essential functions of a computer program. The input and output functions of a computer
facilitate communication with the external world. The user has to input data to process it in the
computer and get the result as the output.

Console input/output functions to receive input from keyboard and write out in monitor screen.

Disk input/output functions perform i/o operation on disk drive.

Port input/output functions perform i/o operations on various ports.

C provides two types of console Input/Output functions


1. Formatted functions(Simple input and output with scanf() and printf()
 Formatted input functions(scanf())
 Formatted output functions(printf())
2. Unformatted functions.
a) Unformatted input functions
b) Unformatted output functions

Formatted input functions


scanf() function

The scanf() function is used to read multiple data values of different data types from the
keyboard. The scanf() function is built-in function defined in a header file called "stdio.h". When
we want to use scanf() function in our program, we need to include the respective header file
(stdio.h) using #include statement. The scanf() function has the following syntax...

Syntax:

scanf("format strings",&Address_variableNames);

Write a C program to print sum of two variables

#include <stdio.h>
int main(void)
{
int a, b, sum;
printf("Enter two integer numbers:\n");
scanf("%d %d", &a, &b);
sum = a + b;
printf("Sum: %d\n", sum);
return 0;
}
Output: Enter two integer numbers:
10
20
Sum: 30
The scanf function also used to read multiple data values of different or the same data types.

Formatted output functions


printf() function

The printf() function is used to print string or data values or a combination of string and data
values on the output screen (User screen). The printf() function is built-in function defined in a
header file called "stdio.h". When we want to use printf() function in our program we need to
include the respective header file (stdio.h) using the #include statement. The printf() function has
the following syntax...

Syntax: printf(“control string”, var1, var2…);

Write a C program to print subtraction of two variables

#include <stdio.h>
int main(void)
{
int a, b, sub;
printf("Enter two integer numbers:\n");
scanf("%d %d", &a, &b);
sub = a - b;
printf("Sub: %d\n", sum);
return 0;
}
Output: Enter two integer numbers:
20
10
Sub: 10

In the above example program, we used the printf() function to print a string on to the output
screen.The printf() function is also used to display data values. When we want to display data
values we use format string of the data value to be displayed.
Unformatted input functions

getchar() function

The getchar() function is used to read a character from the keyboard and return it to the program.
This function is used to read a single character. To read multiple characters we need to write
multiple times or use a looping statement. Consider the following example program.

Syntax: character variable=getchar();

Write a c program to print pressed character from keyboard by using getchar().

#include<stdio.h>
#include<conio.h>
void main()
{
char ch;
printf("\nEnter any character : ");
ch = getchar();
printf("\nYou have entered : %c\n",ch);
}
Output: Enter any character : pec

You have entered : p


getch() function
The getch() function is similar to getchar function. The getch() function is used to read a
character from the keyboard and return it to the program. This function is used to read a single
character. To read multiple characters we need to write multiple times or use a looping
statement.

Syntax: character variable=getch();

Consider the following example program...

Example Program

#include<stdio.h>
#include<conio.h>
void main()
{
char ch;
printf("\nEnter any character : ");
ch = getch();
printf("\nYou have entered : %c",ch);
}
Output: Enter any character :

You have entered : S

gets() function
The gets() function is used to read a line of string and stores it into a character array. The gets()
function reads a line of string or sequence of characters till a newline symbol enters.
Syntax: gets(string_name);
Consider the following example program...
Write a c program to print college name by using gets().
#include<stdio.h>
#include<conio.h>
void main()
{
char name[30];
printf("\nEnter your favourite college name: ");
gets(name);
printf("%s",name);
}
Output:
Enter your favorite college name:
Pallavi Engineering College

Unformatted output functions

putchar() function

The putchar() function is used to display a single character on the output screen. The putchar()
functions prints the character which is passed as a parameter to it and returns the same character
as a return value. This function is used to print only a single character. To print multiple
characters we need to write multiple times or use a looping statement. Consider the following
example program.

Syntax: putchar(character_variable);

Write a c program to print character by using putchar().

#include<stdio.h>
#include<conio.h>
void main()
{
char ch = 'A';
putchar(ch);
}
Output: A
puts() function

The puts() function is used to display a string on the output screen. The puts() functions prints a
string or sequence of characters till the newline. Consider the following example program.

Syntax: puts(string_name);

Write a c program to print string name by using puts().

#include<stdio.h>
#include<conio.h>
void main()
{
char name[30];
printf("\nEnter your favourite college name: ");
gets(name);
puts(name);
}
Output: Enter your favourite college name
Pallavi Engineering College

Introduction to Standard streams(stdin, stdout and stderr)

Standard streams

The standard streams in c are file pointers used by I/O system for performing I/O operations on
the console. They are created during the program execution and closed after the program
termination. Though the streams refer to the console, they can also be redirected to other device
the support redirectable I/O. c language provides three types of standard streams stdin, stdout and
stderr.

stdin(Standard Input)

This stream identifies the standard input of the program and is associated with the terminal
window. It provides input to the standard I/O functions that perform input without considering
file pointer as an input.

Example fscanf(stdin, “%x”, &x);

Generally, scanf() reads its input from stdin. Any call to scanf() is identical to a call to fscanf()
which takes stdin as first argument. It reads next integer from the standard input which is
basically the terminal window.

Stdout(Standard Output)

This stream identifies the standard out and is associated with the terminal window.

Example: printf(“pallavi engineering college\n”);

A call to this statement can be replaced and is identical to the call to fprintf() using stdout as the
first argument.

fprintf(stdout, “ pallavi engineering college\n”);

stderr(Standard Error)

This stream identifies the standard error file and is associated with the terminal window.
Standard error file contains all the error messages generated by the system. Using this stream, a
user can introduce error messages to a device or any other file and redirect the output of the
program to this device/file. However, the system error messages will still appear on the window.

Example if(file 1 = fopen(“data”, “r”))==NULL)


{

Fprintf(stderr, “cannot open file for reading\n”);

Here, the call to fprintf() writes the user generated error message to stderr if the file cannot be
opened for reading. Even though, the standard output is redirected to a file, the error message
still appears on the window.

Decision Making

In the C programming language, the program execution flow is line by line from top to bottom.
That means the c program is executed line by line from the main method. But this type of
execution flow may not be suitable for all the program solutions. Sometimes, we make some
decisions or we may skip the execution of one or more lines of code. Consider a situation, where
we write a program to check whether a student has passed or failed in a particular subject. Here,
we need to check whether the marks are greater than the pass marks or not. If marks are greater,
then we decide that the student has passed otherwise failed. To solve such kind of problems in c
we use the control statements called decision making statements.

Definition

Decision-making statements are the statements that are used to verify a given condition and
decide whether a block of statements gets executed or not based on the condition result.

C provides three types of control statements or control structures.

1. Conditional control or branching


2. Loop control or looping
3. Unconditional control or jumping
'if' Statement in C

In the c programming language, there are three decision-making statements they are as follows.

1. if statement

2. switch statement

3. Conditional operator

if statement in c

In c, if statement is used to make decisions based on a condition. The if statement verifies the
given condition and decides whether a block of statements are executed or not based on the
condition result. In c, if statement is classified into four types as follows...

1. Simple if statement

2. if-else statement

3. Nested if statement

4. if-else-if statement (if-else ladder)

Simple if statement

Simple if statement is used to verify the given condition and executes the block of statements
based on the condition result. The simple if statement evaluates specified condition. If it is
TRUE, it executes the next statement or block of statements. If the condition is FALSE, it skips
the execution of the next statement or block of statements. The general syntax and execution
flow of the simple if statement is as follows.

Syntax: if (expression)

Statement; or

If (expression) statement;
Simple if statement is used
sed when we have only one option that is executed or skipped based on a
condition.

Multiple statements within if

if we wants more than one statement to execute following the if statement, they may be grouped
together to form a compound statement surrounded by paired curly braces.

Syntax
If(expression)
{
Statement 1;
Statement 2;
……………
Statement n;
}

Example Program | Test whether given number is divisible by 5.

#include<stdio.h>
#include<conio.h>

void main(){
int n ;
clrscr() ;
printf("Enter any integer
nteger number: ") ;
scanf("%d", &n) ;
if ( n%5 == 0 )
printf("Given number is divisible by 55\n") ;
printf("statement does not belong to if!!!") ;
}
Output1: Enter any integer number: 30
Given number is divisible by 5
Output2: Statement does not belong to if!!!
Enter any integer number: 19
Statement does not belong to if!!!
if-else statement

The if-else
else statement is used to verify the given condition and executes only one out of the two
blocks of statements based on the condition result. The iif-else
else statement evaluates the specified
condition. If it is TRUE, it executes a block of statements (True block). If the condition is
FALSE, it executes another block of statements (False block). The general syntax and execution
flow of the if-else statement
ent is as follows.

The if-else
else statement is used when we have two options and only one option has to be executed
based on a condition result (TRUE or FALSE).

Note: the conditional or ternary operator is closely related to the if ..else structure

Ex: if(10>5)?;10:5;

Example Program | Test whether given number is even or odd.

#include<stdio.h>
#include<conio.h>
void main(){
int n ;
clrscr() ;
printf("Enter any integer number: ") ;
scanf("%d", &n) ;
if ( n%2 == 0 )
printf("Given number is EVEN
EVEN\n") ;
else
printf("Given number is ODD
ODD\n") ;
}
Output 1:: Enter any integer number: 8
Given number is Even
Output 2:: Enter any integer number: 29
Given number is ODD
Example: write a c program to find the given year is leap year oor not.

#include<stdio.h>
main()
int year;
Printf(“ Enter a year: “);
scanf(“%d”, &year);
if(year%4==0 && year%100!=0 || year%400==0)
printf(“%d is a leap year \n”,
n”, year);
else
print(“%d is not a leap year \n”,
n”, year);
}
Output:
Enter a year: 2000

2000 is a leap year

Nested if statement
Writing a if statement inside another if statement is called nested if statement.. This is useful
when a series of decisions are involued.
The general syntax of the nested if statement is as follows...

The nested if statementt can be defined using any combination of simple if & if
if-else
else statements.
Example Program | Test whether given number is even or odd if it is below 100.
#include<stdio.h>
#include<conio.h>
void main()
{
int n ;
clrscr() ;
printf("Enter any integer number: ") ;
scanf("%d", &n) ;
if ( n < 100 )
{
printf("Given number is below 100
100\n") ;
if( n%2 == 0)
printf("And it is EVEN") ;
else
printf("And it is ODD") ;
}
else
printf("Given number is not below 100") ;
}
Output 1:: Enter any integer number: 30
Given number is below 100
And it is EVEN
Output 2:: Enter any integer number: 99
Given number is below 100
And it is ODD
Output 3:: Enter any integer number: 105
Given number is not below 100

if-else-if statement (if-else


else ladder)
Writing a if statement inside else of an if statement is called if
if-else-if
if statement. The general
syntax of the if-else-if
if statement is as follows...

The if-else-if
if statement can be defined using any comb
combination of simple if & if-else
else statements.
Example Program | Find the largest of three numbers.
#include<stdio.h>
#include<conio.h>
void main()
{
int a, b, c ;
clrscr() ;
printf("Enter any three integer numbers: ") ;
scanf("%d%d%d", &a, &b, &c) ;
if( a>=b && a>=c)
printf("%d is the largest number", a) ;
else if (b>=a && b>=c)
printf("%d is the largest number", b) ;
else
printf("%d is the largest number", c) ;
}
Output: Enter any three integer numbers 10 20 30
30 is the largest number
Example: program to find the largest of three given numbers.

#include<stdio.h>
#include<conio.h>
main()
{
float a, b, c, max;
printf(“ Enter a, b, c:\n);
scanf(“%f%f%f”, &a, &b, &c);
max= a;
if(b>max)max=b;
if(c>max)max=c;
printf(“largest of three given numbers = %f\n”, max);
}

Output

Enter a, b, c:

12.00 5.00 30.00

Largest of three given numbers = 30.00

Switch statement
Consider a situation in which we have many options out of which we need to select only one
option that is to be executed. Such kind of problems can be solved using nested if statement. But
as the number of options increases, the complexity of the program also gets increased. This type
of problem can be solved very easily using a switch statement. Using the switch statement, one
can select only one option from more number of options very easily. In the switch statement, we
provide a value that is to be compared with a value associated with each option. Whenever the
given value matches the value associate
associated
d with an option, the execution starts from that option. In
the switch statement, every option is defined as a case.

The switch statement has the following syntax and execution flow diagram.

The switch statement contains one or more cases and each case has a value associated with it. At
first switch statement compares the first case value with the switch Value, if it gets matched the
execution starts from the first case. If it doesn't match the switch statement compares the second
case value with the switch
itch Value and if it is matched the execution starts from the second case.
This process continues until it finds a match. If no case value matches with the switch Value
specified in the switch statement, then a special case called default is executed.

When a case value matches with the switch Value, the execution starts from that particular case.
This execution flow continues with the next case statements also. To avoid this, we use the
"break"" statement at the end of each case. That means the break statement
nt is used to terminate
the switch statement. However, it is optional.

When we use switch statement, we must follow the following...

 Both switch and case are keywords so they must be used only in lower case letters.
 The data type of case value and the value specified in the switch statement must be the
same.

 switch and case values must be either integer or character but not float or string.

 A switch statement can contain any number of cases.

 The keyword case and its value must be separated with a white space.

 The case values need not be defined in sequence, they can be in any order.

 The default case is optional and it can be defined anywhere inside the switch statement.

 The switch value might be direct, a variable or an expression.

Example Program | Display pressed digit in words.

#include<stdio.h>
#include<conio.h>
void main()
{
int n ;
clrscr() ;
printf("Enter any digit: ") ;
scanf("%d", &n) ;
switch( n )
{
case 0: printf("ZERO") ;
break ;
case 1: printf("ONE") ;
break ;
case 2: printf("TWO") ;
break ;
case 3: printf("THREE") ;
break ;
case 4: printf("FOUR") ;
break ;
case 5: printf("FIVE") ;
break ;
case 6: printf("SIX") ;
break ;
case 7: printf("SEVEN") ;
break ;
case 8: printf("EIGHT") ;
break ;
case 9: printf("NINE") ;
break ;
default: printf("Not a Digit") ;
}
getch() ;
}
Output
Enter any digit: 7
Seven

Example: Write a C program to read a value in range 1 to 12 and print the name of that
month.

#include<stdio.h>
#include<conio.h>
main()
{
int month;
printf(“Enter a number between 1 to 12\n:”);
scanf(“%d”, &month);
switch(month)
{
case 1:
printf(“January\n”);
break;
case 2:
printf(“February\n”);
break;
case 3:
printf(“March\n”);
break;
case 4:
printf(“April\n”);
break;
case 5:
printf(“May\n”);
break;
case 6:
printf(“June\n”);
break;
case 7:
printf(“July\n”);
break;
case 8:
printf(“August\n”);
break;
case 9:
printf(“September\n”);
break;
case 10:
printf(“October\n”);
break;
case 11:
printf(“November\n”);
break;
case 12:
printf(“December\n”);
break;
default:
printf(“Unrecognized number”);
}
}
Output:
Enter a number between 1 to 12: 6

June

Looping Statements

Looping (iteration)

In C programs the instructions were executed in the same order in which they appeared in the
program. Each instruction was executed repeatedly, until some condition has been satisfied. This
is known as looping.

Loop: A loop is a group of instructions the computer executes repeatedly a certain number of
times. The repetition continues while a condition is true. When the condition becomes false, the
loop terminates and the control passes to the statement (if any) following the loop. A loop
consists of two segments, one is known as control statement and the other is the body of the loop.

There are three kinds of loop structures or list of loop statements in C language.

1. For loop

2. While loop

3. Do-while loop

for statement
The for statement is used to execute a single statement or a block of statements repeatedly as
long as the given condition is TRUE. The for statement has the following syntax and execution
flow diagram.

At first, the for statement executes initialization followed by condition evaluation. If the
condition is evaluated to TRUE, the single statement or block of statements of for statement are
executed. Once the execution gets completed, the modification statement is executed and again
the condition is evaluated. If it is TRUE, again the same statements are executed. The same
process is repeated until the condition is evaluated to FALSE. Whenever the condition is
evaluated to FALSE, the execution control moves out of the for block.

Example Program | Program to display even numbers upto 10.

#include<stdio.h>
#include<conio.h>

void main(){
int n ;
clrscr() ;
printf("Even numbers upto 10\n");

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


{
if( n%2 == 0)
printf("%d\t", n) ;
}

getch() ;
}
Output
Even numbers upto 10

0 2 4 6 8 10

When we use for statement, we must follow the following...

 for is a keyword so it must be used only in lower case letters.

 Every for statement must be provided with initialization, condition, and modification

(They can be empty but must be separated with ";")


Ex: for ( ; ; ) or for ( ; condition ; modification ) or for ( ; condition ; )

 In for statement, the condition may be a direct integer value, a variable or a condition.

 The for statement can be an empty statement.

While Statement

The while statement is used to execu


execute
te a single statement or block of statements repeatedly as
long as the given condition is TRUE.

The while statement is also known as Entry control looping statement.. The while statement
has the following syntax...

At first, the given condition is evalu


evaluated.
ated. If the condition is TRUE, the single statement or block
of statements gets executed. Once the execution gets completed the condition is evaluated again.
If it is TRUE, again the same statements get executed. The same process is repeated until the
condition
dition is evaluated to FALSE. Whenever the condition is evaluated to FALSE, the execution
control moves out of the while block.

Example Program | Program to display even numbers upto 10.

#include<stdio.h>
#include<conio.h>

void main(){
int n = 0;
clrscr() ;
printf("Even numbers upto 10\n");

while( n <= 10 )
{
if( n%2 == 0)
printf("%d\t", n) ;
n++ ;
}
getch() ;
}
Output:
Even numbers up to 10

0 2 4 6 8 10

When we use a while statement, we must follow the following...

 while is a keyword so it must be used only in lower case letters.

 If the condition contains a variable, it must be assigned a value before it is used.

 The value of the variable used in condition must be modified according to the
requirement inside the while block.

 In a while statement, the condition may be a direct integer value, a variable or a


condition.

 A while statement can be an empty statement.

do-while statement in

The do-while statement is used to execute a single statement or block of statements repeatedly as
long as given the condition is TRUE. The do-while statement is also known as the Exit control
looping statement. The do-while statement has the following syntax...
At first, the single statement or block of statements which are def
defined in do block are executed.
After the execution of the do block, the given condition gets evaluated. If the condition is
evaluated to TRUE, the single statement or block of statements of do block are executed again.
Once the execution gets completed aga again
in the condition is evaluated. If it is TRUE, again the
same statements are executed. The same process is repeated until the condition is evaluated to
FALSE. Whenever the condition is evaluated to FALSE, the execution control moves out of the
while block.

Example Program | Program to display odd numbers upto 10.

#include<stdio.h>
#include<conio.h>
void main(){
int n = 0;
clrscr() ;
printf("Odd numbers upto 10\n");
n");

do
{
if( n%2 == 1)
printf("%d\t", n) ;
n++ ;
}while( n <= 10 ) ;

getch() ;
}
Output
Enter odd numbers up to 10

1 3 5 9
When we use the do-while statement, we must follow the following...

 Both do and while are keywords so they must be used only in lower case letters.

 If the condition contains a variable, it must be assigned a value before it is used.

 The value of the variable used in the condition must be modified according to the
requirement inside the do block.

 In a do-while statement, the condition may be a direct integer value, a variable or a


condition.

 A do-while statement can be an empty statement.

 In do-while, the block of statements is executed at least once.

Nesting of loops

C programming allows to use one loop inside another loop. The following section shows a few
examples to illustrate the concept.

Nested for loop

The syntax for a nested for loop statement in C is as follows −

for ( init; condition; increment )


{
for ( init; condition; increment )
{
statement(s);
}
statement(s);
}
Nesting for loop example
#include <stdio.h>

void main()
{

int i, j;
for(j=1; j<=4; j++)
{
for(i=1; i<=5; i++)
{
printf("@");
}
printf("\n");
}
}
Output
@@@@@
@@@@@
@@@@@
@@@@@
Nested while loop
The syntax for a nested while loop statement in C programming language is as follows −
while(condition)
{
while(condition)
{
statement(s);
}
statement(s);
}
Example
#include <stdio.h>
int main()
{
int a = 1, b = 1;
while(a <= 5)
{
b = 1;
while(b <= 5)
{
printf("%d ", b);
b++;
}
printf("\n");
a++;
}
return 0;
}
Output
12345
12345
12345
12345
12345

Nested do while loop

Syntax of nested do while loop is

do
{
statement n;
do
{
statement n;
}
while(test condition);
}
while(test expression);
Example
#include <stdio.h>

void main()
{

int i=1, j=3;


do
{
do
{
printf("%d", j);
j--;
}
while(j>0);
i++;
printf("%d", i);
}
while(i<4);
}
Output
3210203-14
Comparisons of different loop statements

For loop While loop

 Initialization may be either in loop


statement or outside the loop.  Initialization is always outside the loop.

 Once the statement(s) is executed then  Increment can be done before or after the
after increment is done. execution of the statement(s).

 It is normally used when the number  It is normally used when the number of
of iterations is known. iterations is unknown.

 Condition may be expression or non-zero


 Condition is a relational expression. value.

 It is used when initialization and


increment is simple.  It is used for complex initialization.

 For is entry controlled loop.  While is also entry controlled loop.

 while ( condition )
 for ( init ; condition ; iteration ) { statement(s); }
{ statement(s); }

Do-While Loop
 This is exit control loop. Checks condition when coming out from loop
 Do-While may run more than one times but at least once.
 The variable for loop condition may also be initialized in the loop also.
 Do
{
// statements
}
While(condition);

Unconditional control statements or Breaking


In some situations, the flow of control may be transferred to another part of the program without
testing for any condition. Sometimes, when executing a loop it becomes essential to skip a part
of the loop or to leave the loop as soon as a certain condition occurs. The following are three typ
es of jumping statements.
1. break statement
2. continue statement
3. goto statement
The above three statements do not need any condition to control the program execution flow.
break statement
In C, the break statement is used to perform the fol
following two things...
1. break statement is used to terminate the switch case statement
2. break statement is also used to terminate looping statements like while, do-while
do and for.
When a break statement is encountered inside the switch case statement, the execution
execu control m
oves out of the switch statement directly. For example, consider the following program.
Syntax break;

Example
#include <stdio.h>

void main()
{
int a, i, sum=0;
for(i=1; i<=5; i++)
{
printf("Enter a integer:");
scanf("%d",&a);
if(a<0)
{
break;
}
sum=sum+a;
}
printf("%d", sum);
}
Output
Enter a integer: 9
Enter a integer:6
Enter a integer:-4 sum=15
When we use break we must follow the following...
 The break is a keyword so it must be used only in lower case letters.
 The break statement can not be used with if statement.
 The break statement can be used only in switch case and looping statements.
 The break statement can be used with if statement, only if that if statement is written ins
ide the switch case or looping statements.

Continue
The continue statement is used to move the program execution control to the beginning of the lo
oping statement. When the continue statement is encountered in a looping statement, the executi
on control skips the rest of the statements in the looping block and directly jumps to the beginnin
g of the loop. The continue statement can be used with looping statements like while, do-while
do a
nd for. Syntax continue;

When we use continue stat


ement with while and do-while statements the execution control directly jumps to the condition.
When we use continue statement with for statement the execution control directly jumps to the
modification portion (increment/decrement/any modification) of the for lo
loop.
op. The continue state
ment execution is as shown in the following figure.

#include <stdio.h>
void main()
{
int a, i, sum=0;
for(i=1; i<=5; i++)
{
printf("Enter a integer:");
scanf("%d",&a);
if(a<0)
{
continue;
}
sum=sum+a;
}
printf("%d", sum);
}
Output
Enter a integer:1
Enter a integer:6
Enter a integer:-6
Enter a integer:4
Enter a integer:-9
11
When we use continue, we must follow the following...
 The continue is a keyword so it must be used only in lower case letters.
 The continue statement is used only within looping statements.
 The continue statement can be used with if statement, only if that if statement is written
inside the looping statements.
Differences between break and continue statements
Break Statement Continue Statement

 The Break statement is used to exit from  The continue statement is not used to
the loop constructs. exit from the loop constructs.

 The break statement is usually used with  The continue statement is not used
the switch statement, and it can also use with the switch statement, but it can be
it within the while loop, do-while loop, used within the while loop, do-while
or the for-loop. loop, or for-loop.

 When the continue statement is


 When a break statement is encountered encountered then the control
then the control is exited from the loop automatically passed from the
construct immediately. beginning of the loop statement.

 Syntax:  Syntax:
break; continue;

goto statement
The goto statement is used to jump from one line to another line in the program. Using goto state
ment we can jump from top to bottom or bottom to top. To jump from one line to another line, th
e goto statement requires a label. Label is a name given to the instruction or line in the program.
When we use a goto statement in the program, the execution control directly jumps to the line wi
th the specified label.
Syntax goto label;
#include <stdio.h>
void main()
{
int age;
printf("Enter age:");
scanf("%d", &age);
if(age>=18)
goto vote;
else
{
printf("not eligible to vote");
}
vote: printf("Eligible for vote");
}
Output
Enter age:19
Eligible for vote
When we use goto statements, we must follow the following...
 The goto is a keyword so it must be used only in lower case letters.
 The goto statement must require a label.
 The goto statement can be used with any statement like if, switch, while, do-while, and fo
r, etc.

Command Line Arguments

Command line argument is a parameter supplied to the program when it is invoked. Command
line argument is an important concept in C programming.

 It is mostly used when you need to control your program from outside.

 Command line arguments are passed to the main() method.

Syntax: int main(int argc, char *argv[])

Here, argc counts the number of arguments on the command line

 argv[ ] is a pointer array which holds pointers of type char which points to the arguments
passed to

 the program. argv[0] holds the name of the program and argv[1] points to the first command
line argument

 and argv[n] gives the last argument. If no argument is supplied, argc will be 1.
Passing some values from the command line to C programs when they are executed. These
values are called command line arguments and many times they are important for C program
especially when we want to control our program from outside instead of hard coding those
values inside the code. The command line arguments are handled using main() function
arguments where argc refers to the number of arguments passed, and argv[] is a pointer array
which points to each argument passed to the program.

Following is a simple example which checks if there is any argument supplied from the
command line and take action accordingly –

#include <stdio.h>
#include <conio.h>
int main(int argc, char *argv[])
{
int i;
if( argc >= 2 )
{
printf("The arguments supplied are:\n");
for(i = 1; i < argc; i++)
{
printf("%s\t", argv[i]);
}
}
else
{
printf("argument list is empty.\n");
}
return 0;
}
Output: argument list is empty
Important question Unit – I

1. Explain about various Arithmetic operators available in C language with examples.

2.a) Differentiate between typecasting and type conversion.

b)Write a program to count the number of vowels in a text.

c)Explain the use of Command line argument with an example

3.a) What is precedence and associativity in an expression? What is their need?

b)Write down the significance of break statement inside a switch statement.

c)List and explain various storage classes available in C

4.a) Write a C Program to find maximum number among three numbers using conditional
operator.

b) Define Flow Chart. List some commonly used symbols and specify its purpose.

5.a) write an algorithm and flowchart for finding the factorial of a given number.

b)Define Data type. Briefly discuss the fundamental data types supported in C.

c)How entry controlled loop is different from exit controlled loop? Explain

6.a) Write about structure of C programming language in detail.

b) Explain if else statement and write a program in ‘C’ to check whether a given integer number
is odd or even.
7.a) difference between algorithm, flowchart and program.

b) write and explain steps involved in execution of c.

8.a) write a c program to print Fibonacci series.


b)Define switch with suitable example.
9.a) difference between local and global variables.

b) what is number system and explain its conversion techniques with examples

10.Explain the formatted I/O and unformatted(I/O) functions with example?


UNIT – II

Arrays, Strings, Structures and Pointers

Arrays:
one and two-dimensional arrays, creating, accessing and manipulating elements of arrays

Strings: Introduction to strings, handling strings as array of characters, basic string functions
availablein C (strlen, strcat, strcpy, strstr etc.), arrays of strings

Structures: Defining structures, initializing structures, unions, Array of structures

Pointers: Idea of pointers, Defining pointers, Pointers to Arrays and Structures, Use of Pointers
in selfreferential structures, usage of self referential structures in linked list (no implementation)
Enumeration data type.
Arrays
Definition 1: An array is a collection of similar data items stored in continuous memory
locations with single name.

Definition 2: An array is a special type of variable used to store multiple values of same data
type at a time.

Array is another form of data type. An array is an ordered finite collection of similar quantities'.
That is, an array is a group of elements of the same data type. There can be arrays of integers,
arrays of floating point numbers, arrays of characters, etc. Thus, an integer array will have all its
elements as integers only. An array is also known as a subscripted variable.

An array is a group of continuous memory locations represented with the same name and the
same type. To refer to a particular location or element in the array, we specify the name of the
array and the position number of the particular element in the array. For example, the distance of
different stars from the earth may be denoted by x₁, x₂. x3,…. xn. These distances could be called
by a common name x and may be represented by a vector.
X=[x1,x2,x3….xn]
Where x₁, x₂, X, X, are called elements of the vector x and can have numerical values. If x is
represented numerically as

x= [1.8, 3.6, 5.1, 1.23...]

then x1, represents 1.8, x2, represents 3.6 and so on.

In C, variables x1, x₂, x3….xn are represented by x[0], x[1]. x[2]....... x[n − 1] called subscripted
variables. The entire set of these subscripted variables is called an array known by the variable
name x.
Remember The Following:

1. An array is a finite collection of similar elements, each of the same type.

That is, we cannot have an array of 30 numbers, of which 10 are ints, 10 are floats and 10 are
chars.

2. The first element in the array is numbered 0, so the last element is 1 less than the size of the
array.

3. Before using an array its type and dimension must be specified.

4. A subscript is a number used to refer to individual array element. It is also called an index.

Arrays are two types

1. One – Dimensional array/single dimensional array


2. Two – Dimensional Array/Multi Dimensional array

One – Dimensional array/single dimensional array

In C programming, One- dimensional


imensional array is stores the multiple numbers/elements with
single name and same datatype in sequential order(row).

Accessing/Declaration of One – Dimensional Array

In C programming language, when we want to create an array we must know the datatype of
values
alues to be stored in that array and also the number of values to be stored in that array.

We use the following general syntax to (Declaration/sized) declare an array...

datatype arrayName [ size ] ;

Syntax for creating an array with size and (initializat


(initialization/sized) initial values

datatype arrayName [ size ] = {value1, value2, ...} ;

Syntax for creating an array without size(unsized) and with initial values

datatype arrayName [ ] = {value1, value2, ...} ;

In the above syntax, the datatype specifies the type of values we store in that array
and size specifies the maximum number of values that can be stored in that array.

Example Code

int a [3] ;

Here, the compiler allocates 12 bytes of contiguous memory locations with a single name 'a' and
tells the compiler to store three different integer values (each in 4 bytes of memory) into that 12
bytes of memory. For the above declaration, the memory is organized as follows...

In the above memory allocation, all the three memory locations have a common name 'a'. So
accessing
ccessing individual memory location is not possible directly. Hence compiler not only allocates
the memory but also assigns a numerical reference value to every individual memory location of
an array. This reference number is called "Index" or "subscript" or "indices". Index values for the
above example are as follows...
Accessing Individual Elements of an Array

The individual elements of an array are identified using the combination of 'arrayName' and
'indexValue'. We use the following general syntax to access individual elements of an array...

arrayName [ indexValue ] ;

For the above example the individual elements can be denoted as follows...

For example, if we want to assign a value to the second memory location of above array 'a', we
use the following statement...

Example Code

a [1] = 100 ;

The result of the above assignment statement is as follows...

Initializing an Array
Like other types of variables, you can give values to each array element when the array is first
defined. Intializing an array gives a value to each of its elements. It is also called as Compile
time initialization.

Compile time initialization.

The general form of array initialization for one-dimensional array is

type array_name[size] = (list of values):

The values in the list are separated by commas. The first value will be placed in the first position
of the array, the second value in the second position, and so on. For example, the statement

int x[3] = {1, 4, 9];

will assign the value 1 to x[0], the value 4 to x[1] and 9 to x[2].

Similarly, the statement

char Gender[2] = {'M', 'F'};

will assign the value 'M' to Gender [0], the value 'F' to Gender [1] and 10 to gender 2 Also you
can initialize only some of the elements of the array. If the numbers values in the list is less than
the number of elements, then only that elements will be initialized. The remaining elements will
be set to zeros automatically. For example, the statement

int age[5] = {26, 18, 65);

allocates five elements to age, and then initializes age[0] to 26, age[1] to 18 and age[2] to 65,
setting the remaining elements to 0.

Note that arrays not auton ally initialized to zero. The programmer mu atleast initialize the first
element to zero for the remaining elements to be automatically zero.

It is not always necessary to specify the size (or dimension) of an array if it is being initialized. If
you don't specify the size in a declaration with an initializer list, the compiler counts the number
of initialization constants and uses that value as the size ofthe array.

For example, the statement

int num[ ] = {21,62,38,65,70);

will declare num array to contain five elements, and then initializes num[0] to 21, num[1] to 62,
num[2] to 38, num[3] to 65 and num[4] to 70. If the dimension is not specified explicitly, then
such an array is called an unsized array.
An unsized array is useful because it is easier for you to change the size of the initialization list
without having to count it and then change the array dimension.

For example, the statement

If the dimension is specified explicitly, and the values in the list are more than are needed, a
syntax error is flagged by the compiler. For example, the statement

float balance [5] = {11.2, 15.8, 61.5, 18.0, 95.0, 100.0};

causes a syntax error because there are six initializers and only five array elements.

Run time Initialization:

An array can also be explicitly initialized at run time. For example consider the following
segment of a c program.

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

scanf(“%d”,&x[i]);

Note: Remember the following rules while initializing an array.

1. If the number of initializers is less than the number of elements in the array. the remaining
elements are set to zero.

2. It is an error to specify more initializers than the number of elements in the array.

3. If initializers have been provided for an array, it is not necessary to explicitly specify the size
of the array, in which case the size taken by counting the initializers.

Program: Write a C program to store the elements in the array and to print them from the
array

#include<stdio.h>
void main()
{
int array[5], i;
printf("Ente 5 numbers to store then in array \n");
for(i=0;i<5;i++)
{
scanf("%d", &array[i]);
}printf("Elements in the array are - \n \n");
for(i=0;i<5;i++)
{
printf("Element stored at a[%d] = %d \n", i, array[i]);
}
getch();
}
Output:
Ente 5 numbers to store then in array
78
45
12
89
56
Elements in the array are -

Element stored at a[0] = 78

Element stored at a[1] = 45

Element stored at a[2] = 12

Element stored at a[3] = 89

Element stored at a[4] = 56

Program: Write a C program to initialize a string of characters in a one – dimensional


array and to display the content of the array.

#include <stdio.h>
main()
{
int i;
char a[]={'c','o','m','p','u','t','e','r'};
printf("\n content of the array:\n \t");
for(i=0; i<9;i++)
printf("%c", a[i]);
}
Output:
Content of the array: Computer

Accessing array out of bounds problem


What if programmer accidentally accesses any index of array which is out of bound ?

C don’t provide any specification which deal with problem of accessing invalid index. As per
ISO C standard it is called Undefined Behavior.
An undefined behavior (UB) is a result of executing computer code whose behavior is not
prescribed by the language specification to which the code can adhere to, for the current state of
the program (e.g. memory). This generally happens when the translator of the source code makes
certain assumptions, but these assumptions are not satisfied during execution.

Examples of Undefined Behavior while accessing array out of bounds

Access non allocated location of memory: The program can access some piece of memory
which is owned by it.

// Program to demonstrate

// accessing array out of bounds

#include <stdio.h>

int main()

int arr[] = {1,2,3,4,5};

printf("arr [0] is %d\n", arr[0]);

// arr[10] is out of bound

printf("arr[10] is %d\n", arr[10]);

return 0;

Output :

arr [0] is 1

arr[10] is -1786647872

It can be observed here, that arr[10] is accessing a memory location containing a garbage value.

Reordering an array in ascending order


In an array, we select an element from an array and place it to its correct position by comparing
with subsequent elements. Then that procedure is called ascending or descending order.
For Example:
Input :- From the user {4,3,6,1,8}
Output :- In ascending order {1,3,4,6,8} and In descending order {8,6,4,3,1}.

Implementation:-

 Input size of array.


 Store it in some variable say n and a[].
 To select each element from array, run an outer loop from 0 to n-1.
 Run another inner loop from i + 1 to n – 1 to place newly selected element at its correct
position.
 Inside inner loop to compare currently selected element with subsequent element and swap
two array elements, if not placed at its correct position.

Program: write a C Program to sort an array in ascending or descending order

#include <stdio.h>
void main()
{
int i,j,n,a[100],temp,p,q,temp1;
printf("Enter the size of array : \n") ; //Taking size of array
scanf("%d",&n) ;
printf("Enter the elements : \n") ; //Taking input from user
for(i=0;i<n;i++)
{
scanf("%d",&a[i]) ;
}
for(i=0;i<n;i++) // loop for sorting array in ascending order
{
for(j=i+1;j<n;j++) { if(a[i]>a[j])
{
temp=a[i];
a[i]=a[j];
a[j]=temp;
}
}
}
printf("Ascending order of an array : \n"); //print ascending order
for(i=0;i<n;i++)
{
printf("%d ",a[i]) ;
}

for(p=0;p<n;p++) // loop for sorting array in descending order


{
for(q=p+1;q<n;q++)
{
if(a[p]<a[q])
{
temp1=a[p];
a[p]=a[q];
a[q]=temp1;
}
}
}
printf("\n Descending order of an array : \n"); // print descending order
for(p=0;p<n;p++)
{
printf("%d ",a[p]) ;
}
}
Output: Enter the size of array :
4

Enter the elements :

23

45

56

43

Ascending order of an array :

23 43 45 56

Descending order of an array :

56 45 43 23

average of elements in an array

In this we have to find out the average of given elements


Program: Write a C program that stores integers given by users in an one dimensional
array. Your program should display the sum and average of array.

#include <stdio.h>

int main()
{
int Arr[100], n, i, sum = 0;
printf("Enter the number of elements you want to insert : ");
scanf("%d", &n);
for (i = 0; i < n; i++)
{
printf("Enter element %d : ", i + 1);
scanf("%d", &Arr[i]);
sum += Arr[i];
}
printf("\nThe sum of the array is : %d", sum);
printf("\nThe average of the array is : %0.2f", (float)sum / n);
return 0;
}
Output

Enter the number of elements you want to insert : 4

Enter element 1 : 5

Enter element 2 : 6

Enter element 3 : 5

Enter element 4 : 6

The sum of the array is : 22

The average of the array is : 5.50

largest element in an array

In given arrays elements we have to find out the largest element i.e program will read a one-
dimensional array and find out the largest element present in the array.

Input : arr[] = {10, 20, 4}

Output : 20

Input : arr[] = {20, 10, 20, 4, 100}


Output : 100

Program: Write a C program to find the largest element in the One- dimensional array

#include <stdio.h>
int main()
{
int size, i, largest;
printf("\n Enter the size of the array: ");
scanf("%d", &size);
int array[size];
printf("\n Enter %d elements of the array: \n", size);
for (i = 0; i < size; i++)
{
scanf("%d", &array[i]);
}
largest = array[0];
for (i = 1; i < size; i++)
{
if (largest < array[i])
largest = array[i];
}
printf("\n largest element present in the given array is : %d", largest);
return 0;
}
Output
Enter the size of the array: 4
Enter 4 elements of the array:
4
5
6
9
largest element present in the given array is : 9

Multi Dimensional Array/Two Dimensional Array

An array of arrays is called as multi dimensional array. In simple words, an array created with
more than one dimension (size) is called as multi dimensional array.

Multi dimensional array can be of two dimensional array or three dimensional array or four
dimensional array or more...
Most popular and commonly used multi dimensional array is two dimensional array. The 2-D
arrays are used to store data in the form of table. We also use 2-D arrays to create
mathematical matrices.

Accessing/Declaration of Two Dimensional Array

We use the following general syntax for declaring a two dimensional array...

datatype arrayName [ rowSize ] [ columnSize ] ;

or

datatype array_name[row_size][column_size];

Example

int matrix_X [2][3] ;

The above declaration of two dimensional array reserves 6 continuous memory locations of 4
bytes each in the form of 2 rows and 3 columns.

Size of multidimensional arrays

Total number of elements that can be stored in a multidimensional array can be calculated by
multiplying the size of all the dimensions.
For example:
The array int x[10][20] can store total (10*20) = 200 elements.
Similarly array int x[5][10][20] can store total (5*10*20) = 1000 elements

 We can declare a two dimensional integer array say ‘x’ of size 10,20 as:

 int x[10][20];

 Elements in two-dimensional arrays are commonly referred by x[i][j] where i is the row
number and ‘j’ is the column number.

 A two – dimensional array can be seen as a table with ‘x’ rows and ‘y’ columns where
the row number ranges from 0 to (x-1) and column number ranges from 0 to (y-1). A two
– dimensional array ‘x’ with 3 rows and 3 columns is shown below:

Initialization of Two Dimensional Array

We use the following general


al syntax for declaring and initializing a two dimensional array with
specific number of rows and coloumns with initial values.

datatype arrayName [rows][colmns] = {{r1c1value, r1c2value, ...},{r2c1, r2c2,...}...} ;

Example

int matrix_X [2][3] = { {1, 2, 3},{4,


},{4, 5, 6} } ;

The above declaration of two-dimensional


dimensional array reserves 6 contiguous memory locations of 2
bytes each in the form of 2 rows and 3 columns. And the first row is initialized with values 1, 2
& 3 and second row is initialized with values 4, 5 & 6.

We can also initialize as follows...

Example

int matrix_X [2][3] = {

{1, 2, 3},

{4, 5, 6}

Accessing Individual Elements of Two Dimensional Array

In a c programming language, to access elements of a two-dimensional


dimensional array we use array name
followed by row index value and column index value of the element that to be accessed. Here the
row and column index values must be enclosed in separate square braces. In case of the two-
two
dimensional array the compiler assigns separate index values for rows and columns.

We use the following general syntax to access the individual elements of a two-dimensional
array...

arrayName [ rowIndex ] [ columnIndex ]

Example

matrix_X [0][1] = 10 ;

In the above statement, the element with row index 0 and column index 1 of matrix_A array is
assinged with value 10.

Program: Write a C program to print matrix and calculate sum by using 2d array
#include <stdio.h>
int main()
{
int x[4][4], i,j,sum=0;
printf("Enter the elements of the array:");
for(i=0;i<4;i++) // entering array elements
{
for(j=0; j<4;j++)
{
scanf("%d", &x[i][j]);
}
}
printf(" the matrix is: \n");
for(i=0;i<4;i++) // printing array elements
{
for(j=0; j<4;j++)
{
printf("%d\t", x[i][j]);
sum=sum+x[i][j];
}
printf("\n");
}
printf("\n sum=%d", sum);
}
Output
Enter the elements of the array:1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
the matrix is:
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16

sum=136

Program: Write a C program to print Transpose of matrix by using 2D/Multi dimensional


array
#include<stdio.h>
int main()
{
int x[2][3], i,j;
printf("Enter the elements of the matrix:");
for(i=0;i<2;i++) // entering array elements
{
for(j=0; j<3;j++)
{
scanf("%d", &x[i][j]);
}
}
printf(" the matrix is: \n");
for(i=0;i<2;i++) // printing array elements
{
for(j=0; j<3;j++)
{
printf("%d\t", x[i][j]);
}
printf("\n");
}
printf("Transpose of matrix is: \n");
for(i=0;i<3;i++)
{
for(j=0;j<2;j++)
{
printf("%d\t", x[j][i]);
}
printf("\n");

}}Output
Enter the elements of the matrix:1
2
3
4
5
6
the matrix is: 1 2 3
4 5 6
Transpose of matrix is:
1 4
2 5
3 6
Program: Write a C program to add two matrixs by using 2D/Multi dimensional array
#include<stdio.h>
int main()
{
int A[2][3],B[2][3],C[2][3],i,j;
printf("Enter the elements of the matrix A:");
for(i=0;i<2;i++) // entering array elements of A matrix
{
for(j=0; j<3;j++)
{
scanf("%d", &A[i][j]);
}
}
printf("Enter the elements of the matrix B:");
for(i=0;i<2;i++) // entering array elements of B matrix
{
for(j=0; j<3;j++)
{
scanf("%d", &B[i][j]);
}
}
printf(" matrix A is: \n");
for(i=0;i<2;i++)
{
for(j=0;j<3;j++)
{
printf("%d\t", A[i][j]);
}
printf("\n");

}
printf(" matrix B is: \n");
for(i=0;i<2;i++)
{
for(j=0;j<3;j++)
{
printf("%d\t", B[i][j]);
}
printf("\n");

}
printf(" The matrix C is: \n");
for(i=0;i<2;i++)
{
for(j=0;j<3;j++)
{
C[i][j]=A[i][j]+B[i][j];
printf("%d \t", C[i][j]);
}
printf("\n");
}
}
Output
Enter the elements of the matrix A:1
2
3
4
5
6
Enter the elements of the matrix B:1
2
3
4
5
6
matrix A is:
1 2 3
4 5 6
matrix B is:
1 2 3
4 5 6
The matrix C is:
2 4 6
8 10 12

Program: Write a C program to subtract two matrix by using 2D/Multi dimensional array
#include<stdio.h>
int main()
{
int A[2][3],B[2][3],C[2][3],i,j;
printf("Enter the elements of the matrix A:");
for(i=0;i<2;i++) // entering array elements of A matrix
{
for(j=0; j<3;j++)
{
scanf("%d", &A[i][j]);
}
}
printf("Enter the elements of the matrix B:");
for(i=0;i<2;i++) // entering array elements of B matrix
{
for(j=0; j<3;j++)
{
scanf("%d", &B[i][j]);
}
}
printf(" matrix A is: \n");
for(i=0;i<2;i++)
{
for(j=0;j<3;j++)
{
printf("%d\t", A[i][j]);
}
printf("\n");

}
printf(" matrix B is: \n");
for(i=0;i<2;i++)
{
for(j=0;j<3;j++)
{
printf("%d\t", B[i][j]);
}
printf("\n");

}
printf(" The matrix C is: \n");
for(i=0;i<2;i++)
{
for(j=0;j<3;j++)
{
C[i][j]=A[i][j]-B[i][j];
printf("%d \t", C[i][j]);
}
printf("\n");
}
}
Output
Enter the elements of the matrix A:7
8
9
4
5
6
Enter the elements of the matrix B:4
5
6
1
2
3
matrix A is:
7 8 9
4 5 6
matrix B is:
4 5 6
1 2 3
The matrix C is:
3 3 3
3 3 3
Program: Write a C program to find matrix Multiplication by using 2D/Multi dimensional
array
#include <stdio.h>
#define N 50
int main()
{
int a[N][N], b[N][N], c[N][N], i, j, k, sum, m, n, p, q;
printf("enter Enter rows and columns of a matrix: \n");
scanf("%d%d", &m, &n);
printf("Enter a matrix: \n");
for(i=0; i<m;i++)
{
for(j=0;j<n;j++)
{
scanf("%d", &a[i][j]);
}
}
printf("enter Enter rows and columns of b matrix: \n");
scanf("%d%d", &p, &q);
printf("Enter a matrix: \n");
for(i=0; i<p;i++)
{
for(j=0;j<q;j++)
{
scanf("%d", &b[i][j]);
}
}
printf(" matrix a is: \n");
for(i=0; i<m;i++)
{
for(j=0;j<n;j++)
{
printf("%d \t", a[i][j]);
}
printf("\n");
}
printf("\n matrix b is: \n");
for(i=0; i<p;i++)
{
for(j=0;j<q;j++)
{
printf("%d \t", b[i][j]);
}
printf("\n");
}
if(n!=p)
{
printf(" can not multiply");
}
else
{
for(i=0; i<m; i++)
{
for(j=0; j<q; j++)
{
sum=0;
for(k=0; k<m; k++)
{
sum=sum+(a[i][k]*b[k][j]);
}
c[i][j]=sum;
}
}
printf("Multiplication is c: \n");
for(i=0;i<m;i++)
{
for(j=0;j<q;j++)
{
printf("%d \t", c[i][j]);
}
printf("\n");
}
}
}
Output
Enter rows and columns of a matrix:
3
3
Enter a matrix:
1
2
3
4
5
6
7
8
9
Enter rows and columns of b matrix:
3
3
Enter a matrix:
1
2
3
4
5
6
7
8
9
matrix a is:
1 2 3
4 5 6
7 8 9

matrix b is:
1 2 3
4 5 6
7 8 9
Multiplication is c:
30 36 42
66 81 96
102 126 150

Applications of Arrays in C

In c programming language, arrays are used in wide range of applications. Few of them are as
follows...

● Arrays are used to Store List of values

In c programming language, single dimensional arrays are used to store list of values of same
datatype. In other words, single dimensional arrays are used to store a row of values. In single
dimensional array data is stored in linear form.

● Arrays are used to Perform Matrix Operations

We use two dimensional arrays to create matrix. We can perform various operations on matrices
using two dimensional arrays.

● Arrays are used to implement Search Algorithms

We use single dimensional arrays to implement search algorihtms like ...

1. Linear Search

2. Binary Search

● Arrays are used to implement Sorting Algorithms

We use single dimensional arrays to implement sorting algorihtms like ...

1. Insertion Sort

2. Bubble Sort

3. Selection Sort

4. Quick Sort

5. Merge Sort, etc.,


● Arrays are used to implement Datastructures

We use single dimensional arrays to implement data structures like...

1. Stack Using Arrays

2. Queue Using Arrays

● Arrays are also used to implement CPU Scheduling Algorithms.

Strings

String is a set of characters enclosed in double quotation marks. It is also defined as array of
characters. or
Every string in C programming language is enclosed within double quotes and it is terminated
with NULL (\0) character. Whenever c compiler encounters a string value it automatically
appends a NULL character (\0) at the end. or
A string is a series of characters enclosed within double quotation marks. A string may include
letters, digits and various special characters such as +, -, *. and $. String constants also referred
as string literals.
All of the following are valid C literals:
"abcd8"

“Programming for Problem Solving"


“\”
“\0”

A double quote included in the literal as “\” is regarded as part of the literal and not as a
delimiter. A pair of double quotes with nothing between them is called the null string. It is stored
as a null character and has a length of 0.
Array of string
C has no built-in string data type. A string in C is defined as an array of characters ending in the
null character (‘\0’). A string is an array of characters. The elements of the character array are
stored in contiguous memory locations. Strings are used by programming languages to
manipulate text such as words and sentences.

Declaring and Initializing String Variables


A string variable must be declared as an array using the following general form:
Syntax
char string_name [size];

The size specifies the maximum number of characters in the string_name .


Some examples are

char name[20];

char color[8]:

When the compiler assigns a character string to a character array, it automatically supplies a null
character (‘\0’) at the end of the string. Therefore, the size should be equal to the maximum
number of characters in the string plus one.

C permits a character array to be initialized as follows.

char city[ ] = "HYDERABAD";

The above declaration initialize a variable to the string "HYDERABAD". It creates a 10-element
array city containing the characters 'H', 'Y', 'D', 'E, R 'A', 'B', 'A', 'D' and 10'. The declaration

char city[ ] = "HYDERABAD";

actually is an abbreviation for the declaration

char city[ ] = {'H', 'Y', 'D','E'. 'R', 'A', 'B', 'A', 'D', \0'};

Each character in the array occupies one byte of memory. When declaring a character array to
contain a string, the array must be large enough to store the string and its terminating null
character. The above declaration automatically determines the size of the array based on the
number of initializers in the initializer list.

C also permits to initialize a character array with size. For example;

char city[10] = 'HYDERABAD"; It stores as

H Y D E R A B A D \0
Write a C program to print name of a string
#include<stdio.h>
#include<conio.h>
int main(){
char name[50];
printf("Please enter your name : ");
scanf("%s", name);
printf("Hello! %s , welcome to PPS class !!", name);
return 0;
}
Output: Please enter your name : Pallavi
Hello! Pallavi , welcome to PPS class !!

Points to remember
 A string is a collection of characters
 A string is also called as an array of characters.
 A string must access by %s format specifier in c language.
 A string is always terminated with \0(null) character.
 A string always recognized in double quotes.
 A string also consider space as a character.
Ex: “Pallavi Engineering”
 The above string contains 20 characters.
Ex: char name[20];
The above example will store 19 characters with 1 null(\0) character.

String Handling Functions in C

The string handling library provides many useful functions for manipulating strings. It is used to
perform several operations on sequence of characters or string name.
C programming language provides a set of pre-defined functions called string handling
functions to work with string values. The string handling functions are defined in a header file
called string.h. Whenever we want to use any string handling function we must include the
header file called string.h.
The following are most commonly used string handling functions.
Strlen(), strcpy(), strcat(), strcmp(), strlwr(), strupr(), strrev() etc.
1. Strlen()
strlen( ) function is used to find the length of a character string. strlen() function returns
the length of a string. It returns an integer value.
Syntax:
int strlen(const char *str);
or
strlen(string_name);

Example: int n;
char city[20] = “Bangalore”;
n = strlen(city);
• This will return the length of the string 9 which is assigned to an integer variable n.
• Note that the null character “\0‟ available at the end of a string is not counted.

Write a C program to print length of string by strlen() function


#include <stdio.h>
#include <string.h>
int main ()
{
int count;
char name[20] = "programming";
count=strlen(name);
printf("count=%d\n", count);
//printf("Length of string string1: %ld", strlen(name));
return 0;
}
Count=11
2. Strcpy()
strcpy( ) function copies contents of one string into another string. Syntax for strcpy
function is given below.
Syntax: char * strcpy (char * destination, const char * source);
Or
Strcpy(destination_string, source_string);

Example: strcpy ( str1, str2) – It copies contents of str2 into str1.


strcpy ( str2, str1) – It copies contents of str1 into str2.

If destination string length is less than source string, entire source string value won’t be
copied into destination string.
For example, consider destination string length is 20 and source string length is 30. Then,
only 20 characters from source string will be copied into destination string and remaining
10 characters won’t be copied and will be truncated.
Write a c program to copy one string into another string by using strcpy() function
#include <stdio.h>
#include <string.h>
int main ()
{
char subject1[35] = "physics";
char subject2[35] = "programming for problem solving";
strcpy(subject1,subject2);
printf("subject1 is: %s", subject1);
return 0;
}
Output: subject1 is: programming for problem solving
3. Strcat()
strcat( ) function in C language concatenates two given strings. It concatenates source
string at the end of destination string. Syntax for strcat( ) function is given below.
Syntax : char * strcat ( char * destination, const char * source );
Or
Strcat(destination_string, Source_string);
Example :
strcat ( str2, str1 ); - str1 is concatenated at the end of str2.
strcat ( str1, str2 ); - str2 is concatenated at the end of str1.
• As you know, each string in C is ended up with null character (‘\0′).

In strcat( ) operation, null character of destination string is overwritten by source string’s first
character and null character is added at the end of new destination string which is created
after strcat( ) operation.

It takes two strings as input and concatenates the second string to the first string, which means it
will attach the second string to the end of the first string and save the concatenated string to the
first string. The size of the first string should be large enough to save the result.

Write a c program to print two string names in one string name by using strcat() function
#include <stdio.h>
#include <string.h>
int main ()
{
char name1[30] = "welcome to ";
char name2[10] = "pps class";
strcat(name1,name2);
printf("Concatenation using strcat: %s", name1);
return 0;
}
Output: Concatenation using strcat: welcome to pps class
4. Strcmp()
strcmp( ) function in C compares two given strings and returns zero if they are same. If
length of string1 < string2, it returns < 0 value. If length of string1 > string2, it returns >
0 value.
Syntax : int strcmp ( const char * str1, const char * str2 );
Or
Strcmp(string_name1, string_name2);
strcmp( ) function is case sensitive. i.e., “A” and “a” are treated as different characters.
Example :
char city[20] = “Madras”;
char town[20] = “Mangalore”;
strcmp(city, town);
This will return an integer value “-10‟ which is the difference in the ASCII values of the
first mismatching letters “D‟ and “N‟.
* Note that the integer value obtained as the difference may be assigned to an integer
variable as follows:
int n;
n = strcmp(city, town);
strcmp() takes two strings as input then compares them, and returns an integer based on
the following condition:

Expression Returns

string 1 > string 2 Positive integer


Expression Returns

string 1 < string 2 Negative


string 1 = string 2 Zero
Program 1: Write a c program to print string comparison by using strcmp() function
#include <stdio.h>
#include <string.h>
int main ()
{ char s1[20] = "cse a";
char s2[20] = "cse b";
if (strcmp(s1, s2) ==0)
{ printf("string 1 and string 2 are equal");
}
else
{ printf("string 1 and 2 are different");
}
}
Output: string 1 and string 2 are equal
Program 2: Write a c program to print string comparison by using strcmp() function
#include <stdio.h>
#include <string.h>
int main() {
char str1[] = "abcd", str2[] = "abCd", str3[] = "abcd";
int result;
// comparing strings str1 and str2
result = strcmp(str1, str2);
printf("strcmp(str1, str2) = %d\n", result);
// comparing strings str1 and str3
result = strcmp(str1, str3);
printf("strcmp(str1, str3) = %d\n", result);
return 0;
}
Output: strcmp(str1, str2) = 32
strcmp(str1, str3) = 0

5. Strupr()

String Functions are the built-in functions provided by C to operate and manipulate a string. C
strupr() function converts a string to uppercase letters.

Syntax: char *strupr(char *str);

Or

Strupr(string_name);

Example:

Char name[5]=”pec”;

Strupr(name);

Output(PEC)

Write a C Program to convert a string into uppercase letter by using strupr() function.

#include<stdio.h>

#include<string.h>

int main()

char name[]="programming for problem solving";

strupr(name);

printf("%s", name);

return 0;

}
Output: PROGRAMMING FOR PROBLEM SOLVING

6. strlwr()

String Functions are the built-in functions provided by C to operate and manipulate a string. C
strlwr() function converts a string to lowercase letters.

Syntax: char *strlwr(char *str);


Example: Char name[5]=”PEC”;

Strupr(name);

Output(pec)

Write a C Program to convert a string into lowercase letter by using strlwr() function.

#include<stdio.h>

#include<string.h>

int main()

char name[]="PROGRAMMING FOR PROBLEM SOLVING ";

strlwr(name);

printf("%s", name);

return 0;

Output: programming for problem solving

7. strrev()

The strrev() function is a built-in function in C and is defined in string.h header file. The
strrev() function is used to reverse the given string.

Syntax:

char *strrev(char *str);


or

strrev(string_name);

Write a C program to convert given string into reverse by using strrev() function

#include<stdio.h>

#include<conio.h>

#include<string.h>

int main()

char string[20] = “Pallavi123”;

strrev(string);

printf(“%s”, string);

return 0;

Output: 321ivallaP

8. strdup()

The function strdup() is used to duplicate a string. It returns a pointer to null-terminated byte
string.

Here is the syntax of strdup() in C language,

char *strdup(const char *string);

or

strdup(string_name);
ex: char source[5]=”hello”;

char *target;

target = strdup(source);

target = hello

Write a C program to store duplicate value into another string by using strdup() function

#include<stdio.h>

#include<conio.h>

#inlcude<string.h>

int main()

char source[5]=”hello”;

char *target;

target = strdup(source);

printf(“taget=%s”, target);

return 0;

Output: target = hello

The c library supports a large number of string functions for string manipulations as given below.

Function Syntax (or) Example Description

strcpy() strcpy(string1, string2) Copies string2 value into string1

strncpy() strncpy(string1, string2, 5) Copies first 5 characters string2 into string1


Function Syntax (or) Example Description

strlen() strlen(string1) returns total number of characters in string1

strcat() strcat(string1,string2) Appends string2 to string1

strncat() strncpy(string1, string2, 4) Appends first 4 characters of string2 to string1

strcmp() strcmp(string1, string2) Returns 0 if string1 and string2 are the


less than 0 if string1<string2; greater than 0 if string1>string2

strncmp() strncmp(string1, string2, 4) Compares first 4 characters of both string1 and string2

strcmpi() strcmpi(string1,string2) Compares two strings, string1 and string2 by ignoring case (upper or lower)

stricmp() stricmp(string1, string2) Compares two strings, string1 and string2 by ignoring case (similar to strcmpi())

strlwr() strlwr(string1) Converts all the characters of string1 to lower case.

strupr() strupr(string1) Converts all the characters of string1 to upper case.

strdup() string1 = strdup(string2) Duplicated value of string2 is assigned to string1

strchr() strchr(string1, 'b') Returns a pointer to the first occurrence of character 'b' in string1

strrchr() 'strrchr(string1, 'b') Returns a pointer to the last occurrence of character 'b' in string1

strstr() strstr(string1, string2) Returns a pointer to the first occurrence of string2 in string1

strset() strset(string1, 'B') Sets all the characters of string1 to given character 'B'.

strnset() strnset(string1, 'B', 5) Sets first 5 characters of string1 to given character 'B'.

strrev() strrev(string1) It reverses the value of string1

Important Programs on String in c

Write a C program to determine if the given string is a palindrome or not (Spelled same in
both directions with or without a meaning like madam, civic, noon, abcba, etc.)
#include <stdio.h>
#include <string.h>
int main()
{
char string1[20];
int i, length;
int flag = 0;
printf("Enter a string:");
scanf("%s", string1);
length = strlen(string1);
for(i=0;i < length ;i++)
{
if(string1[i] != string1[length-i-1])
{
flag = 1;
break;
}
}
if (flag)
{
printf("%s is not a palindrome", string1);
}
else
{
printf("%s is a palindrome", string1);
}
return 0;
}
Output: Enter a string:madam
madam is a palindrome
Structures

INTRODUCTION
We have seen variables of data types, such as char, int, float, double, etc. Variables of such types
holds only one item of information at a time. Arrays hold a number of items of information or
data of the same type. Therefore, an array stores homogeneous data. In some situations, you need
to process many data items of different types together as a unit, then the data types discussed so
far are not sufficient. For example, when you want a program dealing with data concerning
students in a college, then you may want to store the student's roll number (an integer), name (a
character array), average marks (a floating-point number), etc. together as a unit. This is not
possible using an array data type, because it stores data of the same type. Hence, we would need
to use several different types of arrays an integer array for roll numbers, a character array for
names, floating-point array for average marks, etc. This approach although possible, is a tedious
one. In order to solve this problem, "C" provides a special data type, called structure. Structure is
synonymous with a 'record' in many other languages. Structures help to organize complex data in
a more meaningful manner and are used to hold related data belonging to different data types.
Another related concept known as union is also discussed.

Structure Definition
The C language provides another tool for grouping elements together. To store heterogeneous
(different) types of data in a single group, 'C' provides a facility called the structure. A structure
definition creates a format that may be used to declare structure variables.

Definition: A structure is a collection of variables of different data types that are logically
grouped together and referenced under a single name. Or

Structure is a collection of different type of elements under a single name that acts as user
defined data type in C.
Each variable within a structure is called a member of the structure. The main use of structure is
to represent the different attributes or characteristics of an entity. It creates a format, which may
be used to declare many other variables in that format.

Generally, structures are used to define a record in the c programming language. Structures allow
us to combine elements of a different data type into a group. The elements that are defined in a
structure are called members of structure.

Creating structure

To create structure in c, we use the keyword called "struct". We use the following syntax to
create structures in c programming language.

Syntax:

struct <structure_name>
{
data_type member1;
data_type member2, member3;
.
.

data_type member n
}variable ;

Following is the example of creating a structure called Student which is used to hold student
record.

Creating structure in C

struct Student
{
char stud_name[30];
int roll_number;
float percentage;
};
structure variables;
In a c programming language, there are two ways to create structure variables. We can create
structure variable while defining the structure and we can also create after terminating structure
using struct keyword.

Declaration of structures

1. structure definition
struct student
{
int rollno;
char name[10];
float marks;
}s1,s2;

2. Using the structure tag

struct student
{
int rollno;
char name[10];
float marks;
};
Void main(){
struct student s1, s2;
…….
}
To access members of a structure using structure variable, we use dot (.) operator. Consider the
following example code...
Creating and Using structure variables in C

Write a C Program to Print student details using structures.


#include<stdio.h>
struct Student
{
char sname[30];
int sroll_number;
float spercentage;
} s1 ; // while defining structure

void main(){
//struct Student s2; // using struct keyword
printf("Enter details of s1 : \n");
printf("Name : ");
scanf("%s", s1.sname);
printf("Roll Number : ");
scanf("%d", &s1.sroll_number);
printf("Percentage : ");
scanf("%f", &s1.spercentage);
printf("***** Student 1 Details *****\n");
printf("Name of the Student : %s\n", s1.sname);
printf("Roll Number of the Student : %i\n", s1.sroll_number);
printf("Percentage of the Student : %f\n", s1.spercentage);
}
Output:
Enter details of s1 :
Name : naresh
Roll Number : 34
Percentage : 67
***** Student 1 Details *****
Name of the Student : naresh
Roll Number of the Student : 34
Percentage of the Student : 67.000000

In the above example program, the stucture variable "s1 is created while defining the structure
and the variable "s2 is careted using struct keyword. Whenever we access the members of a
structure we use the dot (.) operator

Initialization of structure variables

The structure variables can also be initialized at the time of declaring the structure variables.

Syntax: struct tagname variable = { value 1, value 2, ……., value n};

Ex: struct student s1={1, “naresh”, 57.51};


Memory storage of structure

When ever we declare variables for structure then only memory is allocated for it

struct student
{
int rollno;
char name[10];
float marks; int char float
}; 4 1*10=10 4 =18 bytes
void main() s1=
{ 100 104-113 114-117
struct student s1;
……
}

accessing structure members in c


1.Array elements are accessed using the Subscript variable , Similarly Structure members are
accessed using dot [.] operator.

2.(.) is called as “Structure member Operator”.

3.Use this Operator in between “Structure name” & “member name”

Other way of initialization using designated initialization


Write a c program to print variable values by using structure

#include<stdio.h>
struct Point
{
int x, y, z;
};
int main()
{
// Examples of initialization using designated initialization
struct Point p1 = {.y = 0, .z = 1, .x = 2};
struct Point p2 = {.x = 20};

printf ("x = %d, y = %d, z = %d\n", p1.x, p1.y, p1.z);


printf ("x = %d", p2.x);
return 0;
}
Output: x = 2, y = 0, z = 1
x = 20
Size of a structure
The size of structure refers to the number of bytes required for storage of a given structure
variable. We can find out size of a structure from sizeof operator.The size of structure can be
determined by the expression.

Syntax: sizeof(struct variable name)

size of a struct is the sum of all the data members. Like for the following struct,
struct A{
int a;
int* b;
char c;
char *d;
};
Size of the struct should be sum of all the data member, which is: Size of int a+ size of int* b
+size of char c+ size of char* d

Now considering the 64-bit system,

Size of int is 4 Bytes

Size of character is 1 Byte

Size of any pointer type is 8 Bytes

(Pointer size doesn't depend on what kind of data type they are pointing too)
So the size of the struct should be: (4+8+1+8)=21 Bytes.

Write a c program to print size of given structure by using structure

#include<stdio.h>
struct Student
{
char sname[30];
int sroll_number;
float spercentage;
};
void main()
{
struct Student s1; // using struct keyword
printf("size of structure = %u\n", sizeof(s1));
printf("Enter details of s1 : \n");
printf("Name : ");
scanf("%s", s1.sname);
printf("Roll Number : ");
scanf("%d", &s1.sroll_number);
printf("Percentage : ");
scanf("%f", &s1.spercentage);
printf("***** Student 1 Details *****\n");
printf("Name of the Student : %s\n", s1.sname);
printf("Roll Number of the Student : %i\n", s1.sroll_number);
printf("Percentage of the Student : %f\n", s1.spercentage);
}
output
size of structure = 38
Enter details of s1 :
Name : pallavi
Roll Number : 32
Percentage : 99
***** Student 1 Details *****
Name of the Student : pallavi
Roll Number of the Student : 32
Percentage of the Student : 99.000000
Exercise 1: Write a c program to print employee details by using structures
#include<stdio.h>
struct employee
{
char ename[20];
int eid;
float esalary;
};
void main()
{
struct employee e1; // using struct keyword
printf("size of structure = %lu\n", sizeof(e1));
printf("Enter details of e1 : \n");
scanf("%s%d%f", e1.ename,&e1.eid, &e1.esalary);
printf("***** employee Details *****\n");
printf("%s %d %f", e1.ename, e1.eid, e1.esalary);
}
Output: size of structure = 28
Enter details of e1 :
pallavi
36
20000
***** employee Details *****
pallavi 36 20000.000000

Exercise 2: Program to read Student Details and Calculate total and average using
structures.
#include<stdio.h>
void main()
{
struct stud
{
int rno;
char sname[20];
int m1,m2,m3;
};
struct stud s; int tot;
float avg;
printf("Enter the student roll number: \n");
scanf("%d",&s.rno);
printf("Enter the student name: \n");
scanf("%s",s.sname);
printf("Enter the three subjects marks: \n");
scanf("%d%d%d",&s.m1,&s.m2,&s.m3);
tot = s.m1 + s.m2 +s.m3; avg = tot/3.0;
printf("Roll Number : %d\n",s.rno);
printf("Student Name: %s\n",s.sname);
printf("Total Marks : %d\n",tot);
printf("Average : %f\n",avg);
}
Output: Enter the student roll number:
45
Enter the student name:
pallavi
Enter the three subjects marks:
23
67
98
Roll Number : 45
Student Name: pallavi
Total Marks : 188
Average : 62.666668
Exercise 3: Program to read Item Details and Calculate Total Amount of Items
#include<stdio.h>
void main()
{
struct item
{
int itemno;
char itemname[20];
float rate;
int qty;
};
struct item i;
float tot_amt;
printf("Enter the Item Number \n");
scanf("%d",&i.itemno);
printf("Enter the Item Name \n");
scanf("%s",i.itemname);
printf("Enter the Rate of the Item \n");
scanf("%f",&i.rate);
printf("Enter the number of %s purchased ",i.itemname);
scanf("%d",&i.qty);
tot_amt = i.rate * i.qty;
printf("Item Number: %d\n",i.itemno);
printf("Item Name: %s\n",i.itemname);
printf("Rate: %f\n",i.rate);
printf("Number of Items: %d\n",i.qty);
printf("Total Amount: %f",tot_amt);
}
Output: Enter the Item Number
1
Enter the Item Name
book
Enter the Rate of the Item
400
Enter the number of book purchased 60
Item Number: 1
Item Name: book
Rate: 400.000000
Number of Items: 60
Total Amount: 24000.000000

Array of Structures
An array of structure in C programming is a collection of different datatype variables, grouped
together under a single name.
General form of structure declaration
The structural declaration is as follows −
struct tagname{
datatype member1;
datatype member2;
datatype member n;
};
Struct tagname array_variable[size];
Here, struct is the keyword
tagname specifies name of structure
member1, member2 specifies the data items that make up structure.
Example
The following example shows the usage of array of structures in C programming −
struct book{
int pages;
char author [30];
float price;
};
Struct book b[3];
 The most common use of structure in C programming is an array of structures.
 To declare an array of structure, first the structure must be defined and then an array
variable of that type should be defined.
 For Example − struct book b[10]; //10 elements in an array of structures of type ‘book’
Example
The following program shows the usage of array of structures.
#include<stdio.h>
struct Student
{
char sname[30];
int sroll_number;
float spercentage;
};
void main()
{
struct Student s[3]; // array of stucure variable using struct keyword
int i;
printf("Enter studet details : \n");
for(i=0; i<3; i++)
{
scanf("%s%d%f", s[i]. sname, &s[i]. sroll_number, &s[i]. spercentage);
}
printf("studnet details are: \n");
for(i=0; i<3; i++)
{
printf("%s %d %f\n", s[i]. sname, s[i]. sroll_number, s[i]. spercentage);
}
}
Output
Enter studet details :
Naresh
33
67.00
Suresh
63
89.56
Ramesh
98
79.45
studnet details are:
Naresh 33 67.000000
Suresh 63 89.559998
Ramesh 98 79.449997

Difference between arrays and structure

ARRAY STRUCTURE
Structure refers to a collection
Array refers to a collection consisting of consisting of elements of
elements of homogeneous data type. heterogeneous data type.

Array uses subscripts or “[ ]” (square Structure uses “.” (Dot operator) for
bracket) for element access element access

Array is pointer as it points to the first


element of the collection. Structure is not a pointer

Instantiation of Array objects is not Instantiation of Structure objects is


possible. possible.

Array size is fixed and is basically the Structure size is not fixed as each
number of elements multiplied by the size element of Structure can be of different
of an element. type and size.

Bit filed is not possible in an Array. Bit filed is possible in an Structure.


Array declaration is done simply using [] Structure declaration is done with the
and not any keyword. help of “struct” keyword.
ARRAY STRUCTURE
Arrays is a non-primitive datatype Structure is a user-defined datatype.

Array traversal and searching is easy and Structure traversal and searching is
fast. complex and slow.

struct sruct_name{ data_type1 ele1;


data_type array_name[size]; data_type2 ele2; };
Structure elements may or may not be
Array elements are stored in continuous stored in a continuous memory
memory locations. location.

Array elements are accessed by their Structure elements are accessed by


index number using subscripts. their names using dot operator.

Union
Union Definition
A union is a special data type available in C that allows storing different data types in the
same memory location.
 You can define a union with many members, but only one member can contain a value at
any given time.
 Unions provide an efficient way of using the same memory location for multiple
purposes.
 The union statement defines a new data type with more than one member for your
program. The format of the union statement is as follows:
Syntax:
union [union name/tagname]
{
Data_type member 1;
Data_type member 2
.
.
.
Data_type member n;
}umion_variable;
Example
union student
{
int rno;
char name[10];
float marks;
};
union student u;

Size of union

In a union, at most one of the data members can be active at any time, that is, the value of at
most one of the data. Members can be stored in a union at any time. The size of a union is
sufficient to contain the largest of its data members. Each data member is allocated as if it were
the sole member of a struct.
Let us observe the source code of the C program to find the size of a Union.
#include <stdio.h>
union codewindow
{ // Define the union named codewindow.
int s;
float k;
char c;
}; // Declare three variables s, k and c of different data types.
int main() {
union codewindow u;
// Use the keyword sizeof() to find the size of a union and print the same.
printf("The size of union = %d\n", sizeof(u));
return 0;
}
Output
The size of union = 4
Memory allocation of union
When the unions are used in the c programming language, the memory does not allocate on
defining union. The memory is allocated when we create the variable of a particular union. As long
as the variable of a union is created no memory is allocated. The size of memory allocated is equal
to the maximum memory required by an individual member among all members of that union
union student
{
int rollno;
char name[50];
float salary;
};
The size of union = 4bytes(largest datatype)

Write a c program to print student details by using union(and also print the first declared
decla
value)

#include<stdio.h>

union student

int srno;

char sname[10];

float smarks;

};

void main()

union student u1;

printf(" enter student details:\n");


n");

printf("enter student roll number


number\n");

scanf("%d", &u1.srno);

printf("student
f("student roll number is:%d
is:%d\n", u1.srno);

printf("enter student name:\n");


n");

scanf("%s", u1.sname);

printf("student name is:%s\n",


n", u1.sname);

printf("Enter student marks:\n");


n");

scanf("%f", &u1.smarks);

printf("student marks is:%f\n",


n", u1.smarks);
printf("student roll number is:%d\n", u1.srno); //again accessing previous declared
value its print garbage value

Output:

enter student details:

enter student roll number

60

student roll number is:60

enter student name:

pallavi

student name is:pallavi

Enter student marks:

76.56

student marks is:76.559998

student roll number is:1117331128

Difference between union and structure


Before going into the differences, let's first look at an example.ruc = 48
#include <stdio.h>
struct student1 { //defining a union
int roll_no;
char name[40];
int phone_number;
};
union student2 {
int roll_no;
char name[40];
int phone_number;
};
int main(){
struct student1 s1;
union student2 u1;
printf("size of structure = %d\n",sizeof(s1));
printf("size of union = %d\n", sizeof(u1));
return 0;
}
Output
size of structure = 48
size of union = 40
Talking about the above example, the amount of memory required to store a structure is the
sum of the memory sizes of all its members. In the above example, the memory sizes of the
variables roll_no and phone_number will be 4 bytes each (since both are of type integer) and the
memory size of the character array name[40] will be 40 bytes (since the array occupies the
memory of 40 characters and the size of char is 1). Thus, the memory occupied by the structure
will be 4+40+4 = 48 bytes.
Now coming to the union, the memory size of a union is equal to the size of its member
occupying the maximum space in the memory. The size of roll_no and phone_number is 4
bytes each and that of name[40] is 40 bytes. So, the union will occupy a memory space of 40
bytes.
Pointers

Definition:

Pointer is a special type of variable used to store the memory location address of a variable.

Or

Pointer is a special type of variable used to store the address of any other variable.

In the c programming language, we use normal variables to store user data values. When we
declare a variable, the compiler allocates required memory with the specified name. In the c
programming language, every variable has a name, datatype, value, storage class, and address.
We use a special type of variable called a pointer to store the address of another variable with the
same data type.

we can create pointer variables of any datatype. Every pointer stores the address the variable
with same datatype only. That means integer pointer is used store the address of integer variable
only.

Declaration and initialization of Pointers.


Declaring Pointers (Creating Pointers)

In c programming language, declaration of pointer variable is similar to the creation of normal


variable but the name is prefixed with * symbol. We use the following syntax to declare a pointer
variable.

Syntax: datatype *pointerName ;


A variable declaration prefixed with * symbol becomes a pointer variable.

Example Code

int *ptr ;

In the above example declaration, the variable "ptr" is a pointer variable that can be used to
store any integer variable address.

Initialization /Assigning Address to Pointer

To assign address to a pointer variable we use assignment operator with the following syntax...

pointerVariableName = & variableName ;

Example: int a, *ptr ;

In the above declaration, variable "a" is a normal integer variable and variable "ptr" is an integer
pointer variable. If we want to assign the address of variable "a" to pointer variable "ptr" we use
the following statement.

Example Code

ptr = &a ;

In the above statement, the address of variable "a" is assigned to pointer variable "prt". Here we
say that pointer variable ptr is pointing to variable a.

Accessing the address of a variable using & operator or address of operator (Reference
operator)
Reference operator "&" is used to access the address of variable.

For example, to access the address of a variable "marks" we use "&marks". We use the
following printf statement to display memory location address of variable "marks".

Example Code

printf("Address : %u", &marks) ;

In the above example statement %u is used to display address of marks variable. Address of any
memory location is unsigned integer value.

Some points to remember


 It is an “address of” operator which returns the address of any variable. The statement
&marks represents the address of marks variable.
 Since it can be used anywhere but with the pointers, it is required to use for initializing
the pointe with the address of another variable.
 The “address of” operator denoted by the ampersand character (&), it is unary operator,
which returns the address of a variable.
 After declaration of a pointer variable, we need to initialize the pointer with the valid
memory address; to get the memory address of a variable address of operator (&) is used.
Program: write a program to access address of a variables using ‘&” operator.
#include<stdio.h>
void main()
{
int a=50;
float b=10.50;
char c='A';
printf("%d is stored at address %u\n", a, &a);
printf("%f is stored at address %u\n", b, &b);
printf("%c is stored at address %u\n", c, &c);
}
Output: 50 is stored at address 623653256
10.500000 is stored at address 623653260
A is stored at address 623653255
Accessing a value of a variable through pointer(De-referencing operator)
Pointer variables are used to store the address of other variables. We can use this address to
access the value of the variable through its pointer. We use the symbol "*" in front of pointer
variable name to access the value of variable to which the pointer is pointing. It is also called as
de-referencing opearator.

general syntax.

*pointerVariableName

Example Program

#include<stdio.h>
#include<conio.h>
void main()
{
int a = 10, *ptr ;
ptr = &a ;
printf("Address of variable a = %u\n", ptr) ;
printf("Value of variable a = %d\n", *ptr) ;
printf("Address of variable ptr = %u\n", &ptr) ;
}

Output: Address of variable a = 43764


Value of variable a = 10
Address of variable ptr = 43768
In the above example program, variable a is a normal variable and variable ptr is a pointer
variable. Address of variable a is stored in pointer variable ptr. Here ptr is used to access the
address of variable a and *ptr is used to access the value of variable a.

Memory Allocation of Pointer Variables


Every pointer variable is used to store the address of another variable. In computer memory
address of any memory location is an unsigned integer value. In c programming language,
unsigned integer requires 4 bytes of memory. So, irrespective of pointer datatype every pointer
variable is allocated with 4 bytes of memory.

Differentiate between address and de-referencing operators.


Address Operator

 The & is a unary operator in C which returns the memory address of the passed operand.
 This is also known as address of operator.
 The & is a reference operator. It display address of the variable in the memory. To
displays the address of the variable it should be preceded by the variable name.
 Example
 int a = 10;
printf(“%u”, &a);
note: format specifier u is used to unsign integer.
 The above statement displays the address of the integer variable a.

De-referencing operator

 The * is a unary operator which returns the value of object pointed by a pointer variable.
 It is also known as value of operator. It is also used for declaring pointer variable.
 It is also called as indirection operator.
 It is used to declare a variable and to get the value of a variable using a pointer
 The operand * is used to display the value stored at the address of the variable.
 Example: int b=20;
printf(“%d”, *(&b));
 The above statement displays the value stored at address of b i.e., value of b.

Pointer Arithmetic

Pointers variables are also known as address data types because they are used to store the
address of another variable. The address is the memory location that is assigned to the variable.
It doesn’t store any value.

We can perform arithmetic operations on the pointers like addition, subtraction, etc. However, as
we know that pointer contains the address, the result of an arithmetic operation performed on the
pointer will also be a pointer if the other operand is of type integer. In pointer-from-pointer
subtraction, the result will be an integer value. Following arithmetic operations are possible on
the pointer in C language:

 Increment

 Decrement

 Addition

 Subtraction

Incrementing Pointer in C

If we increment a pointer by 1, the pointer will start pointing to the immediate next location. This
is somewhat different from the general arithmetic since the value of the pointer will get increased
by the size of the data type to which the pointer is pointing.

We can traverse an array by using the increment operation on a pointer which will keep pointing
to every element of the array, perform some operation on that, and update itself in a loop.

Syntax:

new_address= current_address + i * size_of(data type)

Where i is the number by which the pointer get increased.

32-bit:For 32-bit int variable, it will be incremented by 2 bytes.

64-bit:For 64-bit int variable, it will be incremented by 4 bytes.


Program: Write a C program for incrementing pointer variable on 64-bit architecture

#include<stdio.h>
int main(){
int number=50;
int *p;//pointer to int
p=&number;//stores the address of number variable
printf("Address of p variable is %u \n",p);
p++;
printf("After increment: Address of p variable is %u \n",p); // in our case, p will get incremented
by 4 bytes.
return 0;
}
Output:
Address of p variable is 619816884
After increment: Address of p variable is 619816888

Decrementing Pointer in C

Like increment, we can decrement a pointer variable. If we decrement a pointer, it will start
pointing to the previous location. The formula of decrementing the pointer is given below:
Syntax;
new_address= current_address - i * size_of(data type)
32-bit:For 32-bit int variable, it will be decremented by 2 bytes.
64-bit: For 64-bit int variable, it will be decremented by 4 bytes.
Let's see the example of decrementing pointer variable on 64-bit OS.

Program: Write a C program for decrementing pointer variable on 64-bit architecture.

#include <stdio.h>
void main(){
int number=50;
int *p;//pointer to int
p=&number;//stores the address of number variable
printf("Address of p variable is %u \n",p);
p--;
//p=p-1;
printf("After decrement: Address of p variable is %u \n",p); // P will now point to the immediate
previous location.
}
OUTPUT: Address of p variable is 1207106964
After decrement: Address of p variable is 1207106960
C Pointer Addition

We can add a value to the pointer variable.


Syntax
new_address= current_address + (number * size_of(data type))
For 32-bit int variable, it will add 2 * number.
For 64-bit int variable, it will add 4 * number.
Let's see the example of adding value to pointer variable on 64-bit architecture.

Program: Write a C program for Addition pointer variable on 64-bit architecture.

#include<stdio.h>
int main()
{
int number=50;
int *p;//pointer to int
p=&number;//stores the address of number variable
printf("Address of p variable is %u \n",p);
p=p+3; //adding 3 to pointer variable
printf("After adding 3: Address of p variable is %u \n",p);
return 0;
}
Output:
Address of p variable is 2284849764
After adding 3: Address of p variable is 2284849776
As you can see, the address of p is 2284849764. But after adding 3 with p variable, it is
2284849776, i.e., 4*3=12 increment. Since we are using 64-bit architecture, it increments 12.
But if we were using 32-bit architecture, it was incrementing to 6 only, i.e., 2*3=6. As integer
value occupies 2-byte memory in 32-bit OS.

C Pointer Subtraction

Like pointer addition, we can subtract a value from the pointer variable. Subtracting any number
from a pointer will give an address.
Syntax: new_address= current_address - (number * size_of(data type))
For 32-bit int variable, it will subtract 2 * number.
For 64-bit int variable, it will subtract 4 * number.

Program: Write a C program for Subtraction pointer variable on 64-bit architecture.

#include<stdio.h>
int main()
{
int number=50;
int *p;//pointer to int
p=&number;//stores the address of number variable
printf("Address of p variable is %u \n",p);
p=p-3; //subtracting 3 from pointer variable
printf("After subtracting 3: Address of p variable is %u \n",p);
return 0;
}
Output:

Address of p variable is 3556580244

After subtracting 3: Address of p variable is 3556580232

Pointer to Array
Accessing array elements using pointers
When we declare an array the compiler allocate the required amount of memory and also
creates a constant pointer with array name and stores the base address of that pointer in it. The
address of the first element of an array is called as base address of that array.
The array name itself acts as a pointer to the first element of that array. Consider the following
example of array declaration.
int marks[6] ;
For the above declaration, the compiler allocates 12 bytes of memory and the address of first
memory location (i.e., marks[0]) is stored in a constant pointer called marks. That means in the
above example, marks is a pointer to marks[0].
Write a program to access the base address of array using pointer.
#include<stdio.h>
#include<conio.h>

int main()
{
int marks[6] = {89, 45, 58, 72, 90, 93} ;
int *ptr ;

ptr = marks ;
printf("Base Address of 'marks' array = %u\n", ptr) ;
return 0;
}
Output: Base Address of 'marks' array = 4190133328

Write a program to access elements of an array using pointer


#include <stdio.h>

int main()
{
int a[5]= {11.21,90,45,43};
int i, *b;
b=&a[0];
for(i=0; i<5; i++)
{
printf("value of a[%d]=%d\n", i, *b);
printf("address of a[%d]=%u\n", i, b);

b=b+1;
}
}
Output: value of a[0]=11
address of a[0]=2254514016
value of a[1]=90
address of a[1]=2254514020
value of a[2]=45
address of a[2]=2254514024
value of a[3]=43
address of a[3]=2254514028
value of a[4]=0
address of a[4]=2254514032

Discuss Array of Pointers with examples.


Array can be declare as int, float, char etc. we can also declare an array of pointers “Array of
Pointers” is an array of the pointer variables. It is also known as pointer arrays.
It is collection of addresses (or) collection of pointers
Declaration

Syntax: datatype *pointername [size];

For example,
int *p[5];
It represents an array of pointers that can hold 5 integer element addresses.
Initialization

‘&’ is used for initialisation.


For Example,
int a[3] = {10,20,30};
int *p[3], i;
for (i=0; i<3; i++) (or) for (i=0; i<3,i++)
p[i] = &a[i]; or
p[i] = a+i;
Accessing

Indirection operator (*) is used for accessing.


For Example,
for (i=0, i<3; i++)
printf ("%d", *p[i]);
Write a program to find the elements in the pointer array
#include<stdio.h>
main ( ){
int a[3] = {10,20,30};
int *p[3],i;
for (i=0; i<3; i++)
p[i] = &a[i];
printf ("elements of the array are \n");
for (i=0; i<3; i++)
printf ("%d \t", *p[i]);
}
Output: elements of the array are
10 20 30

Use of Pointer to structure


Pointer pointing to a structure is known as structure pointers
 It is used to create complex data structures such as linked lists, trees, graphs and so on.
 The members of the structure can be accessed using a special operator called as an arrow
operator ( -> ).
Declaration/syntax: struct tagname *ptr;
Here the variable represents the structure type variable and *ptr represents the name of
the pointer.
For example − struct student *s
Accessing
It is explained below how to access the pointers to structures.
Ptr-> membername;
For example − s->sno, s->sname, s->marks;
Example Program: usage of pointers to structures
#include<stdio.h>
struct student{
int sno;
char sname[30];
float marks;
};
main ( ){
struct student s;
struct student *st;
printf("enter sno, sname, marks:");
scanf ("%d%s%f", & s.sno, s.sname, &s. marks);
st = &s;
printf ("details of the student are");
printf ("Number = %d\n", st ->sno);
printf ("name = %s\n", st->sname);
printf ("marks =%f\n", st ->marks);
getch ( );
}
Output:
enter sno, sname, marks:1
naresh
89
details of the student are
Number = 1
name = naresh
marks =89.00

Example 2: Which explains the functioning of pointers to structures.


#include<stdio.h>
struct person{
int age;
float weight;
};
int main(){
struct person *personPtr, person1;
personPtr = &person1;
printf("Enter age: ");
scanf("%d", &personPtr->age);
printf("Enter weight: ");
scanf("%f", &personPtr->weight);
printf("Displaying:\n");
printf("Age: %d\n", personPtr->age);
printf("weight: %f", personPtr->weight);
return 0;
}
Output:
Enter age: 33
Enter weight: 49
Displaying:
Age: 33
weight: 49.00
Self-referential structure/pointer in Self-referential in c

A self-referential structure is a structure that can have members which point to a structure
variable of the same type. They can have one or more pointers pointing to the same type of
structure as their member. The self-referential structure is widely used in dynamic data structures
such as trees, linked lists, and so on. The next node of a node will be pointed in linked lists,
which consists of the same struct type. It is a unique type of structure containing a member of its
type. The member of its type is a pointer variable of the same structure in which it has been
declared. In the context of blockchain, each block is linked to a previous node or a next node,
similar to a linked list.

Syntax:
struct structure_name
{
datatype datatype_name;
structure_name * pointer_name;
};

Example:
struct node
{
int data;
struct node *next;
};
Where ‘next’ is a pointer to a struct node variable, it should be remembered that the pointer to
the structure is similar to the pointer to any other variable. Hence, a self-referential data structure
is generally a structure definition that includes at least one member that is a pointer to the
structure of its kind.
Types of self-referential structures
1. Self-referential structure with a single link: these structures are allowed to have only one
self-pointer as their member.
The following example will shows the how to connect the objects of a self-referential structure
with the single link and access the corresponding data members.

Example
#include <stdio.h>

struct node {
int data1;
char data2;
struct node* link;
};

int main()
{
struct node ob1; // Node1

// Initialization
ob1.link = NULL;
ob1.data1 = 10;
ob1.data2 = 20;
struct node ob2; // Node2
// Initialization
ob2.link = NULL;
ob2.data1 = 30;
ob2.data2 = 40;
// Linking ob1 and ob2
ob1.link = &ob2;
// Accessing data members of ob2 using ob1
printf("%d", ob1.link->data1);
printf("\n%d", ob1.link->data2);
return 0;
}
Output:
30
40

2. Self-referential structure with multiple links (linked lists)


 These types of structures can have more than one self-pointers.
 Many complicated data structures can be easily constructed using these structures. Such
structures can easily connect to more than one node at a time.
 The following example shows one such structures with more than one links.

Program:
#include <stdio.h>

struct node {
int data;
struct node* prev_link;
struct node* next_link;
};

int main()
{
struct node ob1; // Node1
// Initialization
ob1.prev_link = NULL;
ob1.next_link = NULL;
ob1.data = 10;

struct node ob2; // Node2

// Initialization
ob2.prev_link = NULL;
ob2.next_link = NULL;
ob2.data = 20;

struct node ob3; // Node3

// Initialization
ob3.prev_link = NULL;
ob3.next_link = NULL;
ob3.data = 30;

// Forward links
ob1.next_link = &ob2;
ob2.next_link = &ob3;

// Backward links
ob2.prev_link = &ob1;
ob3.prev_link = &ob2;

// Accessing data of ob1, ob2 and ob3 by ob1


printf("%d\t", ob1.data);
printf("%d\t", ob1.next_link->data);
printf("%d\n", ob1.next_link->next_link->data);

// Accessing data of ob1, ob2 and ob3 by ob2


printf("%d\t", ob2.prev_link->data);
printf("%d\t", ob2.data);
printf("%d\n", ob2.next_link->data);

// Accessing data of ob1, ob2 and ob3 by ob3


printf("%d\t", ob3.prev_link->prev_link->data);
printf("%d\t", ob3.prev_link->data);
printf("%d", ob3.data);
return 0;
}
OUTPUT:
10 20 30
10 20 30
10 20 30
 In the above example we can see that ‘ob1’, ‘ob2’ and ‘ob3’ are three objects of the self
referential structure ‘node’.
 And they are connected using their links in such a way that any of them can easily access
each other’s data.
 This is the beauty of the self referential structures. The connections can be manipulated
according to the requirements of the programmer.
Enumeration Data Type
Enumeration data type is a user-defined data type. It allows a user to create its own data
type and define the values that the variables of this data type can take.
The syntax of an enumeration data type is similar to the syntax of a structure.
Syntax
Enum datatype_name
{
Value11, value2….., valuen;};
Example 1: Printing the Values of Weekdays

#include <stdio.h>
enum days{Sunday=1, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday};
int main(){
// printing the values of weekdays
for(int i=Sunday;i<=Saturday;i++){
printf("%d, ",i);
}
return 0;
}
Output:1,2,3,4,5,6,7,
In the above code, we declared an enum named days consisting of the name of the weekdays
starting from Sunday. We then initialized the value of Sunday to be 1. This will assign the value
for the other days as the previous value plus 1. To iterate through the enum and print the values
of each day, we have created a for loop and initialized the value for i as Sunday.

Example 2: Printing the Values of months

#include <stdio.h>
enum months{jan=1, feb, march, april, may, june, july, august, september, october, nove
mber, december};
int main()
{
// printing the values of months
for(int i=jan;i<=december;i++)
{
printf("%d, ",i);
}
return 0;
}
Unit – II Importatn Questions

1.a) What is an array? Write a ‘C’ program for Matrix Multiplication.

b) Write the use of Pointers in self-referential structures.

2.a) List the advantages of Pointers. Explain about pointers to structures.

b) Describe String library functions with syntax as well as example program.

3.a) Write a C program for addition of given two matrices.

b) Discuss pointers to arrays and structures with its syntax and example

4.a) Give a note on unions.(2M)

b)Using two dimensional array, write a C program to find the transpose of a 2×2 matrix.(8M)

5.a) Explain about Enumerated data types with an example.(10M)

b) Consider the array declaration: float a[5]; and the memory address of a[0] is 4056. What is
the memory address of a[2]?
6.a) What is a structure? Explain how to declare, initialize and access the structure
elements.(8M)
b) Write a program to find the string length by using string function.(7M)

7.a) Write a C program to find given string is palindrome or not without using any string
functions.
b) Define pointer. Write the advantages and disadvantages of using pointers

8.a) Differentiate between structure and union in C

b)What is a multidimensional array?

c)Differentiate between structure and an array

9.a) What is an array? Explain the one dimensional array with suitable example program.

b) Write a C program using array of structure to create employee records with the following
fields: emp-id, name, designation, address, salary and display it.
10.Define C string? Explain about the following string handling functions with example
programs.
(i)strlen (ii) strcpy (iii) strcmp (iv) strcat (v)strlwr (vi) strupr (vii) strrev (viii) strdup
Unit - III: Preprocessor and File handling in C
 Preprocessor: Commonly used Preprocessor commands like include, define, undef, if,
ifdef, ifndef.
 Files:Text and Binary files
 Creating and Reading and writing text and binary files, Appending data to existing files,
Writing and reading structures using binary files
 Random access using fseek, ftell and rewind functions.
Pre-processor directives
A program which processes the source code before it passes through the compiler is known as
preprocessor.
 The commands of the preprocessor are known as preprocessor directives.
 It is placed before the main().
 It begins with a # symbol.
 They are never terminated with a semicolon.
 The preprocessor commands can be classified into two categories: Conditional and
Unconditional.

The preprocessor directives are divided into Three different categories which are as follows:
1. Macro expansion
 There are two types of macros - one which takes the argument and another which
does not take any argument.
 Values are passed so that we can use the same macro for a wide range of values.
Syntax: #define name replacement text
(or #define symbolic_constant replacement string)
Ex: #define PI 3.459
Where,
 name – it is known as the micro template.
 replacement text – it is known as the macro expansion.
 A macro name is generally written in capital letters.
 If suitable and relevant names are given macros increase the readability.
 If a macro is used in any program and we need to make some changes
throughout the program we can just change the macro and the changes will be
reflected everywhere in the program.

Example :
#include <stdio.h>
#define PI 3.1459
int main()
{
int r=5;
float Area;
Area = PI*r*r;
printf("Area=%f", Area);

return 0;
}
Output: Area=78.647499
#undef
To undefined a macro means to cancel its definition. This is done with the #undef
directive.
Syntax: #undef name
Ex: undef PI
#include
#define PI 3.1415
#undef PI
int main()
{
int r=5;
float Area;
Area = PI*r*r;
printf("Area=%f", Area);

return 0;
}
The above program show error”undefined PI Variable”.

2. File Inclusion: This type of pre-processor directive tells the compiler to include a file in
the source code program. There are two types of files which can be included by the user
in the program:
a) Header File or Standard Functions: These files contains definition of pre-defined
functions like printf(), scanf() etc. These files must be included for working with these
functions. Different function are declared in different header files. For example standard
I/O functions are in ‘stdio.h’ file whereas functions which perform string operations are
in “string‟ file.
Syntax: #include<file_name>
Ex: #include<stdio.h>
where file_name is the name of file to be included. The ‘<’ and ‘>’ brackets tells the
compiler to look for the file in standard directory.
b) User defined header files: When a program becomes very large, it is good practice to
divide it into smaller files and include whenever needed. These types of files are user
defined files.
These files can be included as: #include"filename"
Ex: #include”swap.h”

3. Conditional compilation
 The conditional compilation is used when we want certain lines of code to be
compiled or not.
 It uses directives like #if, #ifdef, #ifndef, #else and #endif
 The #if direction is a preprocessor used to easily evaluate if-else conditions in the
C language. It is the same as the if condition that is widely used in C
programming.
Example:
#include <stdio.h>
#define NUMBER -2
int main() {

#if (NUMBER>0)
printf("Value of Number greater than 0 is: %d",NUMBER);
#else
printf("Value of Number less than 0 is: %d",NUMBER);

#endif

return 0;
}
Output: Value of Number less than 0 is: -2
#ifdef and #ifndef
 Use the #ifdef statement when you want to compile a section only if a specified
expression has been defined with #define.
 Use #ifndef when you want to compile a section only if a specified expression has not
been defined.
Example :
#include <conio.h>
#include <stdio.h>
#define INPUT
void main() {
int a1=0;
#ifndef INPUT
a1=2;
#else
printf("Enter a1 value :: ");
scanf("%d", &a1);
#endif
printf("The value of a1 :: %d\n", a1);
}
OUTPUT: Enter a1 value :: 7
The value of a1 :: 7
Example 2:
#include <conio.h>
#include <stdio.h>
#define INPUT
void main() {
int a1=0;
#ifdef INPUT
a1=2;
#else
printf("Enter a1 value :: ");
scanf("%d", &a1);
#endif
printf("The value of a1 :: %d\n", a1);
}
OUTPUT: The value of a1 :: 2
Files: Text and Binary files
Files are collection of records (or) it is a place on hard disk, where data is stored permanently.

Types of Files

There are two types of files in C language which are as follows −

 Text file or ASCII Files

 Binary File

Text File

 It contains alphabets and numbers which are easily understood by human beings.

 An error in a text file can be eliminated when seen.

 In text file, the text and characters will store one char per byte.

 For example, the integer value 4567 will occupy 2 bytes in memory, but, it will occupy 5
bytes in text file.

 The data format is usually line-oriented. Here, each line is a separate command.

Binary file

 It contains 1’s and 0’s, which are easily understood by computers.

 The error in a binary file corrupts the file and is not easy to detect.

 In binary file, the integer value 1245 will occupy 2 bytes in memory and in file.

 A binary file always needs a matching software to read or write it.

 For example, an MP3 file can be produced by a sound recorder or audio editor, and it can
be played in a music player.

 MP3 file will not play in an image viewer or a database software.

Files are classified into following

 Sequential files − Here, data is stored and retained in a sequential manner.

 Random access Files − Here, data is stored and retrieved in a random way.
Using Files in C: To use a file four essential actions should be carried out. These are,

a. Declare a file pointer variable.

b. Open a file using the fopen() function.

c. Process the file using suitable functions.

d. Close the file using the fclose() and fflush() functions.

File: a file represents a sequence of bytes on the disk where a group of related data is stored,
FILE is defined data type and is defined in the header file stdio.h, the word FILE must always be
in capitals.

Syntax: FILE

File Pointer: A file pointer is a pointer to a structure, which contains information about the file,
including its name, current position of the file, whether the file is being read or written, and
whether errors or end of the file have occurred.

Declaration of file pointer: A new data type called “FILE” is used to declare file pointer. This
data type is defined in stdio.h file. File pointer is declared as FILE *fp. Where, ‘fp’ is a file
pointer.

FILE *file_pointer_name;

Eg : FILE *fp;

File handling functions

File Handling is the storing of data in a file using a program. In C programming language, the
programs store results, and other data of the program to a file using file handling in C. Also, we
can extract/fetch data from a file to work with it in the program.

The operations that you can perform on a File in C are −

 Creating a new file/Opening an existing file

 Reading data from an existing file

 Writing data to a file

 Closing the file


Creating or opening file using fopen()

The fopen() function is used to create a new file or open an existing file in C. The fopen function
is defined in the stdio.h header file.

Now, lets see the syntax for creation of a new file or opening a file

file = fopen(“file_name”, “file opening mode”);

or

FILE *fopen(const char *fname,const char* mode);

This is a common syntax for both opening and creating a file in C

Example : fp=fopen(“sample.txt”, “r”);

Write a C program to open a file in read mode and check whether the file is present or not
#include<stdio.h>
int main()
{
FILE *fp=NULL;
fp = fopen(“abc.txt”, “r”);
if(fp==NULL)
{
printf(“File is not present\n”);
}
else
{
printf(“File is present in the directory\n”);
}
fclose(fp);
return 0;
}
Output: File is present in the directory
Modes of operations

Now, let’s see all types of modes that are available for us to read or write a file in C

The different modes of opening files are :

“r” (read) mode: The read mode (r) opens an existing file for reading. When a file is opened in
this mode, the file marker or pointer is positioned at the beginning of the file (first character).The
file must already exist: if it does not exist a NULL is returned as an error. If we try to write a file
opened in read mode, an error occurs.

Syntax: fp=fopen (“filename”,”r”);

“w” (write) mode: The write mode (w) opens a file for writing. If the file doesn‟t exist, it is
created. If it already exists, it is opened and all its data is erased; the file pointer is positioned at
the beginning of the file It gives an error if we try to read from a file opened in write mode.
Syntax: fp=fopen (“filename”,”w);

“a” (append) mode: The append mode (a) opens an existing file for writing instead of creating
a new file. However, the writing starts after the last character in the existing file, that is new data
is added, or appended, at the end of the file. If the file doesn‟t exist, new file is created and
opened. In this case, the writing will start at the beginning of the file.
Syntax: fp=fopen (“filename”,”a”);

“r+” (read and write) mode: In this mode file is opened for both reading and writing the data.
If a file does not exist then NULL, is returned.

Syntax: fp=fopen (“filename”,”r+”);

“w+” (read and write) mode: In this mode file is opened for both writing and reading the data.
If a file already exists its contents are erased and if a file does not exist then a new file is created.
Syntax: fp=fopen (“filename”,”w+”);

“a+” (append and read) mode: In this mode file is opened for reading the data as well as data
can be added at the end.

Syntax: fp=fopen (“filename”, “a+”);

NOTE: To perform operations on binary files the following modes are applicable with an
extension b like rb,wb,ab,rb+,wb+,ab+. which has the same meaning but allows to perform
operations on binary files.

Reading data from an existing file

The reading from a file operation is performed using the following pre-defined file handling
methods. (I/O functions for reading a file)

1. fgetc()

2. fgets()

3. fscanf()

4. fgetw()

5. fread()
fgetc() - This function is used to read a character from specified file which is opened in reading

mode. It reads from the current position of the cursor. After reading the character the cursor will
be at next character.
Syntax: fgetc( *file_pointer );

Example: fgetc(fp);
Write a C program to read a character from the file by using fgetc() function
#include<stdio.h>
#include<conio.h>
int main()
{
FILE *fp;
char ch;
clrscr();
fp = fopen("MySample.txt","r");
if(fp==NULL)
{
printf(“file is not present\n”);
}
else
{
printf("Reading character from the file: %c\n",getc(fp));
ch = getc(fp);
printf("ch = %c", ch);
fclose(fp);
getch();
return 0;
}
Output:

fgets() - This method is used for reading a set of characters from a file which is opened in

reading mode starting from the current cursor position. The fgets() function reading terminates
with reading NULL character.

Syntax: fgets( variableName, numberOfCharacters, *file_pointer

Example: fgets(name, 5, fp);


Example Program to illustrate fgets() in C.
#include<stdio.h>
#include<conio.h>
int main()
{
FILE *fp;
char *str;
clrscr();
fp = fopen ("file.txt", "r");
if(fp==NULL)
{
printf(“file is not present\n”);
}
else
{
fgets(str,6,fp);
printf("str = %s", str);
fclose(fp);
getch();
return 0;
}

Output

fscanf() - This function is used to read multiple datatype values from specified file which is
opened in reading mode.

Syntax: fscanf( *file_pointer, typeSpecifier, &variableName );

Example: fscanf(fp, “%c”, ch); or fscanf(fp, “%s”, name);

Example Program to illustrate fscanf() in C.

#include<stdio.h>
#include<conio.h>
int main()
{
FILE *fp;
char ch;
clrscr();
fp = fopen("MySample.txt","r");
if(fp==NULL)
{
printf(“file is not present\n”);
}
else
{
fscanf(fp, “%c”, ch);
printf("ch = %c", ch);
fclose(fp);
getch();
return 0;
}

Output: w

fgetw( ) - This function is used to read an integer value form the specified file which is opened in
reading mode. If the data in file is set of characters then it reads ASCII values of those
characters.

Syntax: fgetw( *file_pointer );

Example: fgetw(fp);

Example Program to illustrate fgetw() in C.

#include<stdio.h>

#include<conio.h>

int main()

FILE *fp;

int i,j;
clrscr();

fp = fopen("MySample.txt","w");

putw(65,fp); // inserts A

putw(97,fp); // inserts a

fclose(fp);

fp = fopen("MySample.txt","r");

i = getw(fp); // reads 65 - ASCII value of A

j = getw(fp); // reads 97 - ASCII value of a

printf("SUM of the integer values stored in file = %d", i+j); // 65 + 97 = 162

fclose(fp);

getch();

return 0;

Output
fread() - This function is used to read specific number of sequence of characters from the
specified file which is opened in reading mode.

Syntax: fread( source, sizeofReadingElement, numberOfCharacters, FILE *pointer )

Example: fread(str,sizeof(char),5,fp);

Example Program to illustrate fread() in C.

#include<stdio.h>

#include<conio.h>

int main()

FILE *fp;

char *str;

clrscr();

fp = fopen ("file.txt", "r");

fread(str,sizeof(char),2,fp);

printf("str = %s", str);

fclose(fp);

getch();

return 0;

Output
Writing into a file

The writing into a file operation is performed using the following pre-defined file handling
methods.

1. fputc()

2. fputs()

3. fprintf()

4. fputw()
5. fwrite()

fputc() - This function is used to write/insert a character to the specified file when the file is
opened in writing mode.

Syntax: fputc( char, *file_pointer );

Ex: fputc(ch, fp);

Example Program to illustrate putc() in C.

#include<stdio.h>

#include<conio.h>

int main()
{

FILE *fp;

char ch;

clrscr();

fp = fopen("MySample.txt","w");

fputc('A',fp);

ch = 'B';

fputc(ch,fp);

fclose(fp);

getch();

return 0;

Output
fputs() - This method is used to insert string data into specified file which is opened in writing
mode.

Syntax: fputs( "string", *file_pointer );

Ex: fputs(“Hello”, fp);

Example Program to illustrate fputs() in C.

#include<stdio.h>

#include<conio.h>

int main()

FILE *fp;

char *text = "\nthis is example text";

clrscr();

fp = fopen("MySample.txt","w");

fputs("Hi!\nHow are you?",fp);

fclose(fp);

getch();

return 0;

}Output
fprintf() - This function is used to writes/inserts multiple lines of text with mixed data types
(char, int, float, double) into specified file which is opened in writing mode.

Syntax: fprintf( *file_pointer, "text");

Ex: fprintf(fp, “%s”, str);

Example Program to illustrate "fprintf()" in C.

#include<stdio.h>

#include<conio.h>

int main()

FILE *fp;

char *text = "\nthis is example text";

int i = 10;

clrscr();

fp = fopen("MySample.txt","w");

fprintf(fp,"This is line1\nThis is line2\n%d", i);

fprintf(fp,text);

fclose(fp);

getch();

return 0;

}Output
fputw() - This function is used to writes/inserts an integer value to the specified file when the
file is opened in writing mode.

Syntax: fputw( int, *file_pointer )

Ex: fputw(i, fp);

Example Program to illustrate putw() in C.

#include<stdio.h>

#include<conio.h>

int main()

FILE *fp;

int i;

clrscr();

fp = fopen("MySample.txt","w");

fputw(66,fp);

i = 100;

putw(i,fp);

fclose(fp);

getch();

return 0;

Output
fwrite() - This function is used to insert specified number of characters into a binary file which is
opened in writing mode.

Syntax: fwrite(“string”, sizeof(char),numberofcharacters, FILE*pointer);

Ex: fwrite(str, 1, 4, fp);

Example Program to illustrate fwrite() in C.

#include<stdio.h>

#include<conio.h>

int main()

FILE *fp;

char *text = "Welcome to C Language";

clrscr();

fp = fopen("MySample.txt","wb");

fwrite(text,sizeof(char),5,fp);

fclose(fp);

getch();

return 0;

Output
Closing and Flushing Files

A file must be closed when no more Input/Output is to be performed on it. The function
fclose() is used to close a file.

Syntax: fclose(file pointer);

Ex: fclose(fp);

The argument fp is the FILE pinter associated with the stream. fclose() returns 0 on success and -
1 on error.

fflush() used when a file’s buffer is to be written to disk while still using the file. Use of
fflushall() to flush the buffers of all open streams. T

the prototype of these two functions are,

int flushall(void);

int fflush(FILE *fp);

Examples:

#include <stdio.h>
main()
{
FILE *fp;
fp = fopen("/tmp/test.txt", "w");
fprintf(fp, "This is testing...\n");
fclose(fp;);
}
Thsi will create a file test.txt in /tmp directory and will write This is testing in that file.
Random access/handling functions/cursor position in a file

Random access means you can move to any part of a file and read or write data from it without
having to read through the entire file.
Random accessing of files in C language can be done with the help of the following functions
 fseek ( )
 ftell ( )
 rewind ( )

fseek()
fseek() functions is used to move the file pointer to a desired locations with in the file.
Syntax:
int fseek(FILE *pointer, long int offset, int position);
or
fseek(FILE *pointer, numberofpositions, fromposition);
Example: fseek(fp, 50, 0)

Offset/numberof positions
 The no of positions to be moved while reading or writing.
 If can be either negative (or) positive.
o Positive - forward direction.
o Negative – backward direction.
Position
It can have three values, which are as follows −
 SEEK_SET – Seek from Beginning of the file.(indicated 0).
 SEEK_CUR – Seek from the Current position.(indicated 1).
 SEEK_END – Seek from the End of the file.(indicated 2).

When the operation is successful, the fseek() will return a zero, if we attempt to move the file
pointer beyond the file boundaries, an error occurs and fseek() returns -1.
Write a C Program to implement random access functions in a file using fseek().
#include<stdio.h>
#include<conio.h>
int main()
{
FILE *fp;
int position;
clrscr();
fp = fopen ("file.txt", "r");
position = ftell(fp);
printf("Cursor position = %d\n",position);
fseek(fp,5,0);
position = ftell(fp);
printf("Cursor position = %d\n", position);
fseek(fp, -5, 2);
position = ftell(fp);
printf("Cursor position = %d", position);
fclose(fp);
getch();
return 0;
}
Output

ftell()

the ftell() function is used to find out the exact position of the file pointer with respect to
the beginning. This function accepts the file pointer as the parameter. This function is useful in
saving the current location of the file pointer.
Syntax: long int ftell(FILE *pointer);
For example,
FILE *fp;
int n;
_____
_____
n = ftell (fp);
Note − ftell ( ) is used for counting the number of characters which are entered into a file
Example Program to illustrate ftell() in C.
#include<stdio.h>
#include<conio.h>
int main()
{
FILE *fp;
int position;
clrscr();
fp = fopen ("file.txt", "r");
position = ftell(fp);
printf("Cursor position = %d\n",position);
fseek(fp,5,0);
position = ftell(fp);
printf("Cursor position = %d", position);
fclose(fp);
getch();
return 0;
}
Output

rewind()
It makes file pointer move to beginning of the file, the rewind() function will reset the file
pointer position to beginning of the file irrespective of the current position.
Syntax: void rewind(FILE *pointer);

Example:
FILE *fp;
-----
-----
rewind (fp);
n = ftell (fp);
Example Program to illustrate rewind() in C.
#include<stdio.h>
#include<conio.h>
int main()
{
FILE *fp;
int position;
clrscr();
fp = fopen ("file.txt", "r");
position = ftell(fp);
printf("Cursor position = %d\n",position);
fseek(fp,5,0);
position = ftell(fp);
printf("Cursor position = %d\n", position);
rewind(fp);
position = ftell(fp);
printf("Cursor position = %d", position);
fclose(fp);
getch();
return 0;
}
Output
Detecting the end of a file:
feop()

When reading from a text-mode file character by character, one can look for the end-
of-file character. The symbolic constant EOF is defined in stdio.h as -1, a value never used
by a real character.

Synatx: int feop(FILE *pointer);

Eg: while((!feof(fp)). This is the general representation of the End Of the File.
ferror()
The ferror() function tests for an error in reading from or writing to the given stream. If an error
occurs, the error indicator for the stream remains set until you close stream, call
the rewind() function.
Syntax: int ferror(FILE *pointer);
Example: if(ferror(fp)!=0)

Error handling during I/O Operating in files


If possible that an error may occur during I/O operations on a file. Typical error situations
include the following:
1. Trying to read beyond the end-of-file mark.
2. Device overflow.
3. Trying to use a file that has not been opened.
4. Trying to perform an operation on a file, when the file is opened for another type
of operation.
5. Opening a file with an invalid name.
6. Attempting to write to a protected file.
We have two library functions like feof() and ferror() that can helps us to detect I/O errors in the
files.
C Program for copying the contents of one file into another file
#include<stdio.h>
#include<stdlib.h>
#include<ctype.h>
int main()
{
FILE *fp1, *fp2;
char ch;
fp1 = fopen("asource.txt", "r");
if (fp1 == NULL)
{
puts("File does not exist..");
exit(1);
}
fp2 = fopen("atarget.txt", "w");
if (fp2 == NULL)
{
puts("File does not exist..");
fclose(fp1);
exit(1);
}
while((ch=fgetc(fp1))!=EOF)
{
fputc(ch,fp2);
}
printf("\nFile successfully copied..");
return 0;
}
Output: Enter the filename to open for reading
asouce.txt
Enter the filename to open for writing
btarget.txt

Contents copied to btarget.txt

Write a program to read a text file, convert all the lowercase characters into upper case and re-
write the uppercase characters in the file
#include<stdio.h>
#include<stdlib.h>
#include<ctype.h>
int main()
{
FILE *fp1, *fp2;
char ch;
fp1 = fopen("a1.txt", "r");
if (fp1 == NULL)
{
puts("File does not exist..");
exit(1);
}
fp2 = fopen("abc.txt", "w");
if (fp2 == NULL)
{
puts("File does not exist..");
fclose(fp1);
exit(1);
}
while((ch=fgetc(fp1))!=EOF)
{
ch = toupper(ch);
fputc(ch,fp2);
}
printf("\nFile successfully copied..");
return 0;
}

Output: File successfully copied..


Unit - III Important Questions

1. a)Define the terms: Binary file and text file.

b) List and explain various file read/write functions available in C with examples.

illustrating their usage and implementation.

2. a)Write the syntax of fseek( ) function in C and explain with program.

b)Explain the concept of streams(standard files) and their significance in I/O operations.

3. Demonstrate the following functions with a correct syntax and Program code:

a) ftell( ) b) fseek( ) c) rewind( )

(or Random access files/ cursor positioning files)

4. a) Write a C program to illustrate define, undef directives.

b) Explain Steps for file operations and different modes of files.

5. a) How can we determine whether a file is successfully opened or not using fopen()

function?

b) Write a ‘C’ program to read a binary file and print it on console(fgetc).

6. List and explain various commonly used pre-processing directives in C with an example

program.(file inclusion, macro expansion and conditional compilation) 15M

7. a)What is a file pointer? Explain the steps for sequential file operations.

b) Write a program to copy the contents of one file to another file

8. Explain file handling functions with Input/Output Operations.

9. Write a program to read a text file, convert all the lowercase characters into upper case

and re-write the uppercase characters in the file.

10. Demonstrate the following functions with a correct syntax code(I/O):

a) fgets( ) b) fgetc( ) c) fscanf( ) d) fread( ) e) fgetw( )

f) fputs( ) g) fputc( ) h) fprintf( ) i) fwrite( ) j) fputw( )


Unit - IV: Function and Dynamic Memory Allocation

 Functions: Designing structured programs, Declaring a function, Signature of a function


 Parameters and return type of a function
 passing parameters to functions
 call by value
 Passing arrays to functions
 passing pointers to functions
 idea of call by reference
 Some C standard functions and libraries
 Recursion: Simple programs, such as Finding Factorial, Fibonacci series etc.,
 Limitations of Recursive functions
 Dynamic memory allocation: Allocating and freeing memory
 Allocating memory for arrays of different data type
Functions: Designing structured programs, declaring a function, Signature of a function

Introduction
We have written "C" programs using three functions, namely, main(), printf() and scanf().
Every program must have a main function to indicate where the execution of the program begins
and ends. If a program is large and if we write all the statements of that large program in main
itself, the program may become too complex and large. As a result, the task of debugging, testing
and even understanding will become very difficult. Experience has shown that the best. way to
develop a large program is to construct it from smaller pieces or modules. A module can be a
single function or a group of related functions carrying out a specific task. Since a programmer
will not be able to comprehend the meaning of a long, continuous program, divide it into a series
of individual modules that are related to each other. Usually, it is easier to break down a difficult
task into a series of smaller tasks and then to solve those subtasks individually and later
combined into a single unit. These subtasks are made user-defined functions In C, such modules
are called functions. The functions are much easier to understand, debug and test.

Designing structured programs

Structured programming is a programming technique in which a larger program is divided into


smaller subprograms to make it easy to understand, easy to implement and makes the code
reusable, etc. Structured programming enables code reusability. Code reusability is a method of
writing code once and using it many times. Using a structured programming technique, we write
the code once and use it many times. Structured programming also makes the program easy to
understand, improves the quality of the program, easy to implement and reduces time.

In C, the structured programming can be designed using functions concept. Using functions
concept, we can divide the larger program into smaller subprograms and these subprograms are
implemented individually. Every subprogram or function in C is executed individually.

Functions

Definition
Function is a subpart of a program used to perform a specific task and is executed individually.

OR

A function is a block of statement that performs a specific task.


When we write a program to solve a larger problem, we divide that larger problem into smaller
sub problems and are solved individually to make the program easier. In C, this concept is
implemented using functions. Functions are used to divide a larger program into smaller
subprograms such that the program becomes easy to understand and easy to implement.

Types of Functions in C

In C Programming Language, based on providing the function definition, functions are divided
into two types. Those are as follows...

 System Defined Functions

 User Defined Functions

System Defined Functions

The C Programming Language provides pre-defined functions to make programming easy. These
pre-defined functions are known as syatem defined functions. The system defined function is
defined as follows...

“The function whose definition is defined by the system is called as system defined function.”

The system defined functions are also called as Library Functions or Standard Functions or Pre-
Defined Functions. The implementation of system defined functions is already defined by the
system.

In C, all the system defined functions are defined inside the header
files like stdio.h, conio.h, math.h, string.h etc., For example, the funtions printf() and scanf() are
defined in the header file called stdio.h.

Whenever we use system defined functions in the program, we must include the respective
header file using #include statement. For example, if we use a system defined function sqrt() in
the program, we must include the header file called math.h because the function sqrt() is defined
in math.h.

User Defined Functions

In C programming language, users can also create their own functions. The functions that are
created by users are called as user defined functions. The user defined function is defined as
follows...

“The function whose definition is defined by the user is called as user defined function.”

That means the function that is implemented by user is called as user defined function. For
example, the function main is implemented by user so it is called as user defined function.
The user defined functions categorized into three types of elements (or function elements)

 Function Declaration (Function Prototype)


 Function Definition
 Function Call
Function Declaration(signature of a function)
The function declaration tells the compiler about function name, the data type of the return value
and parameters. The function declaration is also called a function prototype. The function
declaration is performed before the main function or inside the main function or any other
function.

Function declaration syntax -

returnType functionName(parametersList/argruments_withdata_type);

ex: int sum(int, int);

this example is a function prototype for the function sum() that takes two integer arguments and
returns a integer value as result.

In the above syntax, returnType specifies the data type of the value which is sent as a return
value from the function definition. The functionName is a user-defined name used to identify
the function uniquely in the program. The parametersList is the data values that are sent to the
function definition.

Function Call

The function call tells the compiler when to execute the function definition. When a function call
is executed, the execution control jumps to the function definition where the actual code gets
executed and returns to the same functions call once the execution completes. The function call
is performed inside the main function or any other function or inside the function itself.

Function call syntax -

functionName(parameters);

ex: sum(a,b);

Function Definition

The function definition provides the actual code of that function. The function definition is also
known as the body of the function. The actual task of the function is implemented in the
function definition. That means the actual instructions to be performed by a function are written
in function definition. The actual instructions of a function are written inside the braces "{ }".
The function definition is performed before the main function or after the main function.

Function definition syntax -

returnType functionName(parametersList)
{

Function body

ex: int sum(int a, int b)

Return a+b;

ADVANTAGES OF FUNCTIONS

 Using functions we can implement modular programming.

 Functions make the program more readable and understandable.

 Using functions the program implementation becomes easy.

 Once a function is created it can be used many times (code re-usability).

 Using functions larger programs can be divided into smaller modules.

Write a c program to multiply two numbers by using functions

#include <stdio.h>
#include<conio.h>
int multiplication(int, int);
void main()
{
int a, b, mul=0;
printf("Enter a, b values\n");
scanf("%d%d", &a, &b);
mul=multiplication(a, b);
printf("mul=%d\n", mul);
}
int multiplication(int x, int y)
{
int mul=0;
mul=x*y;
return mul;
}
Output: Enter a, b values
6
8
mul=48
In the above example program, the function declaration statement "int multiplication (int,int)
" tells the compiler that there is a function with name multiplication() which takes two integer
values as parameters and returns an integer value. The function call statement takes the execution
control to the multiplication () definition along with values of a and b. Then function
definition executes the code written inside it and comes back to the function call along
with return value.
In the concept of functions, the function call is known as "Calling Function" and the function
definition is known as "Called Function".
When we make a function call, the execution control jumps from calling function to called
function. After executing the called function, the execution control comes back to calling
function from called function. When the control jumps from calling function to called function it
may carry one or more data values called "Paramenters" and while coming back it may carry a
single value called "return value".

That means the data values transferred from calling function to called function are called
as Parameters and the data value transferred from called funcion to calling function is
called Return value.

Parameters and Return type of a function (different types of user defined functions with respect
to parameter and return type of function.)

The various categories of user defined functions in C is depending on whether arguments are
present or not and whether a value is returned or not may belong to any one of the following
categories:

 Function without Parameters and without Return value


 Function with Parameters and without Return value
 Function without Parameters and with Return value
 Function with Parameters and with Return value

Function without Parameters and without Return value


In this type of functions there is no data transfer between calling function and called function.
Simply the execution control jumps from calling-function to called function and executes called
function, and finally comes back to the calling function. For example, consider the following
program.

Program: Write a C program to add two numbers by using functions

#include<stdio.h>
#include<conio.h>
void addition() ; // function declaration
void main()
{
clrscr() ;
addition() ; // function call
getch() ;
}
void addition() // function definition
{
int num1, num2, sum=0 ;
printf("Enter any two integer numbers : ") ;
scanf("%d%d", &num1, &num2);
sum=num+num2;
printf("Sum = %d", sum ) ;
}
Output:
Enter any two integer numbers : 4
5
Sum = 9

Function with Parameters/arguments and without Return value


In this type of functions there is data transfer from calling-function to called function
(parameters) but there is no data transfer from called function to calling-function (return value).
The execution control jumps from calling-function to called function along with the parameters
and executes called function, and finally comes back to the calling function. For example,
consider the following program...

Example Program
#include<stdio.h>
#include<conio.h>
void addition(int, int) ; // function declaration
void main()
{
int num1, num2 ;
clrscr() ;
printf("Enter any two integer numbers : ") ;
scanf("%d%d", &num1, &num2);
addition(num1, num2) ; // function call
getch() ;
}
void addition(int a, int b) // function definition
{
int sum=0;
sum=a+b;
printf("Sum = %d", sum ) ;
}
Output: Enter any two integer numbers : 5
7
Sum = 12

Function without Parameters and with Return value


In this type of functions there is no data transfer from calling-function to called-function
(parameters) but there is data transfer from called function to calling-function (return value). The
execution control jumps from calling-function to called function and executes called function,
and finally comes back to the calling function along with a return value. For example, consider
the following program...

Example Program
#include<stdio.h>
#include<conio.h>
int addition() ; // function declaration
void main()
{
int result ;
clrscr() ;
result = addition() ; // function call
printf("Sum = %d", result) ;
getch() ;
}
int addition() // function definition
{
int num1, num2, sum=0;
printf("Enter any two integer numbers : ") ;
scanf("%d%d", &num1, &num2);
sum=num1+num2;
return sum;
}
Output: Enter any two integer numbers : 7
9
Sum = 16

Function with Parameters and with Return value


In this type of functions there is data transfer from calling-function to called-function
(parameters) and also from called function to calling-function (return value). The execution
control jumps from calling-function to called function along with parameters and executes called
function, and finally comes back to the calling function along with a return value. For example,
consider the following program...

Example Program
#include<stdio.h>
#include<conio.h>
int addition(int, int) ; // function declaration
void main()
{
int num1, num2, result=0;
/clrscr() ;
printf("Enter any two integer numbers : ") ;
scanf("%d%d", &num1, &num2);
result = addition(num1, num2) ; // function call
printf("Sum = %d", result) ;
getch() ;
}
int addition(int a, int b) // function definition
{
return (a+b) ;
}
Output: Enter any two integer numbers : 7
6
Sum = 13

Parameter Passing in C(passing parameters to functions/Mechanism)


When a function gets executed in the program, the execution control is transferred from calling-
function to called function and executes function definition, and finally comes back to the calling
function. When the execution control is transferred from calling-function to called-function it
may carry one or number of data values. These data values are called as parameters.
“Parameters are the data values that are passed from calling function to called function.”
In C, there are two types of parameters and they are as follows...
 Actual Parameters
 Formal Parameters
The actual parameters are the parameters that are speficified in calling function.
The formal parameters are the parameters that are declared at called function.
When a function gets executed, the copy of actual parameter values are copied into formal
parameters.
In C Programming Language, there are two methods to pass parameters from calling function to
called function and they are as follows...
 Call by Value
 Call by Reference
Call by Value
In call by value parameter passing method, the copy of actual parameter values are copied to
formal parameters and these formal parameters are used in called function. The changes made
on the formal parameters does not effect the values of actual parameters. That means, after
the execution control comes back to the calling function, the actual parameter values remains
same. For example consider the following program.
Example Program
#include<stdio.h>
#include<conio.h>
void main(){
int num1, num2 ;
void swap(int,int) ; // function declaration
clrscr() ;
num1 = 10 ;
num2 = 20 ;
printf("\nBefore swap: num1 = %d, num2 = %d", num1, num2) ;
swap(num1, num2) ; // calling function
printf("\nAfter swap: num1 = %d\nnum2 = %d", num1, num2);
getch() ;
}
void swap(int a, int b) // called function
{
int temp ;
temp = a ;
a=b;
b = temp ;
}
Output:
Before swap: num1 = 10, num2 = 20
After swap: num1 = 10
num2 = 20
In the above example program, the variables num1 and num2 are called actual parameters and
the variables a and b are called formal parameters. The value of num1 is copied into a and the
value of num2 is copied into b. The changes made on variables a and b does not effect the values
of num1 and num2.

Call by Reference
In Call by Reference parameter passing method, the memory location address of the actual
parameters is copied to formal parameters. This address is used to access the memory locations
of the actual parameters in called function. In this method of parameter passing, the formal
parameters must be pointer variables.

That means in call by reference parameter passing method, the address of the actual parameters
is passed to the called function and is received by the formal parameters (pointers). Whenever we
use these formal parameters in called function, they directly access the memory locations of
actual parameters. So the changes made on the formal parameters effects the values of actual
parameters. For example consider the following program.

Example program

#include<stdio.h>
#include<conio.h>
void main(){
int num1, num2 ;
void swap(int *,int *) ; // function declaration
num1 = 10 ;
num2 = 20 ;
printf("\nBefore swap: num1 = %d, num2 = %d", num1, num2) ;
swap(&num1, &num2) ; // calling function
printf("\nAfter swap: num1 = %d, num2 = %d", num1, num2);
getch() ;
}
void swap(int *a, int *b) // called function
{
int temp ;
temp = *a ;
*a = *b ;
*b = temp ;
}
Output:
Before swap: num1 = 10, num2 = 20
After swap: num1 = 20, num2 = 10

Difference between call by value and call by reference

Call By Value(pass by value) Call By Reference(pass by reference)

 While calling a function, instead of


 While calling a function, we pass passing the values of variables, we pass
values of variables to it. Such address of variables(location of variables)
functions are known as “Call By to the function known as “Call By
Values”. References.

 In this method, the value of each  In this method, the address of actual
variable in calling function is variables in the calling function are
copied into corresponding dummy copied into the dummy variables of the
variables of the called function. called function.

 With this method, the changes


made to the dummy variables in the  With this method, using addresses we
called function have no effect on would have an access to the actual
the values of actual variables in the variables and hence we would be able to
calling function. manipulate them.

 In call by values we cannot alter the


values of actual variables through  In call by reference we can alter the
function calls. values of variables through function calls.

Passing arrays to functions

 To process arrays in a large program, we have to be able to pass them to functions.


 The array_name contains the address of the first element. Here, we must notice that we
need to pass only the name of the array in the function which is intended to accept an
array.
 The array defined as the formal parameter will automatically refer to the array specified
by the array name defined as an actual parameter.
We can pass arrays in two ways:
Passing individual elements
Passing a whole array
Passing individual elements:
 Just like normal variable, we can pass individual elements of an array to a
function.
 We can pass either the values (or) the address of an array to a function.
 Call by value: int sum (int arr[]);
 Call by reference: int sum (int* ptr);
 To pass a value to a function, give the array name along with its index in the
function call.
 We can pass the address of individual array elements to a function.
 When we pass the address of an array while calling a function then this is called
function call byreference. When we pass an address as an argument, the function
declaration should have a pointer as a parameter to receive the passed address.

Program: Pass Individual Array Elements

#include<stdio.h>

void fun( int, int );

void main()

int a[5]={ 1,2,3,4,5};

fun(a[3], a[0]); //passing index 3 and 0 elements into function definition

void fun( int x, int y)

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

Output 4, 1

Passing a whole array

 The function prototype must show that the argument is an array.


 The function must be called by passing array name and size.
 To pass a 1-dimensional array, we have to specify the array name without subscript and
with size as arguments.
 In function definition, the formal parameters must be an array type and no need to specify
the size inside the subscript.

Program: to find the sum of elements in the array

#include<stdio.h>

int array_sum( int[], int);

void main()

int result=0;

int a[5]={ 10,20,30,40,50};

result =array_sum(a,5);

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

int array_sum( int x[], int n)

int i, sum=0;

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

sum=sum+x[i];

return sum;

Output: sum=150

Program: to find average of sum of elements in the array

#include<stdio.h>

int array_sum( int[], int);


void main()

int sum=0;

float avg;

int a[5]={ 10,20,30,40,50};

//sum=array_sum(a,5);

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

avg=array_sum(a,5);

printf("avg=%f", avg);

int array_sum( int x[], int n)

int i, sum=0;

float avg;

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

sum=sum+x[i];

avg=sum/n;

return avg;

Output: 30.000000

Passing pointers to functions


When we pass addresses to a function, the parameter receiving the addresses should be pointers.
The process of calling a function using pointers to pass the address of variables is known as “call
by reference”. The function which is called by reference can change the value of the variable
used in the call.

Program: to swap two numbers by using passing pointers to functions

#include<stdio.h>

#include<conio.h>

void swap(int *,int *) ; // function declaration

void main(){

int a, b ;

a = 10 ;

b = 20 ;

printf("\nBefore swap: a = %d, b = %d", a, b) ;

swap(&a, &b) ; // calling function

printf("\nAfter swap: a = %d, b = %d", a, b);

getch() ;

void swap(int *p, int *q) // called function

int temp ;

temp = *p ;

*p = *q ;

*q = temp ;

Output: Before swap: a = 10, b = 20

After swap: a = 20, b = 10


Recursive Functions in C
In C programming language, function calls can be made from the main() function, other
functions or from the same function itself. The recursive function is defined as follows...
A function called by itself is called recursive function.
The recursive functions should be used very carefully because, when a function called by itself it
enters into the infinite loop. And when a function enters into the infinite loop, the function
execution never gets completed. We should define the condition to exit from the function call so
that the recursive function gets terminated.

When a function is called by itself, the first call remains under execution till the last call gets
invoked. Every time when a function call is invoked, the function returns the execution control to
the previous function call.
Program: To print factorial of a number using recursive functions.
#include<stdio.h>
#include<conio.h>
int factorial( int ) ;
int main()
{
int fact, n ;
printf("Enter any positive integer: ") ;
scanf("%d", &n) ;
fact = factorial( n ) ;
printf("\nFactorial of %d is %d\n", n, fact) ;
return 0;
}
int factorial( int n )
{
int temp ;
if( n == 0)
return 1 ;
else
temp = n * factorial( n-1 ) ; // recursive function call
return temp ;
}
Output: Enter any positive integer: 3

Factorial of 3 is 6
In the above example program, the factorial() function call is initiated from main() function with
the value 3. Inside the factorial() function, the function calls factorial(2), factorial(1) and
factorial(0) are called recursively. In this program execution process, the function call
factorial(3) remains under execution till the execution of function calls factorial(2), factorial(1)
and factorial(0) gets completed. Similarly the function call factorial(2) remains under execution
till the execution of function calls factorial(1) and factorial(0) gets completed. In the same way
the function call factorial(1) remains under execution till the execution of function call
factorial(0) gets completed.
Program: write a C program to Fibonacci numbers upto 100 using recursion.
#include<stdio.h>
int fibbonacci(int n);
int main()
{
int n,i;
printf("Enter number of Fibbonacci terms:");
scanf("%d", &n);
printf("Fibbonacci of %d: ", n);
for(i=0;i<n;i++)
{
printf("%d ",fibbonacci(i));
}
}
int fibbonacci(int n)
{
if(n ==0)
{
return 0;
}
else if(n ==1)
{
return 1;
}else
{
return(fibbonacci(n-1)+fibbonacci(n-2));
}
}
Output: Enter number of Fibbonacci terms:10
Fibbonacci of 10: 0 1 1 2 3 5 8 13 21 34
Limitations of Recursion functions

1. Recursive solutions may involve extensive overhead because they use function calls.
2. Each function call requires push of return memory address, parameters, returned results,
etc. and every function return requires that many pops.

3. Each time we make a call we use up some of our memory allocation. If the recursion is
deep that is, if there are many recursive calls then we may run out of memory.

4. Recursion is implemented using system stack. If the stack space on the system is limited,

recursion to a deeper level will be difficult to implement.

5. Aborting a recursive process in midstream is slow and sometimes nasty.

6. Using a recursive function takes more memory and time to execute as compared to its

non-recursive counterpart.

7. It is difficult to find bugs, particularly when using global variables.

8. Recursion uses more processor time.

Standard Functions in C

The standard functions are built-in functions. In C programming language, the standard functions

are declared in header files and defined in .dll files. In simple words, the standard functions can

be defined as "the ready made functions defined by the system to make coding more easy". The
standard functions are also called as library functions or pre-defined functions.

In C when we use standard functions, we must include the respective header file

using #include statement. For example, the function printf() is defined in header

file stdio.h (Standard Input Output header file). When we use printf() in our program, we must
include stdio.h header file using #include<stdio.h> statement.

C Programming Language provides the following header files with standard functions.

Header Example
File Purpose Functions

stdio.h Provides functions to perform standard I/O operations printf(), scanf()


Header Example
File Purpose Functions

conio.h Provides functions to perform console I/O operations clrscr(), getch()

math.h Provides functions to perform mathematical operations sqrt(), pow()

string.h Provides functions to handle string data values strlen(), strcpy()

stdlib.h Provides functions to perform general functions/td> calloc(), malloc()

time.h Provides functions to perform operations on time and date time(), localtime()

ctype.h Provides functions to perform - testing and mapping of isalpha(), islower()


character data values

setjmp.h Provides functions that are used in function calls setjump(),


longjump()

signal.h Provides functions to handle signals during program execution signal(), raise()

assert.h Provides Macro that is used to verify assumptions made by the assert()
program

Dynamic Memory Allocation: Memory allocation done at the time of execution(run time) is
known as dynamic memory allocation. Functions calloc() and malloc() support allocating
dynamic
amic memory. In the Dynamic allocation of memory space is allocated by using these
functions when the value is returned by functions and assigned to pointer variables.
Or The process of allocating memory at runtime is known as dynamic memory allocation.

Therefore, C Dynamic Memory Allocation can be defined as a procedure in which the size of a
data structure (like Array) is changed during the runtime.
C provides some functions to achieve these tasks. There are 4 library functions provided by C
defined under <stdlib.h> header file or to facilitate dynamic memory allocation.
Dynamic memory allocation can be done by four functions.
1. malloc()
2. calloc()
3. free()
4. realloc()
Malloc():
The malloc() function stands for memory allocation. It is a function it is used to allocate a single
large block of memory dynamically. It reserves memory space of specified size and returns the
null pointer pointing to the memory location. The pointer returned is usually of type void. It
means that we can assign malloc function to any ppointer.
Syntax:

ptr = (cast-type*) malloc(size_t*


size_t*byte-size);
For Example:
ptr = (int*) malloc(5 * sizeof(int));
Since the size of int is 4 bytes, this statement will allocate 16 bytes of memory. And, the pointe
r ptr holds the address of the first byte iin the allocated memory.

Program: Write a program for dynamic memory allocation by using malloc() function.

#include <stdio.h>

#include <stdlib.h>

int main ()

int *ptr, size, i;


printf (" Enter the allocated size of memory ");

scanf (" %d", &size);

ptr = malloc (size * sizeof(int));

if (ptr != NULL)

printf (" Enter numbers from the user: ");

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

scanf (" %d", ptr + i);

printf (" Numbers are stores in contiguous memory: \n ");

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

printf (" \n The number is: %d", *(ptr + i));

printf (" \n Memory is created using the malloc() function ");

return 0;

else

printf (" memory is not created ");

return 0;

Output: Enter the allocated size of memory 5


Enter numbers from the user: 7

Numbers are stores in contiguous memory:

The number is: 7

The number is: 9

The number is: 0

The number is: 5

The number is: 8

Memory is created using the malloc() function

Calloc(): The calloc function stands for contiguous allocation. This function is used to allocate
multiple blocks of memory. It is a dynamic memory allocation function which is used to allocate
the memory to complex data structures such as arrays and structures.

Syntax:

ptr = (cast-type*)calloc(size_t, byte-size);


here, n is the no. of elements and element-size is the size of each element.
For Example:

ptr = (int*) calloc(25, sizeof(int));


This statement allocates contiguous space in memory for 25 elements each with the size of the
int.
Program: Write a program for dynamic memory allocation by using Calloc(
Calloc()) function

#include <stdio.h>
#include <stdlib.h>
int main()
{
int* ptr;
int n, i;
printf("Enter n size\n");
scanf("%d", &n);
printf("Enter number of elements: %d %d\n", n);
ptr = (int*)calloc(n, sizeof(int));
if (ptr == NULL)
{
printf("Memory not aallocated.\n");
exit(0);
}
else {

printf("Memory successfully allocated using calloc.


calloc.\n");
for (i = 0; i < n; ++i)
{
scanf("%d", ptr+i);
}
printf("The elements of the array are: ");
for (i = 0; i < n; ++i) {
printf("%d, ", *(ptr+i)
*(ptr+i));
}
}
return 0;
}
Output: Enter n size
5
Enter number of elements: 5
Memory successfully allocated using calloc.
3
7
0
4
6
The elements of the array are: 3, 7, 0, 4, 6,

Realloc():
Realloc() is used dynamically change the memory allocation of a previo
previously
usly allocated memory.
If the previously allocated with the help of malloc or calloc is insufficient, realloc can be used to
dynamically reallocate memory.

Syntax:

ptr = realloc(ptr, newSize);

where ptr is reallocated with new size 'newSize'.

Program:
am: Write a program for dynamic memory allocation by using Realloc() function

#include <stdio.h>

#include <stdlib.h>

int main ()

int *ptr, size, i, n;

size=3;

ptr = malloc (size * sizeof(int));


if (ptr != NULL)

printf (" Enter numbers from the user: ");

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

scanf (" %d", ptr + i);

printf (" Numbers are stores in contiguous memory: \n ");

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

printf (" \n The number is: %d", *(ptr + i));

printf("\n\nEnter the new size of the array: %d\n", n);

scanf("%d", &n);

ptr = realloc(ptr, n * sizeof(int));

printf("Memory successfully re-allocated using realloc.\n");

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

scanf("%d", ptr+i);

printf("The elements of the array are: ");

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

printf("%d, ", *(ptr+i));


}

free(ptr);

printf (" \n Memory is created using the remalloc() function ");

return 0;

else

printf (" memory is not created ");

return 0;

}Output:

Enter numbers from the user: 2

Numbers are stores in contiguous memory:

The number is: 2

The number is: 0

The number is: 6

Enter the new size of the array: 5

Memory successfully re-allocated using realloc.

The elements of the array are: 2, 0, 6, 1, 5,

Memory is created using the remalloc() function


Free():
Free() function is used to dynamically
ynamically de
de-allocate
allocate the memory. The memory allocated using
functions malloc() and calloc() are not de
de-allocated
allocated on their own. Hence the free() method is
used. Whenever the dynamic memory allocation takes place. It helps to reduce wastage of
memory by freeing it.
Syntax:

free(ptr);

Program: Write a program for dynamic memory allocation by using


free() function.
#include <stdio.h>
#include <stdlib.h>
int main()
{
int* ptr;
int n, i;
printf("Enter n size\n");
n");
scanf("%d", &n);
printf("Enter number of elements: %d %d\n", n);
ptr = (int*)calloc(n, sizeof(int));
if (ptr == NULL)
{
printf("Memory not allocated.
allocated.\n");
exit(0);
}
else {

printf("Memory successfully allocated using calloc.


calloc.\n");
for (i = 0; i < n; ++i)
{
scanf("%d", ptr+i);
}
printf("The elements of the array are:
are:\n ");
for (i = 0; i < n; ++i) {
printf("%d, ", *(ptr+i));
}
}
free(ptr);
printf("Memory is successfully freed\n");
return 0;
}
Output: Enter n size
3
Enter number of elements: 3
Memory successfully allocated using calloc.
4
5
6
The elements of the array are:
4, 5, 6, Memory is successfully freed.

Difference between static and dynamic memory allocation.

Static Memory Allocation Dynamic Memory Allocation

In this case, variables get allocated In this case, variables get allocated only if your
permanently program unit gets active

Allocation is done before program execution Allocation is done during program execution

It uses the data structure called stack for It uses the data structure called heap for
implementing static allocation implementing dynamic allocation

Less efficient More efficient

There is no memory reusability There is memory reusability and memory can be


freed when not required
Unit – IV Important Questions

1. a) Explain the call-by-value and call-by-reference parameter passing methods

b) Explain the passing parameters to functions.

2. Write a recursive program to find out the factorial of given number.

3. a) Write a recursive function in C to find the sum of array elements.

b) Define Recursion. what are the limitations of using recursive functions?

4. define function. Explain function definition, function call and function definition with
examples.

5. List and explain different types of user defined functions with respect to parameter and return
type of function

6.a) Explain about the dynamic memory allocation.

b). Write a C program that uses calloc( ) to create a memory block for storing n integers and
print the stored contents

7. Explain about Allocating memory for arrays of different data types.(malloc()and calloc()with
example programs)

8. Explain about Allocating memory for arrays of different data types.( realloc() and free() with
example programs)

9. write a C program to generate Fibonacci series using recursive functions.

10. a) Difference between static and dynamic memory allocation

b) Difference between call by values and call by reference


Unit - V: Introduction to Algorithms

 Algorithms for finding roots of quadratic equations, finding minimum and maximum
numbers of a given set, finding if a number is prime number, etc.
 Basic searching in an array of elements (linear and binary search techniques)
 Basic algorithms to sort array of elements (Bubble, Insertion and Selection sort
algorithms)
 Basic concept of order of complexity through the example programs
 Algorithms for finding roots of a quadratic equation, finding minimum and maximum
numbers of a given set, finding if a number is prime number, etc.
Introduction to Algorithms

Algorithm

Definition:

An algorithm is a step-by-step procedure/method for solving a problem or making


decisions.
Or
An algorithm is a finite sequence of well defined steps for solving a problem.

Characteristics of Algorithm

An algorithm has five important characteristics:

 Inputs: An algorithm may specify the quantities which are to be read.

 Outputs: An algorithm must specify the quantities which are to be displayed or printed.

 Definiteness: Each instruction must be clear and unambiguous.

 Finiteness: An algorithm should be terminated after finite number of steps.

 Effectiveness: An algorithm must be effective which means that all operations are
executable.

 Language Independent: The Algorithm designed must be language-independent, i.e. it


must be just plain instructions that can be implemented in any language, and yet the
output will be same, as expected.

Write an algorithm to check whether a given number is prime or not.

Step 1: Start
Step 2: Read number n

Step 3: Set factors=0

Step 4: For i=1 to n

Step 5: If n mod 1==0 then

Step 6: Set factors ++ and break

Step 7: Loop

Step 8: If factors ==2 then print 'The given number is prime'

else

print 'The given number is not prime'

Step 9: Stop

Write a C program to find whether a given number is prime or not.

#include<stdio.h>
#include<conio.h>
void main()
{
int n, i, factors=0;
printf("enter n value\n");
scanf("%d", &n);
for(i=1;i<=n;i++)
{
if(n%i==0)
{
factors++;
}
}
if(factors==2)
{
printf("Given number is prime\n");
}
else
{
printf("Given number is not prime\n");
}
getch();
}
Output: enter n value
7

Given number is prime

Write an algorithm to find the maximum and minimum number of array elements.

Step 1: Start

Step 2: Input the array size and elements.

Step 3: Initialize min = max = a[0]

Step 4: Repeat from i = 1 to n

Step 5: if(a[i] > max) then update max = a[i] , otherwise

Step 6: if(a[i] < min) then update min = a[i]

Step 7: Print min and max.

Step 8: Stop

Write a c program to find the maximum and minimum number of array elements.

#include<stdio.h>
int main()
{
int a[100], size, i, max, min;
printf("Enter size of the array\n");
scanf("%d", &size);
printf("Enter %d elements into array\n", size);
for(i=0; i<size; i++)
{
scanf("%d", &a[i]);
}
max=a[0];
min=a[0];

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


{
if(a[i]>max)
{
max=a[i];
}
if(a[i]<min)
{
min=a[i];
}
}
printf("maximum element=%d\n", max);
printf("Minimum element=%d", min);
return 0;
}
Output: Enter size of the array
5

Enter 5 elements into array

maximum element=9

Minimum element=0

Write an algorithm to find roots of quadratic equation by considering all cases.

Step 1: start

Step 2: read a, b, c values and declare r1, r2 and D

Step 3: calculate D=b*b-4*a*c

Step 4: if D=0, goto step 5 else goto step 9

Step 5: print roots are equal

Step 6: calculate r1=b/2*a

Step 7: calculate r2=b/2*a

Step 8: display roots r1 and r2 then stop


Step 9: if d>0 then goto step 11 else goto step 14

Step 10 display roots are distinct and real

Step 11: calculate r1=(-b+sqrt*D)/2*a

Step 12: calculate r2=(-b-sqrt*D)/2*a

Step 13: display roots r1 and r2 then stop

Step 14: else roots are imaginary

Step 15: stop

Write c program to find roots of quadratic equation by considering all cases.

#include<stdio.h>
#include<conio.h>
#include<math.h>
void main()
{
float a, b, c, r1, r2, D;
printf("enter a, b, c values\n");
scanf("%f%f%f", &a, &b, &c);
D=b*b-4*a*c;
if(D==0)
{
r1=r2=b/(2*a);
printf("roots are real and equal\n");
printf("root1=%f\n", r1);
printf("root2=%f\n", r2);

}
else if(D>0)
{
printf("Roots are real and unequal\n");
r1=(-b+sqrt(D))/(2*a);
r2=(-b-sqrt(D))/(2*a);
printf("root1=%f\n", r1);
printf("root2=%f\n", r2);
}
else
{
printf("roots are _Imaginary\n");
}
getch();
}
Output 1: enter a, b, c values
1
4
2
Roots are real and unequal
root1=-0.585786
root2=-3.414214
Output 2: enter a, b, c values
4
4
1
roots are real and equal
root1=0.500000
root2=0.500000
Output 3: enter a, b, c values
4
2
3
roots are _Imaginary
Draw a flowchart for quadratic equation for all cases
Basic searching in an array of elements (linear and binary search techniques)

Searching

Searching is a technique of finding an element from the given data list or set of the elements like
an array, lists or trees.

Or

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.

Methods of searching

 Searching is a technique to find out on element in a sorted or unsorted list.


 For example, consider an array of 5 elements
 These data elements are stored in successive memory locations.
 We need to search an element from the given array.
 In the searching operations, assume a particular element n is to be searched.
 The element n is compared with all the elements in a list starting from the first element to
last element.
 The process of searching is continued till the element is found or list is completely
exhausted.
 When the exact match is found then the search process is terminated.
 In case no element found in the given array, the process of searching should be stopped.

State the need of searching

Searching is one of the computer science algorithms. We know that modern computers store a
lot of information. To read this information proficiently, we need very efficient searching
algorithms.

There are certain ways of organizing data that improves the searching process. That means If we
keep the data in proper order it is easy to search the required elements. Sorting is one of the
techniques for making the elements order.

Computer systems are often needed to store large amounts of data from which individual record
are to be retrieved according to some search operation. Information retrieval is an important
application of computer.

Many of our day to day activity like finding the telephone listing with name as a key values, list
all the transactions related to account number and so on involves searching.
Example, we go to an ATM machine to withdraw money. Then we need to swipe card and enter
password then information comes up. There might be hundreds of millions of clients in particular
bank. It is because of very fast search algorithms that this works.

Types of searching

there are three basic searching techniques.

1. Linear search or sequential search


2. Binary search
3. Hash searching

Linear search or sequential search

 It is the simplest method of searching the element to be found is searched sequentially in


this list.
 That means its check every one element in the given array list.
 It can be used on a sorted or an unsorted array list.

Method/Implementation of linear search

The simplest known technique of searching is the linear search algorithm which is also known as
sequential search.

 Linear search does not expect specific ordering of the data. In fact the data is arranged in
the list. At every iteration the record will be compared with the help of the key.
 In this case sometimes all the elements get compared with the key value. All though this
is an simple searching technique.
 Some unnecessary comparisons has to be performed. This method does not give the
satisfactory solution for the system for large number of elements.
 First initialize the key element i.e. the element to be searched in the list.
 Compare key element with 0th index element. If match is found then search is successful.
 If match is found then key element is compared with the next element.
 Repeat the procedure till (n-1)th comparisons.
 After (n-1)th comparison, if match is not found then search is unsuccessful.
Example:
Algorithm for linear search

Step 1; start

Step 2: Accept n values from the user

Step 3: repeat for i=0 to n by 1

If a[i] = search element then

Set found=1

Step 4: write “item found at index or location

Step 5: break; end if statement, end for loop

Step 6: if a[i]! =search element

Set found=0

Step 7: write “item not found”

Step 8: stop.

Complexity of sequential/linear search

Time Complexity
Time Complexity of an algorithm is the representation of the amount of time required by the
algorithm to execute to completion. Time requirements can be denoted or defined as a numerical
function
The time complexity of algorithms is most commonly expressed using the big O notation. It's an
asymptotic notation to represent the time complexity(O(n).
Best Case: Record found at position 1. Hence only 1 comparison is performed. Thus the best
case time complexity is O(1).

Worst Case: Record is not found in the table, n comparisons are performed. Hence, the worst-
case time complexity is O(n).

Average Case: If the record is found somewhere in the serach table, on an average, the number
of comparision will be (n+1)/2.

Space Complexity of Linear Search: O(1)

Space Complexity
Space complexity is an amount of memory used by the algorithm, to execute it completely and
produce the result.
Similar to time complexity, space complexity is often expressed asymptotically in big O
notation, such as O(n) etc., where n is a characteristic of the input influencing space complexity.

Advantages:

It is a very simple method.

It does not require any additional data structure.

Also, it does not require any additional data structure.

Disadvantages:

It is very inefficient since its time complexity is O(n). If n is very large, this method is very slow.

Program: Linear or sequential search


#include<stdio.h>
#include<conio.h>
void main()
{
int list[20],size,i,sElement,found;
printf("Enter size of the list: ");
scanf("%d",&size);
printf("Enter any %d integer values: ",size);
for(i = 0; i < size; i++)
scanf("%d",&list[i]);
printf("Enter the element to be Search: ");
scanf("%d",&sElement);
// Linear Search Logic
for(i = 0; i < size; i++)
{
if(sElement == list[i])
{
printf("\nElement is found at index:%d", i);
printf("\nElement is found at position:%d ", i+1);
found=1;
break;
}
}
if(!found)
//if(i == size)
printf("Given element is not found in the list!!!");
getch();
}Output 1: Enter size of the list: 5

Enter any 5 integer values: 12


22
32
42
52
Enter the element to be Search: 42
Element is found at 3 index
Output 2: Enter size of the list: 5
Enter any 5 integer values: 12
22
32
42
52
Enter the element to be Search: 30
Given element is not found in the list!!
Binary search

 It is an algorithm for locating the position of an element in a sorted list.


 Binary search is faster method as compared to linear search.
 It inspects the middle element of the sorted list: if equal to the key value, then the
position has been found. Otherwise, the upper half or lower half is chosen for further
searching based on whether the key value is greater than or less than the middle element.

Method of Binary Search


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 cannot be used for a list of elements arranged in random order

 Binary search is a searching algorithm that works efficiently with a sorted list.
 In this method, we make a comparison between key and the middle element of the array.
 Since the array is sorted, this comparisons results either in a match between key and the
middle element of array or identifying the left half or the right half of the array.
 If the key element not matches with the middle position element then the same procedure
is repeated on the half or the half in which the described element is likely to be present.

Example:
Algorithm for Binary Search
Step 1: start
Step 2: accept n values
Step 3: initialize first=0, last=size-1;
Step 4: repeat step 5 and 6 while(first<=last)
Step 5: set mid=(first+last)/2
Step 6: if list[mid]==sElement then
Mid=position and print position of the element
Found=1,
Goto 8 step if list[mid]>sElement then
Set fast=mid-1
Else
Set fast=mid+1,[end of if], [end of forloop]
Step 7: if (!found) then
Print sElement not found
End of if
Step 8: Stop

Complexity of Binary Search


o Best Case Complexity - In Binary search, best case occurs when the element to search is
found in first comparison, i.e., when the first middle element itself is the element to be
searched. The best-case time complexity of Binary search is O(1).
o Average Case Complexity - The average case time complexity of Binary search
is O(logn).
o Worst Case Complexity - In Binary search, the worst case occurs, when we have to
keep reducing the search space till it has only one element. The worst-case time
complexity of Binary search is O(logn).

o The space complexity of binary search is O(1).

Program for Binary Search


#include<stdio.h>
#include<conio.h>
void main()
{
int first, last, middle, size, i,found, sElement, list[100];
//clrscr();
printf("Enter the size of the list: ");
scanf("%d",&size);
printf("Enter %d integer values in Assending order\n", size);
for (i = 0; i < size; i++)
{ scanf("%d",&list[i]);

} printf("Enter value to be search: ");


scanf("%d", &sElement);
first = 0;
last = size - 1;
middle = (first+last)/2;

while (first <= last)


{
if (list[middle] < sElement)
first = middle + 1;
else if (list[middle] == sElement) {
printf("Element found at index %d.\n",middle);
found=1;
break;
} else
last = middle - 1;
middle = (first + last)/2;
}
if(!found) //if (first > last)
printf("Element Not found in the list.");
getch();
}
Output 1:
Enter the size of the list: 5
Enter 5 integer values in Assending order
12
22
32
44
55
Enter value to be search: 32
Element found at index 2.
Enter the size of the list: 5
Enter 5 integer values in Assending order
12
22
32
44
55
Enter value to be search: 67
Element Not found in the list.

Comparisons between Linear/sequential search and Binary search


Linear/sequential search Binary search
 The elements need not be in order  Elements must be in order
 Suitable for few number of elements
 Efficient for large number of elements
and inefficient for large number of
when compared with linear search.
elements
 Search starts from first element and
 Search is not sequential
continues searching all the elements
sequentially until list is exhausted or
required item is found.
 Straight forward algorithm and
 Not suitable to implement with linked
implementation is easy both with arrays
lists.
and linked lists.
Basic algorithms to sort array of elements (Bubble, Insertion and Selection sort algorithms)

Introduction

A sorting algorithm is defined as an algorithm that puts the elements of a list in a certain order.
i.e. the purpose of sorting make the files or records easier to handle. By sorting data, it is easier
to search through it quickly and easily. The simplest example of sorting is a dictionary. Before
the era of the Internet, when you wanted to look up a word in a dictionary, you would do so in
alphabetical order. This made it easy.

Define sorting

Sorting means arranging an elements of an array either in ascending or descending order. or

A Sorting Algorithm is used to rearrange a given array or list elements according to a


comparison operator on the elements. The comparison operator is used to decide the new order
of element in the respective data structure.

There are two different categories in sorting:

 Internal sorting: If the input data is such that it can be adjusted in the main memory at
once, it is called internal sorting.

 External sorting: If the input data is such that it cannot be adjusted in the memory
entirely at once, it needs to be stored in a hard disk, floppy disk, or any other storage
device. This is called external sorting.

Need of sorting

 The main purpose of sorting information is to optimize its usefulness for specific data
related tasks.
 Arranging of data or information in a computer is one of the basic functions.
 To keep data values into an order.
 Finding a particular record in a list becomes easy if the records are in order.
 To insert or replace a data value in a particular location happens in less time if such a list
of data is in order. i.e. whatever operation can be made possible in less time if data of
such a list are in order.

Methods of sorting

Various types of sorting are available, but we mainly use the following

 Bubble sort
 Selection sort
 Insertion sort
 Quick sort
 Merge sort
 Radix sort
 Heap sort
 Shell sort
 Topological sort

Bubble sort

Bubble sort is a simple sorting algorithm. It works by repeatedly stepping through the list
to be sorted, this sorting algorithm is comparison-based algorithm in which each pair of adjacent
elements is compared and the elements are swapped if they are not in order, Which indicates that
the list is sorted. The algorithm gets its name from the way smaller elements “bubble” to the top
of the list.

This algorithm is not suitable for large data sets as its average and worst case complexity are of
Ο(n2) where n is the number of items.

Implementation :

Let the elements of array are -

First Pass/First Iteration

Sorting will start from the initial two elements. Let compare them to check which is greater.

Here, 32 is greater than 13 (32 > 13), so it is already sorted. Now, compare 32 with 26.

Here, 26 is smaller than 36. So, swapping is required. After swapping new array will look like -

Now, compare 32 and 35.


Here, 35 is greater than 32. So, there is no swapping required as they are already sorted.

Now, the comparison will be in between 35 and 10.

Here, 10 is smaller than 35 that are not sorted. So, swapping is required. Now, we reach at the
end of the array. After first pass, the array will be -

Now, move to the second iteration.


Second Pass/Second Iteration

The same process will be followed for second iteration.

Here, 10 is smaller than 32. So, swapping is required. After swapping, the array will be -

Now, move to the third iteration.


Third Pass/Third Iteration

The same process will be followed for third iteration.


Here, 10 is smaller than 26. So, swapping is required. After swapping, the array will be -

Now, move to the fourth iteration.

Fourth pass/Fourth Iteration

Similarly, after the fourth iteration, the array will be -

Hence, there is no swapping required, so the array is completely sorted.

Bubble sort: Algorithm

Step 1: Accept N number

Step 2: Repeat step 3 for i=0 to n-1 by 1

Step 3: repeat for j=0 to n-i-1 by 1

If a[j]> [j+1], then

Set temp = a[j]

A[j] = a[i]

A[i] = temp;

[end of if]
[end of step 3 loop]

[end of step 2 loop]

Step 4: Print sorted array is; a

Step 5: stop.

Time Complexity

 Bubble sort is data sensitive, if there are “n” number of elements in an array then (n-1) th
comparisons are required.
 The worst case arises when the given array is sorted in reverse order
 In this case all the iterations required will be: (n-1)+(n-2)+(n-3)+…..+3+2+1=n(n-1)/2
 Worst case complexity =O(n2)
 Average case complexity =O(n2)
 Best case complexity =O(n2)

or

Complexity Analysis of Bubble Sort

In Bubble Sort, n-1 comparisons will be done in the 1st pass, n-2 in 2nd pass, n-3 in 3rd pass and
so on. So the total number of comparisons will be,

(n-1) + (n-2) + (n-3) + ..... + 3 + 2 + 1


Sum = n(n-1)/2
i.e O(n2)
Hence the time complexity of Bubble Sort is O(n2).

The main advantage of Bubble Sort is the simplicity of the algorithm.

The space complexity for Bubble Sort is O(1), because only a single additional memory space is
required i.e. for temp variable.

Also, the best case time complexity will be O(n), it is when the list is already sorted.

Following are the Time and Space complexity for the Bubble Sort algorithm.

 Worst Case Time Complexity [ Big-O ]: O(n2)


 Best Case Time Complexity [Big-omega]: O(n)
 Average Time Complexity [Big-theta]: O(n2)
 Space Complexity: O(1)
Bubble sort: Program
Write a simple program for the list of numbers in ascending order using Bubble Sort
#include<stdio.h>
#include<conio.h>
void main()
{
int a[20],i,n,j,temp;
printf("\n Enter the no of element to be sorted:");
scanf("%d",&n);
printf("\n Enter %d elements:",n);
for(i=0;i<n;i++)
scanf("%d",&a[i]);

for(i=0;i<n-1;i++)
{
for(j=0;j<n-i-1;j++)
{
if(a[j]>a[j+1])
{
temp=a[j];
a[j]=a[j+1];
a[j+1]=temp;
}
}
}
printf("\n The sorted array is:\n");
for(i=0;i<n;i++)
{
printf("%d",a[i]);
}
getch();
}
Output:
Enter the no of element to be sorted:5

Enter 5 elements:5
7
2
9
0

The sorted array is:


02579
Write a simple program for the list of numbers in ascending order using Bubble Sort (usin
g functions)

#include<stdio.h>
#include<conio.h>
void Bubblesort(int[],int);
void main()
{
int a[20],i,n;
clrscr();
printf("\n Enter the no of element to be sorted:");
scanf("%d",&n);
printf("\n Enter %d elements:",n);
for(i=0;i<n;i++)
scanf("%d",&a[i]);
Bubblesort(a,n);
printf("\n The sorted array is:\n");
for(i=0;i<n;i++)
printf("%4d",a[i]);
getch();
}
void Bubblesort(int x[],int n)
{
int temp,i,j;
for(i=0;i<n-1;i++)
{
for(j=0;j<n-i-1;j++)
{
if(x[j]>x[j+1])
{
temp=x[j];
x[j]=x[j+1];
x[j+1]=temp;
}
}
}
}
Output: Enter the no of element to be sorted:7

Enter 7 elements:12
34
3
5
8
43
24

The sorted array is:


3 5 8 12 24 34 43

Method of Selection sort

The selection sort works by selecting the smallest unsorted item remaining in the list, and then
swaps it with the item in the next position to be filled.

 This is the easiest method of sorting.


 The sort the data in ascending order, the 0th element is compared will all other elements.
If the 0 th element is found to be greater than the compared element then they are
interchanged.
 After the first iteration, the smallest element is placed at the 0 th position.
 The selection sort is nearly the same as exchange sort. It is also known as push-down
sort.
The procedure of selection sort is as follows:

 In the first iteration 0 th element is compared with 1st element, if 0 th element is greater
than they are interchanged.
 If 0 th element is not greater than 1st element then they are not interchanged.
 The process is repeated till the 0 th element is compared with rest of the elements.
 At the end of first iteration 0 th element holds the smallest number.
 Second iteration starts with the 1st element.
 The process of comparison and swapping is repeated.
 After(n-1) interaction, the array is sorted.

To understand the working of the Selection sort algorithm, let's take an unsorted array. It will be
easier to understand the Selection sort via an example.

Let the elements of array are -

Now, for the first position in the sorted array, the entire array is to be scanned sequentially.

At present, 12 is stored at the first position, after searching the entire array, it is found that 8 is
the smallest value.

So, swap 12 with 8. After the first iteration, 8 will appear at the first position in the sorted array

For the second position, where 29 is stored presently, we again sequentially scan the rest of the
items of unsorted array. After scanning, we find that 12 is the second lowest element in the array
that should be appeared at second position.

Now, swap 29 with 12. After the second iteration, 12 will appear at the second position in the
sorted array. So, after two iterations, the two smallest values are placed at the beginning in a
sorted way.

The same process is applied to the rest of the array elements. Now, we are showing a pictorial
representation of the entire sorting process.
Now, the array is completely sorted.

Algorithm for selection sort

Step 1: start

Step 2: Repeat step 4 for i=0 to n-1 by 1

Step 3: set min = a[i]

Step 4: repeat step for j=i+1 to n by 1

If a[j]<min, then min=j, end if and for loop

Set temp = a[i]

A[i] = a[min]

A[min] = temp

End of step 2 loop


Step 5: stop

Selection sort complexity

1. Time Complexity

Case Time Complexity

Best Case O(n2)

Average Case O(n2)

Worst Case O(n2)

o Best Case Complexity - It occurs when there is no sorting required, i.e. the array is
already sorted. The best-case time complexity of selection sort is O(n2).

o Average Case Complexity - It occurs when the array elements are in jumbled order that
is not properly ascending and not properly descending. The average case time complexity
of selection sort is O(n2).

o Worst Case Complexity - It occurs when the array elements are required to be sorted in
reverse order. That means suppose you have to sort the array elements in ascending order,
but its elements are in descending order. The worst-case time complexity of selection sort
is O(n2).

2. Space Complexity

Space Complexity O(1)

Stable YES

o The space complexity of selection sort is O(1). It is because, in selection sort, an extra
variable is required for swapping.

Program for selection sort

//selection sort

#include<stdio.h>

#include<conio.h>

void main()

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

printf("enter array size");

scanf("%d", &n);

printf("elements");

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

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

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

min=i;

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

if(a[j]<a[min])

min=j;

temp=a[i];

a[i]=a[min];

a[min]=temp;

printf("sorted list is");

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

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

getch();

Output: enter array size5

elements6

sorted list is23456

(Or) Program for selection sort by using functions

#include<stdio.h>
#include<conio.h>
void Selection_sort(int[],int);
void main()
{
int a[20],i,n;
clrscr();
printf("\n Enter the no of element to be sorted:");
scanf("%d",&n);
printf("\n Enter %d elements:",n);
for(i=0;i<n;i++)
scanf("%d",&a[i]);
Selection_sort(a,n);
printf("\n The sorted array is:\n");
for(i=0;i<n;i++)
printf("%4d",a[i]);
getch();
}
void Selection_sort(int x[],int n)
{
int min,swap,i,j;
for(i=0;i<n-1;i++)

{min=i;
{

for(j=i+1;j<n;j++)
{
if(x[min]>x[j])
min=j;
}
if(min!=i)
{
swap=x[i];
x[i]=x[min];
x[min]=swap;
}
}
}
}
Output:
Enter the no of element to be sorted:6
Enter 6 elements:78
90
43
25
12
35
The sorted array is:
12 25 35 43 78 90
Method of Insertion sort

The insertion sort algorithm selects each element and inserts it at its proper position in the
earlier sorted sub list.

Suppose an array a with n elements a[1], a[2],….a[n] is in memory. The insertion sort algorithm
scans a from a[1] to a[n], inserting each element a[n] into its proper position in the previously
sorted subarray a[1],a[2],….a[n-1].

Pass 1: a[1] by itself is trivially sorted

Pass 2: a[2] is inserted either before or after a[1] so that: a[1], a[2] is sorted.

Pass 3: a[3] is inserted into its proper place in a[1], a[2], that is before a[1], between a[1] and
a[2], or after a[2], so that: a[1], a[2], a[3] is sorted.

Pass 4: a[4] is inserted into its proper place in a910, a[2], a[3] so that: a[1], a[2], a[3] and a[4] is
sorted.

Pass N: a[n] is inserted into its proper place in a[1], a[2]…..a[n] so that: a[1], a[2], a[3] and a[4]
is sorted.
Algorithm for Insertion sort

Step 1: start

Step 2:Accept n number into array a

Step 3: a[0] is considered a sorted file of one element

Step 4: set i=1

Step 5: for i=1 to (n-1)

Step 6: set key = a[i];

Step 7: set j=i-1;

Step 8: while key<a[j] && (j>=0) perform the following steps

Set a[j+1]=a[j]

End of while loop

Step 9: assign the value of key to a[j+1]

End of for loop

Step 10: exit

Insertion sort complexity

To sort an unsorted list with 'n' number of elements, we need to make (1+2+3+......+n-1) = (n
(n-1))/2 number of comparisions in the worst case. If the list is already sorted then it
requires 'n' number of comparisions.

1. Time Complexity

Case Time Complexity

Best Case O(n)

Average Case O(n2)

Worst Case O(n2)

o Best Case Complexity - It occurs when there is no sorting required, i.e. the array is
already sorted. The best-case time complexity of insertion sort is O(n).
o Average Case Complexity - It occurs when the array elements are in jumbled order that is
not properly ascending and not properly descending. The average case time complexity
of insertion sort is O(n2).

o Worst Case Complexity - It occurs when the array elements are required to be sorted in
reverse order. That means suppose you have to sort the array elements in ascending order,
but its elements are in descending order. The worst-case time complexity of insertion sort
is O(n2).

2. Space Complexity

Space Complexity O(1)

Stable YES

o The space complexity of insertion sort is O(1). It is because, in insertion sort, an extra
variable is required for swapping.

Program: Write a program to implement insertion sort in c language

//Insertion sort

#include<stdio.h>

#include<conio.h>

void main()

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

printf("enter array size");

scanf("%d", &n);

printf("elements");

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

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

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

key=a[i];

j=i-1;

while(j>=0 && a[j]>key)

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

j=j-1;

a[j+1]=key;

printf("sorted list is");

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

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

getch();

Output: enter array size5

elements3

sorted list is02358


(or) Program: Write a program to implement insertion sort by using functions

#include<stdio.h>
#include<conio.h>
void Insertionsort(int[],int);
void main()
{
int a[20],i,n;
clrscr();
printf("\n Enter the no of element to be sorted:");
scanf("%d",&n);
printf("\n Enter %d elements:",n);
for(i=0;i<n;i++)
scanf("%d",&a[i]);
Insertionsort(a,n);
printf("\n The sorted array is:\n");
for(i=0;i<n;i++)
printf("%4d",a[i]);
getch();
}
void Insertionsort(int x[],int n)
{
int i,j,key;
for(j=1;j<n;j++)
{
key=x[j];
i=j-1;
while((i>-1)&&(x[i]>key))
{
x[i+1]=x[i];
i=i-1;
}
x[i+1]=key;
}
}

Output: Enter the no of element to be sorted:5


Enter 5 elements:21
4
0
47
38

The sorted array is:


0 4 21 38 47
Unit 5 Important Questions

1.Write an algorithm for linear search, explain with an illustration (method) and example
program.(15)
2.Write an algorithm for binary search, explain with an illustration (method) and example
program.(15)
3.a. Write an algorithm for bubble sort and explain its implementation.(8M)

b. Write an algorithm for selection sort and explain its implementation.(7m)

4.Write a c program for bubble sort and selection sort.(10)

5.a. What do you mean by sorting? Mention the different types of sorting.(5M)
b. Apply linear search on {22,11,66,44,99,55,88}.(5M)
c. Apply bubble sort on the above given data. (5M)

6.a. How linear search is different from binary search (difference)?(3M)

b. Mention the time complexity of linear search and binary search algorithms.(4M)

7.Explain Algorithm and implementation of Insertion sort with example program.(15M)

8.Write an algorithm to find prime number and quadratic equations.(15M)

9.Write a C program for finding prime number and finding roots of quadratic equation.(7+8M)

10.Write an algorithm and program for finding the minimum and maximum number in Given
array elements.(15M)

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy