Professional Documents
Culture Documents
C & Ds Notes 2022-2023 r22 Syllabus
C & Ds Notes 2022-2023 r22 Syllabus
B.Naveen Kumar
M.Tech.
9959226736, naveen.ab85@gmail.com
I B.Tech EEE,CE,ME (R22) Unit - II C-Programming with Data Structures
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
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.
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
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.
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...
CPU (Processor)
SMPS
Naveen(jntr)
Motherboard
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.
Computing Environments
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.
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
Naveen(jntr)
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.
Computer Languages
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
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.
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
Low-level language instructions require very less time for their execution.
Disadvantages
Low-level language instructions are machine-dependent, that means a program written for a
In low-level language, there is more chance for errors and it is very difficult to find errors, debug
and modify.
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
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
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.
Disadvantages
dependent.
High-Level Language
A high-level language is a computer language which can be understood by the users. The high-level
language is very similar to human languages and has a set of grammar rules that are used to make
instructions more easily. Every high-level language has a set of predefined words known as Keywords
and a set of rules known as Syntax to create instructions. The high-level language is easier to
understand for the users but the computer can not understand it. High-level language needs to be
converted into the low-level language to make it understandable by the computer. We
use Compiler or interpreter to convert high-level language to low-level language.
Languages like COBOL, FORTRAN, BASIC, C, C++, JAVA, etc., are examples of high-level languages. All
these programming languages use human-understandable language like English to write program
instructions. These instructions are converted to low-level language by the compiler so that it can be
understood by the computer.
Advantages
The programs created using high-level language runs on different machines with little change or no
change.
Disadvantages
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.
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)
Select Run
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.
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.
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.
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
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.
Naveen(jntr)
Overall Process
Type the program in C editor and save with .c extension (Press F2 to save).
If there are errors, correct the errors and recompile the program.
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
Maintenance
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.
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.
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
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’.
The CPL was invented by Martin Richards at the University of Cambridge in the early of 1960s.
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.
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.
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.
This is the place where we implement the user-defined functions. The user-defined function
implementation can also be performed before the main method. In this case, the user-defined
function need not be declared. Directly it can be implemented, but it must be before the main method.
In a program, we can define as many user-defined functions as we want. Every user-defined function
needs a function call to execute its statements.
C Character Set
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.
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.
Naveen(jntr)
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
Naveen(jntr)
printf("ASCII==>Character\n");
for(i=-128;i<=127;i++)
printf("%d==>%c\n",i,i);
getch();
return 0;
}
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
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...
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];
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.
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.
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.
The character data type is a set of characters enclosed in single quotations. The following table
The following table provides complete information about all the data types in c programming
language...
Naveen(jntr)
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...
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;
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.,
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
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 can also define string constant by separating it with white space as follows...
"This" "is" "jntuhucer"
Creating constants in C
In a c programming language, constants can be created using two concepts...
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).
Example
#define PI 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...
Property Description
Keyword auto
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(){
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;
}
Property Description
Keyword extern
Property Description
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>
Property Description
Keyword static
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;
}
PropertyDescription
Keyword register
Life time Till the control remains within the block in which variable is defined
Example Program 1
#include<stdio.h>
#include<conio.h>
int main(){
register int a,b;
scanf("%d%d",&a,&b);
printf("%d %d",a,b);
}
Memory
Storage Class Keyword Location Default Value
Scope Life Time
Naveen(jntr)
(RAM) Throughout
the program)
execution does
not come to
end
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()
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);
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
void main(){
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...
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!!!");
}
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:
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.
Example Program
#include<stdio.h>
#include<conio.h>
void main(){
printf("Welcome to ");
printf("jntuhucer ");
printf("the perfect website for learning");
}
Output:
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...
\a Beep sound
\\ Naveen(jntr)
Inserts Backward slash symbol
Example Program
#include<stdio.h>
#include<conio.h>
void main(){
printf("Welcome to\n");
printf("jntuhucer\n");
printf("the perfect website for learning");
}
Output:
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
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
⇒ The remainder of the division operator is used with integer data type only.
The relational operators are the symbols that are used to compare two values. That means the
relational operators are used to check the relationship between two values. Every relational operator
has two results TRUE or FALSE. In simple words, the relational operators are used to define conditions
in a program. The following table provides information about relational operators.
< Returns TRUE if the first value is smaller than 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
> 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
!=
Naveen(jntr)
Returns TRUE if both values are not equal otherwise returns FALSE
10 != 5 is
TRUE
The logical operators are the symbols that are used to combine multiple conditions into one condition.
&& Logical AND - Returns TRUE if all conditions are TRUE 10 < 5 && 12 > 10
otherwise returns FALSE is FALSE
! 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
⇒ Logical OR - Returns FALSE only if all conditions are FALSE, if any of the conditions is TRUE then
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
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:
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.
Naveen(jntr)
Let us consider two variables A and B as A = 25 (11001) and B = 20 (10100).
& the result of Bitwise AND is 1 if all the bits are 1 A&B
otherwise it is 0 ⇒ 16 (10000)
^ the result of Bitwise XOR is 0 if all the bits are same A^B
otherwise it is 1 ⇒ 13 (01101)
<< 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)
Example
A = (10<15)?100:200; ⇒ A value is 100
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
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.
Infix Expression
The expression in which the operator is used between operands is called infix expression.
The infix expression has the following general structure.
Example
Postfix Expression
The expression in which the operator is used after operands is called postfix expression.
Naveen(jntr)
Operand1 Operand2 Operator
Example
Prefix Expression
The expression in which the operator is used before operands is called a prefix expression.
Example
programming language every operator has precedence (priority). When there is more than one
operator in an expression the operator with higher precedence is evaluated first and the operator with
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.
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.
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.
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.
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:
Output 2:
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:
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.
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
The switch statement has the following syntax and execution flow diagram.
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.
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)
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.
The looping statements are used to execute a single statement or block of statements
repeatedly until the given condition is FALSE.
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.
Output:
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...
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:
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...
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:
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...
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)
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)
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:
When we use break, continue and goto statements, we must follow the following...
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
The continue statement can be used with if statement, only if that if statement is written inside the
looping statements.
The goto statement can be used with any statement like if, switch, while, do-while, and for, etc.
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.
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
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...
To use system defined functions the respective header file must be included.
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...
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 ) ;
}
#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
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
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:
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.
exchange information. The process of exchanging information between calling and called functions is
called inter-function communication.
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>
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:
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
printf(), scanf()
operations
Header Example
File Purpose Functions
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.
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...
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...
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...
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'.
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.
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
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.
Naveen(jntr)
We use the following general syntax for declaring a two dimensional array...
We use the following general syntax to access the individual elements of a two-dimensional array...
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'.
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 () {
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.
scanf("%d", &temperature[i][j]);
}
}
printf("\nDisplaying values: \n\n");
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
#include <stdio.h>
int main()
{
float a[2][2], b[2][2], result[2][2];
Naveen(jntr)
{
printf("Enter a%d%d: ", i + 1, j + 1);
scanf("%f", &a[i][j]);
}
if (j == 1)
printf("\n");
}
return 0;
}
Run Code
Output
Sum Of Matrix:
2.2 0.5
-0.9 25.0
Naveen(jntr)
#include <stdio.h>
int main()
{
int test[2][3][2];
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
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
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
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
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
variable "marks"...
Example Code
printf("Address : %u", &marks) ;
In the above example statement %u is used to display address of marks variable. Address
normal variable but the name is prefixed with * symbol. We use the following syntax to
datatype *pointerName ;
Example Code
int *ptr ;
In the above example declaration, the variable "ptr" is a pointer variable that can be used to
syntax...
In the above declaration, variable "a" is a normal integer variable and variable "ptr" is an
integer pointer variable. If we want to assign the address of variable "a" to pointer
Example Code
ptr = &a ;
In the above statement, the address of variable "a" is assigned to pointer variable "prt".
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
*pointerVariableName
Example Code
#include<stdio.h>
#include<conio.h>
void main()
{
int a = 10, *ptr ;
clrscr();
ptr = &a ;
} 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.
Every pointer variable is used to store the address of another variable. In computer memory
unsigned integer requires 2 bytes of memory. So, irrespective of pointer datatype every
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
pointing.
pointers...
1. Addition
2. Subtraction
3. Increment
4. Decrement
5. Comparison
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
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:
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
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
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
getch() ;
}
Output:
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
getch() ;
}
Output:
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.
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.
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
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 ;
Output:
Naveen(jntr)
Pointers to void in C
In the c programming language, pointer to void is the concept of defining a pointer variable
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.
Example Program
#include<stdio.h>
#include<conio.h>
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
The array name itself acts as a pointer to the first element of that array. Consider the
Example Code
int marks[6] ;
For the above declaration, the compiler allocates 12 bytes of memory and the address of
first memory location (i.e., marks[0]) is stored in a constant pointer called marks. That
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:
2. We can use the array name to access the address and value of all the elements of
that array.
Example Code
ptr = marks + 2 ;
Here, the pointer variable "ptr" is assigned with address of "marks[2]" element.
Example Code
printf("Address of 'marks[4]' = %u", 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
In the above example program, the array name marks can be used as follows...
In case of multi dimensional array also the array name acts as a constant pointer to the
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
In the above example of two dimensional array, the element marks[1][2] is accessed
as *(*(marks + 1) + 2).
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
void main()
{
int a = 10, b = 20 ;
clrscr() ;
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) ;
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
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.
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
are FOUR standard library functions that are defined in the header file known as "stdlib.h".
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;
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
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;
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
Example
Naveen(jntr)
Example Program for realloc().
#include<stdio.h>
#include<conio.h>
int main () {
char *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;
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
NULL character (\0) at the end. The formal definition of string is as follows...
In C programming language, there are two methods to create strings and they are as
follows...
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
char str[6] ;
The following declaration creates a string variable of a specific size at the time of program
execution.
2. After declaraation
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 title[20];
*title = "btech smart class";
return 0;
}
Naveen(jntr)
1. Using scanf() method - reads single word
Using scanf() method we can read only one word of string. We use %s to represent string in
int main(){
char name[50];
printf("Please enter your name : ");
scanf("%s", 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
int main(){
char name[50];
printf("Please enter your name : ");
gets(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
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 following table provides most commonly used string handling function and their use...
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
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)
Naveen(jntr)
stricmp() stricmp(string1, string2) Compares two strings, string1 and string2 by ignorin
strcmpi())
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
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
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.
integral constants
We use the keyword enum to create enumerated datatype. The general syntax of enum is
as follows...
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...
In the above syntax, integral constant '10' is assigned to name1, integral constant '30' is
void main(){
today = tuesday ;
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
We can also change the order of integral constants, consider the following example
program.
void main(){
In the above example program, the integral constant value starts with '1' instead of '0'. Here,
We can also create enum with our own integral constants, consider the following example
program.
void main(){
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
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
Naveen(jntr)
enum day {Monday, Tuesday, Wednesday, Thursday = 10, Friday, Saturday, Sunday} ;
void main(){
today = tuesday ;
today = saturday ;
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
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.
In the above example, Number is defined as alias name for integer datatype. So, we can
Naveen(jntr)
use Number to declare integer variables.
void main(){
clrscr() ;
printf("Enter any two integer numbers: ") ;
scanf("%d%d", &a,&b) ;
c = a + b;
printf("Sum = %d", c) ;
}
In C programming language, typedef is also used with arrays. Consider the following
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
void main(){
typedef int Array[5]; // Here Array acts like an integer array type of size
5.
clrscr() ;
Naveen(jntr)
printf("List elements are : \n") ;
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.
In C programming language, typedef is also used with structures and unions. Consider the
}stud;
void main(){
stud s1;
clrscr() ;
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
In C programming language, typedef is also used with pointers. Consider the following
void main(){
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
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
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
To create structure in c, we use the keyword called "struct". We use the following syntax to
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;
} ;
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
To access members of a structure using structure variable, we use dot (.) operator. Consider
void main(){
struct Student stud_2; // using struct keyword
printf("Percentage : ");
scanf("%f", &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
allocate on defining a structure. The memory is allocated when we create the variable of a
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
The memory required by a structure variable is sum of the memory required by individual
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
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
Union is a colloction of different type of elements under a single name that acts as
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
To create union in c, we use the keyword called "union". We use the following syntax to
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;
} ;
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
void main(){
union Student stud_2; // using union keyword
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
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
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
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
bitfield we can specify the memory to be allocated for individual members of a structure. To
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
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
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;
} ;
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
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
char *argv[ ] - It is a character pointer array used to store the actual values of command line
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
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
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
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
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
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
Files in C
Generally, a file is used to store user data in a computer. In other words, computer stores
computer.
C programming language supports two types of files and they are as follows...
Binary Files
Text File (or) ASCII File - The file that contains ASCII codes of data like digits, alphabets and
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
Closing a file
All the above operations are performed using file handling functions available in C. We
The following are the operations performed on files in the c programming language...
Closing a file
All the above operations are performed using file handling functions available in C.
To create a new file or open an existing file, we need to create a file pointer of FILE type.
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
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
S. Mod
No. e Description
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
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.
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
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
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");
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
multiple datatype values from specified file which is opened in reading mode.
int main(){
Naveen(jntr)
fp = fopen ("file.txt", "w+");
fputs("We are in 2016", fp);
rewind(fp); // moves the cursor to begining of the file
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
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.
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
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
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()
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
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
of text with mixed data types (char, int, float, double) into specified file which is
Naveen(jntr)
opened in writing mode.
int main(){
FILE *fp;
char *text = "\nthis is example text";
int i = 10;
clrscr();
fp = fopen("MySample.txt","w");
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
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");
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
function is used to insert specified number of characters into a binary file which is
Naveen(jntr)
opened in writing mode.
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).
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.
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
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
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)
set the cursor position to the specific position. Using this function we can set the
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);
}
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
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.
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
3 No such process.
5 IO Error
6
Naveen(jntr) No such device or address
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
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
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
int main(){
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.
Naveen(jntr)
Why files are needed?
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
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:
3. Closing a file
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
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
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
Mod
Meaning of Mode During Inexistence of file
e
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
a+ Open for both reading and appending. If the file does not exist, it will be creat
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.
fclose(fptr);
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.
#include <stdio.h>
#include <stdlib.h>
int main()
{
int num;
FILE *fptr;
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
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;
fscanf(fptr,"%d", &num);
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.
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
#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;
return 0;
}
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
#include <stdio.h>
#include <stdlib.h>
struct threeNum
Naveen(jntr)
{
int n1, n2, n3;
};
int main()
{
int n;
struct threeNum num;
FILE *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 .
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()
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.
Whence Meaning
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
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;
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
#include <stdio.h>
int main()
{
char name[50];
int marks, i, 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
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;
FILE *fptr;
fptr = (fopen("C:\\student.txt", "a"));
if(fptr == NULL)
{
printf("Error!");
exit(1);
}
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;
}
#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);
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()
char c;
exit(0);
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
fputc(c, fp3);
fclose(fp1);
fclose(fp2);
fclose(fp3);
return 0;
Output:
Naveen(jntr)
Merged file1.txt and file2.txt into file3.txt
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()
{
fs1 = fopen(file1,"r");
fs2 = fopen(file2,"r");
exit(EXIT_FAILURE);
}
ft = fopen(file3,"w");
if( ft == NULL )
{
perror("Error "); Naveen(jntr)
printf("Press any key to exit...\n");
exit(EXIT_FAILURE);
}
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
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
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.
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
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;
}
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:
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 −
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.
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)
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
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
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.
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;
}
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
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
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
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;
}
Naveen(jntr)
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;
}
}
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
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;
}
Program Explained
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
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
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;
}
Naveen(jntr)
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;
}
}
}
}
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:
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
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;
}
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:
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
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
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
Naveen(jntr)
insertion sort technique
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;
}
Naveen(jntr)
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)
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
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
Naveen(jntr)
Linear Search in C
Naveen(jntr)
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
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
Naveen(jntr)
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 in C
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
Naveen(jntr)
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
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
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
// 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;
}
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;
}
Naveen(jntr)
Program Explained
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);
}
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)
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
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:
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
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
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:
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
Naveen(jntr)
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.
Prepared By B.Naveen Kumar (M.Tech.) JNTUH, Rajanna Siricilla. Page 209 of 210