Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 210

C – Programming with data structures

I B.Tech. EEE, CE, ME (R22)

JNTUHUCER, RAJANNA SIRCILLA

B.Naveen Kumar
M.Tech.
9959226736, naveen.ab85@gmail.com
I B.Tech EEE,CE,ME (R22) Unit - II C-Programming with Data Structures

C-Programming with Data Structures


I.B.Tech EEE,CE,ME, UCER
Unit – I
Introduction to Computer Systems
What is a Computer?
The computer is an electronic device which operates under the control of instructions stored in its
memory. A computer can take data from the user through input devices (Input), process the user
given data (Processing), produces the result to the user through output devices (Output)and
stores data (Information) for future use. A Computer can be defined as follows...

The Computer is an electronic device which operates under the control of instructions

stored in its memory and it takes the data from the user, a process that data gives the

result and stores the result for future use.

Naveen(jntr)
What does a computer consist of?
Every computer mainly consists of three things and those are...

1. Hardware
2. Software
3. User

Here the user interacts with the software, and the software makes the computer hardware parts
to work for the user.

What is Computer Hardware?


All physical components of the computer are called as computer hardware. A user can see, touch
and feel every hardware of the computer. All hardware components perform any task based on
the instructions given by the computer software.

The computer hardware is the physical part of a computer.

The computer hardware components are as follows...

1. Input Devices - These are the parts through which a user can give the data to the computer.
2. Output Devices - These are the physical components of a computer through which the computer
gives the result to the user.
3. Storage Devices - These are the physical components of a computer in which the data can be
stored.
4. Devices Drives - Using drives, user can read and write data on to the storage devices like CD,
floppy, etc.,
5. Cables - Various cables (Wires) are used to make connections in a computer

Prepared By B.Naveen Kumar (M.Tech.) JNTUH, Rajanna Siricilla. Page 1 of 210


I B.Tech EEE,CE,ME (R22) Unit - II C-Programming with Data Structures

6. Other Devices - Other than the above hardware components, a computer also contains
components like Motherboard, CPU (Processor), SMPS, Fans, etc.,

Input Devices
Computer input devices are the physical components of the computer which are used to give the
data given by the user to the computer. Using input devices the user can give the data to the
computer.

Example

Naveen(jntr)

Output Devices
Computer output devices are the physical components of the computer which are used to give
the computer result to the User. Using output devices, the user can see the computer-generated
result.

Example

Storage Devices
Computer storage devices are the physical components of the computer which are used to store
data internally or externally.

Prepared By B.Naveen Kumar (M.Tech.) JNTUH, Rajanna Siricilla. Page 2 of 210


I B.Tech EEE,CE,ME (R22) Unit - II C-Programming with Data Structures

Example

Device Drives
Computer Device drives are the physical components of the computer which are used to read and
write data on the storage devices.

Example

Naveen(jntr)
Computer Cables
In a Computer, various cables are used to make connections among the various hardware
components of the computer.

Example

Other Devices
Other devices of the computer are shown below...

Prepared By B.Naveen Kumar (M.Tech.) JNTUH, Rajanna Siricilla. Page 3 of 210


I B.Tech EEE,CE,ME (R22) Unit - II C-Programming with Data Structures

CPU (Processor)

SMPS

CPU Fan (Heat Sink)

Naveen(jntr)

Motherboard

How does Computer work


When a user wants to communicate with the computer, the user interacts with an application. The
application interacts with the operating system, and the operating system makes hardware
components to work according to the user given instructions. The hardware components send the
result back to the operating system, then the operating system forwards the same to the
application and the application shows the result to the user.

By using input devices, the user interacts with the application and the application uses output
devices to show the result. All input and output devices work according to the instructions given
by the operating system. The working process of a computer is shown in the following figure.

Prepared By B.Naveen Kumar (M.Tech.) JNTUH, Rajanna Siricilla. Page 4 of 210


I B.Tech EEE,CE,ME (R22) Unit - II C-Programming with Data Structures

Computing Environments

What is Computing Environment?

Naveen(jntr)
When we want to solve a problem using a computer, the computer makes use of various devices
which work together to solve that problem. There may be a various number of ways to solve a
problem. We use the various number of computer devices arranged in different ways to solve
different problems. The arrangement of computer devices to solve a problem is said to be a
computing environment. The formal definition of the computing environment is as follows.

Computing Environment is a collection of computers which are used to process and

exchange information to solve various types of computing problems.

Types of Computing Environments

The following are the various types of computing environments.

1. Personal Computing Environment


2. Time-Sharing Computing Environment
3. Client-Server Computing Environment
4. Distributed Computing Environment
5. Grid Computing Environment
6. Cluster Computing Environment

Personal Computing Environment

Personal computing is a stand-alone machine. In a personal computing environment, the

complete program resides on the stand-alone machine and executed from the same machine.

Laptops, mobile devices, printers, scanners and the computer systems we use at home, office are

the examples for the personal computing environment.

Prepared By B.Naveen Kumar (M.Tech.) JNTUH, Rajanna Siricilla. Page 5 of 210


I B.Tech EEE,CE,ME (R22) Unit - II C-Programming with Data Structures

Time-Sharing Computing Environment


The time-sharing computing environment is a stand-alone computer in which a single user can
perform multiple operations at a time by using a multitasking operating system. Here the
processor time is divided among different tasks and this is called “Time-sharing”. For example, a
user can listen to music while writing something in a text editor. Windows 95 and later versions of
Windows OS, iOS and Linux operating systems are the examples for this computing environment.

Naveen(jntr)

Client-Server Computing Environment


The client-server environment contains two machines (Client machine and Server machine). These
both machines will exchange the information through an application. Here Client is a normal
computer like PC, Tablet, Mobile, etc., and Server is a powerful computer which stores huge data
and manages the huge amount of file and emails, etc., In this environment, client requests for
data and server provides data to the client. In the client-server environment, the communication
between client and server is performed using HTTP (Hyper Text Transfer Protocol).

Prepared By B.Naveen Kumar (M.Tech.) JNTUH, Rajanna Siricilla. Page 6 of 210


I B.Tech EEE,CE,ME (R22) Unit - II C-Programming with Data Structures

Distributed Computing Environment


In the distributed computing environment, the complete functionality of the software is not on a
single computer but is distributed among multiple computers. Here we use a method of computer
processing in which different programs of an application run simultaneously on two or more
computers. These computers communicate with each other over a network to perform the
complete task. In a distributed computing environment, the data is distributed among different
systems and that data is logically related to each other.

Naveen(jntr)
Grid Computing Environment
Grid computing is a collection of computers from different locations. All these computers work for
a common problem. A grid can be described as a distributed collection of a large number of
computers working for a single application.

Cluster Computing Environment


Cluster computing is a collection of interconnected computers. These computers work together to
solve a single problem. In a cluster computing environment, a collection of systems work together
as a single system.

Computer Languages

What is Computer Language?


Generally, we use languages like English, Hindi, etc., to make communication between two
persons. That means when we want to make communication between two persons we need a
language through which persons can express their feelings. Similarly, when we want to make
communication between user and computer or between two or more computers we need a
language through which user can give information to the computer and vice versa. When a user
wants to give any instruction to the computer the user needs a specific language and that
language is known as a computer language.

The user interacts with the computer using programs and that programs are created using
computer programming languages like C, C++, Java, etc.,

Computer languages are the languages through which the user can communicate with the

computer by writing program instructions.

Prepared By B.Naveen Kumar (M.Tech.) JNTUH, Rajanna Siricilla. Page 7 of 210


I B.Tech EEE,CE,ME (R22) Unit - II C-Programming with Data Structures

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

Computer Languages Classification


Over the years, computer languages have been evolved from Low-Level to High-Level Languages.
In the earliest days of computers, only Binary Language was used to write programs. The
computer languages are classified as follows...

Naveen(jntr)
Low-Level Language (Machine Language)
Low-Level language is the only language which can be understood by the computer. Binary
Language is an example of a low-level language. Low-level language is also known as Machine
Language. The binary language contains only two symbols 1 & 0. All the instructions of binary
language are written in the form of binary numbers 1's & 0's. A computer can directly understand
the binary language. Machine language is also known as the Machine Code.

As the CPU directly understands the binary language instructions, it does not require any
translator. CPU directly starts executing the binary language instructions and takes very less time
to execute the instructions as it does not require any translation. Low-level language is considered
as the First Generation Language (1GL).

Advantages

 A computer can easily understand the low-level language.

 Low-level language instructions are executed directly without any translation.

 Low-level language instructions require very less time for their execution.

Disadvantages

 Low-level language instructions are very difficult to use and understand.

 Low-level language instructions are machine-dependent, that means a program written for a

particular machine does not execute on another machine.

 In low-level language, there is more chance for errors and it is very difficult to find errors, debug

and modify.

Prepared By B.Naveen Kumar (M.Tech.) JNTUH, Rajanna Siricilla. Page 8 of 210


I B.Tech EEE,CE,ME (R22) Unit - II C-Programming with Data Structures

Middle-Level Language (Assembly Language)

Middle-level language is a computer language in which the instructions are created using symbols

such as letters, digits and special characters. Assembly language is an example of middle-level

language. In assembly language, we use predefined words called mnemonics. Binary code

instructions in low-level language are replaced with mnemonics and operands in middle-level

language. But the computer cannot understand mnemonics, so we use a translator

called Assembler to translate mnemonics into binary language. Assembler is a translator which takes

assembly code as input and produces machine code as output. That means, the computer cannot

understand middle-level language, so it needs to be translated into a low-level language to make it

understandable by the computer. Assembler is used to translate middle-level language into low-level

language.

Advantages
Naveen(jntr)
 Writing instructions in a middle-level language is easier than writing instructions in a low-level

language.

 Middle-level language is more readable compared to low-level language.

 Easy to understand, find errors and modify.

Disadvantages

 Middle-level language is specific to a particular machine architecture, that means it is machine-

dependent.

 Middle-level language needs to be translated into low-level language.

 Middle-level language executes slower compared to low-level language.

High-Level Language
A high-level language is a computer language which can be understood by the users. The high-level
language is very similar to human languages and has a set of grammar rules that are used to make
instructions more easily. Every high-level language has a set of predefined words known as Keywords
and a set of rules known as Syntax to create instructions. The high-level language is easier to
understand for the users but the computer can not understand it. High-level language needs to be
converted into the low-level language to make it understandable by the computer. We
use Compiler or interpreter to convert high-level language to low-level language.

Languages like COBOL, FORTRAN, BASIC, C, C++, JAVA, etc., are examples of high-level languages. All
these programming languages use human-understandable language like English to write program
instructions. These instructions are converted to low-level language by the compiler so that it can be
understood by the computer.

Prepared By B.Naveen Kumar (M.Tech.) JNTUH, Rajanna Siricilla. Page 9 of 210


I B.Tech EEE,CE,ME (R22) Unit - II C-Programming with Data Structures

Advantages

 Writing instructions in a high-level language is easier.

 A high-level language is more readable and understandable.

 The programs created using high-level language runs on different machines with little change or no

change.

 Easy to understand, create programs, find errors and modify.

Disadvantages

 High-level language needs to be translated into low-level language.

 High-level language executes slower compared to middle and low-level languages.

Understanding Computer LanguagesNaveen(jntr)


The following figure provides a few key points related to computer languages.

From the above figure, we can observe the following key points...

 The programming languages like C, C++, Java, etc., are written in High-level language which is more
comfortable for the developers.
 A high-level language is closer to the users.
 Low-level language is closer to the computer. Computer hardware can understand only the low-level
language (Machine Language).
 The program written in the high-level language needs to be converted to low-level language to make
communication between the user and the computer.
 Middle-level language is not closer to both user and computer. We can consider it as a combination of
both high-level language and low-level language.

Prepared By B.Naveen Kumar (M.Tech.) JNTUH, Rajanna Siricilla. Page 10 of 210


I B.Tech EEE,CE,ME (R22) Unit - II C-Programming with Data Structures

Creating and Running C Program


Generally, the programs created using programming languages like C, C++, Java, etc., are written using
a high-level language like English. But, the computer cannot understand the high-level language. It can
understand only low-level language. So, the program written in the high-level language needs to be
converted into the low-level language to make it understandable for the computer.

This conversion is performed using either Interpreter or Compiler.

Popular programming languages like C, C++, Java, etc., use the compiler to convert high-level language
instructions into low-level language instructions. A compiler is a program that converts high-level
language instructions into low-level language instructions. Generally, the compiler performs two
things, first it verifies the program errors, if errors are found, it returns a list of errors otherwise it
converts the complete code into the 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…

Naveen(jntr)

Step 1: Creating a Source Code


Source code is a file with C programming instructions in a high-level language. To create source code,
we use any text editor to write the program instructions. The instructions written in the source code
must follow the C programming language rules. The following steps are used to create a source code
file in Windows OS…

 Click on the Start button

 Select Run

 Type cmd and press Enter

 Type cd c:\TC\bin in the command prompt and press Enter

 Type TC press Enter

 Click on File -> New in C Editor window

 Type the program

 Save it as FileName.c (Use shortcut key F2 to save)

Prepared By B.Naveen Kumar (M.Tech.) JNTUH, Rajanna Siricilla. Page 11 of 210


I B.Tech EEE,CE,ME (R22) Unit - II C-Programming with Data Structures

Step 2: Compile Source Code (Alt + F9)


The compilation is the process of converting high-level language instructions into low-level language
instructions. We use the shortcut key Alt + F9 to compile a C program in Turbo C.

The compilation is the process of converting high-level language instructions into low-level
language instructions.

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.

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


After completing compilation successfully, an executable file is created with a .exe extension. The
processor can understand this .exe file content so that it can perform the task specified in the source
file.

Naveen(jntr)
We use a shortcut key Ctrl + F9 to run a C program. Whenever we press Ctrl + F9, the .exe file is
submitted to the CPU. On receiving .exe file, CPU performs the task according to the instruction
written in the file. The result generated from the execution is placed in a window called User Screen.

Step 4: Check Result (Alt + F5)


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

Execution Process of a C Program


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

The file which contains c program instructions in a high-level language is said to be source code. Every
c program source file is saved with .c extension, for example, Sample.c.

Whenever we press Alt + F9 the source file is submitted to the compiler. Compiler checks for the
errors, if there are any errors, it returns a list of errors, otherwise generates object code in a file with
name Sample.obj and submit it to the linker. The linker combines the code from specified header file
into an object file and generates executable file as Sample.exe. With this compilation process
completes.

Prepared By B.Naveen Kumar (M.Tech.) JNTUH, Rajanna Siricilla. Page 12 of 210


I B.Tech EEE,CE,ME (R22) Unit - II C-Programming with Data Structures

Now, we need to run the executable file (Sample.exe). To run a program we press Ctrl + F9. When we
press Ctrl + F9 the executable file is submitted to the CPU. Then CPU performs the task according to
the instructions written in that program and place the result into UserScreen.

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

Important Points

 C program file (Source file) must save with .c extension.

 The compiler converts complete program at a time from high-level language to low-level language.

 Input to the compiler is .c file and output from the compiler is .exe file, but it also generates .obj file in

this process.

 The compiler converts the file only if there are no errors in the source code.

CPU places the result in User Screen window.

Naveen(jntr)

Overall Process

 Type the program in C editor and save with .c extension (Press F2 to save).

 Press Alt + F9 to compile the program.

 If there are errors, correct the errors and recompile the program.

 If there are no errors, then press Ctrl + F9 to execute/run the program.

 Press Alt + F5 to open User Screen and check the result.

Program Development Life Cycle


When we want to develop a program using any programming language, we follow a sequence of steps.

These steps are called phases in program development. The program development life cycle is a set of

steps or phases that are used to develop a program in any programming language.

Generally, the program development life cycle contains 6 phases, they are as follows….

 Problem Definition

 Problem Analysis

 Algorithm Development

 Coding & Documentation

 Testing & Debugging

 Maintenance

Prepared By B.Naveen Kumar (M.Tech.) JNTUH, Rajanna Siricilla. Page 13 of 210


I B.Tech EEE,CE,ME (R22) Unit - II C-Programming with Data Structures

1. Problem Definition
In this phase, we define the problem statement and we decide the boundaries of the problem. In this
phase we need to understand the problem statement, what is our requirement, what should be the
output of the problem solution. These are defined in this first phase of the program development life
cycle.
Naveen(jntr)
2. Problem Analysis
In phase 2, we determine the requirements like variables, functions, etc. to solve the problem. That
means we gather the required resources to solve the problem defined in the problem definition phase.
We also determine the bounds of the solution.

3. Algorithm Development
During this phase, we develop a step by step procedure to solve the problem using the specification
given in the previous phase. This phase is very important for program development. That means we
write the solution in step by step statements.

4. Coding & Documentation


This phase uses a programming language to write or implement the actual programming instructions
for the steps defined in the previous phase. In this phase, we construct the actual program. That
means we write the program to solve the given problem using programming languages like C, C++,
Java, etc.,

5. Testing & Debugging


During this phase, we check whether the code written in the previous step is solving the specified
problem or not. That means we test the program whether it is solving the problem for various input
data values or not. We also test whether it is providing the desired output or not.

6. Maintenance
During this phase, the program is actively used by the users. If any enhancements found in this phase,
all the phases are to be repeated to make the enhancements. That means in this phase, the solution
(program) is used by the end-user. If the user encounters any problem or wants any enhancement,
then we need to repeat all the phases from the starting, so that the encountered problem is solved or
enhancement is added.

Prepared By B.Naveen Kumar (M.Tech.) JNTUH, Rajanna Siricilla. Page 14 of 210


I B.Tech EEE,CE,ME (R22) Unit - II C-Programming with Data Structures

C Background
C is a structured programming language. It is also known as function orientated programming

language. C programming language was developed in the year of 1972 by Dennis Ritchie at Bell

Laboratories in the USA (AT & T).

In the year of 1968, research was started by Dennis Ritchie on programming languages like BCPL, CPL.

The main aim of his research was to develop a new language to create an OS called UNIX. After four

years of research, a new programming language was created with solutions for drawbacks in

languages like BCPL & CPL. In the year of 1972, the new language was introduced with the name

“Traditional C”.

Naveen(jntr)

The name 'c' was selected from the sequence of previous language ‘B’ (BCPL) because most of the
features of 'c' were derived from BCPL (B language).

The first outcome of the c language was the UNIX operating system. The initial UNIX OS was completely
developed using 'c' programming language.

The founder of the ‘C’ language, Dennis Ritchie is known as “Father of C” and also “Father of UNIX”.

The c programming language is very popular because it is reliable, simple and easy to use and it is the
base for almost all the other programming languages.

The following are the language before ‘c’ & various versions of ‘c’.

1. CPL (Common Programming Language)

The CPL was invented by Martin Richards at the University of Cambridge in the early of 1960s.

2. BCPL (Basic Combined Programming Language)


The BCPL was invented by Martin Richards at the University of Cambridge in the year of 1966. It was a
popular programming language at that time. BCPL allows the user, direct access to the computer
memory. BCPL is the extension of CPL.

3. B Language
B language is derived from BCPL. It was introduced in the year of 1969 by Ken Thompson and Dennis
Ritchie at Bell Laboratory, USA. The B language is similar to BCPL.

Prepared By B.Naveen Kumar (M.Tech.) JNTUH, Rajanna Siricilla. Page 15 of 210


I B.Tech EEE,CE,ME (R22) Unit - II C-Programming with Data Structures

4. C Language
C language is derived from the B language. It was introduced in the year of 1972 by Dennis Ritchie at
Bell Laboratory, USA. The C language was mainly developed to create an operating system
called UNIX. The name C is given based on the previous language B and BCPL. Ninety percent of the
UNIX operating system code is written in C language. During the 1970s, the C language became a very
popular programming language. Many universities and organizations began creating their version of C
language for their respective projects. So, C language has got many variants at that time. Later it was
standardized.

5. ANSI C (C89)
In the year of 1983, the ANSI (American National Standards Institute) formed a committee to frame
standard specifications for the C language. In the year of 1989, this committee introduced a standard
version of C with the name "ANSI C" with standard library files. The ANSI C is also called as C89 in short
form.

6. C90
In the year of 1990, the ANSI C was got ISO (International Organization for Standardization)

Naveen(jntr)
standardization with the inclusion of a few new features like new library files, new processor
commands. And it was also added with keywords const, volatile and signed, etc... ISO standardized ANSI
C as ISO/IEC 9899:1990. This version is called as C90 in short form.

7. C99
In the year of 1995, many new features were added to the C90 to create a new version of it. This new
version of C was got ISO standardization in the year of 1999 with the name ISO/IEC 9899:1999. In the
short form, it is called as C99. Later C99 became the official standard version of C.

C Program Basics (Structure of C)


C is a structured programming language. Every c program and its statements must be in a particular
structure. Every c program has the following general structure...

Prepared By B.Naveen Kumar (M.Tech.) JNTUH, Rajanna Siricilla. Page 16 of 210


I B.Tech EEE,CE,ME (R22) Unit - II C-Programming with Data Structures

Line 1: Comments - They are ignored by the compiler


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

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

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

Line 2: Preprocessing 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 statements are used according to the requirements. If we don't
need any header file, then no need to write #include statement. If we don't need any constant, then no
need to write a #define statement.

Line 3: Global Declaration


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

Line 4: int main()


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

Line 5: Open Brace ( { )


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

Line 6: Local Declaration


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

Line 7: Executable statements


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

Line 9: Closing Brace ( } )


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

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


Prepared By B.Naveen Kumar (M.Tech.) JNTUH, Rajanna Siricilla. Page 17 of 210
I B.Tech EEE,CE,ME (R22) Unit - II C-Programming with Data Structures

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.

General rules for any C program


1. Every executable statement must end with a semicolon symbol (;).
2. Every C program must contain exactly one main method (Starting point of the program execution).
3. All the system-defined words (keywords) must be used in lowercase letters.
4. Keywords can not be used as user-defined names(identifiers).
5. For every open brace ({), there must be respective closing brace (}).
6. Every variable must be declared before it is used.

C Character Set
As every language contains a set of characters used to construct words, statements, etc., C language

Naveen(jntr)
also has a set of characters which include alphabets, digits, and special symbols. C language
supports a total of 256 characters.

Every C program contains statements. These statements are constructed using words and these words
are constructed using characters from C character set. C language character set contains the following
set of characters...

1. Alphabets
2. Digits
3. Special Symbols

Alphabets
C language supports all the alphabets from the English language. Lower and upper case letters
together support 52 alphabets.

lower case letters - a to z

UPPER CASE LETTERS - A to Z

Digits
C language supports 10 digits which are used to construct numerical values in C language.

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

Special Symbols
C language supports a rich set of special symbols that include symbols to perform mathematical
operations, to check conditions, white spaces, backspaces, and other special symbols.

Special Symbols - ~ @ # $ % ^ & * ( ) _ - + = { } [ ] ; : ' " / ? . > , < \ | tab newline space NULL bell
backspace verticaltab etc.,

Every character in C language has its equivalent ASCII (American Standard Code for Information
Interchange) value.

Commonly used characters in C with thier ASCII values


Prepared By B.Naveen Kumar (M.Tech.) JNTUH, Rajanna Siricilla. Page 18 of 210
I B.Tech EEE,CE,ME (R22) Unit - II C-Programming with Data Structures

Naveen(jntr)

C program to print all the characters of C character Set


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

C Tokens
Every C program is a collection of instructions and every instruction is a collection of some individual
units. Every smallest individual unit of a c program is called token. Every instruction in a c program is a
collection of tokens. Tokens are used to construct c programs and they are said to the basic building
blocks of a c program.
In a c program tokens may contain the following...

1. Keywords
Prepared By B.Naveen Kumar (M.Tech.) JNTUH, Rajanna Siricilla. Page 19 of 210
I B.Tech EEE,CE,ME (R22) Unit - II C-Programming with Data Structures

2. Identifiers
3. Operators
4. Special Symbols
5. Constants
6. Strings
7. Data values

In a C program, a collection of all the keywords, identifiers, operators, special symbols,


constants, strings, and data values are called tokens.

Consider the following C program...

C program to print all the characters of C character Set


#include<stdio.h>
#include<conio.h>
int main() {
int i;
clrscr();

Naveen(jntr)
printf("ASCII==>Character\n");
for(i=-128;i<=127;i++)
printf("%d==>%c\n",i,i);
getch();
return 0;
}

In the above program there are 22 tokens.

C Keywords
As every language has words to construct statements, C programming also has words with a specific
meaning which are used to construct c program instructions. In the C programming language,
keywords are special words with predefined meaning. Keywords are also known as reserved words in
C programming language.

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

Keywords are the reserved words with predefined meaning which already known to the

compiler

Whenever C compiler come across a keyword, automatically it understands its meaning.

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 can not be used as user-defined names like variable, functions, arrays, pointers, etc...
4. Every keyword in C programming language represents something or specifies some kind of action to
be performed by the compiler.

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

Prepared By B.Naveen Kumar (M.Tech.) JNTUH, Rajanna Siricilla. Page 20 of 210


I B.Tech EEE,CE,ME (R22) Unit - II C-Programming with Data Structures

Naveen(jntr)

C Identifiers
In C programming language, programmers can specify their name to a variable, array, pointer,
function, 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.

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

Example
int marks;
char studentName[30];

Here, marks and studentName are identifiers.

Rules for Creating Identifiers


1. An identifier can contain letters (UPPERCASE and lowercase), numerics & underscore symbol only.
2. An identifier should not start with a numerical value. It can start with a letter or an underscore.
3. We should not use any special symbols in between the identifier even whitespace. However, the only
underscore symbol is allowed.
4. Keywords should not be used as identifiers.
5. There is no limit for the length of an identifier. However, the compiler considers the first 31 characters
only.
6. An identifier must be unique in its scope.

Prepared By B.Naveen Kumar (M.Tech.) JNTUH, Rajanna Siricilla. Page 21 of 210


I B.Tech EEE,CE,ME (R22) Unit - II C-Programming with Data Structures

Rules for Creating Identifiers for better programming


The following are the commonly used rules for creating identifiers for better programming...

1. The identifier must be meaningful to describe the entity.


2. Since starting with an underscore may create conflict with system names, so we avoid starting an
identifier with an underscore.
3. We start every identifier with a lowercase letter. If an identifier contains more than one word then the
first word starts with a lowercase letter and second word onwards first letter is used as an UPPERCASE
letter. We can also use an underscore to separate multiple words in an identifier.

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.

Naveen(jntr)
In a c program, each variable or constant or array must have a data type and this data type specifies
how much memory is to be allocated and what type of values are to be stored in that variable or
constant or array. The formal definition of a data type is as follows...

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

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

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


2. Derived data types (Secondary data types OR User-defined data types)
3. Enumeration data types
4. Void data type

Primary data types


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

1. Integer data type


2. Floating Point data type
3. Double data type
4. Character data type

Prepared By B.Naveen Kumar (M.Tech.) JNTUH, Rajanna Siricilla. Page 22 of 210


I B.Tech EEE,CE,ME (R22) Unit - II C-Programming with Data Structures

Integer Data type


The integer data type is a set of whole numbers. Every integer value does not have the decimal value.
We use the keyword "int" to represent integer data type in c. We use the keyword int to declare the

Naveen(jntr)
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.

Floating Point data types


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

 float
 double

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

Prepared By B.Naveen Kumar (M.Tech.) JNTUH, Rajanna Siricilla. Page 23 of 210


I B.Tech EEE,CE,ME (R22) Unit - II C-Programming with Data Structures

Character data type

The character data type is a set of characters enclosed in single quotations. The following table

provides complete details about the character data type.

The following table provides complete information about all the data types in c programming

language...

Naveen(jntr)

void data type


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

Enumerated data type


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

Derived data types


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

 Arrays
 Structures
 Unions
 Enumeration
Prepared By B.Naveen Kumar (M.Tech.) JNTUH, Rajanna Siricilla. Page 24 of 210
I B.Tech EEE,CE,ME (R22) Unit - II C-Programming with Data Structures

C Variables
Variables in a c programming language are the named memory locations where the user can store
different values of the same datatype during the program execution. That means a variable is a name
given to a memory location in which we can store different values of the same data type. In other
words, a variable can be defined as a storage container to hold values of the same datatype during the
program execution. The formal definition of a data type is as follows...

Variable is a name given to a memory location where we can store different values of the same
datatype during the program execution.

Every variable in c programming language must be declared in the declaration section before it is used.
Every variable must have a datatype that determines the range and type of values be stored and the
size of the memory to be allocated.

A variable name may contain letters, digits and underscore symbol. The following are the rules to
specify a variable name...

1. Variable name should not start with a digit.

Naveen(jntr)
2. Keywords should not be used as variable names.
3. A variable name should not contain any special symbols except underscore(_).
4. A variable name can be of any length but compiler considers only the first 31 characters of the variable
name.

Declaration of Variable
Declaration of a variable tells the compiler to allocate the required amount of memory with the
specified variable name and allows only specified datatype values into that memory location. In C
programming language, the declaration can be performed either before the function as global
variables or inside any block or function. But it must be at the beginning of block or function.

Declaration Syntax:

datatype variableName;

Example: int number;

The above declaration tells to the compiler that allocates 2 bytes of memory with the
name number and allows only integer values into that memory location.

C Constants
In C programming language, a constant is similar to the variable but the constant hold only one value
during the program execution. That means, once a value is assigned to the constant, that value can't
be changed during the program execution. Once the value is assigned to the constant, it is fixed
throughout the program. A constant can be defined as follows...

A constant is a named memory location which holds only one value throughout the program

execution.

In C programming language, a constant can be of any data type like integer, floating-point, character,
string and double, etc.,

Prepared By B.Naveen Kumar (M.Tech.) JNTUH, Rajanna Siricilla. Page 25 of 210


I B.Tech EEE,CE,ME (R22) Unit - II C-Programming with Data Structures

Integer constants
An integer constant can be a decimal integer or octal integer or hexadecimal integer. A decimal integer
value is specified as direct integer value whereas octal integer value is prefixed with 'o' and
hexadecimal value is prefixed with 'OX'.
An integer constant can also be unsigned type of integer constant or long type of integer constant.
Unsigned integer constant value is suffixed with 'u' and long integer constant value is suffixed with 'l'
whereas unsigned long integer constant value is suffixed with 'ul'.

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

Floating Point constants


Naveen(jntr)
A floating-point constant must contain both integer and decimal parts. Some times it may also contain
the exponent part. When a floating-point constant is represented in exponent form, the value must be
suffixed with 'e' or 'E'.

Example
The floating-point value 3.14 is represented as 3E-14 in exponent form.

Character Constants
A character constant is a symbol enclosed in single quotation. A character constant has a maximum
length of one character.

Example
'A'
'2'
'+'

In the C programming language, there are some predefined character constants called escape
sequences. Every escape sequence has its own special functionality and every escape sequence is
prefixed with '\' symbol. These escape sequences are used in output function called 'printf()'.

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

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


"This is jntuhucer"

We can define string constant using multiple lines as follows...


" This\
is\
jntuhucer "

Prepared By B.Naveen Kumar (M.Tech.) JNTUH, Rajanna Siricilla. Page 26 of 210


I B.Tech EEE,CE,ME (R22) Unit - II C-Programming with Data Structures

We can also define string constant by separating it with white space as follows...
"This" "is" "jntuhucer"

All the above three defines the same string constant.

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

1. Using the 'const' keyword


2. Using '#define' preprocessor

Using the 'const' keyword


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

const datatype constantName ;


Naveen(jntr) OR

const datatype constantName = value ;


Example
const int x = 10 ;

Here, 'x' is a integer constant with fixed value 10.

Example Program
#include<stdio.h>
#include<conio.h>
void main(){
int i=9 ;
const int x=10;
i=15;
x=100; // creates an error
printf("i=%d\nx=%d",i,x) ;
}

The above program gives an error because we are trying to change the constant variable value (x =
100).

Using '#define' preprocessor


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

#define CONSTANTNAME value

Prepared By B.Naveen Kumar (M.Tech.) JNTUH, Rajanna Siricilla. Page 27 of 210


I B.Tech EEE,CE,ME (R22) Unit - II C-Programming with Data Structures

Example
#define PI 3.14

Here, PI is a constant with value 3.14

Example Program
#include<stdio.h>
#include<conio.h>
#defien PI 3.14
void main(){
int r,area;
printf("Please enter the radius of circle : ");
scanf("%d",&r);
area=PI*(r*r);
printf("Area of the circle =%d",area);
}

C Storage Classes
Naveen(jntr)
In C programming language, storage classes are used to define things like storage location (whether
RAM or REGISTER), scope, lifetime and the default value of a variable.

In the C programming language, the memory of variables is allocated either in computer memory
(RAM) or CPU Registers. The allocation of memory depends on storage classes.

In C programming language, there are FOUR storage classes and they are as follows...

1. auto storage class


2. extern storage class
3. static storage class
4. register storage class

auto storage class


The default storage class of all local variables (variables declared inside block or function) is auto
storage class. Variable of auto storage class has the following properties...

Property Description

Keyword auto

Storage Computer Memory (RAM)

Default Value Garbage Value

Scope Local to the block in which the variable is defined

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

Prepared By B.Naveen Kumar (M.Tech.) JNTUH, Rajanna Siricilla. Page 28 of 210


I B.Tech EEE,CE,ME (R22) Unit - II C-Programming with Data Structures

Example Program 1
#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;
}

Example Program 2
#include<stdio.h>
#include<conio.h>

Naveen(jntr)
int main(){
int a=10;
{
int a=20;
printf("%d",a);
}
printf(" %d",a);
return 0;
}
Example Program 3
#include<stdio.h>
#include<conio.h>
int main(){
{
int a=20;
printf("%d",a);
}
printf("%d",a); //a is not visible here
return 0;
}

External storage class


The default storage class of all global varibles (variables declared outside function) is external storage
class. Variable of external storage class has the following properties...

Property Description

Keyword extern

Storage Computer Memory (RAM)

Prepared By B.Naveen Kumar (M.Tech.) JNTUH, Rajanna Siricilla. Page 29 of 210


I B.Tech EEE,CE,ME (R22) Unit - II C-Programming with Data Structures

Property Description

Default Value Zero

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

Life time As long as the program’s execution does not comes to end

Example Program 1
#include<stdio.h>
#include<conio.h>

Naveen(jntr)
int i; //By default it is extern variable
int main(){
printf("%d",i);
return 0;
}

Example Program 2
#include<stdio.h>
#include<conio.h>

extern int i; //extern variable


int main(){
printf("%d",i);
return 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.
Variable of static storage class has the following properties...

Property Description

Keyword static

Storage Computer Memory (RAM)

Default Value Zero

Scope Local to the block in which the variable is defined

Prepared By B.Naveen Kumar (M.Tech.) JNTUH, Rajanna Siricilla. Page 30 of 210


I B.Tech EEE,CE,ME (R22) Unit - II C-Programming with Data Structures

Property Description

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

Example Program 2
#include<stdio.h>
#include<conio.h>
static int i=10; Naveen(jntr)
int main(){
i=25; //Assignment statement
printf("%d",i);
return 0;
}

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. Variable of register storage class has the following properties...

PropertyDescription

Keyword register

Storage CPU Register

Default Value Garbage Value

Scope Local to the block in which the variable is defined

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

Example Program 1
#include<stdio.h>
#include<conio.h>
int main(){
register int a,b;

Prepared By B.Naveen Kumar (M.Tech.) JNTUH, Rajanna Siricilla. Page 31 of 210


I B.Tech EEE,CE,ME (R22) Unit - II C-Programming with Data Structures

scanf("%d%d",&a,&b);
printf("%d %d",a,b);
}

The following table provides detailed properties of all storage classes...

Memory
Storage Class Keyword Location Default Value
Scope Life Time

Automati auto Computer Garbag Local to the Till the control


c Memory e Value block in remains within
(RAM) which the the block in
variable has which variable
defined is defined

External extern Computer Zero Global to the As long as the


Memory program (i.e., program’s

Naveen(jntr)
(RAM) Throughout
the program)
execution does
not come to
end

Static static Computer Zero Local to the The value of


Memory block in the persists
(RAM) which the between
variable has different
defined function calls
(i.e.,
Initialization is
done only
once)

Register registe CPU Garbag Local to the Till the control


r Register e Value block in remains within
which the the block in
variable has which variable
defined is defined

C Input Functions
C programming language provides built-in functions to perform input operations. The input operations
are used to read user values (input) from the keyboard. The c programming language provides the
following built-in input functions.

1. scanf()
2. getchar()
3. getch()
4. gets()
5. fscanf()

Prepared By B.Naveen Kumar (M.Tech.) JNTUH, Rajanna Siricilla. Page 32 of 210


I B.Tech EEE,CE,ME (R22) Unit - II C-Programming with Data Structures

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

Syntax:

scanf("format strings",&variableNames);
Example Program
#include<stdio.h>
#include<conio.h>
void main(){
int i;
printf("\nEnter any integer value: ");
scanf("%d",&i);
Naveen(jntr)
printf("\nYou have entered %d number",i);
}

Output:

In the above example program, we used the scanf() function to read an integer value from the
keyboard and store it into variable 'i'.

The scanf function also used to read multiple data values of different or the same data types. Consider
the following example program...

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

void main(){
int i;
float x;
printf("\nEnter one integer followed by one float value : ");
scanf("%d%f",&i, &x);
printf("\ninteger = %d, float = %f",i, x);

Prepared By B.Naveen Kumar (M.Tech.) JNTUH, Rajanna Siricilla. Page 33 of 210


I B.Tech EEE,CE,ME (R22) Unit - II C-Programming with Data Structures

Output:

In the above example program, we used the scanf() function to read one integer value and one float
value from the keyboard. Here 'i' is an integer variable so we have used format string %d, and 'x' is a
float variable so we have used format string %f.

The scanf() function returns an integer value equal to the total number of input values read using scanf
function.

Example Program
#include<stdio.h>
Naveen(jntr)
#include<conio.h>
void main(){
int i,a,b;
float x;
printf("\nEnter two integers and one float : ");
i = scanf("%d%d%f",&a, &b, &x);
printf("\nTotal inputs read : %d",i);
}

Output:

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


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

void main(){

Prepared By B.Naveen Kumar (M.Tech.) JNTUH, Rajanna Siricilla. Page 34 of 210


I B.Tech EEE,CE,ME (R22) Unit - II C-Programming with Data Structures

char ch;
printf("\nEnter any character : ");
ch = getchar();
printf("\nYou have entered : %c\n",ch);

Output:

getch() function
The getch() function is similar to getchar function. The getch() function is used to read a character from

Naveen(jntr)
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...

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:

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. Consider the
following example program...

Prepared By B.Naveen Kumar (M.Tech.) JNTUH, Rajanna Siricilla. Page 35 of 210


I B.Tech EEE,CE,ME (R22) Unit - II C-Programming with Data Structures

Example Program
#include<stdio.h>
#include<conio.h>
void main(){
char name[30];
printf("\nEnter your favourite website: ");
gets(name);
printf("%s",name);
}

Output:

fscanf() function
Naveen(jntr)
The fscanf() function is used with the concept of files. The fscanf() function is used to read data values
from a file. When you want to use fscanf() function the file must be opened in reading mode.

C Output Functions
C programming language provides built-in functions to perform output operation. The output
operations are used to display data on user screen (output screen) or printer or any file. The c
programming language provides the following built-in output functions...

1. printf()
2. putchar()
3. puts()
4. fprintf()

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

Syntax:

printf("message to be display!!!");
Example Program
#include<stdio.h>
#include<conio.h>
void main(){
printf("Hello! Welcome to jntuhucer!!!");
}

Prepared By B.Naveen Kumar (M.Tech.) JNTUH, Rajanna Siricilla. Page 36 of 210


I B.Tech EEE,CE,ME (R22) Unit - II C-Programming with Data Structures

Output:

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.

Syntax:

printf("format string",variableName);
Example Program
#include<stdio.h>

Naveen(jntr)
#include<conio.h>
void main(){
int i = 10;
float x = 5.5;
printf("%d %f",i, x);
}

Output:

In the above example program, we used the printf() function to print data values of variables i and x on
to the output screen. Here i is a an integer variable so we have used format string %d and x is a float
variable so we have used format string %f.

The printf() function can also be used to display string along with data values.

Syntax:

printf("String format string",variableName);


Example Program
#include<stdio.h>
#include<conio.h>
void main(){
int i = 10;
float x = 5.5;
printf("Integer value = %d, float value = %f",i, x);
}

Prepared By B.Naveen Kumar (M.Tech.) JNTUH, Rajanna Siricilla. Page 37 of 210


I B.Tech EEE,CE,ME (R22) Unit - II C-Programming with Data Structures

Output:

In the above program, we are displaying string along with data values.

Every function in the C programming language must have a return value. The printf() function also
have an integer as a return value. The printf() function returns an integer value equivalent to the total
number of characters it has printed.

Example Program
#include<stdio.h>
#include<conio.h>
void main(){
int i;
i = printf("jntuhucer");

}
Naveen(jntr)
printf(" is %d number of characters.",i);

Output:

In the above program, first printf() function printing "jntuhucer" which is of 15 characters. So it returns
integer value 15 to the variable "i". The value of "i" is printed in the second printf() function.

Formatted printf() function


Generally, when we write multiple printf() statements the result is displayed in a single line because the
printf() function displays the output in a single line. Consider the following example program...

Example Program
#include<stdio.h>
#include<conio.h>
void main(){
printf("Welcome to ");
printf("jntuhucer ");
printf("the perfect website for learning");
}

Output:

Prepared By B.Naveen Kumar (M.Tech.) JNTUH, Rajanna Siricilla. Page 38 of 210


I B.Tech EEE,CE,ME (R22) Unit - II C-Programming with Data Structures

In the above program, there are 3 printf() statements written in different lines but the output is
displayed in single line only.

To display the output in different lines or as we wish, we use some special characters called escape
sequences. Escape sequences are special characters with special functionality used in printf() function
to format the output according to the user requirement. In the C programming language, we have the
following escape sequences...

Escape sequence Meaning

\n Moves the cursor to New Line

\t Inserts Horizontal Tab (5 characters space)

\v Inserts Vertical Tab (5 lines space)

\a Beep sound

\b Backspace (removes the previous character from its current position)

\\ Naveen(jntr)
Inserts Backward slash symbol

\? Inserts Question mark symbol

\' Inserts Single quotation mark symbol

\" Inserts Double quotation mark symbol

Consider the following example program...

Example Program
#include<stdio.h>
#include<conio.h>
void main(){
printf("Welcome to\n");
printf("jntuhucer\n");
printf("the perfect website for learning");
}

Output:

Prepared By B.Naveen Kumar (M.Tech.) JNTUH, Rajanna Siricilla. Page 39 of 210


I B.Tech EEE,CE,ME (R22) Unit - II C-Programming with Data Structures

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

Example Program
#include<stdio.h>
#include<conio.h>
void main(){
char ch = 'A';
putchar(ch);
}

Output:

Naveen(jntr)
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...

Example Program
#include<stdio.h>
#include<conio.h>
void main(){
char name[30];
printf("\nEnter your favourite website: ");
gets(name);
puts(name);
}

Output:

fprintf() function
The fprintf() function is used with the concept of files. The fprintf() function is used to print a line into
the file. When you want to use fprintf() function the file must be opened in writting mode.

C Operators
Prepared By B.Naveen Kumar (M.Tech.) JNTUH, Rajanna Siricilla. Page 40 of 210
I B.Tech EEE,CE,ME (R22) Unit - II C-Programming with Data Structures

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

1. Arithmetic Operators
2. Relational Operators
3. Logical Operators
4. Increment & Decrement Operators
5. Assignment Operators
6. Bitwise Operators
7. Conditional Operator
8. Special Operators

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

The arithmetic operators are the symbols that are used to perform basic mathematical operations like

Naveen(jntr)
addition, subtraction, multiplication, division and percentage modulo. The following table provides
information about arithmetic operators.

Operator
Meaning Example

+ Addition 10 + 5 = 15

- Subtraction 10 - 5 = 5

* Multiplication 10 * 5 = 50

/ Division 10 / 5 = 2

% Remainder of the Division 5%2=1


⇒ The addition operator can be used with numerical data types and character data type. When it is
used with numerical values, it performs mathematical addition and when it is used with character data
type values, it performs concatination (appending).

⇒ The remainder of the division operator is used with integer data type only.

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

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

Operator Meaning Example

< Returns TRUE if the first value is smaller than second value 10 < 5 is
otherwise returns FALSE FALSE
Prepared By B.Naveen Kumar (M.Tech.) JNTUH, Rajanna Siricilla. Page 41 of 210
I B.Tech EEE,CE,ME (R22) Unit - II C-Programming with Data Structures

Operator Meaning Example

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

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

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

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


FALSE

!=
Naveen(jntr)
Returns TRUE if both values are not equal otherwise returns FALSE
10 != 5 is
TRUE

Logical Operators (&&, ||, !)

The logical operators are the symbols that are used to combine multiple conditions into one condition.

The following table provides information about logical operators.

Operator Meaning Example

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

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


otherwise returns TRUE TRUE

! Logical NOT - Returns TRUE if condition is FLASE and !(10 < 5 && 12 >
returns FALSE if it is TRUE 10) is TRUE

⇒ Logical AND - Returns TRUE only if all conditions are TRUE, if any of the conditions is FALSE then

complete condition becomes FALSE.

⇒ Logical OR - Returns FALSE only if all conditions are FALSE, if any of the conditions is TRUE then

complete condition becomes TRUE.

Prepared By B.Naveen Kumar (M.Tech.) JNTUH, Rajanna Siricilla. Page 42 of 210


I B.Tech EEE,CE,ME (R22) Unit - II C-Programming with Data Structures

Increment & Decrement Operators (++ & --)

The increment and decrement operators are called unary operators because both need only one

operand. The increment operators adds one to the existing value of the operand and the decrement

operator subtracts one from the existing value of the operand. The following table provides

information about increment and decrement operators.

Operator Meaning Example

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


a++; ⇒ a = 6

-- Decrement - Subtracts one from existing value int a = 5;


a--; ⇒ a = 4

Naveen(jntr)
The increment and decrement operators are used infront of the operand (++a) or after the operand
(a++). If it is used infront of the operand, we call it as pre-increment or pre-decrement and if it is
used after the operand, we call it as post-increment or post-decrement.

Pre-Increment or Pre-Decrement
In the case of pre-increment, the value of the variable is increased by one before the expression
evaluation. In the case of pre-decrement, the value of the variable is decreased by one before the
expression evaluation. That means, when we use pre-increment or pre-decrement, first the value of
the variable is incremented or decremented by one, then the modified value is used in the expression
evaluation.
Example Program
#include<stdio.h>
#include<conio.h>
void main(){
int i = 5,j;
j = ++i; // Pre-Increment
printf("i = %d, j = %d",i,j);
}
Output:

Post-Increment or Post-Decrement
In the case of post-increment, the value of the variable is increased by one after the expression
evaluation. In the case of post-decrement, the value of the variable is decreased by one after the
expression evaluation. That means, when we use post-increment or post-decrement, first the
expression is evaluated with existing value, then the value of the variable is incremented or
decremented by one.
Example Program
#include<stdio.h>
Prepared By B.Naveen Kumar (M.Tech.) JNTUH, Rajanna Siricilla. Page 43 of 210
I B.Tech EEE,CE,ME (R22) Unit - II C-Programming with Data Structures

#include<conio.h>
void main(){
int i = 5,j;
j = i++; // Post-Increment
printf("i = %d, j = %d",i,j);
}
Output:

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

Naveen(jntr)
The assignment operators are used to assign right-hand side value (Rvalue) to the left-hand side

variable (Lvalue). The assignment operator is used in different variants along with arithmetic

operators. The following table describes all the assignment operators in the C programming language.

Operator Meaning Example

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


hand side variable

+= Add both left and right-hand side values A += 10


and store the result into left-hand side ⇒ A = A+10
variable

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


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

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


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

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


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

Prepared By B.Naveen Kumar (M.Tech.) JNTUH, Rajanna Siricilla. Page 44 of 210


I B.Tech EEE,CE,ME (R22) Unit - II C-Programming with Data Structures

Operator Meaning Example

into the left-hand side variable

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


right-hand side variable value and store ⇒ A = A%B
the remainder
into the left-hand side variable

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


The bitwise operators are used to perform bit-level operations in the c programming language. When
we use the bitwise operators, the operations are performed based on the binary values. The following
table describes all the bitwise operators in the C programming language.

Naveen(jntr)
Let us consider two variables A and B as A = 25 (11001) and B = 20 (10100).

Operator Meaning Example

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

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


otherwise it is 1 ⇒ 29 (11101)

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

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


the bit (Flipping) ⇒ 6 (00110)

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

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

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.

Prepared By B.Naveen Kumar (M.Tech.) JNTUH, Rajanna Siricilla. Page 45 of 210


I B.Tech EEE,CE,ME (R22) Unit - II C-Programming with Data Structures

Condition ? TRUE Part : FALSE Part;

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

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


The following are the special operators in c programming language.

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

sizeof(variableName);

Example

Pointer operator (*)


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

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

Comma operator (,)


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

Dot operator (.)


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

C Expressions
What is an expression?
In any programming language, if we want to perform any calculation or to frame any condition etc., we
use a set of symbols to perform the task. These set of symbols makes an expression.
In the C programming language, an expression is defined as follows.
An expression is a collection of operators and operands that represents a specific value.
In the above definition, an operator is a symbol that performs tasks like arithmetic operations, logical
operations, and conditional operations, etc.
Operands are the values on which the operators perform the task. Here operand can be a direct value
or variable or address of memory location.

Expression Types in C
In the C programming language, expressions are divided into THREE types. They are as follows...

1. Infix Expression
2. Postfix Expression
3. Prefix Expression
The above classification is based on the operator position in the expression.

Prepared By B.Naveen Kumar (M.Tech.) JNTUH, Rajanna Siricilla. Page 46 of 210


I B.Tech EEE,CE,ME (R22) Unit - II C-Programming with Data Structures

Infix Expression
The expression in which the operator is used between operands is called infix expression.
The infix expression has the following general structure.

Operand1 Operator Operand2

Example

Postfix Expression
The expression in which the operator is used after operands is called postfix expression.

The postfix expression has the following general structure.

Naveen(jntr)
Operand1 Operand2 Operator

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 Operator Precedence and Associativity


What is Operator Precedence?
Operator precedence is used to determine the order of operators evaluated in an expression. In c

programming language every operator has precedence (priority). When there is more than one

Prepared By B.Naveen Kumar (M.Tech.) JNTUH, Rajanna Siricilla. Page 47 of 210


I B.Tech EEE,CE,ME (R22) Unit - II C-Programming with Data Structures

operator in an expression the operator with higher precedence is evaluated first and the operator with

the least precedence is evaluated last.

What is Operator Associativity?


Operator associativity is used to determine the order of operators with equal precedence evaluated in

an expression. In the c programming language, when an expression contains multiple operators with

equal precedence, we use associativity to determine the order of evaluation of those operators.

In c programming language the operator precedence and associativity are as shown in the following

table.

Precedence Operator Operator Meaning Associativity

1 () function call Left to Right


[]
->
.
Naveen(jntr)
array reference
structure member access
structure member access

2 ! negation Right to Left


~ 1's complement
+ Unary plus
- Unary minus
++ increment operator
-- decrement operator
& address of operator
* pointer
sizeof returns size of a variable
(type) type conversion

3 * multiplication Left to Right


/ division
% remainder

4 + addition Left to Right


- subtraction

5 << left shift Left to Right


>> right shift

6 < less than Left to Right


<= less than or equal to
> greater than
>= greater than or equal to

7 == equal to Left to Right


!= not equal to

8 & bitwise AND Left to Right

9 ^ bitwise EXCLUSIVE OR Left to Right

10 | bitwise OR Left to Right

11 && logical AND Left to Right

Prepared By B.Naveen Kumar (M.Tech.) JNTUH, Rajanna Siricilla. Page 48 of 210


I B.Tech EEE,CE,ME (R22) Unit - II C-Programming with Data Structures

Precedence Operator Operator Meaning Associativity

12 || logical OR Left to Right

13 ?: conditional operator Left to Right

14 = assignment Right to Left


*= assign multiplication
/= assign division
%= assign remainder
+= assign addition
-= assign subtraction
&= assign bitwise AND
^= assign bitwise XOR
|= assign bitwise OR
<<= assign left shift
>>= assign right shift

15 , separator Left to Right


In the above table, the operator precedence decreases from top to bottom and increases from bottom

Naveen(jntr)
to top.

C Expression Evaluation
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.

An expression is evaluated based on the precedence and associativity of the operators in that
expression.

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.

Type Casting and Conversion in C


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

Prepared By B.Naveen Kumar (M.Tech.) JNTUH, Rajanna Siricilla. Page 49 of 210


I B.Tech EEE,CE,ME (R22) Unit - II C-Programming with Data Structures

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

Naveen(jntr)
i = x ; =======> x value 15.5 is converted as 15 and assigned to variable i
x = i ; =======> Here i value 10 is converted as 10.000000 and assigned to variable x
i = ch ; =======> Here the ASCII value of A (65) is assigned to i

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

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
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
Prepared By B.Naveen Kumar (M.Tech.) JNTUH, Rajanna Siricilla. Page 50 of 210
I B.Tech EEE,CE,ME (R22) Unit - II C-Programming with Data Structures

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

Example
int totalMarks = 450, maxMarks = 600 ;
float average ;
average = (float) totalMarks / maxMarks * 100 ;
In the above example code, both totalMarks and maxMarks are integer data values. When we perform
totalMarks / maxMarks the result is a float value, but the destination (average) datatype is a float. So
we use type casting to convert totalMarks and maxMarks into float data type.

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

Naveen(jntr)
void main(){
int a, b, c ;
float avg ;
printf("Enter any three integer values : ");
scanf("%d%d%d",&a,&b,&c);
avg = (a + b + c) / 3 ;
printf("avg before casting = %d",avg);
avg = (float)(a + b + c) / 3 ;
printf("avg after casting = %d",avg);
}
Output:

UNIT - II Statements
'if' Statement in C
What is Decision Making Statement?
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 statements called decision
making statements.

Prepared By B.Naveen Kumar (M.Tech.) JNTUH, Rajanna Siricilla. Page 51 of 210


I B.Tech EEE,CE,ME (R22) Unit - II C-Programming with Data Structures

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 two decision-making statements they are as follows.

1. if statement
2. switch statement

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

1. Simple if statement
2. if-else statement
3. Nested if statement
4. if-else-if statement (if-else ladder)

Simple if statement
Naveen(jntr)
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.

Simple if statement is used when we have only one option that is executed or skipped based on a
condition.

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


#include<stdio.h>
#include<conio.h>
void main(){
int n ;
clrscr() ;
printf("Enter any integer number: ") ;
scanf("%d", &n) ;
if ( n%5 == 0 )
printf("Given number is divisible by 5\n") ;
printf("statement does not belong to if!!!") ;
}
Output 1:
Prepared By B.Naveen Kumar (M.Tech.) JNTUH, Rajanna Siricilla. Page 52 of 210
I B.Tech EEE,CE,ME (R22) Unit - II C-Programming with Data Structures

Output 2:

if-else statement
The if-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 if-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 is as
follows.
Naveen(jntr)

The if-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).
Example Program | Test whether given number is even or odd.
#include<stdio.h>
#include<conio.h>
void main(){
int n ;
clrscr() ;
printf("Enter any integer number: ") ;
scanf("%d", &n) ;
if ( n%2 == 0 )
printf("Given number is EVEN\n") ;
else
printf("Given number is ODD\n") ;
}
Output 1:
Prepared By B.Naveen Kumar (M.Tech.) JNTUH, Rajanna Siricilla. Page 53 of 210
I B.Tech EEE,CE,ME (R22) Unit - II C-Programming with Data Structures

Output 2:

Nested if statement
Writing a if statement inside another if statement is called nested if statement. The general syntax of
the nested if statement is as follows...

Naveen(jntr)

The nested if statement can be defined using any combination of simple if & if-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\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:

Prepared By B.Naveen Kumar (M.Tech.) JNTUH, Rajanna Siricilla. Page 54 of 210


I B.Tech EEE,CE,ME (R22) Unit - II C-Programming with Data Structures

Output 2:

if-else-if statement (if-else ladder)


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

Naveen(jntr)

The if-else-if statement can be defined using any combination of simple if & if-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:

Prepared By B.Naveen Kumar (M.Tech.) JNTUH, Rajanna Siricilla. Page 55 of 210


I B.Tech EEE,CE,ME (R22) Unit - II C-Programming with Data Structures

MOST IMPORTANT POINTS TO BE REMEMBERED

When we use a conditional control statement like if statement, the condition might be an expression
evaluated to a numerical value, a variable or a direct numerical value. If the expression value or
direct value is zero the condition becomes FALSE otherwise becomes TRUE.

To understand more consider the following statements.

 if(10) - is TRUE
 if(x) - is FALSE if x value is zero otherwise TRUE
 if(a+b) - is FALSE if a+b value is zero otherwise TRUE
 if(a = 99) - is TRUE because a value is non-zero
 if(10, 5, 0) - is FALSE because it considers last value
 if(0) - is FALSE
 if(a=10, b=15, c=0) - is FALSE because last value is zero

'switch' statement in C
Naveen(jntr)
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 associated 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.

Prepared By B.Naveen Kumar (M.Tech.) JNTUH, Rajanna Siricilla. Page 56 of 210


I B.Tech EEE,CE,ME (R22) Unit - II C-Programming with Data Structures

Naveen(jntr)
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 switchValue, 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 switchValue 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 switchValue specified in the switch statement,
then a special case called default is executed.

When a case value matches with the switchValue, 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 is used to terminate the switch
statement. However, it is optional.

Example Program | Display pressed digit in words.


#include<stdio.h>
#include<conio.h>
void main(){
int n ;
clrscr() ;
printf("Enter any digit: ") ;
scanf("%d", &n) ;
switch( n )
{
case 0: printf("ZERO") ;
break ;
case 1: printf("ONE") ;
break ;
case 2: printf("TWO") ;
break ;
case 3: printf("THREE") ;
break ;
case 4: printf("FOUR") ;
break ;
case 5: printf("FIVE") ;

Prepared By B.Naveen Kumar (M.Tech.) JNTUH, Rajanna Siricilla. Page 57 of 210


I B.Tech EEE,CE,ME (R22) Unit - II C-Programming with Data Structures

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

Output 2:
Naveen(jntr)

MOST IMPORTANT POINTS TO BE REMEMBERED

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

 Both switch and case are keywords so they must be used only in lower case letters.
 The data type of case value and the value specified in the switch statement must be the same.
 switch and case values must be either integer or character but not float or string.
 A switch statement can contain any number of cases.
 The keyword case and its value must be superated with a white space.
 The case values need not be defined in sequence, they can be in any order.
 The default case is optional and it can be defined anywhere inside the switch statement.
 The switch value might be direct, a variable or an expression.

'while' statement in C
Consider a situation in which we execute a single statement or block of statements repeatedly for the
required number of times. Such kind of problems can be solved using looping statements in C. For
example, assume a situation where we print a message 100 times. If we want to perform that task
without using looping statements, we have to either write 100 printf statements or we have to write
the same message 100 times in a single printf statement. Both are complex methods. The same task
can be performed very easily using looping statements.

Prepared By B.Naveen Kumar (M.Tech.) JNTUH, Rajanna Siricilla. Page 58 of 210


I B.Tech EEE,CE,ME (R22) Unit - II C-Programming with Data Structures

The looping statements are used to execute a single statement or block of statements
repeatedly until the given condition is FALSE.

C language provides three looping statements...

 while statement
 do-while statement
 for statement

while Statement
The while statement is used to execute a single statement or block of statements repeatedly as long as
the given condition is TRUE. The while statement is also known as Entry control looping statement.
The while statement has the following syntax...

Naveen(jntr)
The while statement has the following execution flow diagram...

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

Example Program | Program to display even numbers upto 10.


#include<stdio.h>
#include<conio.h>
void main(){
int n = 0;
clrscr() ;
printf("Even numbers upto 10\n");
while( n <= 10 )
{
if( n%2 == 0)
printf("%d\t", n) ;
n++ ;
}
getch() ;
}
Prepared By B.Naveen Kumar (M.Tech.) JNTUH, Rajanna Siricilla. Page 59 of 210
I B.Tech EEE,CE,ME (R22) Unit - II C-Programming with Data Structures

Output:

MOST IMPORTANT POINTS TO BE REMEMBERED


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

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


 If the condition contains a variable, it must be assigned a value before it is used.
 The value of the variable used in condition must be modified according to the requirement inside the
while block.
 In a while statement, the condition may be a direct integer value, a variable or a condition.
 A while statement can be an empty statement.

Naveen(jntr)
'do-while' statement in C
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...

The do-while statement has the following execution flow diagram...

Prepared By B.Naveen Kumar (M.Tech.) JNTUH, Rajanna Siricilla. Page 60 of 210


I B.Tech EEE,CE,ME (R22) Unit - II C-Programming with Data Structures

At first, the single statement or block of statements which are 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 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 while block.
Example Program | Program to display even numbers upto 10.
#include<stdio.h>
#include<conio.h>

void main(){
int n = 0;
clrscr() ;
printf("Even numbers upto 10\n");
do
{
if( n%2 == 0)
printf("%d\t", n) ;
n++ ;
}while( n <= 10 ) ;
Naveen(jntr)
getch() ;
}
Output:

MOST IMPORTANT POINTS TO BE REMEMBERED


When we use the do-while statement, we must follow the following...

 Both do and while are keywords so they must be used only in lower case letters.
 If the condition contains a variable, it must be assigned a value before it is used.
 The value of the variable used in the condition must be modified according to the requirement inside
the do block.
 In a do-while statement, the condition may be a direct integer value, a variable or a condition.
 A do-while statement can be an empty statement.
 In do-while, the block of statements is executed at least once.

'for' statement in C
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...

Prepared By B.Naveen Kumar (M.Tech.) JNTUH, Rajanna Siricilla. Page 61 of 210


I B.Tech EEE,CE,ME (R22) Unit - II C-Programming with Data Structures

Naveen(jntr)
At first, the for statement executes initialization followed by condition evaluation. If the condition is
evaluated to TRUE, the single statement or block of statements of for statement are executed. Once
the execution gets completed, the modification statement is executed and again the condition is
evaluated. If it is TRUE, again the same statements are executed. The same process is repeated until
the condition is evaluated to FALSE. Whenever the condition is evaluated to FALSE, the execution
control moves out of the for block.
Example Program | Program to display even numbers upto 10.
#include<stdio.h>
#include<conio.h>
void main(){
int n ;
clrscr() ;
printf("Even numbers upto 10\n");
for( n = 0 ; n <= 10 ; n++ )
{
if( n%2 == 0)
printf("%d\t", n) ;
}
getch() ;
}
Output:

Prepared By B.Naveen Kumar (M.Tech.) JNTUH, Rajanna Siricilla. Page 62 of 210


I B.Tech EEE,CE,ME (R22) Unit - II C-Programming with Data Structures

MOST IMPORTANT POINTS TO BE REMEMBERED


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

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


 Every for statement must be provided with initialization, condition, and modification (They can be
empty but must be separated with ";")
Ex: for ( ; ; ) or for ( ; condition ; modification ) or for ( ; condition ; )
 In for statement, the condition may be a direct integer value, a variable or a condition.
 The for statement can be an empty statement.

break, continue and goto in C


In c, there are control statements that do not need any condition to control the program execution
flow. These control statements are called as unconditional control statements. C programming
language provides the following unconditional control statements...

 break
 continue

Naveen(jntr)
 goto
The above three statements do not need any condition to control the program execution flow.

break statement
In C, the break statement is used to perform the following two things...

1. break statement is used to terminate the switch case statement


2. break statement is also used to terminate looping statements like while,
do-while and for.
When a break statement is encountered inside the switch case statement, the execution control
moves out of the switch statement directly. For example, consider the following program.
Example Program to perform all arithmetic operations using switch
statement.
#include<stdio.h>
#include<conio.h>
void main(){
int number1, number2, result ;
char operator;
clrscr() ;
printf("Enter any two integer numbers: ") ;
scanf("%d%d", &number1, &number2) ;
printf("Please enter any arithmetic operator: ");
operator = getchar();
switch(operator)
{
case '+': result = number1 + number2 ;
printf("Addition = %d", result) ;
break;
case '-': result = number1 - number2 ;
printf("Subtraction = %d", result) ;
break;
case '*': result = number1 * number2 ;
printf("Multiplication = %d", result) ;
break;

Prepared By B.Naveen Kumar (M.Tech.) JNTUH, Rajanna Siricilla. Page 63 of 210


I B.Tech EEE,CE,ME (R22) Unit - II C-Programming with Data Structures

case '/': result = number1 / number2 ;


printf("Division = %d", result) ;
break;
case '%': result = number1 % number2 ;
printf("Remainder = %d", result) ;
break;
default: printf("\nWrong selection!!!") ;
}
getch() ;
}
Output:

When the break statement is encountered inside the looping statement, the execution control moves
out of the looping statements. The break statement execution is as shown in the following figure.

Naveen(jntr)

For example, consider the following example program...


Example Program for break statement.
#include<stdio.h>
#include<conio.h>
void main(){
char ch ;
clrscr() ;
do
{
printf("Enter Y / N : ") ;
scanf("%c", &ch) ;
if(ch == 'Y')
{
printf("Okay!!! Repeat again !!!\n") ;
}
else
{
printf("Okay !!! Breaking the loop !!!") ;
break ;
}
} while( 1 ) ;
getch() ;
}
Prepared By B.Naveen Kumar (M.Tech.) JNTUH, Rajanna Siricilla. Page 64 of 210
I B.Tech EEE,CE,ME (R22) Unit - II C-Programming with Data Structures

Output:

continue statement
The continue statement is used to move the program execution control to the beginning of the
looping statement. When the continue statement is encountered in a looping statement, the
execution control skips the rest of the statements in the looping block and directly jumps to the
beginning of the loop. The continue statement can be used with looping statements like while, do-
while and for.
When we use continue statement with while and do-while statements the execution control directly
jumps to the condition. When we use continue statement with for statement the execution control
directly jumps to the modification portion (increment/decrement/any modification) of the for loop.
The continue statement execution is as shown in the following figure.

Naveen(jntr)

Example Program Program to illustrate continue statement.


#include<stdio.h>
#include<conio.h>
void main(){
int number ;
clrscr() ;
while( 1 )
{
printf("Enter any integer number: ") ;
scanf("%d", &number) ;
if(number%2 == 0)
{
printf("Entered number is EVEN!!! Try another number!!!\n") ;
continue ;
}
else
{
printf("You have entered ODD number!!! Bye!!!") ;
exit(0) ;
}
}
getch() ;
Prepared By B.Naveen Kumar (M.Tech.) JNTUH, Rajanna Siricilla. Page 65 of 210
I B.Tech EEE,CE,ME (R22) Unit - II C-Programming with Data Structures

Output:

goto statement
The goto statement is used to jump from one line to another line in the program.
Using goto statement we can jump from top to bottom or bottom to top. To jump from one line to
another line, the 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 with the specified label.
Example Program for goto statement.

Naveen(jntr)
#include<stdio.h>
#include<conio.h>
void main(){
clrscr() ;
printf("We are at first printf statement!!!\n") ;
goto last ;
printf("We are at second printf statement!!!\n") ;
printf("We are at third printf statement!!!\n") ;
last: printf("We are at last printf statement!!!\n") ;
getch() ;
}

Output:

MOST IMPORTANT POINTS TO BE REMEMBERED

When we use break, continue and goto statements, 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 inside the

switch case or looping statements.

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

 The continue statement is used only within looping statements.

Prepared By B.Naveen Kumar (M.Tech.) JNTUH, Rajanna Siricilla. Page 66 of 210


I B.Tech EEE,CE,ME (R22) Unit - II C-Programming with Data Structures

 The continue statement can be used with if statement, only if that if statement is written inside the

looping statements.

 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 for, etc.

Designing Structured Programs in C


Structured programming is a programming technique in which a larger program is divided into smaller
subprograms to make it easy to understand, easy to implement and makes the code reusable, etc.
Structured programming enables code reusability. Code reusability is a method of writing code once
and using it many times. Using a structured programming technique, we write the code once and use it
many times. Structured programming also makes the program easy to understand, improves the
quality of the program, easy to implement and reduces time.

In C, the structured programming can be designed using functions concept. Using functions concept,

Naveen(jntr)
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 in C
When we write a program to solve a larger problem, we divide that larger problem into smaller
subproblems and are solved individually to make the program easier. In C, this concept is
implemented using functions. Functions are used to divide a larger program into smaller subprograms
such that the program becomes easy to understand and easy to implement. A function is defined as
follows...

Function is a subpart of a program used to perform a specific task and is executed individually.

Every C program must contain at least one function called main(). However, a program may also
contain other functions.

Every function in C has the following...

 Function Declaration (Function Prototype)


 Function Definition
 Function Call

Function Declaration
The function declaration tells the compiler about function name, the data type of the return value and
parameters. The function declaration is also called a function prototype. The function declaration is
performed before the main function or inside the main function or any other function.
Function declaration syntax -
returnType functionName(parametersList);
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 Definition
Prepared By B.Naveen Kumar (M.Tech.) JNTUH, Rajanna Siricilla. Page 67 of 210
I B.Tech EEE,CE,ME (R22) Unit - II C-Programming with Data Structures

The function definition provides the actual code of that function. The function definition is also known
as the body of the function. The actual task of the function is implemented in the function definition.
That means the actual instructions to be performed by a function are written in function definition.
The actual instructions of a function are written inside the braces "{ }". The function definition is
performed before the main function or after the main function.
Function definition syntax -
returnType functionName(parametersList)
{
Actual code...
}

Function Call
The function call tells the compiler when to execute the function definition. When a function call is
executed, the execution control jumps to the function definition where the actual code gets executed
and returns to the same functions call once the execution completes. The function call is performed
inside the main function or any other function or inside the function itself.
Function call syntax -
Naveen(jntr)
functionName(parameters);
ADVANTAGES OF FUNCTIONS

 Using funcions we can implement modular programming.


 Functions make the program more readable and understandable.
 Using functions the program implementation becomes easy.
 Once a function is created it can be used many times (code re-usability).
 Using functions larger programs can be divided into smaller modules.

Types of Functions in C
In C Programming Language, based on providing the function definition, functions are divided into two
types. Those are as follows...

 System Defined Functions


 User Defined Functions

System Defined Functions


The C Programming Language provides pre-defined functions to make programming easy. These pre-
defined functions are known as syatem defined functions. The system defined function is defined as
follows...
The function whose definition is defined by the system is called as system defined function.
The system defined functions are also called as Library Functions or Standard Functions or Pre-
Defined Functions. The implementation of system defined functions is already defined by the system.
In C, all the system defined functions are defined inside the header files like
stdio.h, conio.h, math.h, string.h etc., For example, the funtions printf() and scanf() are defined in
the header file called stdio.h.
Whenever we use system defined functions in the program, we must include the respective header file
using #include statement. For example, if we use a system defined function sqrt() in the program, we
must include the header file called math.h because the function sqrt() is defined in math.h.
Points to be Remembered

 System defined functions are declared in header files


 System defined functions are implemented in .dll files. (DLL stands for Dynamic Link Library).
Prepared By B.Naveen Kumar (M.Tech.) JNTUH, Rajanna Siricilla. Page 68 of 210
I B.Tech EEE,CE,ME (R22) Unit - II C-Programming with Data Structures

 To use system defined functions the respective header file must be included.

User Defined Functions


In C programming language, users can also create their own functions. The functions that are created
by users are called as user defined functions. The user defined function is defined as follows...
The function whose definition is defined by the user is called as user defined function.
That means the function that is implemented by user is called as user defined function. For example,
the function main is implemented by user so it is called as user defined function.
In C every user defined function must be declared and implemented. Whenever we make function call
the function definition gets executed. For example, consider the following program in which we create
a fucntion called addition with two paramenters and a return value.
Example Program
#include<stdio.h>
#include<conio.h>
void main(){
int num1, num2, result ;
int addition(int,int) ; // function declaration

Naveen(jntr)
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 ;
}
In the above example program, the function declaration statement "int addition(int,int)" tells the
compiler that there is a function with name addition which takes two integer values as parameters
and returns an integer value. The function call statement takes the execution control to
the additon() definition along with values of num1 and num2. 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.
Based on the data flow between the calling function and called function, the functions are classified as
follows...

 Function without Parameters and without Return value


 Function with Parameters and without Return value
 Function without Parameters and with Return value
 Function with Parameters and with Return value

Function without Parameters and without Return value


Prepared By B.Naveen Kumar (M.Tech.) JNTUH, Rajanna Siricilla. Page 69 of 210
I B.Tech EEE,CE,ME (R22) Unit - II C-Programming with Data Structures

In this type of functions there is no data transfer between calling function and called function. Simply
the execution control jumps from calling-function to called function and executes called function, and
finally comes back to the calling function. For example, consider the following program...
Example Program
#include<stdio.h>
#include<conio.h>
void main(){
void addition() ; // function declaration
clrscr() ;
addition() ; // function call
getch() ;
}
void addition() // function definition
{
int num1, num2 ;
printf("Enter any two integer numbers : ") ;
scanf("%d%d", &num1, &num2);

}
printf("Sum = %d", num1+num2 ) ;
Naveen(jntr)
Function with Parameters and without Return value
In this type of functions there is data transfer from calling-function to called function (parameters) but
there is no data transfer from called function to calling-function (return value). The execution control
jumps from calling-function to called function along with the parameters and executes called function,
and finally comes back to the calling function. For example, consider the following program...
Example Program
#include<stdio.h>
#include<conio.h>
void main(){
int num1, num2 ;
void addition(int, int) ; // function declaration
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
{
printf("Sum = %d", a+b ) ;
}

Function without Parameters and with Return value


In this type of functions there is no data transfer from calling-function to called-function (parameters)
but there is data transfer from called function to calling-function (return value). The execution control
jumps from calling-function to called function and executes called function, and finally comes back to
the calling function along with a return value. For example, consider the following program...
Example Program
#include<stdio.h>

Prepared By B.Naveen Kumar (M.Tech.) JNTUH, Rajanna Siricilla. Page 70 of 210


I B.Tech EEE,CE,ME (R22) Unit - II C-Programming with Data Structures

#include<conio.h>
void main(){
int result ;
int addition() ; // function declaration
clrscr() ;
result = addition() ; // function call
printf("Sum = %d", result) ;
getch() ;
}
int addition() // function definition
{
int num1, num2 ;
printf("Enter any two integer numbers : ") ;
scanf("%d%d", &num1, &num2);
return (num1+num2) ;
}

Naveen(jntr)
Function with Parameters and with Return value
In this type of functions there is data transfer from calling-function to called-function (parameters) and
also from called function to calling-function (return value). The execution control jumps from calling-
function to called function along with parameters and executes called function, and finally comes back
to the calling function along with a return value. For example, consider the following program...
Example Program
#include<stdio.h>
#include<conio.h>
void main(){
int num1, num2, result ;
int addition(int, int) ; // function declaration
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) ;
}
Points to be Remembered

 The parameters specified in calling function are said to be Actual Parameters.


 The parameters declared in called function are said to be Formal Parameters.
 The value of actual parameters is always copied into formal parameters.

Parameter Passing in C
When a function gets executed in the program, the execution control is transferred from calling-
function to called function and executes function definition, and finally comes back to the calling

Prepared By B.Naveen Kumar (M.Tech.) JNTUH, Rajanna Siricilla. Page 71 of 210


I B.Tech EEE,CE,ME (R22) Unit - II C-Programming with Data Structures

function. When the execution control is transferred from calling-function to called-function it may carry
one or number of data values. These data values are called as parameters.
Parameters are the data values that are passed from calling function to called function.
In C, there are two types of parameters and they are as follows...

 Actual Parameters
 Formal Parameters
The actual parameters are the parameters that are speficified in calling function. The formal
parameters are the parameters that are declared at called function. When a function gets executed,
the copy of actual parameter values are copied into formal parameters.
In C Programming Language, there are two methods to pass parameters from calling function to called
function and they are as follows...

 Call by Value
 Call by Reference

Call by Value
In call by value parameter passing method, the copy of actual parameter values are copied to formal

Naveen(jntr)
parameters and these formal parameters are used in called function. The changes made on the
formal parameters does not effect the values of actual parameters. That means, after the
execution control comes back to the calling function, the actual parameter values remains same. For
example consider the following program...
Example Program
#include<stdio.h>
#include<conio.h>
void main(){
int num1, num2 ;
void swap(int,int) ; // function declaration
clrscr() ;
num1 = 10 ;
num2 = 20 ;
printf("\nBefore swap: num1 = %d, num2 = %d", num1, num2) ;
swap(num1, num2) ; // calling function
printf("\nAfter swap: num1 = %d\nnum2 = %d", num1, num2);
getch() ;
}
void swap(int a, int b) // called function
{
int temp ;
temp = a ;
a=b;
b = temp ;
}

Output:

Prepared By B.Naveen Kumar (M.Tech.) JNTUH, Rajanna Siricilla. Page 72 of 210


I B.Tech EEE,CE,ME (R22) Unit - II C-Programming with Data Structures

In the above example program, the variables num1 and num2 are called actual parameters and the
variables a and b are called formal parameters. The value of num1 is copied into a and the value of
num2 is copied into b. The changes made on variables a and b does not effect the values
of num1 and num2.

Call by Reference
In Call by Reference parameter passing method, the memory location address of the actual
parameters is copied to formal parameters. This address is used to access the memory locations of the
actual parameters in called function. In this method of parameter passing, the formal parameters
must be pointer variables.
That means in call by reference parameter passing method, the address of the actual parameters is
passed to the called function and is recieved 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 ; Naveen(jntr)
void swap(int *,int *) ; // function declaration
clrscr() ;
num1 = 10 ;
num2 = 20 ;
printf("\nBefore swap: num1 = %d, num2 = %d", num1, num2) ;
swap(&num1, &num2) ; // calling function
printf("\nAfter swap: num1 = %d, num2 = %d", num1, num2);
getch() ;
}
void swap(int *a, int *b) // called function
{
int temp ;
temp = *a ;
*a = *b ;
*b = temp ;
}

Output:

In the above example program, the addresses of variables num1 and num2 are copied to pointer
variables a and b. The changes made on the pointer variables a and b in called function effects the
values of actual parameters num1 and num2 in calling function.

Inter Function Communication in C


When a function gets executed in the program, the execution control is transferred from calling a
function to called function and executes function definition, and finally comes back to the calling
function. In this process, both calling and called functions have to communicate with each other to

Prepared By B.Naveen Kumar (M.Tech.) JNTUH, Rajanna Siricilla. Page 73 of 210


I B.Tech EEE,CE,ME (R22) Unit - II C-Programming with Data Structures

exchange information. The process of exchanging information between calling and called functions is
called inter-function communication.

In C, the inter function communication is classified as follows...

 Downward Communication
 Upward Communication
 Bi-directional Communication

Downward Communication
In this type of inter function communication, the data is transferred from calling function to called
function but not from called function to calling function. The functions with parameters and without
return value are considered under downward communication. In the case of downward
communication, the execution control jumps from calling function to called function along with
parameters and executes the function definition,and finally comes back to the calling function without
any return value. For example consider the following program...
Example Program
#include<stdio.h>

Naveen(jntr)
#include<conio.h>
void main(){
int num1, num2 ;
void addition(int, int) ; // function declaration
clrscr() ;
num1 = 10 ;
num2 = 20 ;
printf("\nBefore swap: num1 = %d, num2 = %d", num1, num2) ;
addition(num1, num2) ; // calling function
getch() ;
}
void addition(int a, int b) // called function
{
printf("SUM = %d", a+b) ;
}

Output:

Upward Communication
In this type of inter-function communication, the data is transferred from called function to calling-
function but not from calling-function to called-function. The functions without parameters and with
return value are considered under upward communication. In the case of upward communication, the
execution control jumps from calling-function to called-function without parameters and executes the
function definition, and finally comes back to the calling function along with a return value. For
example, consider the following program...
Example Program
#include<stdio.h>
#include<conio.h>

Prepared By B.Naveen Kumar (M.Tech.) JNTUH, Rajanna Siricilla. Page 74 of 210


I B.Tech EEE,CE,ME (R22) Unit - II C-Programming with Data Structures

void main(){
int result ;
int addition() ; // function declaration
clrscr() ;
result = addition() ; // calling function
printf("SUM = %d", result) ;
getch() ;
}
int addition() // called function
{
int num1, num2 ;
num1 = 10;
num2 = 20;
return (num1+num2) ;
}

Output:

Naveen(jntr)
Bi - Directional Communication
In this type of inter-function communication, the data is transferred from calling-function to called
function and also from called function to calling-function. The functions with parameters and with
return value are considered under bi-directional communication. In the case of bi-directional
communication, the execution control jumps from calling-function to called function along with
parameters and executes the function definition and finally comes back to the calling function along
with a return value. For example, consider the following program...
Example Program
#include<stdio.h>
#include<conio.h>
void main(){
int num1, num2, result ;
int addition(int, int) ; // function declaration
clrscr() ;
num1 = 10 ;
num2 = 20 ;
result = addition(num1, num2) ; // calling function
printf("SUM = %d", result) ;
getch() ;
}
int addition(int a, int b) // called function
{
return (a+b) ;
}

Output:

Prepared By B.Naveen Kumar (M.Tech.) JNTUH, Rajanna Siricilla. Page 75 of 210


I B.Tech EEE,CE,ME (R22) Unit - II C-Programming with Data Structures

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

stdio.h
Naveen(jntr)
Purpose

Provides functions to perform standard I/O


Functions

printf(), scanf()
operations

conio.h Provides functions to perform console I/O clrscr(), getch()


operations

math.h Provides functions to perform mathematical sqrt(), pow()


operations

string.h Provides functions to handle string data values strlen(), strcpy()

stdlib.h Provides functions to perform general calloc(), malloc()


functions/td>

time.h Provides functions to perform operations on time time(), localtime()


and date

ctype.h Provides functions to perform - testing and isalpha(), islower()


mapping of character data values

setjmp.h Provides functions that are used in function calls setjump(),


longjump()

signal.h Provides functions to handle signals during signal(), raise()


program execution

assert.h Provides Macro that is used to verify assumptions assert()


made by the program

Prepared By B.Naveen Kumar (M.Tech.) JNTUH, Rajanna Siricilla. Page 76 of 210


I B.Tech EEE,CE,ME (R22) Unit - II C-Programming with Data Structures

Header Example
File Purpose Functions

locale.h Defines the location specific settings such as date setlocale()


formats and currency symbols

stdarg.h Used to get the arguments in a function if the va_start(), va_end(),


arguments are not specified by the function va_arg()

errno.h Provides macros to handle the system calls Error, errno

graphics.h Provides functions to draw graphics. circle(), rectangle()

float.h Provides constants related to floating point data


values

stddef.h Defines various variable types

limits.h Naveen(jntr)
Defines the maximum and minimum values of
various variable types like char, int and long

Arrays in C
When we work with a large number of data values we need that any number of different variables. As
the number of variables increases, the complexity of the program also increases and so the
programmers get confused with the variable names. There may be situations where we need to work
with a large number of similar data values. To make this work easier, C programming language
provides a concept called "Array".
An array is a special type of variable used to store multiple values of same data type at a time.
An array can also be defined as follows...
An array is a collection of similar data items stored in continuous memory locations with single
name.

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

We use the following general syntax to create an array...

datatype arrayName [ size ] ;


Syntax for creating an array with size and initial values

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


Syntax for creating an array without size and with initial values

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


In the above syntax, the datatype specifies the type of values we store in that array and size specifies
the maximum number of values that can be stored in that array.
Example Code
int a [3] ;

Prepared By B.Naveen Kumar (M.Tech.) JNTUH, Rajanna Siricilla. Page 77 of 210


I B.Tech EEE,CE,ME (R22) Unit - II C-Programming with Data Structures

Here, the compiler allocates 6 bytes of contiguous memory locations with a single name 'a' and tells
the compiler to store three different integer values (each in 2 bytes of memory) into that 6 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
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


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

arrayName [ indexValue ] ;
For the above example the individual elements can be denoted as follows...

For example, if we want to assign a value to the second memory location of above array 'a', we use the
following statement...
Example Code
a [1] = 100 ;
The result of the above assignment statement is as follows...

Types of Arrays in C
In c programming language, arrays are classified into two types. They are as follows...

1. Single Dimensional Array / One Dimensional Array


2. Multi Dimensional Array

Single Dimensional Array


Prepared By B.Naveen Kumar (M.Tech.) JNTUH, Rajanna Siricilla. Page 78 of 210
I B.Tech EEE,CE,ME (R22) Unit - II C-Programming with Data Structures

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. Single dimensional arrays are also called as one-
dimensional arrays, Linear Arrays or simply 1-D Arrays.
Declaration of Single Dimensional Array
We use the following general syntax for declaring a single dimensional array...

datatype arrayName [ size ] ;


Example Code
int rollNumbers [60] ;
The above declaration of single dimensional array reserves 60 continuous memory locations of 2 bytes
each with the name rollNumbers and tells the compiler to allow only integer values into those
memory locations.
Initialization of Single Dimensional Array
We use the following general syntax for declaring and initializing a single dimensional array with size
and initial values.

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


Example Code
Naveen(jntr)
int marks [6] = { 89, 90, 76, 78, 98, 86 } ;
The above declaration of single dimensional array reserves 6 contiguous memory locations of 2 bytes
each with the name marks and initializes with value 89 in first memory location, 90 in second memory
location, 76 in third memory location, 78 in fourth memory location, 98 in fifth memory location and 86
in sixth memory location.
We can also use the following general syntax to intialize a single dimensional array without specifying
size and with initial values...

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


The array must be initialized if it is created without specifying any size. In this case, the size of the array
is decided based on the number of values initialized.
Example Code
int marks [] = { 89, 90, 76, 78, 98, 86 } ;

char studentName [] = "jntuhucer" ;


In the above example declaration, size of the array 'marks' is 6 and the size of the
array 'studentName' is 16. This is because in case of character array, compiler stores one exttra
character called \0 (NULL) at the end.

Accessing Elements of Single Dimensional Array


In c programming language, to access the elements of single dimensional array we use array name
followed by index value of the element that to be accessed. Here the index value must be enclosed in
square braces. Index value of an element in an array is the reference number given to each element at
the time of memory allocation. The index value of single dimensional array starts with zero (0) for first
element and incremented by one for each element. The index value in an array is also called
as subscript or indices.

We use the following general syntax to access individual elements of single dimensional array...

arrayName [ indexValue ]
Example Code
marks [2] = 99 ;
In the above statement, the third element of 'marks' array is assinged with value '99'.

Prepared By B.Naveen Kumar (M.Tech.) JNTUH, Rajanna Siricilla. Page 79 of 210


I B.Tech EEE,CE,ME (R22) Unit - II C-Programming with Data Structures

Example
Following is the C program on compile time initialization −
Live Demo

#include<stdio.h>
int main ( ){
int a[5] = {10,20,30,40,50};
int i;
printf ("elements of the array are");
for ( i=0; i<5; i++)
printf ("%d", a[i]);
}

Output
Upon execution, you will receive the following output −
Elements of the array are
10 20 30 40 50
Naveen(jntr)
Example
Following is the C program on runtime initialization −
Live Demo

#include<stdio.h>
main ( ){
int a[5],i;
printf ("enter 5 elements");
for ( i=0; i<5; i++)
scanf("%d", &a[i]);
printf("elements of the array are");
for (i=0; i<5; i++)
printf("%d", a[i]);
}

Output
The output is as follows −
enter 5 elements 10 20 30 40 50
elements of the array are : 10 20 30 40 50
Note
 The output of compile time initialised program will not change during different
runs of the program.
 The output of run time initialised program will change for different runs
because, user is given a chance of accepting different values during execution.

Prepared By B.Naveen Kumar (M.Tech.) JNTUH, Rajanna Siricilla. Page 80 of 210


I B.Tech EEE,CE,ME (R22) Unit - II C-Programming with Data Structures

Example
Following is another C program for one dimensional array −
Live Demo

#include <stdio.h>
int main(void){
int a[4];
int b[4] = {1};
int c[4] = {1,2,3,4};
int i; //for loop counter
//printing all elements of all arrays
printf("
Array a:
");
for( i=0; i<4; i++ )
printf("arr[%d]: %d
",i,a[i]); Naveen(jntr)
printf("
Array b:
");
for( i=0; i<4; i++)
printf("arr[%d]: %d
",i,b[i]);
printf("
Array c:
");
for( i=0; i<4; i++ )
printf("arr[%d]: %d
",i, c[i]);
return 0;
}

Output
The output is stated below −
Array a:
arr[0]: 8
arr[1]: 0
arr[2]: 54
arr[3]: 0
Array b:
arr[0]: 1
arr[1]: 0
arr[2]: 0
arr[3]: 0
Prepared By B.Naveen Kumar (M.Tech.) JNTUH, Rajanna Siricilla. Page 81 of 210
I B.Tech EEE,CE,ME (R22) Unit - II C-Programming with Data Structures

Array c:
arr[0]: 1
arr[1]: 2
arr[2]: 3
arr[3]: 4

Multi Dimensional Array


An array of arrays is called as multi dimensional array. In simple words, an array created with more
than one dimension (size) is called as multi dimensional array. Multi dimensional array can be of two
dimensional array or three dimensional array or four dimensional array or more...

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

Declaration of Two Dimensional Array

Naveen(jntr)
We use the following general syntax for declaring a two dimensional array...

datatype arrayName [ rowSize ] [ columnSize ] ;


Example Code
int matrix_A [2][3] ;
The above declaration of two dimensional array reserves 6 continuous memory locations of 2 bytes
each in the form of 2 rows and 3 columns.
Initialization of Two Dimensional Array
We use the following general syntax for declaring and initializing a two dimensional array with specific
number of rows and coloumns with initial values.
datatype arrayName [rows][colmns] = {{r1c1value, r1c2value, ...},{r2c1, r2c2,...}...} ;
Example Code
int matrix_A [2][3] = { {1, 2, 3},{4, 5, 6} } ;
The above declaration of two-dimensional array reserves 6 contiguous memory locations of 2 bytes
each in the form of 2 rows and 3 columns. And the first row is initialized with values 1, 2 & 3 and
second row is initialized with values 4, 5 & 6.
We can also initialize as follows...
Example Code
int matrix_A [2][3] = {
{1, 2, 3},
{4, 5, 6}
} ;
Accessing Individual Elements of Two Dimensional Array
In a c programming language, to access elements of a two-dimensional array we use array name
followed by row index value and column index value of the element that to be accessed. Here the row
and column index values must be enclosed in separate square braces. In case of the two-dimensional
array the compiler assigns separate index values for rows and columns.

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

arrayName [ rowIndex ] [ columnIndex ]


Example Code
matrix_A [0][1] = 10 ;

Prepared By B.Naveen Kumar (M.Tech.) JNTUH, Rajanna Siricilla. Page 82 of 210


I B.Tech EEE,CE,ME (R22) Unit - II C-Programming with Data Structures

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

Multi-dimensional Arrays in C
C programming language allows multidimensional arrays. Here is the general form of a
multidimensional array declaration −
type name[size1][size2]...[sizeN];
For example, the following declaration creates a three dimensional integer array −
int threedim[5][10][4];
Two-dimensional Arrays
The simplest form of multidimensional array is the two-dimensional array. A two-
dimensional array is, in essence, a list of one-dimensional arrays. To declare a two-
dimensional integer array of size [x][y], you would write something as follows −
type arrayName [ x ][ y ];

Naveen(jntr)
Where type can be any valid C data type and arrayName will be a valid C identifier. A two-
dimensional array can be considered as a table which will have x number of rows and y
number of columns. A two-dimensional array a, which contains three rows and four columns
can be shown as follows −

Thus, every element in the array a is identified by an element name of the form a[ i ][ j ],
where 'a' is the name of the array, and 'i' and 'j' are the subscripts that uniquely identify each
element in 'a'.

Initializing Two-Dimensional Arrays


Multidimensional arrays may be initialized by specifying bracketed values for each row.
Following is an array with 3 rows and each row has 4 columns.

int a[3][4] = {
{0, 1, 2, 3} , /* initializers for row indexed by 0 */
{4, 5, 6, 7} , /* initializers for row indexed by 1 */
{8, 9, 10, 11} /* initializers for row indexed by 2 */
};

The nested braces, which indicate the intended row, are optional. The following initialization
is equivalent to the previous example −
int a[3][4] = {0,1,2,3,4,5,6,7,8,9,10,11};
Accessing Two-Dimensional Array Elements
An element in a two-dimensional array is accessed by using the subscripts, i.e., row index
and column index of the array. For example −
int val = a[2][3];
Prepared By B.Naveen Kumar (M.Tech.) JNTUH, Rajanna Siricilla. Page 83 of 210
I B.Tech EEE,CE,ME (R22) Unit - II C-Programming with Data Structures

The above statement will take the 4th element from the 3rd row of the array. You can verify
it in the above figure. Let us check the following program where we have used a nested loop
to handle a two-dimensional array −
Live Demo

#include <stdio.h>

int main () {

/* an array with 5 rows and 2 columns*/


int a[5][2] = { {0,0}, {1,2}, {2,4}, {3,6},{4,8}};
int i, j;

/* output each array element's value */


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

for ( j = 0; j < 2; j++ ) {


printf("a[%d][%d] = %d\n", i,j, a[i][j] );
}
}

return 0;
Naveen(jntr)
}

When the above code is compiled and executed, it produces the following result −
a[0][0]: 0
a[0][1]: 0
a[1][0]: 1
a[1][1]: 2
a[2][0]: 2
a[2][1]: 4
a[3][0]: 3
a[3][1]: 6
a[4][0]: 4
a[4][1]: 8
As explained above, you can have arrays with any number of dimensions, although it is likely
that most of the arrays you create will be of one or two dimensions.

Example 1: Two-dimensional array to store and print values


// C program to store temperature of two cities of a week and display it.
#include <stdio.h>
const int CITY = 2;
const int WEEK = 7;
int main()
{
int temperature[CITY][WEEK];

// Using nested loop to store values in a 2d array


for (int i = 0; i < CITY; ++i)
{
for (int j = 0; j < WEEK; ++j)
{
printf("City %d, Day %d: ", i + 1, j + 1);
Prepared By B.Naveen Kumar (M.Tech.) JNTUH, Rajanna Siricilla. Page 84 of 210
I B.Tech EEE,CE,ME (R22) Unit - II C-Programming with Data Structures

scanf("%d", &temperature[i][j]);
}
}
printf("\nDisplaying values: \n\n");

// Using nested loop to display vlues of a 2d array


for (int i = 0; i < CITY; ++i)
{
for (int j = 0; j < WEEK; ++j)
{
printf("City %d, Day %d = %d\n", i + 1, j + 1, temperature[i][j]);
}
}
return 0;
}
Run Code

Output

City
City
1,
1,
Day
Day
1:
2:
33
34
Naveen(jntr)
City 1, Day 3: 35
City 1, Day 4: 33
City 1, Day 5: 32
City 1, Day 6: 31
City 1, Day 7: 30
City 2, Day 1: 23
City 2, Day 2: 22
City 2, Day 3: 21
City 2, Day 4: 24
City 2, Day 5: 22
City 2, Day 6: 25
City 2, Day 7: 26

Displaying values:

City 1, Day 1 = 33
City 1, Day 2 = 34
City 1, Day 3 = 35
City 1, Day 4 = 33
City 1, Day 5 = 32
City 1, Day 6 = 31
City 1, Day 7 = 30
City 2, Day 1 = 23
City 2, Day 2 = 22
City 2, Day 3 = 21
City 2, Day 4 = 24
City 2, Day 5 = 22
City 2, Day 6 = 25
City 2, Day 7 = 26

Prepared By B.Naveen Kumar (M.Tech.) JNTUH, Rajanna Siricilla. Page 85 of 210


I B.Tech EEE,CE,ME (R22) Unit - II C-Programming with Data Structures

Example 2: Sum of two matrices


// C program to find the sum of two matrices of order 2*2

#include <stdio.h>
int main()
{
float a[2][2], b[2][2], result[2][2];

// Taking input using nested for loop


printf("Enter elements of 1st matrix\n");
for (int i = 0; i < 2; ++i)
for (int j = 0; j < 2; ++j)

Naveen(jntr)
{
printf("Enter a%d%d: ", i + 1, j + 1);
scanf("%f", &a[i][j]);
}

// Taking input using nested for loop


printf("Enter elements of 2nd matrix\n");
for (int i = 0; i < 2; ++i)
for (int j = 0; j < 2; ++j)
{
printf("Enter b%d%d: ", i + 1, j + 1);
scanf("%f", &b[i][j]);
}

// adding corresponding elements of two arrays


for (int i = 0; i < 2; ++i)
for (int j = 0; j < 2; ++j)
{
result[i][j] = a[i][j] + b[i][j];
}

// Displaying the sum


printf("\nSum Of Matrix:");

for (int i = 0; i < 2; ++i)


for (int j = 0; j < 2; ++j)
{
printf("%.1f\t", result[i][j]);

if (j == 1)
printf("\n");
}
return 0;
}

Prepared By B.Naveen Kumar (M.Tech.) JNTUH, Rajanna Siricilla. Page 86 of 210


I B.Tech EEE,CE,ME (R22) Unit - II C-Programming with Data Structures

Run Code

Output

Enter elements of 1st matrix


Enter a11: 2;
Enter a12: 0.5;
Enter a21: -1.1;
Enter a22: 2;
Enter elements of 2nd matrix
Enter b11: 0.2;
Enter b12: 0;
Enter b21: 0.23;
Enter b22: 23;

Sum Of Matrix:
2.2 0.5
-0.9 25.0

Naveen(jntr)

Example 3: Three-dimensional array


// C Program to store and print 12 values entered by the user

#include <stdio.h>
int main()
{
int test[2][3][2];

printf("Enter 12 values: \n");

for (int i = 0; i < 2; ++i)


{
for (int j = 0; j < 3; ++j)
{
for (int k = 0; k < 2; ++k)
{
scanf("%d", &test[i][j][k]);
}
}
}

// Printing values with the proper index.

printf("\nDisplaying values:\n");
for (int i = 0; i < 2; ++i)
{
Prepared By B.Naveen Kumar (M.Tech.) JNTUH, Rajanna Siricilla. Page 87 of 210
I B.Tech EEE,CE,ME (R22) Unit - II C-Programming with Data Structures

for (int j = 0; j < 3; ++j)


{
for (int k = 0; k < 2; ++k)
{
printf("test[%d][%d][%d] = %d\n", i, j, k, test[i][j][k]);
}
}
}

return 0;
}
Run Code

Output

Enter 12 values:
1
2
3
4
5
Naveen(jntr)
6
7
8
9
10
11
12

Displaying Values:
test[0][0][0] = 1
test[0][0][1] = 2
test[0][1][0] = 3
test[0][1][1] = 4
test[0][2][0] = 5
test[0][2][1] = 6
test[1][0][0] = 7
test[1][0][1] = 8
test[1][1][0] = 9
test[1][1][1] = 10
test[1][2][0] = 11
test[1][2][1] = 12

Prepared By B.Naveen Kumar (M.Tech.) JNTUH, Rajanna Siricilla. Page 88 of 210


I B.Tech EEE,CE,ME (R22) Unit - II C-Programming with Data Structures

Previous Tutorial:

Pointers in C

Naveen(jntr)
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 datatype. A pointer is defined as follows...

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

variable.

In the c programming language, 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.

Accessing the Address of Variables

In c programming language, we use the reference operator "&" to access the address of

variable. For example, to access the address of a variable "marks" we use "&marks". We

use the following printf statement to display memory location address of

variable "marks"...

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

In the above example statement %u is used to display address of marks variable. Address

of any memory location is unsigned integer value.

Declaring Pointers (Creating Pointers)


Prepared By B.Naveen Kumar (M.Tech.) JNTUH, Rajanna Siricilla. Page 89 of 210
I B.Tech EEE,CE,ME (R22) Unit - II C-Programming with Data Structures

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

normal variable but the name is prefixed with * symbol. We use the following syntax to

declare a pointer variable...

datatype *pointerName ;

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

Example Code
int *ptr ;

In the above example declaration, the variable "ptr" is a pointer variable that can be used to

store any integer variable address.

Assigning Address to Pointer


Naveen(jntr)
To assign address to a pointer variable we use assignment operator with the following

syntax...

pointerVariableName = & variableName ;

For example, consider the following variables declaration...

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


int a, *ptr ;

In the above declaration, variable "a" is a normal integer variable and variable "ptr" is an

integer pointer variable. If we want to assign the address of variable "a" to pointer

variable "ptr" we use the following statement...

Example Code
ptr = &a ;

In the above statement, the address of variable "a" is assigned to pointer variable "prt".

Here we say that pointer variable ptr is pointing to variable a.

Accessing Variable Value Using Pointer

Pointer variables are used to store the address of other variables. We can use this address

to access the value of the variable through its pointer. We use the symbol "*" infront of

pointer variable name to access the value of variable to which the pointer is pointing. We

use the following general syntax...

Prepared By B.Naveen Kumar (M.Tech.) JNTUH, Rajanna Siricilla. Page 90 of 210


I B.Tech EEE,CE,ME (R22) Unit - II C-Programming with Data Structures

*pointerVariableName
Example Code
#include<stdio.h>
#include<conio.h>

void main()
{
int a = 10, *ptr ;
clrscr();
ptr = &a ;

printf("Address of variable a = %u\n", ptr) ;


printf("Value of variable a = %d\n", *ptr) ;

} Naveen(jntr)
printf("Address of variable ptr = %u\n", &ptr) ;

Output:

In the above example program, variable a is a normal variable and variable ptr is a pointer

variable. Address of variable a is stored in pointer variable ptr. Here ptr is used to access

the address of variable a and *ptr is used to access the value of variable a.

Memory Allocation of Pointer Variables

Every pointer variable is used to store the address of another variable. In computer memory

address of any memory location is an unsigned integer value. In c programming language,

unsigned integer requires 2 bytes of memory. So, irrespective of pointer datatype every

pointer variable is allocated with 2 bytes of memory.

Pointers Arithmetic Operations in C


Pointer variables are used to store the address of variables. Address of any variable is an

unsigned integer value i.e., it is a numerical value. So we can perform arithmetic operations

on pointer values. But when we perform arithmetic operations on pointer variable, the

result depends on the amount of memory required by the variable to which the pointer is

Prepared By B.Naveen Kumar (M.Tech.) JNTUH, Rajanna Siricilla. Page 91 of 210


I B.Tech EEE,CE,ME (R22) Unit - II C-Programming with Data Structures

pointing.

In the c programming language, we can perform the following arithmetic operations on

pointers...

1. Addition

2. Subtraction

3. Increment

4. Decrement

5. Comparison

Addition Operation on Pointer


Naveen(jntr)
In the c programming language, the addition operation on pointer variables is calculated

using the following formula...

AddressAtPointer + ( NumberToBeAdd *
BytesOfMemoryRequiredByDatatype )
Example Program
void main()
{
int a, *intPtr ;
float b, *floatPtr ;
double c, *doublePtr ;
clrscr() ;
intPtr = &a ; // Asume address of a is 1000
floatPtr = &b ; // Asume address of b is 2000
doublePtr = &c ; // Asume address of c is 3000

intPtr = intPtr + 3 ; // intPtr = 1000 + ( 3 * 2 )


floatPtr = floatPtr + 2 ; // floatPtr = 2000 + ( 2 * 4 )
doublePtr = doublePtr + 5 ; // doublePtr = 3000 + ( 5 * 6 )

printf("intPtr value : %u\n", intPtr) ;


printf("floatPtr value : %u\n", floatPtr) ;
printf("doublePtr value : %u", doublePtr) ;

getch() ;
Prepared By B.Naveen Kumar (M.Tech.) JNTUH, Rajanna Siricilla. Page 92 of 210
I B.Tech EEE,CE,ME (R22) Unit - II C-Programming with Data Structures

Output:

Subtraction Operation on Pointer

In the c programming language, the subtraction operation on pointer variables is calculated

using the following formula...

Naveen(jntr)
AddressAtPointer - ( NumberToBeAdd *
BytesOfMemoryRequiredByDatatype )
Example Program
void main()
{
int a, *intPtr ;
float b, *floatPtr ;
double c, *doublePtr ;
clrscr() ;
intPtr = &a ; // Asume address of a is 1000
floatPtr = &b ; // Asume address of b is 2000
doublePtr = &c ; // Asume address of c is 3000

intPtr = intPtr - 3 ; // intPtr = 1000 - ( 3 * 2 )


floatPtr = floatPtr - 2 ; // floatPtr = 2000 - ( 2 * 4 )
doublePtr = doublePtr - 5 ; // doublePtr = 3000 - ( 5 * 6 )

printf("intPtr value : %u\n", intPtr) ;


printf("floatPtr value : %u\n", floatPtr) ;
printf("doublePtr value : %u", doublePtr) ;

getch() ;
}

Output:
Prepared By B.Naveen Kumar (M.Tech.) JNTUH, Rajanna Siricilla. Page 93 of 210
I B.Tech EEE,CE,ME (R22) Unit - II C-Programming with Data Structures

Increment & Decrement Operation on Pointer

The increment operation on pointer variable is calculated as follows...

AddressAtPointer +
NumberOfBytesRequiresByDatatype
Example Program
void main()
{
Naveen(jntr)
int a, *intPtr ;
float b, *floatPtr ;
double c, *doublePtr ;
clrscr() ;
intPtr = &a ; // Asume address of a is 1000
floatPtr = &b ; // Asume address of b is 2000
doublePtr = &c ; // Asume address of c is 3000

intPtr++ ; // intPtr = 1000 + 2


floatPtr++ ; // floatPtr = 2000 + 4
doublePtr++ ; // doublePtr = 3000 + 6

printf("intPtr value : %u\n", intPtr) ;


printf("floatPtr value : %u\n", floatPtr) ;
printf("doublePtr value : %u", doublePtr) ;

getch() ;
}

Output:

Prepared By B.Naveen Kumar (M.Tech.) JNTUH, Rajanna Siricilla. Page 94 of 210


I B.Tech EEE,CE,ME (R22) Unit - II C-Programming with Data Structures

The decrement operation on pointer variable is calculated as follows...

AddressAtPointer - NumberOfBytesRequiresByDatatype
Example Program
void main()
{

Naveen(jntr)
int a, *intPtr ;
float b, *floatPtr ;
double c, *doublePtr ;
clrscr() ;
intPtr = &a ; // Asume address of a is 1000
floatPtr = &b ; // Asume address of b is 2000
doublePtr = &c ; // Asume address of c is 3000

intPtr-- ; // intPtr = 1000 - 2


floatPtr-- ; // floatPtr = 2000 - 4
doublePtr-- ; // doublePtr = 3000 - 6

printf("intPtr value : %u\n", intPtr) ;


printf("floatPtr value : %u\n", floatPtr) ;
printf("doublePtr value : %u", doublePtr) ;

getch() ;
}

Output:

Prepared By B.Naveen Kumar (M.Tech.) JNTUH, Rajanna Siricilla. Page 95 of 210


I B.Tech EEE,CE,ME (R22) Unit - II C-Programming with Data Structures

Comparison of Pointers

The comparison operation is perform between the pointers of same datatype only. In c

programming language, we can use all comparison operators (relational operators) with

pointers.

We can't perform multiplication and division operations on pointers.

Pointers to Pointers in C
In the c programming language, we have pointers to store the address of variables of any

datatype. A pointer variable can store the address of a normal variable. C programming

language also provides a pointer variable to store the address of another pointer variable.

This type of pointer variable is called a pointer to pointer variable. Sometimes we also call it

Naveen(jntr)
a double pointer. We use the following syntax for creating pointer to pointer…

datatype **pointerName ;
Example Program
int **ptr ;

Here, ptr is an integer pointer variable that stores the address of another integer pointer

variable but does not stores the normal integer variable address.

MOST IMPORTANT POINTS TO BE REMEMBERED

1. To store the address of normal variable we use single pointer variable

2. To store the address of single pointer variable we use double pointer variable

3. To store the address of double pointer variable we use triple pointer variable

4. Similarly the same for remaining pointer variables also…

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

int main()
{
int a ;
int *ptr1 ;
int **ptr2 ;
int ***ptr3 ;
Prepared By B.Naveen Kumar (M.Tech.) JNTUH, Rajanna Siricilla. Page 96 of 210
I B.Tech EEE,CE,ME (R22) Unit - II C-Programming with Data Structures

ptr1 = &a ;
ptr2 = &ptr1 ;
ptr3 = &ptr2 ;

printf("\nAddress of normal variable 'a' = %u\n", ptr1) ;


printf("Address of pointer variable '*ptr1' = %u\n", ptr2) ;
printf("Address of pointer-to-pointer '**ptr2' = %u\n", ptr3) ;
return 0;
}

Output:

Naveen(jntr)
Pointers to void in C
In the c programming language, pointer to void is the concept of defining a pointer variable

that is independent of data type. In C programming language, a void pointer is a pointer

variable used to store the address of a variable of any datatype. That means single void

pointer can be used to store the address of integer variable, float variable, character

variable, double variable or any structure variable. We use the keyword "void" to create

void pointer. We use the following syntax for creating a pointer to void…

void *pointerName ;
Example Code
void *ptr ;

Here, "ptr" is a void pointer variable which is used to store the address of any datatype

variable.

MOST IMPORTANT POINTS TO BE REMEMBERED

1. void pointer stores the address of any datatype variable.

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

Prepared By B.Naveen Kumar (M.Tech.) JNTUH, Rajanna Siricilla. Page 97 of 210


I B.Tech EEE,CE,ME (R22) Unit - II C-Programming with Data Structures

int main()
{
int a ;
float b ;
char c ;

void *ptr ;

clrscr() ;

ptr = &a ;
printf(“Address of integer variable ‘a’ = %u\n”, ptr) ;

ptr = &b ;
Naveen(jntr)
printf(“Address of float variable ‘b' = %u\n”, ptr) ;

ptr = &c ;
printf(“Address of character variable ‘c’ = %u\n”, ptr) ;
return 0;
}

Output:

Pointers to Arrays in C
In the c programming language, 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...

Example Code
int marks[6] ;

Prepared By B.Naveen Kumar (M.Tech.) JNTUH, Rajanna Siricilla. Page 98 of 210


I B.Tech EEE,CE,ME (R22) Unit - II C-Programming with Data Structures

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

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

int main()
{
int marks[6] = {89, 45, 58, 72, 90, 93} ;
int *ptr ;

clrscr() ;

ptr = marks ;
Naveen(jntr)
printf(“Base Address of 'marks' array = %u\n”, ptr) ;
return 0;
}

Output:

MOST IMPORTANT POINTS TO BE REMEMBERED

1. An array name is a constant pointer.

2. We can use the array name to access the address and value of all the elements of

that array.

3. Since array name is a constant pointer we can't modify its value.

Consider the following example statements...

Example Code
ptr = marks + 2 ;

Prepared By B.Naveen Kumar (M.Tech.) JNTUH, Rajanna Siricilla. Page 99 of 210


I B.Tech EEE,CE,ME (R22) Unit - II C-Programming with Data Structures

Here, the pointer variable "ptr" is assigned with address of "marks[2]" element.

Example Code
printf("Address of 'marks[4]' = %u", marks+4) ;

The above printf statement displays the address of element "marks[4]".

Example Code
printf("Value of 'marks[0]' = %d", *marks) ;
printf("Value of 'marks[3]' = %d", *(marks+3)) ;

In the above two statements, first printf statement prints the value 89 (i.e., value of

marks[0]) and the second printf statement prints the value 72 (i.e., value of marks[3]).

Example Code
marks++ ;

Naveen(jntr)
The above statement generates compilation error because the array name acts as a

constant pointer. So we can't change its value.

In the above example program, the array name marks can be used as follows...

marks is same as &marks[0]

marks + 1 is same as &marks[1]

marks + 2 is same as &marks[2]

marks + 3 is same as &marks[3]

marks + 4 is same as &marks[4]

marks + 5 is same as &marks[5]

*marks is same as marks[0]

*(marks + 1) is same as marks[1]

*(marks + 2) is same as marks[2]

*(marks + 3) is same as marks[3]

*(marks + 4) is same as marks[4]

*(marks + 5) is same as marks[5]

Pointers to Multi Dimensional Array

In case of multi dimensional array also the array name acts as a constant pointer to the

base address of that array. For example, we declare an array as follows...

Example Code
Prepared By B.Naveen Kumar (M.Tech.) JNTUH, Rajanna Siricilla. Page 100 of 210
I B.Tech EEE,CE,ME (R22) Unit - II C-Programming with Data Structures

int marks[3][3] ;

In the above example declaration, the array name marks acts as constant pointer to the

base address (address of marks[0][0]) of that array.

In the above example of two dimensional array, the element marks[1][2] is accessed

as *(*(marks + 1) + 2).

Pointers for Functions in C


In the c programming language, there are two ways to pass parameters to functions. They

are as follows...

1. Call by Value

2. Call By Reference

Naveen(jntr)
We use pointer variables as formal parameters in call by reference parameter passing

method.

In case of call by reference parameter passing method, the address of actual parameters is

passed as arguments from the calling function to the called function. To recieve this

address, we use pointer variables as formal parameters.

Consider the following program for swapping two variable values...


Example - Swapping of two variable values using Call by
Reference
#include<stdio.h>
#include<conio.h>

void swap(int *, int *) ;

void main()
{
int a = 10, b = 20 ;

clrscr() ;

printf(“Before swap : a = %d and b = %d\n", a, b) ;

Prepared By B.Naveen Kumar (M.Tech.) JNTUH, Rajanna Siricilla. Page 101 of 210
I B.Tech EEE,CE,ME (R22) Unit - II C-Programming with Data Structures

swap(&a, &b) ;

printf(“After swap : a = %d and b = %d\n", a, b) ;

getch() ;
}
void swap(int *x, int *y)
{
int temp ;
temp = *x ;
*x = *y ;
*y = temp ;
}

Output:
Naveen(jntr)

In the above example program, we are passing the addresses of variables a and b and these

are recieved by the pointer variables x and y. In the called function swap we use the pointer

variables x and y to swap the values of variables a and b.

Dynamic Memory Allocation in C


In C programming language, when we declare variables memory is allocated in space called

stack. The memory allocated in the stack is fixed at the time of compilation and remains

until the end of the program execution. When we create an array, we must specify the size

at the time of the declaration itself and it can not be changed during the program execution.

This is a major problem when we do not know the number of values to be stored in an

array. To solve this we use the concept of Dynamic Memory Allocation. The dynamic

memory allocation allocates memory from heap storage. Dynamic memory allocation is

defined as follow...

Allocation of memory during the program execution is called dynamic memory

allocation.

or

Prepared By B.Naveen Kumar (M.Tech.) JNTUH, Rajanna Siricilla. Page 102 of 210
I B.Tech EEE,CE,ME (R22) Unit - II C-Programming with Data Structures

Dynamic memory allocation is the process of allocating the memory manually at the

time of program execution.

We use pre-defined or standard library functions to allocate memory dynamically. There

are FOUR standard library functions that are defined in the header file known as "stdlib.h".

They are as follows...

1. malloc()

2. calloc()

3. realloc()

4. free()

malloc()
Naveen(jntr)
malloc() is the standard library function used to allocate a memory block of specified

number of bytes and returns void pointer. The void pointer can be casted to any datatype. If

malloc() function unable to allocate memory due to any reason it returns NULL pointer.

Syntax

void* malloc(size_in_bytes)

Example
Example Program for malloc().
#include<stdio.h>
#include<conio.h>

int main () {

char *title;

title = (char *) malloc(15);

strcpy(title, "c programming");


printf("String = %s, Address = %u\n", title, title);

return(0);

}
Prepared By B.Naveen Kumar (M.Tech.) JNTUH, Rajanna Siricilla. Page 103 of 210
I B.Tech EEE,CE,ME (R22) Unit - II C-Programming with Data Structures

calloc()

calloc() is the standard library function used to allocate multiple memory blocks of the

specified number of bytes and initializes them to ZERO. calloc() function returns void

pointer. If calloc() function unable to allocate memory due to any reason it returns a NULL

pointer. Generally, calloc() is used to allocate memory for array and structure. calloc()

function takes two arguments and they are 1. The number of blocks to be allocated, 2. Size

of each block in bytes

Syntax

Naveen(jntr)
void* calloc(number_of_blocks,
size_of_each_block_in_bytes)

Example
Example Program for calloc().
#include<stdio.h>
#include<conio.h>

int main () {
int i, n;
int *ptr;

printf("Number of blocks to be created:");


scanf("%d",&n);

ptr = (int*)calloc(n, sizeof(int));


printf("Enter %d numbers:\n",n);
for( i=0 ; i < n ; i++ ) {
scanf("%d",&ptr[i]);
}

printf("The numbers entered are: ");


for( i=0 ; i < n ; i++ ) {
printf("%d ",ptr[i]);
}

Prepared By B.Naveen Kumar (M.Tech.) JNTUH, Rajanna Siricilla. Page 104 of 210
I B.Tech EEE,CE,ME (R22) Unit - II C-Programming with Data Structures

return(0);
}

realloc()

realloc() is the standard library function used to modify the size of memory blocks that were

previously allocated using malloc() or calloc(). realloc() function returns void pointer. If

calloc() function unable to allocate memory due to any reason it returns NULL pointer.

Syntax

void* realloc(*pointer, new_size_of_each_block_in_bytes)

Example
Naveen(jntr)
Example Program for realloc().
#include<stdio.h>
#include<conio.h>

int main () {

char *title;

title = (char *) malloc(15);

strcpy(title, "c programming");


printf("Before modification : String = %s, Address = %u\n", title, title);

title = (char*) realloc(title, 30);

strcpy(title,"C Programming Language");


printf("After modification : String = %s, Address = %u\n", title, title);

return(0);

Prepared By B.Naveen Kumar (M.Tech.) JNTUH, Rajanna Siricilla. Page 105 of 210
I B.Tech EEE,CE,ME (R22) Unit - II C-Programming with Data Structures

free()

free() is the standard library function used to deallocate memory block that was previously

allocated using malloc() or calloc(). free() function returns void pointer. When free() function

is used with memory allocated that was created using calloc(), all the blocks are get

deallocated.

Syntax

void free(*pointer)

Example
Example Program for free().

Naveen(jntr)
#include<stdio.h>
#include<conio.h>

int main () {

char *title;

title = (char *) malloc(15);

strcpy(title, "c programming");


printf("Before modification : String = %s, Address = %u\n", title, title);

title = (char*) realloc(title, 30);

strcpy(title,"C Programming Language");


printf("After modification : String = %s, Address = %u\n", title, title);

free(title);

return(0);

Strings in C
String is a set of characters that are enclosed in double quotes. In the C programming

language, strings are created using one dimension array of character datatype. Every string

Prepared By B.Naveen Kumar (M.Tech.) JNTUH, Rajanna Siricilla. Page 106 of 210
I B.Tech EEE,CE,ME (R22) Unit - II C-Programming with Data Structures

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. The formal definition of string is as follows...

String is a set of characters enclosed in double quotation marks. In C programming,

the string is a character array of single dimension.

In C programming language, there are two methods to create strings and they are as

follows...

1. Using one dimensional array of character datatype ( static memory allocation )

2. Using a pointer array of character datatype ( dynamic memory allocation )

Naveen(jntr)
Creating string in C programming language
In C, strings are created as a one-dimensional array of character datatype. We can use both

static and dynamic memory allocation. When we create a string, the size of the array must

be one more than the actual number of characters to be stored. That extra memory block is

used to store string termination character NULL (\0). The following declaration stores a

string of size 5 characters.

char str[6] ;

The following declaration creates a string variable of a specific size at the time of program

execution.

char *str = (char *) malloc(15) ;

Assigning string value in C programming language


String value is assigned using the following two methods...

1. At the time of declaration (initialization)

2. After declaraation

Examples of assigning string value

int main()
{
char str1[6] = "Hello";

Prepared By B.Naveen Kumar (M.Tech.) JNTUH, Rajanna Siricilla. Page 107 of 210
I B.Tech EEE,CE,ME (R22) Unit - II C-Programming with Data Structures

char str2[] = "Hello!";


char name1[] = {'s','m','a','r','t'};
char name2[6] = {'s','m','a','r','t'};

char title[20];
*title = "btech smart class";

return 0;
}

Reading string value from user in C programming language


We can read a string value from the user during the program execution. We use the

following two methods...

Naveen(jntr)
1. Using scanf() method - reads single word

2. Using gets() method - reads a line of text

Using scanf() method we can read only one word of string. We use %s to represent string in

scanf() and printf() methods.

Examples of reading string value using scanf() method


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

int main(){

char name[50];
printf("Please enter your name : ");

scanf("%s", name);

printf("Hello! %s , welcome to btech smart class !!", name);

return 0;
}

When we want to read multiple words or a line of text, we use a pre-defined method gets().

The gets() method terminates the reading of text with Enter character.

Prepared By B.Naveen Kumar (M.Tech.) JNTUH, Rajanna Siricilla. Page 108 of 210
I B.Tech EEE,CE,ME (R22) Unit - II C-Programming with Data Structures

Examples of reading string value using gets() method


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

int main(){

char name[50];
printf("Please enter your name : ");

gets(name);

printf("Hello! %s , welcome to btech smart class !!", name);

return 0;
}
Naveen(jntr)
C Programming language provides a set of pre-definied functions called String Handling

Functions to work with string values. All the string handling functions are defined in a

header file called string.h.

String Handling Functions in C


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 table provides most commonly used string handling function and their use...

Function Syntax (or) Example Description

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

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

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

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

Prepared By B.Naveen Kumar (M.Tech.) JNTUH, Rajanna Siricilla. Page 109 of 210
I B.Tech EEE,CE,ME (R22) Unit - II C-Programming with Data Structures

Function Syntax (or) Example Description

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

strcmp() strcmp(string1, string2) Returns 0 if string1 and string2 are the same;
less than 0 if string1<string2; greater than 0 if string1

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

strcmpi() strcmpi(string1,string2) Compares two strings, string1 and string2 by ignorin

Naveen(jntr)
stricmp() stricmp(string1, string2) Compares two strings, string1 and string2 by ignorin
strcmpi())

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

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

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

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

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

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

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

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

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

Prepared By B.Naveen Kumar (M.Tech.) JNTUH, Rajanna Siricilla. Page 110 of 210
I B.Tech EEE,CE,ME (R22) Unit - II C-Programming with Data Structures

Enumerated Types (enum) in C


In C programming language, an enumeration is used to create user-defined datatypes.

Using enumeration, integral constants are assigned with names and we use these names in

the program. Using names in programming makes it more readable and easy to maintain.

Enumeration is the process of creating user defined datatype by assigning names to

integral constants

We use the keyword enum to create enumerated datatype. The general syntax of enum is

as follows...

enum {name1, name2, name3, ... }

Naveen(jntr)
In the above syntax, integral constant '0' is assigned to name1, integral constant '1' is

assigned to name2 and so on. We can also assign our own integral constants as follows...

enum {name1 = 10, name2 = 30, name3 = 15, ... }

In the above syntax, integral constant '10' is assigned to name1, integral constant '30' is

assigned to name2 and so on.

Example Program for enum with default values


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

enum day { Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday} ;

void main(){

enum day today;

today = tuesday ;

printf("\ntoday = %d ", today) ;

In the above example program a user defined datatype "day is created seven values,

monday as integral constant '0', tuesday as integral constant '1', wednesday as integral

constant '2', thursday as integral constant '3', friday as integral constant '4', saturday as
Prepared By B.Naveen Kumar (M.Tech.) JNTUH, Rajanna Siricilla. Page 111 of 210
I B.Tech EEE,CE,ME (R22) Unit - II C-Programming with Data Structures

integral constant '5' and sunday as integral constant '6'. Here, when we display tuesday it

displays the respective integral constant '1'.

We can also change the order of integral constants, consider the following example

program.

Example Program for enum with changed integral constant


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

enum day { Monday = 1, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday} ;

void main(){

enum day today; Naveen(jntr)


today = tuesday ;

printf("\ntoday = %d ", today) ;

In the above example program, the integral constant value starts with '1' instead of '0'. Here,

tuesday value is displayed as '2'.

We can also create enum with our own integral constants, consider the following example

program.

Example Program for enum with defferent integral constant


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

enum threshold {low = 40, normal = 60, high = 100} ;

void main(){

enum threshold status;

status = low ;

Prepared By B.Naveen Kumar (M.Tech.) JNTUH, Rajanna Siricilla. Page 112 of 210
I B.Tech EEE,CE,ME (R22) Unit - II C-Programming with Data Structures

printf("\nYou are at %d state. Work hard to improve!!", status) ;

Some times we may assign our own integral constant from other than the first name. In this

case, compiler follows default integral constants for the name that is before the user-

defined integral constant and from user-defined constant onwards it resumes. Consider the

following example program.

Example Program for enum with changed integral constant


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

Naveen(jntr)
enum day {Monday, Tuesday, Wednesday, Thursday = 10, Friday, Saturday, Sunday} ;

void main(){

enum day today;

today = tuesday ;

printf("\ntoday = %d ", today) ;

today = saturday ;

printf("\ntoday = %d ", today) ;

In the above example program a user defined datatype "day is created seven values,

monday as integral constant '0', tuesday as integral constant '1', wednesday as integral

constant '2', thursday as integral constant '10', friday as integral constant '11', saturday as

integral constant '12' and sunday as integral constant '13'.

Note - In enumeration, more than one name may given with same integral constant.

typedef in C

Prepared By B.Naveen Kumar (M.Tech.) JNTUH, Rajanna Siricilla. Page 113 of 210
I B.Tech EEE,CE,ME (R22) Unit - II C-Programming with Data Structures

In C programming language, typedef is a keyword used to create alias name for the existing

datatypes. Using typedef keyword we can create a temporary name to the system defined

datatypes like int, float, char and double. we use that temporary name to create a variable.

The general syntax of typedef is as follows...

typedef <existing-datatype> <alias-name>

typedef with primitive datatypes

Consider the following example of typedef

typedef int Number

In the above example, Number is defined as alias name for integer datatype. So, we can

Naveen(jntr)
use Number to declare integer variables.

Example Program to illustrate typedef in C.


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

typedef int Number;

void main(){

Number a,b,c; // Here a,b,&c are integer type of variables.

clrscr() ;
printf("Enter any two integer numbers: ") ;
scanf("%d%d", &a,&b) ;

c = a + b;

printf("Sum = %d", c) ;
}

typedef with Arrays

In C programming language, typedef is also used with arrays. Consider the following

example program to understand how typedef is used with arrays.

Prepared By B.Naveen Kumar (M.Tech.) JNTUH, Rajanna Siricilla. Page 114 of 210
I B.Tech EEE,CE,ME (R22) Unit - II C-Programming with Data Structures

Example Program to illustrate typedef with arrays in C.


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

void main(){

typedef int Array[5]; // Here Array acts like an integer array type of size
5.

Array list = {10,20,30,40,50}; // List is an array of integer type with size


5.
int i;

clrscr() ;

Naveen(jntr)
printf("List elements are : \n") ;

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


printf("%d\t", list[i]) ;
}

In the above example program, Array is the alias name of integer array type of size 5. We

can use Array as datatype to create integer array of size 5. Here, list is an integer array of

size 5.

typedef with user defined datatypes like structures,


unions etc.,

In C programming language, typedef is also used with structures and unions. Consider the

following example program to understand how typedef is used with structures.

Example Program to illustrate typedef with arrays in C.


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

typedef struct student


{
char stud_name[50];
int stud_rollNo;
Prepared By B.Naveen Kumar (M.Tech.) JNTUH, Rajanna Siricilla. Page 115 of 210
I B.Tech EEE,CE,ME (R22) Unit - II C-Programming with Data Structures

}stud;

void main(){

stud s1;
clrscr() ;

printf("Enter the student name: ") ;


scanf("%s", s1.stud_name);
printf("Enter the student Roll Number: ");
scanf("%d", &s1.stud_rollNo);

printf("\nStudent Information\n");
printf("Name - %s\nHallticket Number - %d", s1.stud_name, s1.stud_rollNo);
}
Naveen(jntr)
In the above example program, stud is the alias name of student structure. We can

use stud as datatype to create variables of student structure. Here, s1 is a variable of

student structure datatype.

typedef with Pointers

In C programming language, typedef is also used with pointers. Consider the following

example program to understand how typedef is used with pointers.

Example Program to illustrate typedef with Pointers in C.


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

void main(){

typedef int* intPointer;

intPointer ptr; // Here ptr is a pointer of integer datatype.


int a = 10;

clrscr() ;

Prepared By B.Naveen Kumar (M.Tech.) JNTUH, Rajanna Siricilla. Page 116 of 210
I B.Tech EEE,CE,ME (R22) Unit - II C-Programming with Data Structures

ptr = &a;

printf("Address of a = %u ",ptr) ;
printf("\nValue of a = %d ",*ptr);
}

Structures in C
In C programming language, a structure is a collection of elements of the different data

type. The structure is used to create user-defined data type in the C programming language.

As the structure used to create a user-defined data type, the structure is also said to be

“user-defined data type in C”.

In other words, a structure is a collection of non-homogeneous elements. Using structure

we can define new data types called user-defined data types that holds multiple values of

Naveen(jntr)
the different data type. The formal definition of structure is as follows...

Structure is a colloction of different type of elements under a single name that acts as

user defined data type in C.

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.

How to create structure?

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

create structures in c programming language.

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

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

record.

Prepared By B.Naveen Kumar (M.Tech.) JNTUH, Rajanna Siricilla. Page 117 of 210
I B.Tech EEE,CE,ME (R22) Unit - II C-Programming with Data Structures

Creating structure in C
struct Student
{
char stud_name[30];
int roll_number;
float percentage;
} ;

Importent Points to be Remembered

Every structure must terminated with semicolon symbol (;).

"struct" is a keyword, it must be used in lowercase letters only.

Naveen(jntr)
Creating and Using 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.

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


struct Student
{
char stud_name[30];
int roll_number;
float percentage;
} stud_1 ; // while defining structure

void main(){
struct Student stud_2; // using struct keyword

printf("Enter details of stud_1 : \n");


printf("Name : ");
scanf("%s", stud_1.stud_name);
printf("Roll Number : ");
scanf("%d", &stud_1.roll_number);
Prepared By B.Naveen Kumar (M.Tech.) JNTUH, Rajanna Siricilla. Page 118 of 210
I B.Tech EEE,CE,ME (R22) Unit - II C-Programming with Data Structures

printf("Percentage : ");
scanf("%f", &stud_1.percentage);

printf("***** Student 1 Details *****\n);


printf("Name of the Student : %s\n", stud_1.stud_name);
printf("Roll Number of the Student : %i\n", stud_1.roll_number);
printf("Percentage of the Student : %f\n", stud_1.percentage);
}

In the above example program, the stucture variable "stud_1 is created while defining the

structure and the variable "stud_2 is careted using struct keyword. Whenever we access the

members of a structure we use the dot (.) operator.

Memory allocation of Structure


Naveen(jntr)
When the structures are used in the c programming language, the memory does not

allocate on defining a structure. The memory is allocated when we create the variable of a

particular structure. As long as the variable of a structure is created no memory is allocated.

The size of memory allocated is equal to the sum of memory required by individual

members of that structure. In the above example program, the variables stud_1 and stud_2

are allocated with 36 bytes of memory each.

Importent Points to be Remembered

All the members of a structure can be used simultaneously.

Until variable of a structure is created no memory is allocated.

The memory required by a structure variable is sum of the memory required by individual

members of that structure.


Prepared By B.Naveen Kumar (M.Tech.) JNTUH, Rajanna Siricilla. Page 119 of 210
I B.Tech EEE,CE,ME (R22) Unit - II C-Programming with Data Structures

Unions in C
In C programming language, the union is a collection of elements of the different data type.

The union is used to create user-defined data type in the C programming language. As the

union used to create a user-defined data type, the union is also said to be “user-defined

data type in C”.

In other words, the union is a collection of non-homogeneous elements. Using union we can

define new data types called user-defined data types that holds multiple values of the

different data type. The formal definition of a union is as follows...

Union is a colloction of different type of elements under a single name that acts as

user defined data type in C.

Naveen(jntr)
Generally, unions are used to define a record in the c programming language. Unions allow

us to combine elements of a different data type into a group. The elements that are defined

in a union are called members of union.

How to create union?

To create union in c, we use the keyword called "union". We use the following syntax to

create unions in c programming language.

union <structure_name>
{
data_type member1;
data_type member2, member3;
.
.
};

Following is the example of creating a union called Student which is used to hold student

record.

Creating union in C
union Student
{
char stud_name[30];
int roll_number;

Prepared By B.Naveen Kumar (M.Tech.) JNTUH, Rajanna Siricilla. Page 120 of 210
I B.Tech EEE,CE,ME (R22) Unit - II C-Programming with Data Structures

float percentage;
} ;

Importent Points to be Remembered

Every union must terminated with semicolon symbol (;).

"union" is a keyword, it must be used in lowercase letters only.

Creating and Using union variables

In a c programming language, there are two ways to create union variables. We can create

using
Naveen(jntr)
union variable while the union is defined and we can also create after terminating union

union keyword.

TO access members of a union using union variable, we use dot (.) operator. Consider the

following example code...

Creating and Using union variables in C


union Student
{
char stud_name[30];
int roll_number;
float percentage;
} stud_1 ; // while defining union

void main(){
union Student stud_2; // using union keyword

printf("Enter details of stud_1 : \n");


printf("Name : ");
scanf("%s", stud_1.stud_name);
printf("Roll Number : ");
scanf("%d", &stud_1.roll_number);
printf("Percentage : ");
scanf("%f", &stud_1.percentage);

printf("***** Student 1 Details *****\n);


printf("Name of the Student : %s\n", stud_1.stud_name);

Prepared By B.Naveen Kumar (M.Tech.) JNTUH, Rajanna Siricilla. Page 121 of 210
I B.Tech EEE,CE,ME (R22) Unit - II C-Programming with Data Structures

printf("Roll Number of the Student : %i\n", stud_1.roll_number);


printf("Percentage of the Student : %f\n", stud_1.percentage);
}

In the above example program, the union variable "stud_1 is created while defining the

union and the variable "stud_2 is careted using union keyword. Whenever we access the

members of a union we use the dot (.) operator.

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

Naveen(jntr)
memory allocated is equal to the maximum memory required by an individual member

among all members of that union. In the above example program, the variables stud_1 and

stud_2 are allocated with 30 bytes of memory each.

Bit Fields in C
When we use structures in the c programming language, the memory required by structure

variable is the sum of memory required by all individual members of that structure. To save

memory or to restrict memory of members of structure we use bitfield concept. Using

bitfield we can specify the memory to be allocated for individual members of a structure. To

understand the bitfields, let us consider the following example code...

Date structure in C
struct Date
{
unsigned int day;
Prepared By B.Naveen Kumar (M.Tech.) JNTUH, Rajanna Siricilla. Page 122 of 210
I B.Tech EEE,CE,ME (R22) Unit - II C-Programming with Data Structures

unsigned int month;


unsigned int year;
} ;

Here, the variable of Date structure allocates 6 bytes of memory.

In the above example structure the members day and month both does not requires 2 bytes

of memory for each. Becuase member day stores values from 1 to 31 only which requires 5

bits of memory, and the member month stores values from 1 to 12 only which required 4

bits of memory. So, to save the memory we use the bitfields.

Naveen(jntr)
Consider the following structure with bitfields...

Date structure in C
struct Date
{
unsigned int day : 5;
unsigned int month : 4;
unsigned int year;
} ;

Here, the variable of Date structure allocates 4 bytes of memory.

Command Line Arguments in C


In C programming language, command line arguments are the data values that are passed

from command line to our program. Using command line arguments we can control the

program execution from the outside of the program. Generally, all the command line

arguments are handled by the main() method. Generally, the command line arguments can

be understood as follows...

Command line arguments are the parameters passing to main() method from the

command line.

When command line arguments are passed main() method receives them with the help of

two formal parameters and they are,

Prepared By B.Naveen Kumar (M.Tech.) JNTUH, Rajanna Siricilla. Page 123 of 210
I B.Tech EEE,CE,ME (R22) Unit - II C-Programming with Data Structures

 int argc

 char *argv[ ]

int argc - It is an integer argument used to store the count of command line arguments are

passed from the command line.

char *argv[ ] - It is a character pointer array used to store the actual values of command line

arguments are passed from the command line.

Importent Points to be Remembered

The command line arguments are supperated with SPACE.

Always the first command line argument is file path.

Only string values Naveen(jntr)


can be passed as command line arguments.

All the command line arguments are stored in a character pointer array called argv[ ].

Total count of command line arguments including file path argument is stored in a integer

parameter called argc.

Consider the following example program...

Example Program to illustrate command line arguments in


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

int main(int argc, char *argv[]){

int i;
clrscr() ;

if(argc == 1){
printf("Please provide command line arguments!!!");
return 0;
}
else{

Prepared By B.Naveen Kumar (M.Tech.) JNTUH, Rajanna Siricilla. Page 124 of 210
I B.Tech EEE,CE,ME (R22) Unit - II C-Programming with Data Structures

printf("Total number of arguments are - %d and they are\n\n", argc);


for(i=0; i<argc ; i++){
printf("%d -- %s \n", i+1, argv[i]);
}
return 0;
}
}

When execute the above program by passing "Hello welcome to

www.btechsmartclass.com" as command line arguments it produce the following output.

Naveen(jntr)
In the above example program we are passing 4 string arguments (Hello, welcome, to and

www.btechsmartclass.com) but the default first argument is a file path. So, the total count of

command line arguments is 5.

Whenever we want to pass numerical values as command line arguments, they are passed

as string values only and we need to convert them into numerical values in the program.

Consider the following program that calculates the sum of all command line arguments and

displays the result.

Example Program to display sum of all command line


arguments in C.
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>

int main(int argc, char *argv[]){

int i, n, sum = 0;
clrscr() ;

if(argc == 1){
printf("Please provide command line arguments!!!");
return 0;

Prepared By B.Naveen Kumar (M.Tech.) JNTUH, Rajanna Siricilla. Page 125 of 210
I B.Tech EEE,CE,ME (R22) Unit - II C-Programming with Data Structures

}
else{
printf("Total number of arguments are - %d and sum of those is ", argc);
for(i=0; i<argc ; i++){
n = atoi(argv[i]);
sum += n;
}
printf("%d\n", sum);
return 0;
}
}

When execute the above program by passing "10 20 30 40 50" as command line arguments

it produce the following output.

Naveen(jntr)
In the above example program we are passing 5 string arguments (10, 20, 30 40 and 50).

They are converted into integer values by using atoi() method which is available

in stdlib.h header file.

Files in C
Generally, a file is used to store user data in a computer. In other words, computer stores

the data using files. we can define a file as follows...

File is a collection of data that stored on secondary memory like haddisk of a

computer.

C programming language supports two types of files and they are as follows...

 Text Files (or) ASCII Files

 Binary Files

Text File (or) ASCII File - The file that contains ASCII codes of data like digits, alphabets and

symbols is called text file (or) ASCII file.

Binary File - The file that contains data in the form of bytes (0's and 1's) is called as binary

file. Generally, the binary files are compiled version of text files.
Prepared By B.Naveen Kumar (M.Tech.) JNTUH, Rajanna Siricilla. Page 126 of 210
I B.Tech EEE,CE,ME (R22) Unit - II C-Programming with Data Structures

File Operations in C

The following are the operations performed on files in c programming langauge...

 Creating (or) Opening a file

 Reading data from a file

 Writing data into a file

 Closing a file

All the above operations are performed using file handling functions available in C. We

discuss file handling functions in the next topic.

File Handling Functions in C


Naveen(jntr)
File is a collection of data that stored on secondary memory like hard disk of a computer.

The following are the operations performed on files in the c programming language...

 Creating (or) Opening a file

 Reading data from a file

 Writing data into a file

 Closing a file

All the above operations are performed using file handling functions available in C.

Creating (or) Opening a file

To create a new file or open an existing file, we need to create a file pointer of FILE type.

Following is the sample code for creating file pointer.


File *f_ptr ;

We use the pre-defined method fopen() to create a new file or to open an existing file.

There are different modes in which a file can be opened. Consider the following code...
File *f_ptr ;
*f_ptr = fopen("abc.txt", "w") ;

The above example code creates a new file called abc.txt if it does not exists otherwise it is

opened in writing mode.

Prepared By B.Naveen Kumar (M.Tech.) JNTUH, Rajanna Siricilla. Page 127 of 210
I B.Tech EEE,CE,ME (R22) Unit - II C-Programming with Data Structures

In C programming language, there different modes are available to open a file and they are

shown in the following table.

S. Mod
No. e Description

1 r Opens a text file in reading mode.

2 w Opens a text file in wirting mode.

3 a Opens a text file in append mode.

4 r+ Opens a text file in both reading and writing mode.

5 w+
Naveen(jntr)
Opens a text file in both reading and writing mode. It set the cursor position
file if it exists.

6 a+ Opens a text file in both reading and writing mode. The reading operation is
begining and writing operation is performed at the end of the file.

Note - The above modes are used with text files only. If we want to work with binary files

we use

rb, wb, ab, rb+, wb+ and ab+.

Reading from a file

The reading from a file operation is performed using the following pre-defined file handling

methods.

1. getc()

2. getw()

3. fscanf()

4. fgets()

5. fread()

Prepared By B.Naveen Kumar (M.Tech.) JNTUH, Rajanna Siricilla. Page 128 of 210
I B.Tech EEE,CE,ME (R22) Unit - II C-Programming with Data Structures

 getc( *file_pointer ) - 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.

Example Program to illustrate getc() in C.


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

int main(){

FILE *fp;
char ch;

Naveen(jntr)
clrscr();
fp = fopen("MySample.txt","r");
printf("Reading character from the file: %c\n",getc(fp));

ch = getc(fp);
printf("ch = %c", ch);
fclose(fp);
getch();
return 0;
}

Output

 getw( *file_pointer ) - 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.

Prepared By B.Naveen Kumar (M.Tech.) JNTUH, Rajanna Siricilla. Page 129 of 210
I B.Tech EEE,CE,ME (R22) Unit - II C-Programming with Data Structures

Example Program to illustrate getw() in C.


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

int main(){

FILE *fp;
int i,j;
clrscr();
fp = fopen("MySample.txt","w");
putw(65,fp); // inserts A
putw(97,fp); // inserts a
fclose(fp);

i = getw(fp);
Naveen(jntr)
fp = fopen("MySample.txt","r");

// reads 65 - ASCII value of A

j = getw(fp); // reads 97 - ASCII value of a


printf("SUM of the integer values stored in file = %d", i+j); // 65 +
97 = 162
fclose(fp);
getch();

return 0;
}

Output

Prepared By B.Naveen Kumar (M.Tech.) JNTUH, Rajanna Siricilla. Page 130 of 210
I B.Tech EEE,CE,ME (R22) Unit - II C-Programming with Data Structures

 fscanf( *file_pointer, typeSpecifier, &variableName ) - This function is used to read

multiple datatype values from specified file which is opened in reading mode.

Example Program to illustrate fscanf() in C.


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

int main(){

char str1[10], str2[10], str3[10];


int year;
FILE * fp;
clrscr();

Naveen(jntr)
fp = fopen ("file.txt", "w+");
fputs("We are in 2016", fp);
rewind(fp); // moves the cursor to begining of the file

fscanf(fp, "%s %s %s %d", str1, str2, str3, &year);


printf("Read String1 - %s\n", str1 );
printf("Read String2 - %s\n", str2 );
printf("Read String3 - %s\n", str3 );
printf("Read Integer - %d", year );
fclose(fp);
getch();

return 0;
}

Output

Prepared By B.Naveen Kumar (M.Tech.) JNTUH, Rajanna Siricilla. Page 131 of 210
I B.Tech EEE,CE,ME (R22) Unit - II C-Programming with Data Structures

 fgets( variableName, numberOfCharacters, *file_pointer ) - 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.

Example Program to illustrate fgets() in C.


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

int main(){

FILE *fp;

Naveen(jntr)
char *str;
clrscr();
fp = fopen ("file.txt", "r");

fgets(str,6,fp);
printf("str = %s", str);
fclose(fp);
getch();

return 0;
}

Output

 fread( source, sizeofReadingElement, numberOfCharacters, FILE *pointer ) - This

function is used to read specific number of sequence of characters from the

specified file which is opened in reading mode.


Prepared By B.Naveen Kumar (M.Tech.) JNTUH, Rajanna Siricilla. Page 132 of 210
I B.Tech EEE,CE,ME (R22) Unit - II C-Programming with Data Structures

Example Program to illustrate fgets() in C.


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

int main(){

FILE *fp;
char *str;
clrscr();
fp = fopen ("file.txt", "r");

fread(str,sizeof(char),5,fp);
str[strlen(str)+1] = 0;

Naveen(jntr)
printf("str = %s", str);
fclose(fp);
getch();

return 0;
}

Output

Writing into a file

The writing into a file operation is performed using the following pre-defined file handling

methods.

1. putc()

Prepared By B.Naveen Kumar (M.Tech.) JNTUH, Rajanna Siricilla. Page 133 of 210
I B.Tech EEE,CE,ME (R22) Unit - II C-Programming with Data Structures

2. putw()

3. fprintf()

4. fputs()

5. fwrite()

 putc( char, *file_pointer ) - This function is used to write/insert a character to the

specified file when the file is opened in writing mode.

Example Program to illustrate putc() in C.


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

int main(){
Naveen(jntr)
FILE *fp;
char ch;
clrscr();
fp = fopen("C:/TC/EXAMPLES/MySample.txt","w");

putc('A',fp);
ch = 'B';
putc(ch,fp);
fclose(fp);
getch();

return 0;
}

Output

Prepared By B.Naveen Kumar (M.Tech.) JNTUH, Rajanna Siricilla. Page 134 of 210
I B.Tech EEE,CE,ME (R22) Unit - II C-Programming with Data Structures


Naveen(jntr)
putw( int, *file_pointer ) - This function is used to writes/inserts an integer value to

the specified file when the file is opened in writing mode.

Example Program to illustrate putw() in C.


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

int main(){

FILE *fp;
int i;
clrscr();
fp = fopen("MySample.txt","w");
putw(66,fp);
i = 100;
putw(i,fp);
fclose(fp);
getch();

return 0;
}

Output

Prepared By B.Naveen Kumar (M.Tech.) JNTUH, Rajanna Siricilla. Page 135 of 210
I B.Tech EEE,CE,ME (R22) Unit - II C-Programming with Data Structures

 fprintf( *file_pointer, "text" ) - This function is used to writes/inserts multiple lines

of text with mixed data types (char, int, float, double) into specified file which is

Naveen(jntr)
opened in writing mode.

Example Program to illustrate "fprintf()" in C.


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

int main(){

FILE *fp;
char *text = "\nthis is example text";
int i = 10;
clrscr();
fp = fopen("MySample.txt","w");

fprintf(fp,"This is line1\nThis is line2\n%d", i);

fprintf(fp,text);
fclose(fp);
getch();

return 0;
}

Output

Prepared By B.Naveen Kumar (M.Tech.) JNTUH, Rajanna Siricilla. Page 136 of 210
I B.Tech EEE,CE,ME (R22) Unit - II C-Programming with Data Structures

 fputs( "string", *file_pointer ) - TThis method is used to insert string data into

specified file which is opened in writing mode.

Naveen(jntr)
Example Program to illustrate fputs() in C.
#include<stdio.h>
#include<conio.h>

int main(){

FILE *fp;
char *text = "\nthis is example text";
clrscr();
fp = fopen("MySample.txt","w");

fputs("Hi!\nHow are you?",fp);


fclose(fp);
getch();

return 0;
}

Output

Prepared By B.Naveen Kumar (M.Tech.) JNTUH, Rajanna Siricilla. Page 137 of 210
I B.Tech EEE,CE,ME (R22) Unit - II C-Programming with Data Structures

 fwrite( “StringData”, sizeof(char), numberOfCharacters, FILE *pointer ) - This

function is used to insert specified number of characters into a binary file which is

Naveen(jntr)
opened in writing mode.

Example Program to illustrate fwrite() in C.


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

int main(){

FILE *fp;
char *text = "Welcome to C Language";
clrscr();
fp = fopen("MySample.txt","wb");

fwrite(text,sizeof(char),5,fp);
fclose(fp);
getch();

return 0;
}

Output

Prepared By B.Naveen Kumar (M.Tech.) JNTUH, Rajanna Siricilla. Page 138 of 210
I B.Tech EEE,CE,ME (R22) Unit - II C-Programming with Data Structures

Closing a file

Naveen(jntr)
Closing a file is performed using a pre-defined method fclose().
fclose( *f_ptr )

The method fclose() returns '0'on success of file close otherwise it returns EOF (End Of File).

Cursor Positioning Functions in Files

C programming language provides various pre-defined methods to set the cursor position in

files. The following are the methods available in c, to position cursor in a file.

1. ftell()

2. rewind()

3. fseek()

 ftell( *file_pointer ) - This function returns the current position of the cursor in the

file.

Example Program to illustrate ftell() in C.


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

int main(){

FILE *fp;
int position;
clrscr();

Prepared By B.Naveen Kumar (M.Tech.) JNTUH, Rajanna Siricilla. Page 139 of 210
I B.Tech EEE,CE,ME (R22) Unit - II C-Programming with Data Structures

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

Naveen(jntr)

 rewind( *file_pointer ) - This function is used reset the cursor position to the

beginning of the file.

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

Prepared By B.Naveen Kumar (M.Tech.) JNTUH, Rajanna Siricilla. Page 140 of 210
I B.Tech EEE,CE,ME (R22) Unit - II C-Programming with Data Structures

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

Naveen(jntr)

 fseek( *file_pointer, numberOfCharacters, fromPosition ) - This function is used to

set the cursor position to the specific position. Using this function we can set the

cursor position from three different position they are as follows.

o from beginning of the file (indicated with 0)

o from current cursor position (indicated with 1)

o from ending of the file (indicated with 2)

Example Program to illustrate fseek() in C.


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

int main(){

FILE *fp;

Prepared By B.Naveen Kumar (M.Tech.) JNTUH, Rajanna Siricilla. Page 141 of 210
I B.Tech EEE,CE,ME (R22) Unit - II C-Programming with Data Structures

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;
Naveen(jntr)
Output

Error Handling in C
C programming language does not support error handling that are occured at program

execution time. However, C provides a header file called error.h. The header

file error.h contains few methods and variables that are used to locate error occured during

the program execution. Generally, c programming function returns NULL or -1 in case of

any error occured, and there is a global variable called errno which stores the error code or

error number. The following table lists few errno values and thier meaning.

Error Number Meaning

1 Specified operation not permitted

Prepared By B.Naveen Kumar (M.Tech.) JNTUH, Rajanna Siricilla. Page 142 of 210
I B.Tech EEE,CE,ME (R22) Unit - II C-Programming with Data Structures

Error Number Meaning

2 No such file or directory.

3 No such process.

4 Interrupted system call.

5 IO Error

6
Naveen(jntr) No such device or address

7 Argument list too long

8 Exec format error

9 Bad file number

10 No child processes

11 Try again

12 Out of memory

13 Permission denied

C programming language provides the following two methods to represent errors occured

during program execution.

 perror( )

 strerror( )

Prepared By B.Naveen Kumar (M.Tech.) JNTUH, Rajanna Siricilla. Page 143 of 210
I B.Tech EEE,CE,ME (R22) Unit - II C-Programming with Data Structures

perror( ) - The perror() function returns a string passed to it along with the textual

representation of current errno value.

strerror( ) - The strerror() function returns a pointer to the string representation of the

current errno value. This method is defined in the header file string.h

Consider the following example program...

Example Program to illustrate error handling in C.


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

int main(){

FILE *f_ptr; Naveen(jntr)


f_ptr = fopen("abc.txt", "r");

if(f_ptr == NULL){
printf("Value of errno: %d\n ", errno);
printf("The error message is : %s\n", strerror(errno));
perror("Message from perror");
}
else{
printf("File is opened in reading mode!");
fclose(f_ptr);
}

return 0;
}

Output

Prepared By B.Naveen Kumar (M.Tech.) JNTUH, Rajanna Siricilla. Page 144 of 210
I B.Tech EEE,CE,ME (R22) Unit - II C-Programming with Data Structures

C File Handling
In this tutorial, you will learn about file handling in C. You will learn to
handle standard I/O in C using fprintf(), fscanf(), fread(), fwrite(), fseek()
etc. with the help of examples.

A file is a container in computer storage devices used for storing data.

Naveen(jntr)
Why files are needed?

 When a program is terminated, the entire data is lost. Storing in a file


will preserve your data even if the program terminates.

 If you have to enter a large number of data, it will take a lot of time to
enter them all.
However, if you have a file containing all the data, you can easily
access the contents of the file using a few commands in C.
 You can easily move your data from one computer to another without
any changes.

Types of Files

When dealing with files, there are two types of files you should know about:

1. Text files

2. Binary files

1. Text files

Text files are the normal .txt files. You can easily create text files using any
simple text editors such as Notepad.
Prepared By B.Naveen Kumar (M.Tech.) JNTUH, Rajanna Siricilla. Page 145 of 210
I B.Tech EEE,CE,ME (R22) Unit - II C-Programming with Data Structures

When you open those files, you'll see all the contents within the file as plain
text. You can easily edit or delete the contents.

They take minimum effort to maintain, are easily readable, and provide the
least security and takes bigger storage space.

2. Binary files

Binary files are mostly the .bin files in your computer.


Instead of storing data in plain text, they store it in the binary form (0's and
1's).

They can hold a higher amount of data, are not readable easily, and
provides better security than text files.

Naveen(jntr)

File Operations

In C, you can perform four major operations on files, either text or binary:

1. Creating a new file

2. Opening an existing file

3. Closing a file

4. Reading from and writing information to a file

Working with files

When working with files, you need to declare a pointer of type file. This
declaration is needed for communication between the file and the program.

FILE *fptr;

Prepared By B.Naveen Kumar (M.Tech.) JNTUH, Rajanna Siricilla. Page 146 of 210
I B.Tech EEE,CE,ME (R22) Unit - II C-Programming with Data Structures

Opening a file - for creation and edit

Opening a file is performed using the fopen() function defined in


the stdio.h header file.
The syntax for opening a file in standard I/O is:

ptr = fopen("fileopen","mode");

For example,

Naveen(jntr)
fopen("E:\\cprogram\\newprogram.txt","w");

fopen("E:\\cprogram\\oldprogram.bin","rb");

 Let's suppose the file newprogram.txt doesn't exist in the location E:\

cprogram . The first function creates a new file named newprogram.txt and
opens it for writing as per the mode 'w'.
The writing mode allows you to create and edit (overwrite) the
contents of the file.
 Now let's suppose the second binary file oldprogram.bin exists in the
location E:\cprogram . The second function opens the existing file for
reading in binary mode 'rb'.
The reading mode only allows you to read the file, you cannot write
into the file.
Opening Modes in Standard I/O

Mod
Meaning of Mode During Inexistence of file
e

If the file does not exist, fopen() retur


r Open for reading.
NULL.

If the file does not exist, fopen() retur


rb Open for reading in binary mode.
NULL.

Prepared By B.Naveen Kumar (M.Tech.) JNTUH, Rajanna Siricilla. Page 147 of 210
I B.Tech EEE,CE,ME (R22) Unit - II C-Programming with Data Structures

Opening Modes in Standard I/O

Mod
Meaning of Mode During Inexistence of file
e

If the file exists, its contents are overwr


w Open for writing.
If the file does not exist, it will be creat

If the file exists, its contents are overwr


wb Open for writing in binary mode.
If the file does not exist, it will be creat

Open for append.


a If the file does not exist, it will be creat
Data is added to the end of the file.

ab
Naveen(jntr)
Open for append in binary mode.
Data is added to the end of the file.
If the file does not exist, it will be creat

If the file does not exist, fopen() retur


r+ Open for both reading and writing.
NULL.

If the file does not exist, fopen() retur


rb+ Open for both reading and writing in binary mode.
NULL.

If the file exists, its contents are overwr


w+ Open for both reading and writing.
If the file does not exist, it will be creat

If the file exists, its contents are overwr


wb+ Open for both reading and writing in binary mode.
If the file does not exist, it will be creat

a+ Open for both reading and appending. If the file does not exist, it will be creat

Open for both reading and appending in binary


ab+ If the file does not exist, it will be creat
mode.

Prepared By B.Naveen Kumar (M.Tech.) JNTUH, Rajanna Siricilla. Page 148 of 210
I B.Tech EEE,CE,ME (R22) Unit - II C-Programming with Data Structures

Closing a File

The file (both text and binary) should be closed after reading/writing.

Closing a file is performed using the fclose() function.

fclose(fptr);

Here, fptr is a file pointer associated with the file to be closed.

Reading and writing to a text file


Naveen(jntr)
For reading and writing to a text file, we use the
functions fprintf() and fscanf().

They are just the file versions of printf() and scanf() . The only difference is
that fprintf() and fscanf() expects a pointer to the structure FILE.

Example 1: Write to a text file

#include <stdio.h>
#include <stdlib.h>

int main()
{
int num;
FILE *fptr;

// use appropriate location if you are using MacOS or Linux


fptr = fopen("C:\\program.txt","w");

if(fptr == NULL)
{
printf("Error!");
exit(1);
}

Prepared By B.Naveen Kumar (M.Tech.) JNTUH, Rajanna Siricilla. Page 149 of 210
I B.Tech EEE,CE,ME (R22) Unit - II C-Programming with Data Structures

printf("Enter num: ");


scanf("%d",&num);

fprintf(fptr,"%d",num);
fclose(fptr);

return 0;
}

This program takes a number from the user and stores in the file program.txt .

After you compile and run this program, you can see a text
file program.txt created in C drive of your computer. When you open the file,
you can see the integer you entered.

Naveen(jntr)
Example 2: Read from a text file

#include <stdio.h>
#include <stdlib.h>

int main()
{
int num;
FILE *fptr;

if ((fptr = fopen("C:\\program.txt","r")) == NULL){


printf("Error! opening file");

// Program exits if the file pointer returns NULL.


exit(1);
}

fscanf(fptr,"%d", &num);

printf("Value of n=%d", num);


fclose(fptr);

return 0;
}

This program reads the integer present in the program.txt file and prints it
onto the screen.

Prepared By B.Naveen Kumar (M.Tech.) JNTUH, Rajanna Siricilla. Page 150 of 210
I B.Tech EEE,CE,ME (R22) Unit - II C-Programming with Data Structures

If you successfully created the file from Example 1, running this program
will get you the integer you entered.
Other functions like fgetchar() , fputc() etc. can be used in a similar way.

Reading and writing to a binary file

Functions fread() and fwrite() are used for reading from and writing to a file
on the disk respectively in case of binary files.

Naveen(jntr)
Writing to a binary file

To write into a binary file, you need to use the fwrite() function. The
functions take four arguments:
1. address of data to be written in the disk

2. size of data to be written in the disk

3. number of such type of data

4. pointer to the file where you want to write.

fwrite(addressData, sizeData, numbersData, pointerToFile);

Example 3: Write to a binary file using fwrite()

#include <stdio.h>
#include <stdlib.h>

Prepared By B.Naveen Kumar (M.Tech.) JNTUH, Rajanna Siricilla. Page 151 of 210
I B.Tech EEE,CE,ME (R22) Unit - II C-Programming with Data Structures

struct threeNum
{
int n1, n2, n3;
};

int main()
{
int n;
struct threeNum num;
FILE *fptr;

if ((fptr = fopen("C:\\program.bin","wb")) == NULL){


printf("Error! opening file");

// Program exits if the file pointer returns NULL.


exit(1);
}

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


{
Naveen(jntr)
num.n1 = n;
num.n2 = 5*n;
num.n3 = 5*n + 1;
fwrite(&num, sizeof(struct threeNum), 1, fptr);
}
fclose(fptr);

return 0;
}

In this program, we create a new file program.bin in the C drive.


We declare a structure threeNum with three numbers - n1, n2 and n3 , and
define it in the main function as num.
Now, inside the for loop, we store the value into the file using fwrite() .

The first parameter takes the address of num and the second parameter
takes the size of the structure threeNum .

Since we're only inserting one instance of num , the third parameter is 1 . And,
the last parameter *fptr points to the file we're storing the data.
Finally, we close the file.

Prepared By B.Naveen Kumar (M.Tech.) JNTUH, Rajanna Siricilla. Page 152 of 210
I B.Tech EEE,CE,ME (R22) Unit - II C-Programming with Data Structures

Reading from a binary file

Function fread() also take 4 arguments similar to the fwrite() function as


above.

fread(addressData, sizeData, numbersData, pointerToFile);

Example 4: Read from a binary file using fread()

#include <stdio.h>
#include <stdlib.h>

struct threeNum
Naveen(jntr)
{
int n1, n2, n3;
};

int main()
{
int n;
struct threeNum num;
FILE *fptr;

if ((fptr = fopen("C:\\program.bin","rb")) == NULL){


printf("Error! opening file");

// Program exits if the file pointer returns NULL.


exit(1);
}

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


{
fread(&num, sizeof(struct threeNum), 1, fptr);
printf("n1: %d\tn2: %d\tn3: %d\n", num.n1, num.n2, num.n3);
}
fclose(fptr);

return 0;
}

In this program, you read the same file program.bin and loop through the
records one by one.

Prepared By B.Naveen Kumar (M.Tech.) JNTUH, Rajanna Siricilla. Page 153 of 210
I B.Tech EEE,CE,ME (R22) Unit - II C-Programming with Data Structures

In simple terms, you read one threeNum record of threeNum size from the file
pointed by *fptr into the structure num .

You'll get the same records you inserted in Example 3.

Getting data using fseek()

If you have many records inside a file and need to access a record at a
specific position, you need to loop through all the records before it to get
the record.

Naveen(jntr)
This will waste a lot of memory and operation time. An easier way to get to
the required data can be achieved using fseek() .

As the name suggests, fseek() seeks the cursor to the given record in the
file.

Syntax of fseek()

fseek(FILE * stream, long int offset, int whence);

The first parameter stream is the pointer to the file. The second parameter
is the position of the record to be found, and the third parameter specifies
the location where the offset starts.

Different whence in fseek()

Whence Meaning

SEEK_SET Starts the offset from the beginning of the file.

SEEK_END Starts the offset from the end of the file.

Prepared By B.Naveen Kumar (M.Tech.) JNTUH, Rajanna Siricilla. Page 154 of 210
I B.Tech EEE,CE,ME (R22) Unit - II C-Programming with Data Structures

Different whence in fseek()

Whence Meaning

SEEK_CUR Starts the offset from the current location of the cursor in the file.

Example 5: fseek()

Naveen(jntr)
#include <stdio.h>
#include <stdlib.h>

struct threeNum
{
int n1, n2, n3;
};

int main()
{
int n;
struct threeNum num;
FILE *fptr;

if ((fptr = fopen("C:\\program.bin","rb")) == NULL){


printf("Error! opening file");

// Program exits if the file pointer returns NULL.


exit(1);
}

// Moves the cursor to the end of the file


fseek(fptr, -sizeof(struct threeNum), SEEK_END);

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


{
fread(&num, sizeof(struct threeNum), 1, fptr);
printf("n1: %d\tn2: %d\tn3: %d\n", num.n1, num.n2, num.n3);
fseek(fptr, -2*sizeof(struct threeNum), SEEK_CUR);
}
fclose(fptr);

return 0;

Prepared By B.Naveen Kumar (M.Tech.) JNTUH, Rajanna Siricilla. Page 155 of 210
I B.Tech EEE,CE,ME (R22) Unit - II C-Programming with Data Structures

This program will start reading the records from the file program.bin in the
reverse order (last to first) and prints it.

C Files Examples
In this article, you'll find a list of examples to handle file input/output
operations in C programming.

To understand all programs on this page, you should have the knowledge
of the following topics.

Naveen(jntr)
 C Arrays
 C Pointers
 Array and Pointer Relation
 File I/O

C File Examples

1. C program to read name and marks of n number of students and


store them in a file.

#include <stdio.h>
int main()
{
char name[50];
int marks, i, num;

printf("Enter number of students: ");


scanf("%d", &num);

FILE *fptr;
fptr = (fopen("C:\\student.txt", "w"));
if(fptr == NULL)
{
printf("Error!");
exit(1);

Prepared By B.Naveen Kumar (M.Tech.) JNTUH, Rajanna Siricilla. Page 156 of 210
I B.Tech EEE,CE,ME (R22) Unit - II C-Programming with Data Structures

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


{
printf("For student%d\nEnter name: ", i+1);
scanf("%s", name);

printf("Enter marks: ");


scanf("%d", &marks);

fprintf(fptr,"\nName: %s \nMarks=%d \n", name, marks);


}

fclose(fptr);
return 0;
}

Naveen(jntr)
2. C program to read name and marks of n number of students from
and store them in a file. If the file previously exits, add the information
to the file.

#include <stdio.h>
int main()
{
char name[50];
int marks, i, num;

printf("Enter number of students: ");


scanf("%d", &num);

FILE *fptr;
fptr = (fopen("C:\\student.txt", "a"));
if(fptr == NULL)
{
printf("Error!");
exit(1);
}

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


{
printf("For student%d\nEnter name: ", i+1);
scanf("%s", name);

printf("Enter marks: ");


scanf("%d", &marks);

fprintf(fptr,"\nName: %s \nMarks=%d \n", name, marks);


}

Prepared By B.Naveen Kumar (M.Tech.) JNTUH, Rajanna Siricilla. Page 157 of 210
I B.Tech EEE,CE,ME (R22) Unit - II C-Programming with Data Structures

fclose(fptr);
return 0;
}

3. C program to write all the members of an array of structures to a


file using fwrite(). Read the array from the file and display on the
screen.

#include <stdio.h>
struct student
{
char name[50];
int height;
};
int main(){

Naveen(jntr)
struct student stud1[5], stud2[5];
FILE *fptr;
int i;

fptr = fopen("file.txt","wb");
for(i = 0; i < 5; ++i)
{
fflush(stdin);
printf("Enter name: ");
gets(stud1[i].name);

printf("Enter height: ");


scanf("%d", &stud1[i].height);
}

fwrite(stud1, sizeof(stud1), 1, fptr);


fclose(fptr);

fptr = fopen("file.txt", "rb");


fread(stud2, sizeof(stud2), 1, fptr);
for(i = 0; i < 5; ++i)
{
printf("Name: %s\nHeight: %d", stud2[i].name, stud2[i].height);
}
fclose(fptr);
}

C Program to merge contents of two


files into a third file
 Difficulty Level : Easy
 Last Updated : 07 Jul, 2017

 Read
Prepared By B.Naveen Kumar (M.Tech.) JNTUH, Rajanna Siricilla. Page 158 of 210
I B.Tech EEE,CE,ME (R22) Unit - II C-Programming with Data Structures

 Discuss

 Courses

 Practice

 Video

Let the given two files be file1.txt and file2.txt. The following are steps to merge.
1) Open file1.txt and file2.txt in read mode.
2) Open file3.txt in write mode.
3) Run a loop to one by one copy characters of file1.txt to file3.txt.
4) Run a loop to one by one copy characters of file2.txt to file3.txt.
5) Close all files.
To successfully run the below program file1.txt and fil2.txt must exits in same folder.

#include <stdio.h>

#include <stdlib.h>
Naveen(jntr)
int main()

// Open two files to be merged

FILE *fp1 = fopen("file1.txt", "r");

FILE *fp2 = fopen("file2.txt", "r");

// Open file to store the result

FILE *fp3 = fopen("file3.txt", "w");

char c;

if (fp1 == NULL || fp2 == NULL || fp3 == NULL)

puts("Could not open files");

exit(0);

// Copy contents of first file to file3.txt

while ((c = fgetc(fp1)) != EOF)

fputc(c, fp3);

Prepared By B.Naveen Kumar (M.Tech.) JNTUH, Rajanna Siricilla. Page 159 of 210
I B.Tech EEE,CE,ME (R22) Unit - II C-Programming with Data Structures

// Copy contents of second file to file3.txt

while ((c = fgetc(fp2)) != EOF)

fputc(c, fp3);

printf("Merged file1.txt and file2.txt into file3.txt");

fclose(fp1);

fclose(fp2);

fclose(fp3);

return 0;

Output:
Naveen(jntr)
Merged file1.txt and file2.txt into file3.txt

C program to merge two files


This C program merges two files and stores their contents in another file.

The files which are to be merged are opened in read mode and the file which
contains content of both the files is opened in write mode. To merge two files first
we open a file and read it character by character and store the read contents in
another file then we read the contents of another file and store it in file, we read two
files until EOF (end of file) is reached.

Example:

#include<stdio.h>
#include<stdlib.h>

int main()
{

FILE *fs1, *fs2, *ft;


char ch, file1[20], file2[20], file3[20];

printf("Enter name of first file\n");


gets(file1);

printf("Enter name of second file\n");


gets(file2);
Prepared By B.Naveen Kumar (M.Tech.) JNTUH, Rajanna Siricilla. Page 160 of 210
I B.Tech EEE,CE,ME (R22) Unit - II C-Programming with Data Structures

printf("Enter name of file which will store contents of two files\n");


gets(file3);

fs1 = fopen(file1,"r");
fs2 = fopen(file2,"r");

if( fs1 == NULL || fs2 == NULL )


{
perror("Error ");

printf("Press any key to exit...\n");


getch();

exit(EXIT_FAILURE);
}

ft = fopen(file3,"w");

if( ft == NULL )
{
perror("Error "); Naveen(jntr)
printf("Press any key to exit...\n");

exit(EXIT_FAILURE);
}

while( ( ch = fgetc(fs1) ) != EOF )


fputc(ch,ft);

while( ( ch = fgetc(fs2) ) != EOF )


fputc(ch,ft);

printf("Two files were merged into %s file successfully.\n",file3);

fclose(fs1);
fclose(fs2);
fclose(ft);

return 0;
}
Program Output:

Prepared By B.Naveen Kumar (M.Tech.) JNTUH, Rajanna Siricilla. Page 161 of 210
I B.Tech EEE,CE,ME (R22) Unit - II C-Programming with Data Structures

C Program to Copy File


In this article, you will learn and get code about copying the
content of one file to another in C language. But before
going through the program given below, let's first
understand about the things that has to be done before
performing the copy file operation in C.

Things to do before Program

Before going to the program, let's first do the following


things:

 create two files namely codes.txt and cracker.txt


 Place these two files in the same directory where you
Naveen(jntr)
are going to save the source code file (of copy program
in C)

Let's suppose, here we have created a folder named c


programs to the parent directory of Documents folder of
my computer. Here is the snapshot of the folder named c
programs

Prepared By B.Naveen Kumar (M.Tech.) JNTUH, Rajanna Siricilla. Page 162 of 210
I B.Tech EEE,CE,ME (R22) Unit - II C-Programming with Data Structures

Because, this is newly created folder. So the folder is empty


for now. But I'm going to put some files related to copy file
programs

Now it's time to create a file named codes.txt with


following content.
this is codescracker.com

And create second file named cracker.txt without any


content. Save both file in the same folder as shown in the
snapshot given above, that is c programs folder. So the
folder now looks like:

Naveen(jntr)

If you open both the file, then you will see some content
present inside the first file codes.txt whereas the second
file, cracker.txt is empty. Now let's move on to the program
to copy the content of codes.txt file to cracker.txt file.

Program to Copy one File to Another in C

To copy the content of one file to another in C programming,


you have to first open both the file, that is, the source file
and the target file. And then start reading the source file's
content character by character and place or write the
content of source file to target file on every read of
character.

Prepared By B.Naveen Kumar (M.Tech.) JNTUH, Rajanna Siricilla. Page 163 of 210
I B.Tech EEE,CE,ME (R22) Unit - II C-Programming with Data Structures

The question is, write a program in C that copy the content


of one file to another file. The answer to this question is
given below:
#include<stdio.h>
#include<conio.h>
int main()
{
char ch, fileName1[20], fileName2[20];
FILE *fs, *ft;
printf("Enter Source File Name (with extension): ");
gets(fileName1);
fs = fopen(fileName1, "r");
if(fs == NULL)
{
printf("\nError in Opening the file, %s", fileName1);
getch();
return 0;
}
printf("Enter Target File Name (with extension): ");
gets(fileName2);

Naveen(jntr)
ft = fopen(fileName2, "w");
if(ft == NULL)
{
printf("\nError in Opening the file, %s", fileName2);
getch();
return 0;
}
ch = fgetc(fs);
while(ch != EOF)
{
fputc(ch, ft);
ch = fgetc(fs);
}
printf("\nFile copied successfully.");
fclose(fs);
fclose(ft);
getch();
return 0;
}

This program was build and run under Code::Blocks IDE.


Save the source code of above program in the same
directory, that is inside the folder named c programs. To
save it, use File->Save file as... navigation
inside Code::Blocks. Here we have used codescracker.c as
the name of source code file. After saving the source code
of above program in the folder c programs present inside
the Documents, the folder looks like:

Prepared By B.Naveen Kumar (M.Tech.) JNTUH, Rajanna Siricilla. Page 164 of 210
I B.Tech EEE,CE,ME (R22) Unit - II C-Programming with Data Structures

Naveen(jntr)
Now it's time to build and run the above program. Here is the
sample run:

Now supply the name of first file, codes.txt (source file as


created at early of this article inside the same folder where
the source code belongs to). Press ENTER key, then again
supply the name of another file say cracker.txt (the
destination file, where the content of source.txt file is
going to be copied). Finally press ENTER key to see the
following output:

Here is final snapshot of the folder c programs:

Prepared By B.Naveen Kumar (M.Tech.) JNTUH, Rajanna Siricilla. Page 165 of 210
I B.Tech EEE,CE,ME (R22) Unit - II C-Programming with Data Structures

Naveen(jntr)
Now if you will open the file cracker.txt (created with
empty content at early of this article), then you will see the
content of codes.txt file gets copied into it. That's it. To
learn more about file input and output operation in C, then
refer to File Input/Output in C tutorial.

SORTINGS
Explain the sorting techniques in C language
CServer Side ProgrammingProgramming

Problem
What are the different sorting techniques in C Language? Explain any one sorting technique
with an example.

Solution
C language provides five sorting techniques, which are as follows −

 Bubble sort (or) Exchange Sort.


 Selection sort.
 Insertion sort (or) Linear sort.
Prepared By B.Naveen Kumar (M.Tech.) JNTUH, Rajanna Siricilla. Page 166 of 210
I B.Tech EEE,CE,ME (R22) Unit - II C-Programming with Data Structures

 Quick sort (or) Partition exchange sort.


 Merge Sort (or) External sort.
Bubble sort
It is the simplest sorting technique which is also called as an exchange sort.

Procedure
 Compare the first element with the remaining elements in the list and
exchange(swap) them if they are not in order.
 Repeat the same for other elements in the list until all the elements gets sorted.
30 50 40 10 20
Consider the elements given below −

Naveen(jntr)

First pass
Compare first element with the remaining elements.

a[0] > a[1] □◻ □◻30 >50 (F) □◻ □◻no exchange


a[0] > a[2] □◻ □◻ 30 >40 (F) □◻ □◻ no exchange
a[0] > a[3] □◻ □◻ 30 >10 (T) □◻ □◻ exchange
a[0] > a[4] □◻ □◻ 10>20 (F) □◻ □◻ no exchange
10 50 40 30 20
Second Pass
Compare second element with the remaining elements.

Prepared By B.Naveen Kumar (M.Tech.) JNTUH, Rajanna Siricilla. Page 167 of 210
I B.Tech EEE,CE,ME (R22) Unit - II C-Programming with Data Structures

Naveen(jntr)

a[1] > a[2] □◻ □◻ 50 >40 (T) □◻ □◻ exchange


a[1] > a[3] □◻ □◻ 40 >30 (T) □◻ □◻ exchange
a[1] > a[4] □◻ □◻ 30 >20 (T) □◻ □◻ exchange
10 20 50 40 30
Third Pass
Compare third element with the remaining elements.

Prepared By B.Naveen Kumar (M.Tech.) JNTUH, Rajanna Siricilla. Page 168 of 210
I B.Tech EEE,CE,ME (R22) Unit - II C-Programming with Data Structures

a[2] > a[3] □◻ □◻ 50 >40 (T) □◻ □◻ exchange


a[2] > a[4] □◻ □◻ 40 >30 (T) □◻ □◻ exchange
10 20 30 50 40
Fourth Pass
Compare fourth element with the remaining elements.

Naveen(jntr)
a[3] > a[4] □◻ □◻ 50 >40 (T) □◻ □◻ exchange
10 20 30 40 50
Procedure
Refer the procedure for bubble sort as given below −
for (i=0; i<n-1; i++){
for (j=i+1; j<n; j++){
if (a[i] > a[j]){
t=a[i];
a[i] = a[j];
a[j] = t;
}
}
}

Example
Following is the C program for bubble sorting technique −
Live Demo

#include<stdio.h>
int main(){
int a[50], i,j,n,t;
printf("enter the No: of elements in the list:
");

Prepared By B.Naveen Kumar (M.Tech.) JNTUH, Rajanna Siricilla. Page 169 of 210
I B.Tech EEE,CE,ME (R22) Unit - II C-Programming with Data Structures

scanf("%d", &n);
printf("enter the elements:
");
for(i=0; i<n; i++){
scanf ("%d", &a[i]);
}
printf("Before bubble sorting the elements are:
");
for(i=0; i<n; i++)
printf("%d \t
", a[i]);
for (i=0; i<n-1; i++){
for (j=i+1; j<n; j++){
if (a[i] > a[j]){
t = a[i];
a[i] = a[j];
a[j] = t;
Naveen(jntr)
}
}
}
printf ("after bubble sorting the elements are:
");
for (i=0; i<n; i++)
printf("%d\t", a[i]);
return 0;
}

Output
When the above program is executed, it produces the following result −
enter the No: of elements in the list:
5
enter the elements:
12 11 45 26 67
Before bubble sorting the elements are:
12
11
45
26
67
after bubble sorting the elements are:
11 12 26 45 67

Prepared By B.Naveen Kumar (M.Tech.) JNTUH, Rajanna Siricilla. Page 170 of 210
I B.Tech EEE,CE,ME (R22) Unit - II C-Programming with Data Structures

C Program for Selection Sort


In this tutorial, we will learn about how to create a program
in C that sorts an array using Selection sort technique. At
last we have also created a function that can be used to
sort any given array in ascending order using selection sort
technique.

But before, going through the program, if you are not aware
about how selection sort works, then refer to the step by
step working of Selection Sort. Now let's move on and
implement it in a C program.

C Selection Sort Program

Naveen(jntr)
To sort an array in ascending order using selection sort
technique in C programming, you have to ask from user to
enter the array size and its elements. Then apply the
selection sort mechanism and print the sorted array as
output just like the program given below:
#include<stdio.h>
#include<conio.h>
int main()
{
int size, arr[50], i, j, temp, small, count=0, index;
printf("Enter size for Array: ");
scanf("%d", &size);
printf("Enter %d array elements: ", size);
for(i=0; i<size; i++)
scanf("%d", &arr[i]);
for(i=0; i<(size-1); i++)
{
small = arr[i];
for(j=(i+1); j<size; j++)
{
if(small>arr[j])
{
small = arr[j];
count++;
index = j;
}
}
if(count!=0)
{
temp = arr[i];
arr[i] = small;
arr[index] = temp;
}
count=0;
}
printf("\nNow the Array after sorting is:\n");
for(i=0; i<size; i++)
printf("%d ", arr[i]);
getch();

Prepared By B.Naveen Kumar (M.Tech.) JNTUH, Rajanna Siricilla. Page 171 of 210
I B.Tech EEE,CE,ME (R22) Unit - II C-Programming with Data Structures

return 0;
}

As the above program was written under Code::Blocks IDE,


therefore here is the sample run after successful build and
run. This is the first snapshot of sample run:

Now supply size for array say 5 and its element as 54 21 8


18 3 and press ENTER key to see the sorted array as shown
Naveen(jntr)
in the second snapshot of sample run given here:

Here is another sample run. This is the final snapshot:

Prepared By B.Naveen Kumar (M.Tech.) JNTUH, Rajanna Siricilla. Page 172 of 210
I B.Tech EEE,CE,ME (R22) Unit - II C-Programming with Data Structures

Naveen(jntr)
C Selection Sort Program Explained

 Receive size of array by user at run-time


 Receive elements of that size for array by user at run-
time
 For example, if user has supplied 5 as array size, then
ask him/her to enter 5 array elements
 Create a for loop that runs from 0 to one less than the
(size-1) of array. That is, if array's size is 5 then run
the loop from 0 to one less than 5-1 or 4
 Inside the loop, initialize element present at current
index to a variable say small
 And using another for loop (runs from 0 to one less
than the size of array), check whether the value
in small variable is greater than any element (present
at index equals to value of i+1 to (size-1 or 4)) or not
 If it is, then initialize that element
to small variable and increment the count variable,
then initialize the current value of j (inner for loop
variable) to index variable (holds index number where
smallest element presents)
 Never forgot to initialize 0 to count variable at start of
the program
 Now after exiting from the inner for loop, check
whether count holds any value other than 0 or not

Prepared By B.Naveen Kumar (M.Tech.) JNTUH, Rajanna Siricilla. Page 173 of 210
I B.Tech EEE,CE,ME (R22) Unit - II C-Programming with Data Structures

 If it holds any value other than 0, then program flow


gone inside the if statement of inner for loop. And it
means, any element was initialized to small variable
 Therefore, we have to perform swapping operation, that
is place element at beginning to any variable say temp,
and then initialize value of small at beginning, and at
last value of temp is initialized at that index from
where the element was initialized to small variable
before swapping
 After swapping, initialize 0 to count variable and
continue
 For example, if user has entered 5 as array size and 54
21 8 18 3 as array elements
 Then at first run of for loop, i holds 0. And i<(size-

Naveen(jntr)
1) or 0<0(5-1) or 0<4 evaluates to be true. Therefore
program flow goes inside the loop
 The value at arr[0] or 54 gets initialized to small.
Therefore small holds 54
 Now in inner for loop, and value of i+1 (0+1)
or 1 gets initialized to j (inner loop's variable).
Therefore j holds 1. And 1 is less than size or 5.
Therefore program flow goes inside inner for loop
 Now the
statement small>arr[j] or 54>arr[1] or 54>21 gets
evaluated to be true,
therefore arr[j] or arr[1] or 21 gets initialized
to small. The value of count gets incremented and
becomes 1, and value of j or 1 gets initialized
to index
 Again value of j gets incremented and compared that
whether j is less than size or not, that is j (2) is less
than size(5), therefore again program flow goes inside
the loop
 And
again small>arr[j] or 21>arr[2] or 21>8 evaluates to
be true, therefore after swapping
 The
variable small holds 8, count holds 2, index holds 2
 Again value of j gets incremented and compared that
whether j is less than size or not, that is j (3) is less

Prepared By B.Naveen Kumar (M.Tech.) JNTUH, Rajanna Siricilla. Page 174 of 210
I B.Tech EEE,CE,ME (R22) Unit - II C-Programming with Data Structures

than size(5), therefore again program flow goes inside


the loop
 And again small>arr[j] or 8>arr[3] or 8>18 evaluates
to be false, therefore no swapping gets performed
 The
variable small holds 8, count holds 2, index holds 2
 Again value of j gets incremented and compared that
whether j is less than size or not, that is j (4) is less
than size(5), therefore again program flow goes inside
the loop
 And again small>arr[j] or 8>arr[4] or 8>3 evaluates
to be true, therefore after swapping
 The
variable small holds 3, count holds 3, index holds 4

Naveen(jntr)
Again value of j gets incremented and compared that
whether j is less than size or not, that is j (5) is less
than size(5) or not. Here the condition evaluates to be
false and program flow goes back at outer for loop and
increments the value of i. Then checks the condition,
that whether i is less than size-1 or 5-1 or 4 or not.
It evaluates to be true, therefore program flow again
goes inside the loop and do the similar steps as told
above until the condition of outer for loop gets
evaluated as false

If you want to print array elements as step by step sorting of


array elements shown on output screen along with its final
array. Then you can modify the above code as shown below
to print array elements after each sorting step:
#include<stdio.h>
#include<conio.h>
int main()
{
int size, arr[50], i, j, temp, small, count=0, index;
printf("Enter size for Array: ");
scanf("%d", &size);
printf("Enter %d array elements: ", size);
for(i=0; i<size; i++)
scanf("%d", &arr[i]);
for(i=0; i<(size-1); i++)
{
small = arr[i];
for(j=(i+1); j<size; j++)
{
if(small>arr[j])
{
small = arr[j];
count++;

Prepared By B.Naveen Kumar (M.Tech.) JNTUH, Rajanna Siricilla. Page 175 of 210
I B.Tech EEE,CE,ME (R22) Unit - II C-Programming with Data Structures

index = j;
}
}
if(count!=0)
{
temp = arr[i];
arr[i] = small;
arr[index] = temp;
}
printf("\nStep %d: ", i+1);
for(j=0; j<size; j++)
printf("%d ", arr[j]);
printf("\n");
count=0;
}
printf("\nNow the Array after sorting is:\n");
for(i=0; i<size; i++)
printf("%d ", arr[i]);
getch();
return 0;
}

Here is the final snapshot of the sample run:

Naveen(jntr)

Selection Sort in C using Function

Let's create the same program, that is to sort an array in


ascending order using selection sort technique, but this
time, with the help of function. Here selection sort is
implemented inside a function named selsort() that uses
two arguments, one is array and second is its size as shown
in the program given below:
#include<stdio.h>

Prepared By B.Naveen Kumar (M.Tech.) JNTUH, Rajanna Siricilla. Page 176 of 210
I B.Tech EEE,CE,ME (R22) Unit - II C-Programming with Data Structures

#include<conio.h>
void selsort(int arr[], int size);
int main()
{
int size, arr[50], i;
printf("Enter size for Array: ");
scanf("%d", &size);
printf("Enter %d array elements: ", size);
for(i=0; i<size; i++)
scanf("%d", &arr[i]);
selsort(arr, size);
printf("\nThe sorted Array is:\n");
for(i=0; i<size; i++)
printf("%d ", arr[i]);
getch();
return 0;
}
void selsort(int arr[], int size)
{
int i, j, temp, small, count=0, index;
for(i=0; i<(size-1); i++)
{
small = arr[i];

Naveen(jntr)
for(j=(i+1); j<size; j++)
{
if(small>arr[j])
{
small = arr[j];
count++;
index = j;
}
}
if(count!=0)
{
temp = arr[i];
arr[i] = small;
arr[index] = temp;
}
count=0;
}
}

Here is the final snapshot of the above program:

The concept used in above program is similar as used in first


program except we have implemented a
function selsort() here. All the selection sort technique is
Prepared By B.Naveen Kumar (M.Tech.) JNTUH, Rajanna Siricilla. Page 177 of 210
I B.Tech EEE,CE,ME (R22) Unit - II C-Programming with Data Structures

implemented inside this function. We only have to pass any


array and its size to this function as its argument. And all
the elements inside the array gets sorted in ascending
order.

C Program for Bubble Sort


In this tutorial, we will learn about how to create a program
in C that sorts an array in ascending order using bubble
sort technique. At last we have also created a function that
can be used to sort any given array in ascending order.

But before going through the program, if you are not aware
of how bubble sorts works, then refer to the step by step

Naveen(jntr)
working of Bubble Sort. Now let's move on and implement it
in C program.

Bubble Sort in C

Now let's implement bubble sort in a C program as given


below. I'll explain each and every line of code later on. The
question is, write a program in C that sorts given array in
ascending order using Bubble Sort technique. The answer to
this question is:
#include<stdio.h>
#include<conio.h>
int main()
{
int arr[50], i, j, n, temp;
printf("Enter total number of elements to store: ");
scanf("%d", &n);
printf("Enter %d elements:", n);
for(i=0; i<n; i++)
scanf("%d", &arr[i]);
printf("\nSorting array using bubble sort technique...\n");
for(i=0; i<(n-1); i++)
{
for(j=0; j<(n-i-1); j++)
{
if(arr[j]>arr[j+1])
{
temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
}
}
}
printf("All Array elements sorted successfully!\n");
printf("Array elements in ascending order:\n\n");
for(i=0; i<n; i++)
printf("%d ", arr[i]);
getch();

Prepared By B.Naveen Kumar (M.Tech.) JNTUH, Rajanna Siricilla. Page 178 of 210
I B.Tech EEE,CE,ME (R22) Unit - II C-Programming with Data Structures

return 0;
}

As the above program was written under Code::Blocks IDE,


therefore after successful build and run, here is the first
snapshot of the sample run:

Now supply size for the array say 10 and then


enter 10 array elements. After providing array size and its
element, press ENTER key to sort and print all array
Naveen(jntr)
elements in Ascending order using bubble sort method. Here
is the second snapshot of the sample run:

Program Explained

 We have asked from user to enter array size


 Then to enter array elements of that size
 Now for sorting, we have used first (outer) for
loop from 0 to (n-1) as array indexing starts from 0 not
1.

Prepared By B.Naveen Kumar (M.Tech.) JNTUH, Rajanna Siricilla. Page 179 of 210
I B.Tech EEE,CE,ME (R22) Unit - II C-Programming with Data Structures

 And then second (inner) for loop from 0 to (n-i-1). As


we have to compare two consecutive element, and if
first element is greater than second, then we have to
swap.
 For example, if value of i is 0, then value of j will also
be 0, and then using if statement, 0th element is
compared with (0+1)th or 1st element. If the element
present at 0 will be greater than the element present at
1, then the swapping will be performed.
 The loop will run upto the end that is, if total of 10
elements in the array, then at last the 8th element will
gets compared with (8+1)th element, that is 9th element
which is the last one.
 After running the loop to check, compare and swap

Naveen(jntr)
each and every consecutive element (or every jth to
(j+1)th element), we have sorted the array in ascending
order.
 Finally print out the same array that will show all of its
element in ascending order

Display Array after Each Sort

If you want to display the array after each sort, then here is
the program you may go for:
#include<stdio.h>
#include<conio.h>
int main()
{
int arr[10], i, j, temp;
printf("Enter 10 array elements:");
for(i=0; i<10; i++)
scanf("%d", &arr[i]);
for(i=0; i<(10-1); i++)
{
for(j=0; j<(10-i-1); j++)
{
if(arr[j]>arr[j+1])
{
temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
}
}
printf("\n");
printf("Step %d: ", i+1);
for(j=0; j<10; j++)
printf("%d ", arr[j]);
printf("\n");
}
printf("\nSorted Array is:\n");
for(i=0; i<10; i++)
printf("%d ", arr[i]);

Prepared By B.Naveen Kumar (M.Tech.) JNTUH, Rajanna Siricilla. Page 180 of 210
I B.Tech EEE,CE,ME (R22) Unit - II C-Programming with Data Structures

getch();
return 0;
}

Here is the final snapshot of this program:

Naveen(jntr)

Bubble Sort Program in C using Function

Here is another program that does the same job using a


user-defined function bubbleSort():
#include<stdio.h>
#include<conio.h>
void bubbleSort(int arr[], int n);
int main()
{
int arr[100], nos, i;
printf("How many element that has to be sorted ? ");

Prepared By B.Naveen Kumar (M.Tech.) JNTUH, Rajanna Siricilla. Page 181 of 210
I B.Tech EEE,CE,ME (R22) Unit - II C-Programming with Data Structures

scanf("%d", &nos);
printf("\n");
for(i=0; i<nos; i++)
{
printf("Enter integer value for element no.%d: ",i+1);
scanf("%d",&arr[i]);
}
bubbleSort(arr, nos);
printf("\n\nFinally sorted array is:\n");
for(i=0; i<nos; i++)
printf("%d\n",arr[i]);
getch();
return 0;
}
void bubbleSort(int arr[], int no)
{
int i, j, temp;
for(i=no-2; i>=0; i--)
{
for(j=0; j<=i; j++)
{
if(arr[j]>arr[j+1])
{

Naveen(jntr)
temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
}
}
}
}

After successful build and run. Here is the first screenshot


of the sample run:

And here is the second screenshot of the sample run:

Prepared By B.Naveen Kumar (M.Tech.) JNTUH, Rajanna Siricilla. Page 182 of 210
I B.Tech EEE,CE,ME (R22) Unit - II C-Programming with Data Structures

Program Explained
Naveen(jntr)
All the steps are same as discussed in very first program (of
this article) except function. As here we have used function
to implement bubble sort. Here are some of the main steps
that tells how to use function in this case:

 Here we have asked from user to enter array size and


then all elements of that size one by one using for loop
 We have passed the array and array size to function.
Passing array means passing array elements, here
array size that comes in square bracket, example,
arr[10] is optional.
 After above two steps, we are at function step. In
function, we have used same technique as discussed
above, that is comparing each consecutive elements
from start to end.
 If first is greater than second, then swap, if second is
greater than third then swap and so on.
 But here we have initialized i with (no-1).
Here no indicates to total number of element. For
example, if total number of element is 10, then i is
initialized to 8, and in second loop, j is initialized with 0.
 Then at first run, the jth element is compared with
(j+1)th element. That is 0th element is compared with
(0+1)th element (1st) element. At second run,
1st element is compared with 2nd element and so on.

Prepared By B.Naveen Kumar (M.Tech.) JNTUH, Rajanna Siricilla. Page 183 of 210
I B.Tech EEE,CE,ME (R22) Unit - II C-Programming with Data Structures

This loop will run total of 8 times to compare


8th element with 9th element which is the last element.
 After successfully doing all the above steps, the
function execution will be over and our array gets
sorted in ascending order.
 Now we only have to display the array element with the
help of loop

C Program for Insertion Sort


In this tutorial, we will learn about how to create a program
in C that sorts an array in ascending order using insertion
sort technique. Here we have also created a function that
can be used to sort any given array (by user at run-time) as

Naveen(jntr)
per insertion sort technique in ascending order.

But before going through the program, if you are not aware
about how a insertion sort actually works, then I recommend
you to go through the step by step working of Insertion Sort.
Let's move on and implement it in a C program.

Insertion Sort in C

Let's go through the insertion sort program first. Later on, I'll
explain each and every steps involved in this program. The
question is, Write a program in C that sorts any given array
in Ascending order using insertion sort technique. The
answer to this question is:
#include<stdio.h>
#include<conio.h>
int main()
{
int arr[50], size, i, j, k, element, index;
printf("Enter Array Size: ");
scanf("%d", &size);
printf("Enter %d Array Elements: ", size);
for(i=0; i<size; i++)
scanf("%d", &arr[i]);
for(i=1; i<size; i++)
{
element = arr[i];
if(element<arr[i-1])
{
for(j=0; j<=i; j++)
{
if(element<arr[j])
{
index = j;
for(k=i; k>j; k--)
arr[k] = arr[k-1];
Prepared By B.Naveen Kumar (M.Tech.) JNTUH, Rajanna Siricilla. Page 184 of 210
I B.Tech EEE,CE,ME (R22) Unit - II C-Programming with Data Structures

break;
}
}
}
else
continue;
arr[index] = element;
}
printf("\nSorted Array:\n");
for(i=0; i<size; i++)
printf("%d ", arr[i]);
getch();
return 0;
}

As the above program was written under Code::Blocks IDE,


therefore after successful build and run, you will get the
following output. Here is the first snapshot of the sample
run:

Naveen(jntr)

Now supply size for the array say 5 and enter any 5 array
elements. And then press ENTER key to sort that array. Here
is the second snapshot of the sample run:

Let's take another sample run. Here is the final snapshot of


the sample run:

Prepared By B.Naveen Kumar (M.Tech.) JNTUH, Rajanna Siricilla. Page 185 of 210
I B.Tech EEE,CE,ME (R22) Unit - II C-Programming with Data Structures

Program Explained

 Receive size for an array and then receive elements of


that size
That is, if user supplied 5 as array size, then ask
Naveen(jntr)

him/her to enter any 5 elements for that array
 Create a for loop that runs from 1 to one less than the
size of the array
 Inside the loop, initialize the current element, that is
element present at ith index of the array to
any variable say element
 Use if statement to check whether the current
element is less than the previous element or not
o If it is, then program flow goes inside the if block
o Inside the if block, create another for loop that
runs from start (0) to less than or equal to the
value of i (outer loop variable)
o Inside this loop, check whether the value
of element is less than the value of arr[j] or not
o If it is, then initialize the current index to a
variable say index and push all the element to its
next index one by one using for loop
o That is create a for loop that starts from the
value of i and runs until it is greater than the
value of j (outer loop variable)
o Never forgot to use break keyword to break out of
the for loop
 And if the statement of if's condition evaluates to be
false, then use continue keyword to tell the compiler
to go back to the outer for loop. That is increment its

Prepared By B.Naveen Kumar (M.Tech.) JNTUH, Rajanna Siricilla. Page 186 of 210
I B.Tech EEE,CE,ME (R22) Unit - II C-Programming with Data Structures

variable and continue to do the same process as told


above
 After performing this and continue to increment the
first for loop variable (i), initialize the value
of element variable at arr[index]
 For example, if user has supplied 1 5 2 4 3 as array
 Therefore, at first run of for loop
 The loop variable i is initialized to 1
and i<size or 1<5 evaluates to be true, therefore
program flow goes inside the loop
 The value at arr[i] or arr[1] or 5 gets initialized
to element
 And element<arr[i-1] or 5<arr[0] or 5<1 evaluates to
be false, therefore program flow goes to else block,

Naveen(jntr)
and using continue keyword program flow goes back
to the first for loop
 That is, there was no any swapping gets placed,
therefore the array is still in its original order which
is 1 5 2 4 3
 As the program flow again came back to the for loop
and increments the value of i
 Now i holds 2, and i<size or 2<5 evaluates to be
true. Therefore program flow goes inside the loop again
 Value at arr[i] or arr[2] or 2 gets initialized
to element
 And element<arr[i-1] or 2<arr[1] or 2<5 evaluates to
be true, therefore program flow goes inside
the if block
 The value of j (loop variable of inner for loop) gets
initialized with 0, and j<=i or 0<=2 evaluates to be
true, therefore program flow goes inside the loop
 And element<arr[j] or 2<1 evaluates to be false,
therefore program flow goes back to inner for loop and
increments the value of j
 Now j holds 1 and j<=i or 1<=2 evaluates to be true.
Therefore program flow goes inside the loop
 And again element<arr[j] or 2<5 evaluates to be true,
therefore program flow goes inside the if block
 And j or 1 gets initialized to index variable. And
value of i or 2 gets initialized to k (loop variable)

Prepared By B.Naveen Kumar (M.Tech.) JNTUH, Rajanna Siricilla. Page 187 of 210
I B.Tech EEE,CE,ME (R22) Unit - II C-Programming with Data Structures

 And k>j or 2>1 evaluates to be true, therefore


program flow goes inside the loop and arr[k-
1] or arr[1] or 5 gets initialized at arr[k] or arr[2]
 The value of k now gets decremented and becomes 1.
And k>j or 1>1 evaluates to be false
 Therefore, program flow goes out of this loop, and
found break keyword. Using this program flow exits
the outer for loop (second one) and goes back to
first for loop
 Now the new array is 1 2 5 4 3
 There the value of i again gets incremented
and i<size or 3<5 evaluates to be true, therefore
program flow again goes inside the loop and follow the
same procedure as told above to sort the array as per

Naveen(jntr)
insertion sort technique

Print Array after each Insertion Sort

If you want to see the step by step array after each sorting
on output screen, then you can modify the above program
with below one:
#include<stdio.h>
#include<conio.h>
int main()
{
int arr[50], size, i, j, k, element, index;
printf("Enter Array Size: ");
scanf("%d", &size);
printf("Enter %d Array Elements: ", size);
for(i=0; i<size; i++)
scanf("%d", &arr[i]);
for(i=1; i<size; i++)
{
element = arr[i];
if(element<arr[i-1])
{
for(j=0; j<=i; j++)
{
if(element<arr[j])
{
index = j;
for(k=i; k>j; k--)
arr[k] = arr[k-1];
break;
}
}
}
else
continue;
arr[index] = element;
printf("\nStep %d: ", i);
for(j=0; j<size; j++)
printf("%d ", arr[j]);
printf("\n");

Prepared By B.Naveen Kumar (M.Tech.) JNTUH, Rajanna Siricilla. Page 188 of 210
I B.Tech EEE,CE,ME (R22) Unit - II C-Programming with Data Structures

}
printf("\nSorted Array:\n");
for(i=0; i<size; i++)
printf("%d ", arr[i]);
getch();
return 0;
}

Here is the final snapshot of sample run:

Naveen(jntr)

Here is another final snapshot of another sample run:

Prepared By B.Naveen Kumar (M.Tech.) JNTUH, Rajanna Siricilla. Page 189 of 210
I B.Tech EEE,CE,ME (R22) Unit - II C-Programming with Data Structures

Naveen(jntr)

Insertion Sort in C using while Loop

Let's create another program that also sorts any given array
in ascending order as per insertion sort technique. Here we
have used while loop to short the code:
#include<stdio.h>
#include<conio.h>
int main()
{
int arr[5], i, j, elem;
printf("Enter any 5 array elements: ");
for(i=0; i<5; i++)
scanf("%d", &arr[i]);
for(i=1; i<5; i++)
{
elem = arr[i];
j = i-1;
while((elem<arr[j]) && (j>=0))
{
arr[j+1] = arr[j];
j--;
}
arr[j+1] = elem;
}
printf("\nSorted Array in ascending order:\n");
for(i=0; i<5; i++)
printf("%d ", arr[i]);
getch();
return 0;

Prepared By B.Naveen Kumar (M.Tech.) JNTUH, Rajanna Siricilla. Page 190 of 210
I B.Tech EEE,CE,ME (R22) Unit - II C-Programming with Data Structures

Here is the final snapshot of sample run:

Insertion Sort in C using Function

Naveen(jntr)
Let's create a function that takes any two argument (array
and its size) to sort that array in ascending order as per
insertion sort technique. Here is the program that works
same as above except that here we have created a function
that performs sorting:
#include<stdio.h>
#include<conio.h>
void insertsort(int arr[], int size);
int main()
{
int arr[50], size, i;
printf("How many element you want to store? ");
scanf("%d", &size);
printf("Enter any %d array elements: ", size);
for(i=0; i<size; i++)
scanf("%d", &arr[i]);
insertsort(arr, size);
printf("\nSorted Array in ascending order:\n");
for(i=0; i<size; i++)
printf("%d ", arr[i]);
getch();
return 0;
}
void insertsort(int arr[], int size)
{
int i, elem, j;
for(i=1; i<size; i++)
{
elem = arr[i];
j = i-1;
while((elem<arr[j]) && (j>=0))
{
arr[j+1] = arr[j];
j--;
}
arr[j+1] = elem;
}
}

Prepared By B.Naveen Kumar (M.Tech.) JNTUH, Rajanna Siricilla. Page 191 of 210
I B.Tech EEE,CE,ME (R22) Unit - II C-Programming with Data Structures

As you can see from the above program, we have declared a


function at start of the program, that is
before main() function. This function takes any two
argument, first is the array and second is for its size. We
have defined the function so that after calling the function,
program successfully performs the action as defined in the
function definition. Here is the final snapshot of the sample
run:

Naveen(jntr)

C Program for Linear Search


In this article, you will learn and get code about searching of
a number or an element from given array using linear
search technique. But before going through the program, if
you want to check out the algorithm used for linear search,
then refer to Linear Search.

Linear Search in C

Linear search is an easiest way to search an element from


an array. It is also easy to learn. Let's first create a program
on it. The question is Write a Program in C that asks from
user to enter any 10 array elements, and then ask to enter a
number to search from the given array. The answer to this
question is:
#include<stdio.h>
#include<conio.h>
int main()
{
int arr[10], i, num, pos;
printf("Enter any 10 Numbers: ");
Prepared By B.Naveen Kumar (M.Tech.) JNTUH, Rajanna Siricilla. Page 192 of 210
I B.Tech EEE,CE,ME (R22) Unit - II C-Programming with Data Structures

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


scanf("%d", &arr[i]);
printf("\nEnter a Number to Search: ");
scanf("%d", &num);
for(i=0; i<10; i++)
{
if(arr[i]==num)
{
pos=i;
break;
}
}
printf("\nFound at Index No.%d", pos);
getch();
return 0;
}

This program was build and run under Code::Blocks IDE.


Here is its sample run:

Naveen(jntr)

Now supply any 10 numbers say 1, 2, 3, 4, 5, 6, 7, 8, 9,


10 and then enter a number say 7 to search. On pressing
the ENTER. Here is the output produced:

As you can see from the above code, the number (stored
in num) gets compared with each and every number one by

Prepared By B.Naveen Kumar (M.Tech.) JNTUH, Rajanna Siricilla. Page 193 of 210
I B.Tech EEE,CE,ME (R22) Unit - II C-Programming with Data Structures

one. That is, first number (number at 0th index) gets


compared to num. If found, then initial the index to a
variable say pos and with the help of break keyword, exit
the loop. Print the value of pos as number's index.
Otherwise check for the number at next index. Continue the
process until the number gets found.

Note - Previous program has two limitations. The first one


is, if user enters a number that does not available in the list.
And the second one is, if user enters a number that present
more than one time in the list or array. To overcome this
problem, we have created another program.

Linear Search with Duplicates in C

Naveen(jntr)
This program find and prints index number at which the
number is available. If the given number present in the given
array in repeated order. Then this program also prints its all
the indexes where it is available.
#include<stdio.h>
#include<conio.h>
int main()
{
int arr[50], size, i, num, arrTemp[50], j=0, count=0;
printf("Enter Array Size: ");
scanf("%d", &size);
printf("\nEnter any %d Array Elements: ", size);
for(i=0; i<size; i++)
scanf("%d", &arr[i]);
printf("\nEnter a Number to Search: ");
scanf("%d", &num);
for(i=0; i<size; i++)
{
if(arr[i]==num)
{
arrTemp[j] = i;
j++;
count++;
}
}
if(count>0)
{
printf("\nNumber Found at Index No.");
size = count;
for(i=0; i<size; i++)
printf("%d ", arrTemp[i]);
}
else
printf("\nNumber does not Found!");
getch();
return 0;
}

Prepared By B.Naveen Kumar (M.Tech.) JNTUH, Rajanna Siricilla. Page 194 of 210
I B.Tech EEE,CE,ME (R22) Unit - II C-Programming with Data Structures

Let's suppose user has entered array size as 10 and its 10


elements as 1, 2, 3, 4, 5, 4, 6, 4, 7, 4. And 4 is the number
to be search. Therefore here is its sample output you will
see:

Naveen(jntr)

Here the main logic used is:

 If number gets matched. Then just initialize the current


index number to another array say arrTemp[]
 Increment a variable say count every time,
initializing the index number to the array arrTemp[]
 The array arrTemp[] holds index number(s) where the
number is available and the variable count holds the
size of arrTemp[]

C Program for Binary Search


In this article, you'll learn and get code about how to search
an element from given array using binary search technique.
But before going through the program, if you are not aware
of how binary search works, then I recommend you to go
through the step by step working of Binary search.

Here are the list of programs you will go through over here,
with its step by step explanation:
Prepared By B.Naveen Kumar (M.Tech.) JNTUH, Rajanna Siricilla. Page 195 of 210
I B.Tech EEE,CE,ME (R22) Unit - II C-Programming with Data Structures

 Binary Search without using Function


 Binary Search using Function
 Binary Search using Recursion

Binary Search in C

This is the simplest program of binary search. Simplest in


the sense, here we have directly asked from user to enter 10
element or numbers without giving to specify the size of
array and then enter his/her required amount of element.
Also the sorting code block is not included in this program.
So I've just asked to enter already sorted array as input.
Let's take a look at the program:
#include<stdio.h>
#include<conio.h>
int main()
{ Naveen(jntr)
int i, arr[10], search, first, last, middle;
printf("Enter 10 elements (in ascending order): ");
for(i=0; i<10; i++)
scanf("%d", &arr[i]);
printf("\nEnter element to be search: ");
scanf("%d", &search);
first = 0;
last = 9;
middle = (first+last)/2;
while(first <= last)
{
if(arr[middle]<search)
first = middle+1;
else if(arr[middle]==search)
{
printf("\nThe number, %d found at Position %d", search,
middle+1);
break;
}
else
last = middle-1;
middle = (first+last)/2;
}
if(first>last)
printf("\nThe number, %d is not found in given Array", search);
getch();
return 0;
}

This program was written under Code::Blocks IDE. Here is


the initial snapshot of sample run:

Prepared By B.Naveen Kumar (M.Tech.) JNTUH, Rajanna Siricilla. Page 196 of 210
I B.Tech EEE,CE,ME (R22) Unit - II C-Programming with Data Structures

Now provide any 10 elements in ascending order, say 1, 2,


3, 4, 5, 6, 7, 8, 9, and 10 and then press ENTER key. Again
enter any element or number to be search say 7,
press ENTER key to see the output given in the snapshot
here:

Naveen(jntr)

If user supply all the 10 numbers as entered in above output.


But this time, when he/she entered any number say 15 to
be search from the given list of number, then here is the
output you will see:

Prepared By B.Naveen Kumar (M.Tech.) JNTUH, Rajanna Siricilla. Page 197 of 210
I B.Tech EEE,CE,ME (R22) Unit - II C-Programming with Data Structures

Program Explained
Naveen(jntr)
1. Declare all the required variable say i, arr[], search,
first, last, middle of int (integer type)
2. Here arr[] is declared of size 10 to store upto 10
elements or numbers
3. Now receive 10 numbers as input from user
4. As indexing in an array starts from 0, so first element
gets stored in arr[0], second element gets stored
in arr[1], and so on
5. Now ask to enter the number to be search and store it
in search variable
6. Now initialize 0 to first (index), 9 to last (index), and
find the value of middle (index) using first+last/2
7. Create a while loop, that continue running until the
value of first (index) becomes less than or equal to the
value of last (index)
8. The meaning of above step is, process inside the loop
continue running until the interval becomes zero, as
told in the logic given at start of this article
9. Inside the while loop, first check whether value at
middle index (arr[middle]) is less than search (number
to be search) or not using if statement
10. If it is, then initialize middle+1 to first and go to
the last statement of the loop, that is middle =
(first+last)/2
Prepared By B.Naveen Kumar (M.Tech.) JNTUH, Rajanna Siricilla. Page 198 of 210
I B.Tech EEE,CE,ME (R22) Unit - II C-Programming with Data Structures

11. If 9th step evaluates to be false, then follow further


step given below
12. Now program flow goes to else-if part and checks
whether element at middle (arr[middle]) is equal
to search (number to be search) or not
13. If it is equal, then print the position. Here we have
added the index number by one to display the position
of the number. As indexing starts from 0. For example,
in an array, there are 4 numbers say 10, 20, 30, 40. So,
the index will be 0, 1, 2, 3. But normally people knows
like this:
o 10 preset at first position
o 20 present at second position
o 30 present at third position

14. Naveen(jntr)
o 40 present at fourth position
So i have added 1 to middle and prints its value
as the position of the given number in array
15. Now the program flow goes to the last statement
of the while loop, that is middle = (first+last)/2;
16. If 12th step evaluates to be false, then else block
gets evaluated, and middle-1 is assigned to last and
continue running the loop until the condition
of while loop evaluates to be false

Here is the modified version of binary search program (as


given above) in C. Here we have leave the size of array to be
decided by user at run-time. And before performing the
binary search, bubble sort is used to sort the given array in
ascending order.

Important - This program finds the position of number from


sorted array, not from the actual array that is entered by
user at run-time. For example, if user supply 10, 50, 20, 30,
40 as array input, and 20 as number to be search. Then
this program sort the array, so the array becomes 10, 20,
30, 40, 50 and the position of 20 will be 2.
#include<stdio.h>
#include<conio.h>
int main()
{
int i, j, n, arr[100], search, first, last, middle, temp;
printf("How many element you want to store in array ? ");
scanf("%d", &n);
printf("\nEnter %d array elements: ", n);

Prepared By B.Naveen Kumar (M.Tech.) JNTUH, Rajanna Siricilla. Page 199 of 210
I B.Tech EEE,CE,ME (R22) Unit - II C-Programming with Data Structures

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


scanf("%d", &arr[i]);
printf("\nEnter element to be search: ");
scanf("%d", &search);

// sorting given array using bubble sort


for(i=0; i<(n-1); i++)
{
for(j=0; j<(n-i-1); j++)
{
if(arr[j]>arr[j+1])
{
temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
}
}
}

// sort array
printf("\nNow the sorted Array is:\n");
for(i=0; i<n; i++)
printf("%d ", arr[i]);

first = 0;
last = n-1;
Naveen(jntr)
// back to binary search

middle = (first+last)/2;
while(first <= last)
{
if(arr[middle]<search)
first = middle+1;
else if(arr[middle]==search)
{
printf("\n\nThe number, %d found at Position %d", search,
middle+1);
break;
}
else
last = middle-1;
middle = (first+last)/2;
}
if(first>last)
printf("\nThe number, %d is not found in given Array", search);
getch();
return 0;
}

Here is the snapshot of sample run:

Prepared By B.Naveen Kumar (M.Tech.) JNTUH, Rajanna Siricilla. Page 200 of 210
I B.Tech EEE,CE,ME (R22) Unit - II C-Programming with Data Structures

Naveen(jntr)
Binary Search Program in C using User-defined Function

Now modify the first program of this article that does the
same job but this time using function as shown in the
program given below:
#include<stdio.h>
#include<conio.h>
int binarySearchFun(int arr[], int);
int main()
{
int i, arr[10], search, pos;
printf("Enter 10 elements (in ascending order): ");
for(i=0; i<10; i++)
scanf("%d", &arr[i]);
printf("\nEnter element to be search: ");
scanf("%d", &search);
pos = binarySearchFun(arr, search);
if(pos==0)
printf("\nThe number, %d is not found in given Array", search);
else
printf("\nThe number, %d found at Position %d", search, pos);
getch();
return 0;
}
int binarySearchFun(int arr[], int search)
{
int first, last, middle;
first = 0;
last = 9;
middle = (first+last)/2;
while(first <= last)
{
if(arr[middle]<search)
first = middle+1;
else if(arr[middle]==search)
{
return (middle+1);
}
else

Prepared By B.Naveen Kumar (M.Tech.) JNTUH, Rajanna Siricilla. Page 201 of 210
I B.Tech EEE,CE,ME (R22) Unit - II C-Programming with Data Structures

last = middle-1;
middle = (first+last)/2;
}
return 0;
}

This is the snapshot of sample output produced after


running the above program:

Naveen(jntr)

Program Explained

 In above program, inside the


function binarySearchFun(), if the number gets found or
the condition arr[middle]==search evaluates to be
true, then middle+1 gets returned to the
function binarySearchFun() as its return value and this
function gets terminated
 The return value of this function gets initialized
to pos variable inside main() function
 Otherwise if none of the element (from array) matched
to the given number (to be search), then after exiting
from the while loop from binarySearchFun() function,
the return 0; statement gets executed and 0 gets
returned and initialized to pos variable inside
the main() function
 Now use if-else case (in main() function) to check
and print whether the number is found or not
 If found, then print its position, otherwise print as,
number is not found
Prepared By B.Naveen Kumar (M.Tech.) JNTUH, Rajanna Siricilla. Page 202 of 210
I B.Tech EEE,CE,ME (R22) Unit - II C-Programming with Data Structures

To learn more about function, refer to Function in


C tutorial.

Binary Search Program in C using Recursion

This is the last program on binary search. This program used


recursive function to find the number from the given array
using binary search technique. Let's take a look at the
program:
#include<stdio.h>
#include<conio.h>
int binarySearchRecFun(int [], int, int, int);
int main()
{
int i, arr[10], search, pos;
printf("Enter 10 elements (in ascending order): ");
for(i=0; i<10; i++)

Naveen(jntr)
scanf("%d", &arr[i]);
printf("\nEnter element to be search: ");
scanf("%d", &search);
pos = binarySearchRecFun(arr, 0, 9, search);
if(pos==0)
printf("\nThe number, %d is not found in given Array", search);
else
printf("\nThe number, %d found at Position %d", search, pos);
getch();
return 0;
}
int binarySearchRecFun(int arr[], int first, int last, int search)
{
int middle;
if(first>last)
return 0;
middle = (first+last)/2;
if(arr[middle]==search)
return (middle+1);
else if(arr[middle]>search)
binarySearchRecFun(arr, first, middle-1, search);
else if(arr[middle]<search)
binarySearchRecFun(arr, middle+1, last, search);
}

You will get the same output as shown in the output of


above program, that is, binary search using function. To
learn more about recursion, refer to Recursion in C tutorial.

What are the different searching techniques in C


language?
CServer Side ProgrammingProgramming

Searching technique refers to finding a key element among the list of elements.
 If the given element is present in the list, then the searching process is said to
be successful.
Prepared By B.Naveen Kumar (M.Tech.) JNTUH, Rajanna Siricilla. Page 203 of 210
I B.Tech EEE,CE,ME (R22) Unit - II C-Programming with Data Structures

 If the given element is not present in the list, then the searching process is said
to be unsuccessful.
C language provides two types of searching techniques. They are as follows −

 Linear search
 Binary search
Linear Search
 Searching for the key element is done in a linear fashion.
 It is the simplest searching technique.
 It does not expect the list to be sorted.
 Limitation − It consumes more time and reduce the power of system.
Input (i/p)
Unsorted list of elements, key.
Output (o/p)

 Success − If key is found.



Naveen(jntr)
Unsuccessful − Otherwise.

Example
Following is the C program for linear searching technique −
Live Demo

#include<stdio.h>
int main (){
int a[50], n, i, key, flag = 0;
printf("enter the no: of elements");
scanf ("%d",&n);
printf("enter the elements:
");
for (i=0; i<n; i++)
scanf( "%d", &a[i]);

Prepared By B.Naveen Kumar (M.Tech.) JNTUH, Rajanna Siricilla. Page 204 of 210
I B.Tech EEE,CE,ME (R22) Unit - II C-Programming with Data Structures

printf("enter a key element:


");
scanf ("%d", &key);
for (i=0; i<n; i++){
if (a[i] == key){
flag = 1;
break;
}
}
if (flag == 1)
printf("search is successful:");
else
printf("search is unsuccessfull:");
return 0;
}

Output
Naveen(jntr)
When the above program is executed, it produces the following result −
enter the no: of elements5
enter the elements:12
45
13
67
78
enter a key element:67
search is successful:

Binary Search In C: Everything You Need


To Know Binary Search
Last updated on Mar 29,2022146.2K Views

Share

edureka

Prepared By B.Naveen Kumar (M.Tech.) JNTUH, Rajanna Siricilla. Page 205 of 210
I B.Tech EEE,CE,ME (R22) Unit - II C-Programming with Data Structures

 Bookmark

Binary Search In C: Everything You Need To Know Binary Search

Searching Algorithms are very important as they help search data in patterns
which is otherwise very difficult. In this article we will take take a look at Binary
Search in C with practical implementation. Following Pointers will be covered in
this article:

 Binary Search In C


Example 1
Example 2 Naveen(jntr)
Let us get started with article on Binary Search in C,

Binary Search In C
A Binary Search is a sorting algorithm, that is used to search an element in a
sorted array. A binary search technique works only on a sorted array, so an
array must be sorted to apply binary search on the array. It is a searching
technique that is better then the liner search technique as the number of
iterations decreases in the binary search.

The logic behind the binary search is that there is a key. This key holds the value
to be searched. The highest and the lowest value are added and divided by 2.
Highest and lowest and the first and last element in the array. The mid value is
then compared with the key. If mid is equal to the key, then we get the output
directly. Else if the key is greater then mid then the mid+1 becomes the lowest
value and the process is repeated on the shortened array. Else if the key value is
less then mid, mid-1 becomes the highest value and the process is repeated on
the shortened array. If it is not found anywhere, an error message is displayed.

Let us move further with this Binary Search In C article and see an example,

Example 1
Let’s look at the code:

1#include <stdio.h>
2int main()
3{
4int i, low, high, mid, n, key, array[100];

Prepared By B.Naveen Kumar (M.Tech.) JNTUH, Rajanna Siricilla. Page 206 of 210
I B.Tech EEE,CE,ME (R22) Unit - II C-Programming with Data Structures

printf("Enter number of elementsn");


5scanf("%d",&n);
6printf("Enter %d integersn", n);
7for(i = 0; i < n; i++)
8scanf("%d",&array[i]);
9printf("Enter value to findn");
10
scanf("%d", &key);
11
low = 0;
12
high = n - 1;
13
mid = (low+high)/2;
14
while (low <= high) {
15
if(array[mid] < key)
16

Naveen(jntr)
low = mid + 1;
17
else if (array[mid] == key) {
18
printf("%d found at location %d.n", key, mid+1);
19
break;
20
}
21
else
22
23high = mid - 1;
24mid = (low + high)/2;
25}
26if(low > high)
27printf("Not found! %d isn't present in the list.n", key);
28return 0;
29}

Output:

If the key is present:

Prepared By B.Naveen Kumar (M.Tech.) JNTUH, Rajanna Siricilla. Page 207 of 210
I B.Tech EEE,CE,ME (R22) Unit - II C-Programming with Data Structures

If Key is not present:

Naveen(jntr)

In the program above, We declare i, low, high, mid, n, key, array[100].

 i is used for iteration through the array.


 low is used to hold the first array index.
 high is used to hold the last array index.
 mid holds the middle value calculated by adding high and low and dividing it by
2.
 n is the number of elements in the array.
 key is the element to search.
 array is the array element of size 100.

Prepared By B.Naveen Kumar (M.Tech.) JNTUH, Rajanna Siricilla. Page 208 of 210
I B.Tech EEE,CE,ME (R22) Unit - II C-Programming with Data Structures

We first, take in the number of elements the user array needs and store it in n.
Next, we take the elements from the user. A for loop is used for this process.
Then, we take the number to be searched from the array and store it in the key.

Next, we assign 0 to the low variable which is the first index of an array and n-1
to the high element, which is the last element in the array. We then calculate the
mid value. mid = (low+high)/2 to get the middle index of the array.

There is a while loop which checks if low is less then high to make sure that the
array still has elements in it. If low is greater then, high then the array is empty.
Inside the while loop, we check whether the element at the mid is less than the
key value(array[mid] < key). If yes, then we assign low the value of mid +1
because the key value is greater then mid and is more towards the higher side. If
this is false, then we check if mid is equal to key. If yes, we print and break out of
the loop. If these conditions don’t match then we assign high the value of mid-1,
which means that the key is smaller than mid.

Naveen(jntr)
The last part checks if low is greater then high, which means there are no more
elements left in the array.

Remember, this algorithm won’t work if the array is not sorted.

Prepared By B.Naveen Kumar (M.Tech.) JNTUH, Rajanna Siricilla. Page 209 of 210

You might also like