Pec Cse Pps Course File (5units)
Pec Cse Pps Course File (5units)
Mr. B. NARESH
Assistant Professor
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.
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:
REFERENCE BOOKS:
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
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
(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
(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
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.
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.
Mobile OS
Mobile operating systems are those OS which is especially that are designed to power
smartphones, tablets, and wearables devices.
Computer Languages
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.
Machine Language
The only language which the computer itself can understand is the machine language.
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:
Disadvantages:
1) Machine dependent
3) Difficult to understand
2 =0010
+3 = 0 0 1 1
5 =0101
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:
3) High efficiency
2) Requires translator
5) Less efficient
Example:
2 PUSH2,A
3 PUSH3,B
+ ADDA,B
5 PRINTC
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.
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
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
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…
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.
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.
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.
• This is the process of converting the high level language program to Machine level
Language (Equivalent machine instruction).
• Otherwise the program will be converted into an object file (.obj file) as a result of the
compilation
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.
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 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 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
Ex: 27FB16
Conversion Types
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
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 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.
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
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
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.
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.
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.
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:
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.
(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.
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:
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
Outputs: An algorithm must specify the quantities which are to be displayed or printed.
Effectiveness: An algorithm must be effective which means that all operations are
executable.
To solve a problem on a computer. We need to identify the inputs and outputs to state the
problem in a precise manner,
Advantages of Algorithms:
It is easy to understand.
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:
Ans:
Step 1: Start
Step 5: Stop
Step 5: Stop
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 5: Stop
Ans:
Step 1: Start
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 6: Stop
Ans:
Step 1: Start
Step 7: Stop
Ans:
Step 1: Start
Step 3: sum = 0
Step 4: I = 1
Step 6: I = I +1
Step 7: if I < n
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 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
Start Stop
2. Parallelogram
4. Diamond
If A > B
5. Arrows
Advantages of Flowchart
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.
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
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
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
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
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.
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
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.
What is C?
C is a computer programming language used to design computer software and applications.
Why do we use C?
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.
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.
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.
The open brace indicates the beginning of the block which belongs to the main method. In C
program, every block begins with a '{' symbol.
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.
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.
The close brace indicates the end of the block which belongs to the main method. In C program
every block ends with a '}' symbol.
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.
Digits - 0, 1, 2, 3, 4, 5, 6, 7, 8, 9
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.
#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.
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
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];
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.
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...
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 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
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’
‘,’
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.
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
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...
OR
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...
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
5. Assignment Operators
6. Bitwise Operators
7. Conditional Operator
8. Special Operators
+ Addition 10 + 5 = 15
- Subtraction
ubtraction 10 - 5 = 5
Operator Meaning Example
* Multiplication 10 * 5 = 50
/ Division 10 / 5 = 2
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.
+= Add both left and right-hand side values and store the A += 10
result into left-hand side variable ⇒ A = A+10
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.
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.
< 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
&& Logical AND - Returns TRUE if all conditions 10 < 5 && 12 > 10 is
are TRUE otherwise returns FALSE FALSE
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.
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).
& 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 XOR is 0 if all the bits are same A^B
otherwise it is 1 ⇒ 13 (01101)
Operator Meaning Example
<< 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)
#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);
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.
Example
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
This operator is used to separate variables while they are declaring, separate the expressions in
function calls, etc.
Ex: int a, b, c;
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
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.
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.
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.
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.
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...
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 (;).
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.
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:
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.
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.
The character data type is a set of characters enclosed in single quotations. The following table
provides complete details about the character data type.
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.
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 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
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' ;
#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;
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.
Keyword auto
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
Keyword Extern
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
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
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.
Console input/output functions to receive input from keyboard and write out in monitor screen.
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);
#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.
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...
#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.
#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
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 :
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
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);
#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);
#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
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.
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.
A call to this statement can be replaced and is identical to the call to fprintf() using stdout as the
first argument.
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.
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.
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
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.
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;
}
#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;
#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
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
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:
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.
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.
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.
#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.
#include<stdio.h>
#include<conio.h>
void main(){
int n ;
clrscr() ;
printf("Even numbers upto 10\n");
getch() ;
}
Output
Even numbers upto 10
0 2 4 6 8 10
Every for statement must be provided with initialization, condition, and modification
In for statement, the condition may be a direct integer value, a variable or a condition.
While Statement
The while statement is also known as Entry control looping statement.. The while statement
has the following syntax...
#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
The value of the variable used in condition must be modified according to the
requirement inside the while block.
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.
#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.
The value of the variable used in the condition must be modified according to the
requirement inside the do block.
Nesting of loops
C programming allows to use one loop inside another loop. The following section shows a few
examples to illustrate the concept.
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
do
{
statement n;
do
{
statement n;
}
while(test condition);
}
while(test expression);
Example
#include <stdio.h>
void main()
{
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.
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);
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;
#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.
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 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.
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
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
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) what is number system and explain its conversion techniques with examples
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
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
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:
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.
4. A subscript is a number used to refer to individual array element. It is also called an index.
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.
Syntax for creating an array without size(unsized) and with initial values
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 ;
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.
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
will assign the value 1 to x[0], the value 4 to x[1] and 9 to x[2].
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
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.
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.
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
causes a syntax error because there are six initializers and only five array elements.
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]);
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 -
#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
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.
Access non allocated location of memory: The program can access some piece of memory
which is owned by it.
// Program to demonstrate
#include <stdio.h>
int main()
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.
Implementation:-
#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]) ;
}
23
45
56
43
23 43 45 56
56 45 43 23
#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 element 1 : 5
Enter element 2 : 6
Enter element 3 : 5
Enter element 4 : 6
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.
Output : 20
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
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.
We use the following general syntax for declaring a two dimensional array...
or
datatype array_name[row_size][column_size];
Example
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.
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:
Example
Example
{1, 2, 3},
{4, 5, 6}
We use the following general syntax to access the individual elements of a two-dimensional
array...
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
}}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...
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.
We use two dimensional arrays to create matrix. We can perform various operations on matrices
using two dimensional arrays.
1. Linear Search
2. Binary Search
1. Insertion Sort
2. Bubble Sort
3. Selection Sort
4. Quick Sort
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"
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.
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.
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[ ] = {'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.
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.
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.
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
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.
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()
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.
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()
strlwr(name);
printf("%s", name);
return 0;
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:
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()
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.
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;
The c library supports a large number of string functions for string manipulations as given below.
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())
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'.
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;
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
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
The structure variables can also be initialized at the time of declaring the structure variables.
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;
……
}
#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};
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
(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.
#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
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 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.
Array traversal and searching is easy and Structure traversal and searching is
fast. complex and slow.
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()
scanf("%d", &u1.srno);
printf("student
f("student roll number is:%d
is:%d\n", u1.srno);
scanf("%s", u1.sname);
scanf("%f", &u1.smarks);
Output:
60
pallavi
76.56
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.
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.
To assign address to a pointer variable we use assignment operator with the following syntax...
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
In the above example statement %u is used to display address of marks variable. Address of any
memory location is unsigned integer value.
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) ;
}
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:
#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.
#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
#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.
#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:
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
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
For example,
int *p[5];
It represents an array of pointers that can hold 5 integer element addresses.
Initialization
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
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;
// Initialization
ob2.prev_link = NULL;
ob2.next_link = NULL;
ob2.data = 20;
// 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;
#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.
#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
b) Discuss pointers to arrays and structures with its syntax and example
b)Using two dimensional array, write a C program to find the transpose of a 2×2 matrix.(8M)
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
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
Binary File
Text File
It contains alphabets and numbers which are easily understood by human beings.
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
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.
For example, an MP3 file can be produced by a sound recorder or audio editor, and it can
be played in a music player.
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,
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 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 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
or
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
“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.
“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.
“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.
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.
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.
Output
fscanf() - This function is used to read multiple datatype values from specified file which is
opened in reading mode.
#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.
Example: fgetw(fp);
#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");
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.
Example: fread(str,sizeof(char),5,fp);
#include<stdio.h>
#include<conio.h>
int main()
FILE *fp;
char *str;
clrscr();
fread(str,sizeof(char),2,fp);
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.
#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.
#include<stdio.h>
#include<conio.h>
int main()
FILE *fp;
clrscr();
fp = fopen("MySample.txt","w");
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.
#include<stdio.h>
#include<conio.h>
int main()
FILE *fp;
int i = 10;
clrscr();
fp = fopen("MySample.txt","w");
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.
#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.
#include<stdio.h>
#include<conio.h>
int main()
FILE *fp;
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.
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
int flushall(void);
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.
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)
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;
}
b) List and explain various file read/write functions available in C with examples.
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:
5. a) How can we determine whether a file is successfully opened or not using fopen()
function?
6. List and explain various commonly used pre-processing directives in C with an example
7. a)What is a file pointer? Explain the steps for sequential file operations.
9. Write a program to read a text file, convert all the lowercase characters into upper case
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.
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
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...
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.
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)
returnType functionName(parametersList/argruments_withdata_type);
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.
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.
returnType functionName(parametersList)
{
Function body
Return a+b;
ADVANTAGES OF 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:
#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
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
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
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
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
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.
#include<stdio.h>
void main()
printf("%d, %d",x,y);
Output 4, 1
#include<stdio.h>
void main()
int result=0;
result =array_sum(a,5);
int i, sum=0;
for(i=0;i<n;i++)
sum=sum+x[i];
return sum;
Output: sum=150
#include<stdio.h>
int sum=0;
float avg;
//sum=array_sum(a,5);
//printf("sum=%d", sum);
avg=array_sum(a,5);
printf("avg=%f", avg);
int i, sum=0;
float avg;
for(i=0;i<n;i++)
sum=sum+x[i];
avg=sum/n;
return avg;
Output: 30.000000
#include<stdio.h>
#include<conio.h>
void main(){
int a, b ;
a = 10 ;
b = 20 ;
getch() ;
int temp ;
temp = *p ;
*p = *q ;
*q = temp ;
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,
6. Using a recursive function takes more memory and time to execute as compared to its
non-recursive counterpart.
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
time.h Provides functions to perform operations on time and date time(), localtime()
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:
Program: Write a program for dynamic memory allocation by using malloc() function.
#include <stdio.h>
#include <stdlib.h>
int main ()
if (ptr != NULL)
return 0;
else
return 0;
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:
#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 {
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:
Program:
am: Write a program for dynamic memory allocation by using Realloc() function
#include <stdio.h>
#include <stdlib.h>
int main ()
size=3;
scanf("%d", &n);
scanf("%d", ptr+i);
free(ptr);
return 0;
else
return 0;
}Output:
free(ptr);
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
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
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)
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:
Characteristics of Algorithm
Outputs: An algorithm must specify the quantities which are to be displayed or printed.
Effectiveness: An algorithm must be effective which means that all operations are
executable.
Step 1: Start
Step 2: Read number n
Step 7: Loop
else
Step 9: Stop
#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
Write an algorithm to find the maximum and minimum number of array elements.
Step 1: Start
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];
maximum element=9
Minimum element=0
Step 1: start
#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 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
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
Set found=1
Set found=0
Step 8: stop.
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
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:
Disadvantages:
It is very inefficient since its time complexity is O(n). If n is very large, this method is very slow.
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
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
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 :
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 -
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 -
Here, 10 is smaller than 32. So, swapping is required. After swapping, the array will be -
A[j] = a[i]
A[i] = temp;
[end of if]
[end of step 3 loop]
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
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,
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.
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
#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 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.
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.
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.
Step 1: start
A[i] = a[min]
A[min] = temp
1. Time Complexity
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
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.
//selection sort
#include<stdio.h>
#include<conio.h>
void main()
{
int a[50], n, temp, i, min, j;
scanf("%d", &n);
printf("elements");
for(i=0;i<n;i++)
scanf("%d", &a[i]);
for(i=0;i<n-1;i++)
min=i;
if(a[j]<a[min])
min=j;
temp=a[i];
a[i]=a[min];
a[min]=temp;
{
printf("%d", a[i]);
getch();
elements6
#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 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
Set a[j+1]=a[j]
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
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
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.
//Insertion sort
#include<stdio.h>
#include<conio.h>
void main()
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;
a[j+1]=a[j];
j=j-1;
a[j+1]=key;
printf("%d", a[i]);
getch();
elements3
#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;
}
}
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)
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)
b. Mention the time complexity of linear search and binary search algorithms.(4M)
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)