You are on page 1of 112

Module I

Basics of Computer Hardware and Software

The main components in a typical computer system are the processor, memory, input/output
devices, and the communication channels that connect them.

The processor is the component that executes a program by performing arithmetic and logical
operations on data.

In a typical system there will be only one processor, known at the central processing unit, or CPU. A
processor, or "microprocessor," is a small chip that resides in computers and other electronic devices.
Its basic job is to receive input and provide the appropriate output. The central processor of a computer
is also known as the CPU, or "central processing unit”.

Modern CPUs often include multiple processing cores, which work together to process instructions.
While these "cores" are contained in one physical unit, they are actually individual processors.
Processors that include two cores are called dual-core processors, while those with four cores are
called quad-core processors. Some high-end workstations contain multiple CPUs with multiple cores,
allowing a single machine to have eight, twelve, or even more processing cores.

Memory is a passive component that simply stores information until it is requested by another part of
the system. During normal operations it feeds instructions and data to the processor, and at other times
it is the source or destination of data transferred by I/O devices. Information in a memory is accessed
by its address. In programming language terms, one can view memory as a one-dimensional array M.
A processor's request to the memory might be ``send the instruction at location M[1000]'' or a disk
controller's request might be ``store the following block of data in locations M[0] through M[255].'' ust
like humans, computers rely a lot on memory. They need to process and store data, just like we do.
However, computers store data in digital format, which means the information can always be called
up exactly the way it was stored. Also, unlike our memory, the computer's memory doesn't get worse
over time.
While memory can refer to any medium of data storage, it usually refers to RAM, or random access
memory. When your computer boots up, it loads the operating system into its memory, or RAM. This
allows your computer to access system functions, such as handling mouse clicks and keystrokes, since
the event handlers are all loaded into RAM. Whenever you open a program, the interface and functions
used by that program are also loaded into RAM.
RAM is a very high-speed type of memory, which makes it ideal for storing active programs and
system processes. It is different than hard disk space in that RAM is made up of physical memory
chips, while hard disks are magnetic disks that spin inside a hard drive. Accessing RAM is much faster
than accessing the hard disk because RAM access is based on electric charges, while the hard drive
needs to seek to the correct part of the disk before accessing data. However, all the information stored
in RAM is erased when the computer's power is turned off. The hard disk, on the other hand, stores
data magnetically without requiring any electrical power.

An input device is any device that provides input to a computer. There are dozens of possible input
devices, but the two most common ones are a keyboard and mouse. Every key you press on the

Page 1
keyboard and every movement or click you make with the mouse sends a specific input signal to the
computer. These commands allow you to open programs, type messages, drag objects, and perform
many other functions on your computer.

Since the job of a computer is primarily to process input, computers are pretty useless without input
devices. Just imagine how much fun you would have using your computer without a keyboard or
mouse. Not very much. Therefore, input devices are a vital part of every computer system.

Any device that outputs information from a computer is called, not surprisingly, an output device.
Since most information from a computer is output in either a visual or auditory format, the most
common output devices are the monitor and speakers. These two devices provide instant feedback to
the user's input, such as displaying characters as they are typed or playing a song selected from a
playlist.

While monitors and speakers are the most common output devices, there are many others. Some
examples include headphones, printers, projectors, lighting control systems, audio recording devices,
and robotic machines. A computer without an output device connected to it is pretty useless, since the
output is what we interact with.

The communication channels that tie the system together can either be simple links that connect two
devices or more complex switches that interconnect several components and allow any two of them
to communicate at a given point in time. When a switch is configured to allow two devices to exchange
information, all other devices that rely on the switch are blocked, i.e. they must wait until the switch
can be reconfigured.

Page 2
Application Software & System software
A Computer is an electronic device that can perform various operations of computation at a greater
speed than what an ordinary machine or human mind can do. It is driven by many entities including
the physical and tangible components that we can touch or feel, called the Hardware and programs
and commands that drive the hardware, called the Software.
The Software refers to the set of instructions fed in form of programs to govern the computer system
and process the hardware components.

Page 3
System Software

These are the software that directly allows the user to interact with the hardware components of a
computer system. As the humans and machines follow different languages, there has to be an interface
that will allow the users to interact with the core system, this interface is provided by the software.
The system software can be called the main or the alpha software of a computer system as it handles
the major portion of running a hardware.
This System Software can be further divided into four major types:
1. The Operating System – It is the main program that governs and maintains the inter-
cooperation of the components of a computer system. For eg., Microsoft Windows, Linux, Mac
OS etc.

Page 4
2. The Language Processor – The hardware components present in the computer system does not
understand human language. There are three types of languages involved in the world of human-
machine interaction:
• Machine-Level Language: The machines only understand the digital signals or the binary
codes or the binary language which consist of strings of 0’s and 1’s. These are totally
machine dependent language.
• Assembly-Level Language: These are the Low-Level Language(LLL), that forms a
correspondence between machine level instruction and general assembly level statements.
Assembly language uses a mnemonics to represent each low-level machine instruction or
operation-code also called the op-codes. For eg., ADD instruction is used to add two
entities, the HALT instruction is used to stop a process etc. It is a machine dependent
language and varies from processor to processor.
• High-Level Language: These are the simple English statements, that humans use to
program and code as it is easy to read and understand to the human world. For eg., Java,
C, C++, Python etc.
The machine level language is very complex to understand and code, therefore the users prefer
the High-Level Language or the HLL for coding. These codes need to be converted into the
machine language so that the computer can easily understand and work accordingly. This
operation is performed by the Language Processor which is made up of further three
components:
• Assembler: This language processor is used to convert the assembly language into
machine level language.
• Compiler: This language processor is used to convert High-Level Language into machine
level language in one go, thus execution time is fast. The error detection is difficult in a
compiler. Programming Languages like C, C++ and Scala use compiler. The simplest
definition of a compiler is a program that translates code written in a high-level
programming language (like JavaScript or Java) into low-level code (like Assembly)
directly executable by the computer or another program such as a virtual machine.

• Interpreter: This language processor is also used to convert High-Level Language into
machine level language line-by-line, thus execution time is slow. Error-detection is easier
in an interpreter as it reports as soon as a bug is caught and restarts the process. This
consumes unnecessary memory. Programming Languages like Python, Ruby and Java uses
an interpreter.
Page 5
As the name suggests, an interpreter transforms or interprets a high-level programming
code into code that can be understood by the machine (machine code) or into an
intermediate language that can be easily executed as well. The interpreter reads each
statement of code and then converts or executes it directly.

3. The Device Drivers – The device drivers and the device programs or the system software that
acts as an interface between the various Input-Output device and the users or the operating
system. For eg., the Printers, Web cameras come with a driver disk that is needed to be installed
into the system to make the device run in the system.
4. The BIOS – It stands for Basic Input Output System and is a small firmware, that controls the
peripheral or the input-output devices attached to the system. This software is also responsible
for starting the OS or initiating the booting process.

ApplicationSoftware:
Application Software is the type of software which runs as per user request. It runs on the platform
which is provide by system software. High level languages are used to write the application software.
Its a specific purpose software.

These are the basic software used to run to accomplish a particular action and task. These are the
dedicated software, dedicated to performing simple and single tasks. For eg., a single software cannot
serve to both the reservation system and banking system. These are divided into two types:
1. The General Purpose Application Software: These are the types of application software that
comes in-built and ready to use, manufactures by some company or someone. For eg.,
• Microsoft Excel – Used to prepare excel sheets.
• VLC Media Player – Used to play audio/video files.
Page 6
• Adobe Photoshop – Used for designing and animation and many more.
2. The Specific Purpose Application Software: These are the type of software that is
customizable and mostly used in real-time or business environment. For eg.,
• Ticket Reservation System
• Healthcare Management System
• Hotel Management System
• Payroll Management System

The main difference between System Software and Application Software is that without system
software, system can not run on the other hand without application software, system always runs.

Structured Programming
Structured programming (SP) is a technique devised to improve the reliability and clarity of
programs. In SP, control of program flow is restricted to three structures, sequence, IF THEN ELSE,
and DO WHILE, or to a structure derivable from a combination of the basic three. The result is a
program built of modules that are highly independent of each other. In turn, this allows a
programmer to be more confident that the code contains fewer logic errors and will be easier to
debug and change in the future.
Structured Programming Approach, as the word suggests, can be defined as a programming
approach in which the program is made as a single structure. It means that the code will execute the
instruction by instruction one after the other. It doesn’t support the possibility of jumping from one
instruction to some other with the help of any statement like GOTO, etc. Therefore, the instructions
in this approach will be executed in a serial and structured manner. The languages that support
Structured programming approach are:
• C
• C++
• Java
• C#

The structured program mainly consists of three types of elements:


• Selection Statements
• Sequence Statements
• Iteration Statements
The structured program consists of well structured and separated modules. But the entry and exit in a
Structured program is a single-time event. It means that the program uses single-entry and single-exit
elements. Therefore a structured program is well maintained, neat and clean program. This is the
reason why the Structured Programming Approach is well accepted in the programming world.
Advantages of Structured Programming Approach:
1. Easier to read and understand
2. User Friendly
3. Easier to Maintain
4. Mainly problem based instead of being machine based
5. Development is easier as it requires less effort and time
6. Easier to Debug
7. Machine-Independent, mostly.
Page 7
Disadvantages of Structured Programming Approach:
1. Since it is Machine-Independent, So it takes time to convert into machine code.
2. The converted machine code is not the same as for assembly language.
3. The program depends upon changeable factors like data-types. Therefore it needs to be updated
with the need on the go.
4. Usually the development in this approach takes longer time as it is language-dependent. Whereas
in the case of assembly language, the development takes lesser time as it is fixed for the machine.

Flowcharts and Algorithms


Algorithms and flowcharts are two different tools used for creating new programs, especially in
computer programming. An algorithm is a step-by-step analysis of the process, while a flowchart
explains the steps of a program in a graphical way.
To write a logical step-by-step method to solve the problem is called algorithm, in other words, an
algorithm is a procedure for solving problems. In order to solve a mathematical or computer problem,
this is the first step of the procedure. An algorithm includes calculations, reasoning and data
processing. Algorithms can be presented by natural languages, pseudo code and flowcharts, etc.

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

• Terminal Box - Start / End

• Input / Output

• Process / Instruction

• Decision

Page 8
• Connector / Arrow

The graphics above represent different part of a flowchart. The process in a flowchart can be expressed
through boxes and arrows with different sizes and colors. In a flowchart, we can easily highlight a
certain element and the relationships between each part.

Difference between Algorithm and Flowchart

If you compare a flowchart to a movie, then an algorithm is the story of that movie. In other words,
an algorithm is the core of a flowchart. Actually, in the field of computer programming, there are
many differences between algorithm and flowchart regarding various aspects, such as the accuracy,
the way they display, and the way people feel about them. Below is a table illustrating the differences
between them in detail.

Page 9
How to Use Flowcharts to Represent Algorithms

Now that we have the definitions of algorithm and flowchart, how do we use a flowchart to represent
an algorithm?

Algorithms are mainly used for mathematical and computer programs, whilst flowcharts can be used
to describe all sorts of processes: business, educational, personal and of course algorithms. So
flowcharts are often used as a program planning tool to visually organize the step-by-step process of
a program. Here are some examples:

Example 1: Print 1 to 20:

Algorithm:

Step 1: Initialize X as 0,

Step 2: Increment X by 1,

Step 3: Print X,

Step 4: If X is less than 20 then go back to step 2.

Pseudo code is a term which is often used in programming and algorithm based fields. It is a
methodology that allows the programmer to represent the implementation of an algorithm. Simply,
we can say that it’s the cooked up representation of an algorithm. Often at times, algorithms are
Page
10
represented with the help of pseudo codes as they can be interpreted by programmers no matter what
their programming background or knowledge is. Pseudo code, as the name suggests, is a false code or
a representation of code which can be understood by even a layman with some school level
programming knowledge.

Advantages of Pseudocode

• Improves the readability of any approach. It’s one of the best approaches to start implementation
of an algorithm.
• Acts as a bridge between the program and the algorithm or flowchart. Also works as a rough
documentation, so the program of one developer can be understood easily when a pseudo code
is written out. In industries, the approach of documentation is essential. And that’s where a
pseudo-code proves vital.
• The main goal of a pseudo code is to explain what exactly each line of a program should do,
hence making the code construction phase easier for the programmer.

How to write a Pseudo-code?

1. Arrange the sequence of tasks and write the pseudocode accordingly.


2. Start with the statement of a pseudo code which establishes the main goal or the aim.
Example:
This program will allow the user to check
the number whether it's even or odd.
3. The way the if-else, for, while loops are indented in a program, indent the statements likewise,
as it helps to comprehend the decision control and execution mechanism. They also improve the
readability to a great extent.

Example:

if "1"
print response
"I am case 1"

if "2"
print response
"I am case 2"
4. Use appropriate naming conventions. The human tendency follows the approach to follow what
we see. If a programmer goes through a pseudo code, his approach will be the same as per it, so
the naming must be simple and distinct.

Page
11
5. Use appropriate sentence casings, such as CamelCase for methods, upper case for constants and
lower case for variables.
6. Elaborate everything which is going to happen in the actual code. Don’t make the pseudo code
abstract.
7. Use standard programming structures such as ‘if-then’, ‘for’, ‘while’, ‘cases’ the way we use it
in programming.
8. Check whether all the sections of a pseudo code is complete, finite and clear to understand and
comprehend.
9. Don’t write the pseudo code in a complete programmatic manner. It is necessary to be simple to
understand even for a layman or client, hence don’t incorporate too many technical terms.

Pseudocode is an informal way of programming description that does not require any strict
programming language syntax or underlying technology considerations. It is used for creating an
outline or a rough draft of a program. Pseudocode summarizes a program’s flow, but excludes
underlying details. System designers write pseudocode to ensure that programmers understand a
software project's requirements and align code accordingly.

Examples of Pseudocode
Let's review an example of pseudocode to create a program to add 2 numbers together and then
display the result.
Start Program
Enter two numbers, A, B
Add the numbers together
Print Sum
End Program
Compare that pseudocode to an example of a flowchart to add two numbers
Now, let's look at a few more simple examples of pseudocode. Here is a pseudocode to compute the
area of a rectangle:
Get the length, l, and width, w
Compute the area = l*w
Display the area
Now, let's look at an example of pseudocode to compute the perimeter of a rectangle:
Enter length, l
Enter width, w
Compute Perimeter = 2*l + 2*w
Display Perimeter of a rectangle

Page
12
Bubble Sort
Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent
elements if they are in wrong order.
Example:
First Pass:
( 5 1 4 2 8 ) –> ( 1 5 4 2 8 ), Here, algorithm compares the first two elements, and swaps
since 5 > 1.
( 1 5 4 2 8 ) –> ( 1 4 5 2 8 ), Swap since 5 > 4
( 1 4 5 2 8 ) –> ( 1 4 2 5 8 ), Swap since 5 > 2
( 1 4 2 5 8 ) –> ( 1 4 2 5 8 ), Now, since these elements are already in order (8 > 5),
algorithm does not swap them.
Second Pass:
( 1 4 2 5 8 ) –> ( 1 4 2 5 8 )
( 1 4 2 5 8 ) –> ( 1 2 4 5 8 ), Swap since 4 > 2
( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )
( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )

Now, the array is already sorted, but our algorithm does not know if it is completed. The
algorithm needs one whole pass without any swap to know it is sorted.

Third Pass:
( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )
( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )
( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )
( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )

Algorithm
Suppose A is an array of N values. We want to sort A in ascending order.

Bubble Sort is a simple-minded algorithm based on the idea that we look at the list, and
wherever we find two consecutive elements out of order, we swap them. We do this as
follows: We repeatedly traverse the unsorted part of the array, comparing consecutive
elements, and we interchange them when they are out of order. The name of the algorithm
refers to the fact that the largest element "sinks" to the bottom and the smaller elements
"float" to the top.
For I = 0 to N - 2
For J = 0 to N - 2
If (A(J) > A(J + 1)
Temp = A(J)
A(J) = A(J + 1)
A(J + 1) = Temp
End-If
End-For

Page
13
End-For

Following are the steps involved in bubble sort(for sorting a given array in ascending
order):

1. Starting with the first element(index = 0), compare the current element with the
next element of the array.
2. If the current element is greater than the next element of the array, swap
them.
3. If the current element is less than the next element, move to the next
element. Repeat Step 1.

Linear Search
Linear search is a very simple search algorithm. In this type of search, a sequential search is
made over all items one by one. Every item is checked and if a match is found then that particular
item is returned, otherwise the search continues till the end of the data collection.

Algorithm
Linear Search ( Array A, Value x)

Step 1: Set i to 1
Step 2: if i > n then go to step 7
Step 3: if A[i] = x then go to step 6
Step 4: Set i to i + 1
Step 5: Go to Step 2
Step 6: Print Element x Found at index i and go to step 8
Step 7: Print element not found
Step 8: Exit

Pseudocode
procedure linear_search (list, value)

for each item in the list


if match item == value
return the item's location
end if
end for

end procedure

Page
14
Module II
Character Set
As every language contains a set of characters used to construct words, statements, etc. C language also
has a set of characters which include alphabets, digits, and special symbols. C language supports a total
of 256 characters. C language character set contains the following set of characters...

1. Alphabets
2. Digits
3. Special Symbols

Alphabets
C language supports all the alphabets from the English language. Lower and upper case letters together
support 52 alphabets.
Lower case letters - a to z
Upper case letters - A to Z

Digits
C language supports 10 digits which are used to construct numerical values in C language.
Digits - 0, 1, 2, 3, 4, 5, 6, 7, 8, 9

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

Token
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

Page
15
1. Keywords
2. Identifiers
3. Operators
4. Special Symbols
5. Constants
6. Strings
7. Data values

Keywords

Keywords are specific reserved words in C each of which has a specific feature associated with it.
Keywords are always in lowercase.
There are total of 32 keywords in C:
auto break case char const continue
default do double else enum extern
float for goto if int long
register return short signed sizeof Static
struct switch typedef union unsigned void
volatile while

Identifier

An identifier is a collection of characters which acts as the name of variable, function, array, pointer,
structure, etc.

Rules for Creating Identifiers

1. An identifier can contain letters (Upper case and lower case), digit and underscore symbol
only.
2. An identifier should not start with a digit value. It can start with a letter or an underscore.
3. Should not use any special symbols in between the identifier even whitespace.
4. Keywords should not be used as identifiers.

Page
16
5. There is no limit for the length of an identifier. However, the compiler considers the first
31 characters only.
6. An identifier must be unique in its scope.

Data Types

Data types in the c programming language are used to specify what kind of value can be stored in a variable.
The memory size and type of the value of a variable are determined by the variable data type.
In the c programming language, data types are classified as follows

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


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

I. Primitive Data Types


• char: The most basic data type in C. It stores a single character and requires a single byte
of memory in almost all compilers.
• int: As the name suggests, an int variable is used to store an integer.
• float: It is used to store decimal numbers (numbers with floating point value) with single
precision.
• double: It is used to store decimal numbers (numbers with floating point value) with
double precision.

DATA TYPE MEMORY (BYTES) FORMAT SPECIFIER

Int 2 %d

Char 1 %c

Float 4 %f

Double 8 %lf

Page 3
Note: Size of each data types varies based on machines.

Data Type Qualifier

The basic data types can be augmented by the use of the data type qualifiers short, long, signed and
unsigned. For example, integer quantities can be defined as short int, long int or unsigned int. The
interpretation of a qualified integer data type will vary from one C compiler to another, though there are some
commonsense relationships. Thus, a short int may require less memory than an ordinary int or itmay require
the same amount of memory as an ordinary int, but it will never exceed an ordinary int in word length.
Similarly, a long int may require the same amount of memory as an ordinary int or it may require more
memory, but it will never be less than an ordinary int.
If short int and int both have the same memory requirements (e.g. 2 bytes), then long int will generally have
double the requirements (e.g. 4 bytes). Or if int and long int both have the same memory requirements (e.g.
4 bytes) then short int will generally have half the memory requirements (e.g. 2bytes).
An unsigned int has the same memory requirements as an ordinary int. However, in the case of an ordinary
int, the leftmost bit is reserved for the sign. With an unsigned int, all of the bits are used to represent the
numerical value. Thus, an unsigned int can be approximately twice as large as an ordinary int. For example,
if an ordinary int can vary from -32,768 to +32,767, then an unsigned int will be allowed to vary from 0 to
65,535.

II. void data type

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

Variables

A variable is an identifier that is used to represent some specified type of information within a designated
portion of the program. 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.

Page 4
Declaration
A declaration associates a group of variables with a specific data type. All variables must be declared before
they can appear in executable statements. A declaration consists of a data type, followed by one or more
variable names, ending with a semicolon.
Example
int a,b,c ; float d; char e;
Escape Sequence

Certain nonprinting characters, as well as the backslash (\) and the apostrophe ( ‘), can be expressed in terms
of escape sequences. An escape sequence always begins with a backward slash and is followed by one or
more special characters. For example, a line feed (LF), which is referred to as a newline in C, can be
represented as \n. Such escape sequences always represent single characters, even though they are written in
terms of two or more characters.

Escape Sequence Meaning


\a Alarm or Beep

\b Backspace

\n New Line

\r Carriage Return

\t Tab (Horizontal)

\v Vertical Tab

\\ Backslash

\' Single Quote

\" Double Quote

Constants

Page 5
A constant is a value or variable that can't be changed in the program, for example: 10, 20, 'a', 3.4, "c
programming" etc.
There are different types of constants in C programming.

List of Constants in C

Constant Example
Integer Constant 10, 20, 450 etc.

Real or Floating-point Constant 10.3, 20.2, 450.6 etc.

Octal Constant 021, 033, 046 etc.

Hexadecimal Constant 0x2a, 0x7b, 0xaa etc.


Character Constant 'a', 'b', 'x' etc.

String Constant "c", "c program".

Symbolic Constants
A symbolic constant is a name that substitutes for a sequence of characters. The characters may represent a
numeric constant, a character constant or a string constant. When a program is compiled, each occurrence
of a symbolic constant is replaced by its corresponding character sequence. Symbolic constants are usually
defined at the beginning of a program.
Syntax: #define name text
Example: #define pi 3.14, #define SQR(x) x*x

Console I/O operation


The printf() and scanf() functions are used for input and output in C language. Both functions are inbuilt
library functions, defined in stdio.h (header file).
printf() function
The printf() function is used for output. It prints the given statement to the console. The syntax
of printf() function is given below:
printf("format string",argument_list);

Page 6
scanf() function
The scanf() function is used for input. It reads the input data from the console.
scanf("format string",argument_list);

The format string can be %d (integer), %c (character), %s (string), %f (float) etc.

Structure of C program
/* program to calculate the area of a circle */ /* title (comment) */
#include <stdio.h> / * library file access */
void main( ) / * function heading */
{
float radius,area; /* variable declarations */
printf (“radius =”); / * output statement (prompt) /*
scanf (“%f”, &radius) ; /* input statement * /
area = 3.14 * radius * radius; /* assignment statement */
printf ("area = %f",area) ; / * output statement */
}

Operators

Operators are the foundation of any programming language.

C has many built-in operator types and they are classified as follows:

1. Arithmetic Operators: These are the operators used to perform arithmetic/mathematical


operations on operands. Examples: (+, -, *, /, %,++,–). Arithmetic operator are of two types:
I. Unary Operators: Operators that operates or works with a single operand are unary
operators. For example: (++ , –)
II. Binary Operators: Operators that operates or works with two operands are binary
operators. For example: (+ , – , * , /)
#include<stdio.h>
void main()
{
int a,b;
printf("Enter the value of a and b");
scanf("%d%d",&a,&b);

Page 7
// Uniary Operator
printf("Unary Minus=%d\n",-a);
printf("Increment =%d\n ",a++);
printf("Decrement =%d\n ",a--);

// Binary Operator
printf("Sum =%d\n ",a+b);
printf("Difference =%d\n ",a-b);
printf("Mul =%d\n ",a*b);
printf("Division =%d\n ",a/b);
printf("Modulo =%d\n ",a%b);
}

Output
Enter the value of a and b20 10
Unary Minus=-20
Increment =20
Decrement =21
Sum =30
Difference =10
Mul =200
Division =2
Modulo =0

Relational Operators:
These are used for comparison of the values of two operands.
1. Equal to operator: Represented as ‘==’, the equal to operator checks whether the two given
operands are equal or not. If so, it returns 1. Otherwise it returns 0. For example, 5==5 will
return 1.
2. Not equal to operator: Represented as ‘!=’, the not equal to operator checks whether the
two given operands are equal or not. If not, it returns 1. Otherwise it returns 0. It is the exact
boolean complement of the ‘==’ operator. For example, 5!=5 will return 0.
3. Greater than operator: Represented as ‘>’, the greater than operator checks whether the
first operand is greater than the second operand or not. If so, it returns 1. Otherwise it returns
0. For example, 6>5 will return 1.
4. Less than operator: Represented as ‘<‘, the less than operator checks whether the first
operand is lesser than the second operand. If so, it returns 1. Otherwise it returns 0. For
example, 6<5 will return 0.

Page 8
5. Greater than or equal to operator: Represented as ‘>=’, the greater than or equal to
operator checks whether the first operand is greater than or equal to the second operand. If
so, it returns 1 else it returns 0. For example, 5>=5 will return 1.
6. Less than or equal to operator: Represented as ‘<=’, the less than or equal to operator
checks whether the first operand is less than or equal to the second operand. If so, it returns
1 else 0. For example, 5<=5 will also return 1.

Logical Operators:

They are used to combine two or more conditions/constraints or to complement the evaluation of the
original condition under consideration. They are described below:
1. Logical AND operator: The ‘&&’ operator returns 1 when both the conditions under
consideration are satisfied. Otherwise it returns 0. For example, a && b returns 1 when both
a and b are 1 (i.e. non-zero).
2. Logical OR operator: The ‘||’ operator returns 1 even if one (or both) of the conditions
under consideration is satisfied. Otherwise it returns 0. For example, a || b returns 1 if one of
a or b or both are 1 (i.e. non-zero). Of course, it returns 1 when both a and b are 1.
3. Logical NOT operator: The ‘!’ operator returns 1 the condition in consideration is not
satisfied. Otherwise it returns 0. For example, !a returns 1 if a is 0, i.e. when a=0.

Short-Circuiting in Logical Operators:

In case of logical AND, the second operand is not evaluated if first operand is false. For example, 1>5
&& 5<10, since 1>5 is false, second expression will not be evaluated.

In case of logical OR, the second operand is not evaluated if first operand is true. For example, 1<5 ||
5>10, since 1<5 is true, second expression will not be evaluated.

Assignment Operators:
Assignment operators are used to assign value to a variable. The left side operand of the assignment operator
is a variable and right side operand of the assignment operator is a value. The value on

Page 9
the right side must be of the same data-type of variable on the left side otherwise the compiler will raise an
error.
Different types of assignment operators are shown below:
i. “=”: This is the simplest assignment operator. This operator is used to assign the value on
the right to the variable on the left.
For example: a = 10;
ii. “+=”: This operator is combination of ‘+’ and ‘=’ operators. This operator first adds the
current value of the variable on left to the value on right and then assigns the result to the
variable on the left.
Example: (a += b) can be written as (a = a + b)
If initially value stored in a is 5. Then (a += 6) = 11.

iii. “-=”: This operator is combination of ‘-‘ and ‘=’ operators. This operator first subtracts the
value on right from the current value of the variable on left and then assigns the result to the
variable on the left.
Example: (a -= b) can be written as (a = a - b)
If initially value stored in a is 8. Then (a -= 6) = 2.

iv. “*=”: This operator is combination of ‘*’ and ‘=’ operators. This operator first multiplies the
current value of the variable on left to the value on right and then assigns the result to the
variable on the left.
Example: (a *= b) can be written as (a = a * b)
If initially value stored in a is 5. Then (a *= 6) = 30.

v. “/=”: This operator is combination of ‘/’ and ‘=’ operators. This operator first divides the
current value of the variable on left by the value on right and then assigns the result to the
variable on the left.
Example: (a /= b) can be written as (a = a / b)
If initially value stored in a is 6. Then (a /= 2) = 3.

Bitwise Operators:

Page 10
The Bitwise operators are used to perform bit-level operations on the operands. The operators are first
converted to bit-level and then the calculation is performed on the operands. The mathematical operations
such as addition, subtraction, multiplication etc. can be performed at bit-level for faster processing.

1. & (bitwise AND) in C takes two numbers as operands and does AND on every bit of two
numbers. The result of AND is 1 only if both bits are 1.
2. | (bitwise OR) in C takes two numbers as operands and does OR on every bit of two numbers.
The result of OR is 1 if any of the two bits is 1.
3. ^ (bitwise XOR) in C takes two numbers as operands and does XOR on every bit of two
numbers. The result of XOR is 1 if the two bits are different.
4. << (left shift) in C takes two numbers, left shifts the bits of the first operand, the second
operand decides the number of places to shift.
5. >> (right shift) in C takes two numbers, right shifts the bits of the first operand, the second
operand decides the number of places to shift.
6. ~ (bitwise NOT) in C takes one number and inverts all bits of it.

#include <stdio.h>
int main()
{
// a = 5(00000101), b = 9(00001001)
unsigned char a = 5, b = 9;

// The result is 00000001


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

// The result is 00001101


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

// The result is 00001100


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

// The result is 11111010


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

// The result is 00010010


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

// The result is 00000100

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

return 0;
}

Output

a = 5, b = 9
a&b = 1
a|b = 13
a^b = 12
~a = 250
b<<1 = 18
b>>1 = 4

Swap two number using XOR operation


#include<stdio.h>
void main()
{
int a,b;
printf("Enter the value of a and b");
scanf("%d%d",&a,&b); printf("Before
Swapping\n");
printf("a=%d\tb=%d\n",a,b); a=a^b;
b=a^b;
a=a^b;
printf("After Swapping\n");
printf("a=%d\tb=%d\n",a,b);
}

Output
Enter the value of a and b10 20
Before Swapping
a=10 b=20
After Swapping
a=20 b=10

Notes:
1) The left-shift and right-shift operators are equivalent to multiplication and division by 2
respectively.

Page 12
2) & operator can be used to quickly check if a number is odd or even. The value of expression
(x & 1) would be non-zero only if x is odd, otherwise the value would be zero.
3) The left shift and right shift operators should not be used for negative numbers. If any of
the operands is a negative number, it results in undefined behaviour. For example results of both -
1 << 1 and 1 << -1 is undefined. Also, if the number is shifted more than the size of integer, the
behaviour is undefined. For example, 1 << 33 is undefined if integers are stored using 32 bits.
4) The bitwise operators should not be used in place of logical operators. The result of logical
operators (&&, || and !) is either 0 or 1, but bitwise operators return an integer value. Also, the
logical operators consider any non-zero operand as 1.

Conditional Operator
Conditional operator is of the form Expression1 ? Expression2 : Expression3 . Here, Expression1
is the condition to be evaluated. If the condition(Expression1) is True then we will execute and return the
result of Expression2 otherwise if the condition(Expression1) is false then we will execute and return the
result of Expression3. We may replace the use of if..else statements by conditional operators.

Largest of two numbers using conditional operator (ternary operator)


#include<stdio.h>
void main()
{
int a,b,large;
printf("Enter the value of a and b");
scanf("%d%d",&a,&b);
large = a>b ? a : b;
printf("Largest=%d\n",large);
}

Largest of tthree numbers using conditional operator (ternary operator)

#include<stdio.h>
void main()
{
int a,b,c,large;
printf("Enter the value of a,b and c");
scanf("%d%d%d",&a,&b,&c);
large = a>b && a>c ? a : b>a && b>c ?b:c;

Page 13
printf("Largest=%d\n",large);
}

sizeof operator:
sizeof is a much used in the C/C++ programming language. It is a compile time unary operator
which can be used to compute the size of its operand. The result of sizeof is of unsigned integral type which
is usually denoted by size_t. Basically, sizeof operator is used to compute the size of the variable.
#include <stdio.h>
void main()
{
printf("%d\n", sizeof(char));
printf("%d\n", sizeof(int));
printf("%d\n", sizeof(float));
printf("%d", sizeof(double));
}
Output
1
4
4
8
Control Flow Statement

C provides two styles of flow control:


• Branching
• Looping
Branching is deciding what actions to take and looping is deciding how many times to take a certain action.
Branching

1) if statement

Page 14
This is the simplest form of the branching statements. It takes an expression in parenthesis and a statement
or block of statements. if the expression is true then the statement or block of statements gets executed
otherwise these statements are skipped.

Syntax

• if
if (expression)
{
Block of statements;
}

• if--else • if—else if
if (expression) if (expression)
{ {
Block of statements; Block of statements;
} }
else else if(expression)
{ {
Block of statements; Block of statements;
} }
else
{
Block of statements;
}

Q) Write a program to test whether a number even or odd?


#include <stdio.h>
void main()
{
int n;
printf("Enter the value of n");
scanf("%d",&n);
if( n%2 == 0)
{
printf("Even");
}
else
{
printf("Odd");
}
}

Page 15
Q) Write a program to test whether a number is negative or positive or zero?
#include <stdio.h>
void main()
{
int n;
printf("Enter the value of n");
scanf("%d",&n);
if( n > 0)
{
printf("Positive");
}
else if(n < 0)
{
printf("Negative");
}
else{
printf("Zero");
}
}

Q) Write a program to find largest of two numbers?


#include <stdio.h>
void main()
{
int a,b;
printf("Enter the value of a and b");
scanf("%d%d",&a,&b);
if(a>b)
{
printf("%d is larger than %d",a,b);
}
else
{
printf("%d is larger than %d",b,a);
}
}

Page 16
Q) Write a program to find largest of three numbers?
#include <stdio.h>
void main()
{
int a,b,c;
printf("Enter the value of a and b");
scanf("%d%d",&a,&b,&c);
if(a>b && a>c)
{
printf("%d is largerest",a);
}
else if(b>a && b>c)
{
printf("%d is largerest",b);
}
else
{
printf("%d is largerest",c);
}
}

Q) Write a program to test whether number is even or odd using AND operator?
#include <stdio.h>
void main()
{
int n;
printf("Enter the value of n");
scanf("%d",&n);
if( n & 1 == 0)
{
printf("Even");
}
else
{
printf("Odd");
}
}

Q) Write a program to test whether number is even or odd using shift operator?
#include <stdio.h>
void main()
{
int n;
printf("Enter the value of n");
scanf("%d",&n);
Page 17
if( (n >> 1) <<1 == n)
{
printf("Even");
}
else
{
printf("Odd");
}
}

Page 18
switch statement

The switch statement is much like a nested if .. else statement. Its mostly a matter of preference which you
use, switch statement can be slightly more efficient and easier to read.

Syntax
switch( expression )
{
case constant-expression1: statements1;break; case
constant-expression2: statements2;break; case constant-
expression3: statements3;break; default : statements4;
}

Q) Write a program to read number between 1 and 7 and display the day corresponding to
the number.
#include <stdio.h>
void main()
{
int n;
printf("Enter the value of n");
scanf("%d",&n);
switch(n)
{
case 1: printf("Sunday");
break; case
2: printf("Monday");
break; case
3: printf("Tuesday");
break;
case 4: printf("Wednesday");
break;
case 5: printf("Thursday");
break;
case 6: printf("Friday");
break;
case 7: printf("Saturday");
break;
default:printf("Wrong Choice");
}
}

Page 19
goto statement(Unconditional Jump)
The goto statement allows us to transfer control of the program to the specified label.

Syntax
goto label;
... .. ...
... .. ...
label:
statement;

Q) Write a program to read a number and check whether a number is odd or even. If the
number is negative goto end.
#include <stdio.h>
void main()
{
int n;
printf("Enter the value of n");
scanf("%d",&n);
if(n<0)
goto END;
if(n % 2 ==0)
printf("Even\n");
else
printf("Odd\n");
END:printf("End");
}

Output

Enter the value of n10 Enter the value of n-10


Even End
End

Looping
Loops provide a way to repeat commands and control how many times they are repeated.
C provides a number of looping way.

while loop

The most basic loop in C is the while loop. A while statement is like a repeating if statement. Like an If
statement, if the test condition is true: the statements get executed. The difference is that

Page 20
after the statements have been executed, the test condition is checked again. If it is still true the statements
get executed again. This cycle repeats until the test condition evaluates to false.

Syntax

while ( expression )
{
Single statement
or
Block of statements;
}

Q) Write a program to read a number and find sum of digits of a numbers.


#include <stdio.h>
void main()
{
int n,sum=0,temp;
printf("Enter the value of n");
scanf("%d",&n);
while ( n > 0 )
{
temp = n%10;
sum = sum + temp; n
= n/10;
}
printf("Sum = %d",sum);
}

Q) Write a program to read a number and find reverse of a number.


#include <stdio.h>
void main()
{
int n,rev=0,temp;
printf("Enter the value of n");
scanf("%d",&n);
while ( n > 0 )
{
temp = n%10;
rev = rev * 10 + temp; n
= n/10;
}
printf("Reverse = %d",rev);
}

Page 21
Q) Write a program to read a number and check whether it is palindrome or not.
#include <stdio.h>
void main()
{
int n,rev=0,temp,org;
printf("Enter the value of n");
scanf("%d",&n);
org=n;
while ( n > 0 )
{
temp = n%10;
rev = rev * 10 + temp; n
= n/10;
}
if( org == rev)
{
printf("Palindrome");
}
else
{
printf("Not Palindrome");
}
}

Q) Write a program to read a number and check whether a number is Armstrong or not.
#include <stdio.h>
#include <math.h>
void main()
{
int n,sum=0,temp,org; printf("Enter
the value of n");
scanf("%d",&n);
org=n;
// To find count number of digits in the number
while( n > 0)
{
count++;
n=n/10;
}
while ( n > 0 )
{
temp = n%10;
rev = sum + pow(temp,count); n
= n/10;
}

Page 22
if( org == sum)
{
printf("Armstrong");
}
else
{
printf("Not Armstrong");
}
}

for loop

for loop is similar to while, it's just written differently. for statements are often used to process lists such
a range of numbers:

Basic syntax of for loop is as follows:

for( expression1; expression2; expression3)


{
Single statement
or
Block of statements;
}
In the above syntax:

• expression1 - Initializes variables.


• expression2 - Conditional expression, as long as this condition is true, loop will keep
executing.
• expression3 - expression3 is the modifier which may be simple increment of a variable.

Q) Write a program to find sum of first n natural numbers?


#include <stdio.h>
void main()
{
int n,i,sum=0;
printf("Enter the value of n");
scanf("%d",&n);
for(i=1;i<=n;i++)
{
sum = sum + i;
}

Page 23
printf("Sum = %d",sum);
}

Q) Write a program to find sum of first n natural numbers?


#include <stdio.h>
void main()
{
int n,i,fact=1;
printf("Enter the value of n");
scanf("%d",&n);
for(i=1;i<=n;i++)
{
fact = fact * i;
}
printf("Factorial = %d",fact);
}
Q) Write a program to read n natural numbers and find largest even number and largest
odd number using without using division or modulo?
#include <stdio.h>
void main()
{
int n,a,i;
int le = -1, lo=-1; printf("Enter
the value of n");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("Enter the value of a");
scanf("%d",&a);
if(a & 1 ==0)
{
if(le<a)
le = a;
}
else
{

if(lo<a)
lo = a;
}
}
}

do – while statement

Page 24
The do..while loop is similar to the while loop with one important difference. The body of do...while
loop is executed at least once. Only then, the test expression is evaluated. The syntax of the do...while loop
is:
do
{
// statements inside the body of the loop
}
while (expression);

Q) Write a program to find sum of first n natural numbers using do..while ?


#include <stdio.h>
void main()
{
int n,i,sum=0;
printf("Enter the value of n");
scanf("%d",&n);
i=1;
do
{
sum = sum + i;
i++;
}while(i<=n); printf("Sum
= %d",sum);
}

Difference between while and do while statements

WHILE DO-WHILE

Condition is checked Statement(s) is executed,


first then statement(s) is thereafter condition is
executed. checked.
It might occur statement(s) is At least once the statement(s) is
executed zero times, If condition executed.
is false.
No semicolon at the end of while. Semicolon at the end of
while(condition) while. while(condition);

If there is a single statement, brackets Brackets are always required.


are not required.

while loop is entry controlled loop. do-while loop is exit controlled loop.

24
WHILE DO-WHILE

while(condition) do
{ {
statement(s); statement(s);
} }
while(condition);

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


void main() void main()
{ {
int i=-1; int i=-1; do
while(i>0) {
{ printf("Test");
printf("Test"); }while(i>0);
} printf("End");
printf("End"); }
} Ou
Ou t
t p
p u
u t
t T
E e
n s
d t
E
n
d

25
Module III
Array
An array in C is a collection of items stored at contiguous memory locations and elements can be
accessed randomly using indices of an array. They are used to store similar type of elements as in the
data type must be the same for all elements. They can be used to store collection of primitive data
types such as int, float, double, char, etc of any particular type.
Indices 0 1 2 3
A
Array elements 10 20 30 40

Why do we need arrays?


We can use normal variables (v1, v2, v3) when we have a small number of objects, but if we
want to store a large number of instances, it becomes difficult to manage them with normal variables.
The idea of an array is to represent many instances in one variable.
Different ways of declaring an Array
1. Array declaration by specifying size

Eg: int A[10];

2. Array declaration by initializing elements

Eg: int A[] = { 10, 20, 30, 40 }

3. Array declaration by specifying size and initializing elements


Eg: int A[6] = { 10, 20, 30, 40 }

Advantages of an Array:
1. Random access of elements using array index.
2. Use of less line of code as it creates a single array of multiple elements.
3. Easy access to all the elements.
4. Traversal through the array becomes easy using a single loop.
5. Sorting becomes easy as it can be accomplished by writing less line of code.
Disadvantages of an Array:

26
• It allows us to enter only fixed number of elements into it. We cannot alter the size of
the array once array is declared. Hence if we need to insert more number of records than declared
then it is not possible. We should know array size at the compile time itself.

• Inserting and deleting the records from the array would be costly since we add / delete the
elements from the array, we need to manage memory space too.

• It does not verify the indexes while compiling the array. In case there is any indexes pointed
which is more than the dimension specified, then we will get run time errors rather than
identifying them at compile time.

Eg: int a[3]={1,2,3}


printf("%d",A[3]);
Output: 3245431 (Garbage Value)

1) Write a program to read and display an array of size n.

#include<stdio.h>
void main()
{
int n,A[20],i;
printf("Enter the size of Array");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("Enter the number");
scanf("%d",&A[i]);
}
for(i=0;i<n;i++)
{
printf("%d\t",A[i]);
}
}
2) Write a program to read and display an array of size n in reverse order.

#include<stdio.h>
void main()
{
int n,A[20],i;
printf("Enter the size of Array");
scanf("%d",&n);
for(i=0;i<n;i++)
{
27
printf("Enter the number");
scanf("%d",&A[i]);
}
for(i=n-1;i>=n;i--)
{
printf("%d\t",A[i]);
}
}

3) Write a program to find sum and average of an array content of size n.

#include<stdio.h>
void main()
{
int n,A[20],i,sum;
float avg;
printf("Enter the size of Array");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("Enter the number");
scanf("%d",&A[i]);
}
sum=0;
for(i=0;i<n;i++)
{
sum = sum + i;
}
avg = (float)sum/n;
printf("Sum=%d",sum);
printf("Average=%f",avg);
}

4) Write a program to read and display even display numbers in an array of size n.

#include<stdio.h>
void main()
{
int n,A[20],i;
printf("Enter the size of Array");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("Enter the number");
scanf("%d",&A[i]);
}
28
for(i=0;i<n;i++)
{
if(A[i]%2 == 0)
{
printf("%d\t",A[i]);
}
}
}

5) Write a program to read and display prime numbers in an array of size n.

#include<stdio.h>
void main()
{
int n,A[20],i,flag,j;
printf("Enter the size of Array");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("Enter the number");
scanf("%d",&A[i]);
}
for(i=0;i<n;i++)
{
flag=0;
for(j=2;j<=A[i]/2;j++)
{
if(A[i]%j == 0)
{
flag=1;
break;
}
}
if(flag == 0)
{
printf("%d\t",A[i]);
}
}
}

6) Write a program to search an element in array of size n.

#include<stdio.h>
void main()
{

29
int n,A[20],i,index;
printf("Enter the size of Array");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("Enter the number");
scanf("%d",&A[i]);
}
printf("Enter the element to search");
scanf("%d",&key);
index = -1;
for(i=0;i<n;i++)
{
if(A[i] == key)
{
index = i;
break;
}
}
if(index == -1)
{
printf("No search element found");
}
else
{
prinft("Search Element found at index %d",index);
}
}
7) Write a program to find largest element in array of size n.

#include<stdio.h>
void main()
{
int n,A[20],i,large;
printf("Enter the size of Array");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("Enter the number");
scanf("%d",&A[i]);
}

large=A[0];
for(i=0;i<n;i++)
{
if(large < A[i])
{
30
large = A[i]
}
}
printf("Large =%d",large);
}
8) Write a program to sort element in array of size n.

#include<stdio.h>
void main()
{
int n,A[20],i,j,temp;
printf("Enter the size of Array");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("Enter the number");
scanf("%d",&A[i]);
}
printf("Before Sorting");
for(i=0;i<n;i++)
{
printf("%d\t",A[i]);
}
for(i=0;i<n-1;i++)
{
for(j=0;j<n-i-1;j++)
{
if(A[j]>A[j+1])
{
temp=A[j];
A[j]=A[j+1];
A[j+1]=temp;
}
}
}
printf("Before Sorting");
for(i=0;i<n;i++)
{
printf("%d\t",A[i]);
}

String
Strings are defined as an array of characters. The difference between a character array and a string is
the string is terminated with a special character ‘\0’.
31
Index 0 1 2 3 4 5
Character Array ‘H’ ‘E’ ‘L’ ‘L’ ‘O’
String ‘H’ ‘E’ ‘L’ ‘L’ ‘O’ ‘\0’

Declaration of strings: Declaring a string is as simple as declaring a one dimensional array. Below
is the basic syntax for declaring a string.
char str[20];
In the above syntax str is any name given to the string variable and 20 is used define the length of
the string, i.e. the number of characters strings will store. Please keep in mind that there is an extra
terminating character which is the Null character (‘\0’) used to indicate termination of string which
differs strings from normal character arrays.

Initializing a String:

A string can be initialized in different ways.

1. char str[] = "Programming";

2. char str[50] = "Programming";

3. char str[] = {'P','r','o','g','r','a','m','m','i','n','g','\0'};

4. char str[12] = {'P','r','o','g','r','a','m','m','i','n','g','\0'};

Read a character from User


1) scanf()
• It is used to read the input (character, string, numeric data) from the standard input (keyboard).
• It is used to read the input until it encounters a whitespace, newline or End Of File (EOF).

#include <stdio.h>
void main()
{
char str[20];
printf("Enter the String\n");
scanf("%s", str);
printf("String: %s\n", str);

}
32
Output
Enter the String : Hello World
String: Hello
Issue with scanf: There is a whitespace after Hello. So it read the input till Hello and store it in str.

Solution: use % [^\n] instead of %s.


#include <stdio.h>
void main()
{
char str[20];
printf("enter the string\n");
scanf("%[^\n]", str);
printf("String: %s\n", str);

2) Gets
• It is used to read input from the standard input (keyboard).
• It is used to read the input until it encounters newline or End Of File (EOF).

#include <stdio.h>
void main()
{
char str[20];
printf("Enter the String\n");
gets( str);
printf("String: %s\n", str);

Output
Enter the String: Hello World
String: Hello World

Issue: it reads string from standard input and prints the entered string, but it suffers from Buffer
Overflow as gets() doesn’t do any array bound testing. gets() keeps on reading until it sees a newline
character.
33
Display String value – printf and puts
#include <stdio.h> #include <stdio.h>
void main() void main()
{ {
char str[20]; char str[20];
printf("Enter the String\n"); printf("Enter the String\n");
gets( str); gets( str);
printf("%s\n", str); puts(str);
} }
Output Output
Enter the String: Hello world Enter the String: Hello world
Hello world Hello world

In-built String Function

Function Work of Function

strlen() computes string's length

strcpy() copies a string to another

strcat() concatenates(joins) two strings

strcmp() compares two strings case sensitive checking

strcmpi() compares two strings case insensitive checking

strlwr() converts string to lowercase

strupr() converts string to uppercase

strlen vs sizeof
strlen returns the length of the string stored in array, however sizeof returns the total allocated size
assigned to the array.
#include<stdio.h>
#include<string.h>
void main()
{
char str[]="Hello World";
34
int len=strlen(str);
int size=sizeof(str);
printf("Value=%d",len*size);
}
len value will the length of the string which is 11. But size value will be 12 including the end of
character.
Output
Value=132
strcat
It concatenates two strings and returns the concatenated string.
Syntax: strcat(string1,string2) – concatenate string1 with string2.
#include <stdio.h>
#include <string.h>
void main()
{
char s1[10] = "Hello";
char s2[10] = "World";
strcat(s1,s2);
printf("After concatenation: %s", s1);
}

Output:
After concatenation: HelloWorld
strcpy
It copies the string str2 into string str1, including the end character (terminator char ‘\0’).
Syntax: strcpy(string1,string2) - copy the content of string2 to string1
#include <stdio.h>
#include <string.h>
void main()
{
char s1[30];
char s2[30] = "Hello World";
strcpy(s1,s2);
printf("String s1: %s", s1);
}
Output:
String s1 is: Hello World

strcmp
35
It compares the two strings and returns an integer value. If both the strings are same (equal)
then this function would return 0 otherwise it may return a negative or positive value based on the
comparison.
strcmp(string1,string2) -- Compares the content of string1 and string2

• If string1 < string2 OR string1 is a substring of string2 then it would result in a negative value.
• If string1 > string2 then it would return positive value.
• If string1 == string2 then you would get 0(zero) when you use this function for compare strings.
#include <stdio.h>
#include <string.h>
void main()
{
char s1[20] = "Hello";
char s2[20] = "World";
if (strcmp(s1, s2) ==0)
{
printf("string 1 and string 2 are equal");
}
else
{
printf("string 1 and 2 are different");
}
}
Output:
string 1 and 2 are different

• Write a program to display the content of string in upper and lower case.
#include<stdio.h>
#include<string.h>
void main()
{
char str[20];
printf("Enter the string");
gets(str);
printf("Upper Case String:%s",strupr(str));
printf("Lower Case String:%s",strlwr(str));
}

36
Output
Enter the string Hello World
Upper Case String: HELLO WORLD
Lower Case String: hello world

• Write a program to reverse the content of string.


#include<stdio.h>
#include<string.h>
void main()
{
char str[20];
int len,i,j;
printf("Enter the string");
gets(str);
i=strlen(str)-1;
j=0;
while(i>=0)
{
rev[j]=str[i];
j++;
i--;
}
rev[j]='\0';
printf("Reverse=%s",rev);
}

• Write a program to check whether a string is palindrome or not without using in built
functions.
#include<stdio.h>
#include<string.h>
void main()
{
char str[20];
int len,i,j,flag;
printf("Enter the string");
gets(str);
// Code to find string length
for(len=0;str[len]!='\0';len++);
// Code to check the Palindrome
flag=0;
for(i=0;i<len/2;i++)
{
if(str[i] != str[len-1-i])
37
{
flag=1;
break;
}
}
if(flag == 0)
{
printf("Palindrome");
}
else
{
printf("Not Palindrome");
}
}

• Write a program to count number of vowels in a given string.

#include<stdio.h>
#include<string.h>
void main()
{
char str[20];
int i,count;
printf("Enter the string");
gets(str);
count=0;
for(i=0;i<strlen(str);i++)
{
switch(str[i])
{
case 'A':
case 'a':
case 'E':
case 'e':
case 'i':
case 'I':
case 'O':
case 'o':
case 'U':
case 'u':count++;
break;
}
}
printf("Count of vowels=%d",count);
}

• Write a program to length of string without in built function.


38
#include<stdio.h>
void main()
{
char str[30];
int i=0;
printf("Enter the String:");
scanf("%s",str);
while(str[i] != '\0')
{
i++;
}
printf("Length = %d",i);
}

Output
Enter the String:Sangeeth
Length = 8

• Write a program to copy the content of a string to another location without using in
built function.

#include<stdio.h>
void main()
{
char s1[30],s2[30];
int i=0;
printf("Enter the String:");
scanf("%s",s1);
while(s1[i] != '\0')
{
s2[i]=s1[i];
i++;
}
s2[i]='\0';
printf("Copied String = %s",s2);
}

Output
Enter the String:Sangeeth
Copied String = Sangeeth

• Write a program to concatenate the content of a string with another location without
using in built function.
#include<stdio.h>
39
void main()
{
char s1[30],s2[30],s3[50];
int i=0,j=0;
printf("Enter the String 1:");
scanf("%s",s1);
printf("Enter the String 2:");
scanf("%s",s2);
while(s1[i] != '\0')
{
s3[i]=s1[i];
i++;
}
while(s2[j] != '\0')
{
s3[i]=s2[j];
i++;
j++;
}
s3[i]='\0';
printf("Concatenated String = %s",s3);
}

Output

Enter the String 1:Sangeeth


Enter the String 2:Nagarajan
Concatenated String = SangeethNagarajan

Two Dimensional Array

An array of arrays is known as 2D array. The two dimensional (2D) array is also known as matrix. A
matrix can be represented as a table of rows and columns. The syntax to declare the 2D array is given
below.
data_type array_name[rows][columns];

Initialization of Two Dimensional Array

There are two ways to initialize a two Dimensional arrays during declaration.

1. int A[2][3] = { {10, 11, 12},{14, 15, 16}};


int A[][3] = { {10, 11, 12},{14, 15, 16}};
2. int A[2][3] = { 10, 11, 12, 14, 15, 16};
40
int A[][3] = { 10, 11, 12, 14, 15, 16};

When we initialize a 1 dimensional array during declaration, we need not to specify the size
of it. However that’s not the case with 2D array, you must always specify the second dimension even
if you are specifying elements during the declaration.
/* Valid declaration*/
int A[2][2] = {1, 2, 3 ,4 }
/* Valid declaration*/
int A[][2] = {1, 2, 3 ,4 }
/* Invalid declaration – you must specify second dimension*/
int A[][] = {1, 2, 3 ,4 }
/* Invalid because of the same reason mentioned above*/
int A[2][] = {1, 2, 3 ,4 }

Structure of two dimensional array of size - A[3][5]

A[0][0] A[0][1] A[0][2] A[0][3] A[0][4]


A[1][0] A[1][1] A[1][2] A[1][3] A[1][4]
A[2][0] A[2][1] A[2][2] A[2][3] A[2][4]

1. Write a program to read a matrix of size mXn.


#include<stdio.h>
void main()
{
int m,n,A[20][20],i,j;
printf("Enter the order of matrix");
scanf("%d%d",&m,&n);

// Row
for(i=0;i<m;i++)
{
//Column
for(j=0;j<n;j++)
{
printf("Enter the element");
scanf("%d",&A[i][j]);

41
}
}
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
printf("%d\t",A[i][j]);
}
printf("\n");
}
}

2. Write a program to read a matrix of size mXn and display its transpose.

#include<stdio.h>
void main()
{
int m,n,A[20][20],i,j;
printf("Enter the order of matrix");
scanf("%d%d",&m,&n);
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
printf("Enter the element");
scanf("%d",&A[i][j]);
}
}
printf(“Transpose of Matrix A\n”);
for(j=0;j<n;j++)
{
for(i=0;i<m;i++)
{
printf("%d\t",A[i][j]);
}
printf("\n");
}
}

3. Write a program to read a matrix of size mXn and display its sum of diagonal.
#include<stdio.h>
void main()
{
int m,n,A[20][20],i,j;
printf("Enter the order of matrix");
scanf("%d %d",&m,&n);
42
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
printf("Enter the element");
scanf("%d",&A[i][j]);
}
}
for(i=0;i<m;i++)
{
sum = sum + A[i][i];
}
printf("Sum=%d",sum);
}

4. Write a program to add the content of two matrices.

#include<stdio.h>
#include<stdlib.h> // used for exit(1)
void main()
{
int r1,c1,r2,c2,A[20][20],B[20][20],C[20][20],i,j;
printf("Enter the order of matrices:");
scanf("%d%d%d%d",&r1,&c1,&r2,&c2);
if(r1 != r2 || c1 != c2)
{
printf("Matrices Addition Not possible");
exit(1);
}
printf("Enter the Matrix A\n");
for(i=0;i<r1;i++)
{
for(j=0;j<c1;j++)
{
printf("Enter the element A[%d][%d]:",i,j);
scanf("%d",&A[i][j]);
}
}
printf("Enter the Matrix B\n");
for(i=0;i<r2;i++)
{
for(j=0;j<c2;j++)
{
printf("Enter the element B[%d][%d]:",i,j);
scanf("%d",&B[i][j]);
}
}
43
printf("Added Matrix C:\n");
for(i=0;i<r1;i++)
{
for(j=0;j<c1;j++)
{
C[i][j]=A[i][j] + B[i][j];
printf("%d\t",C[i][j]);
}
printf("\n");
}
}

Output
Enter the order of matrices: 2 2 2 2
Enter the Matrix A
Enter the element A[0][0]:1
Enter the element A[0][1]:2
Enter the element A[1][0]:3
Enter the element A[1][1]:4
Enter the Matrix B
Enter the element B[0][0]:5
Enter the element B[0][1]:6
Enter the element B[1][0]:7
Enter the element B[1][1]:8
Added Matrix C:
6 8
10 12

5. Write a program to perform matrix multiplication.

#include<stdio.h>
#include<stdlib.h> // used for exit(1)
void main()
{
int r1,c1,r2,c2,A[20][20],B[20][20],C[20][20],i,j,k;
printf("Enter the order of matrices:");
scanf("%d%d%d%d",&r1,&c1,&r2,&c2);
if(c1 != r2)
{
printf("Matrices Multiplication Not possible");
exit(1);
}
printf("Enter the Matrix A\n");
for(i=0;i<r1;i++)
{
for(j=0;j<c1;j++)
44
{
printf("Enter the element A[%d][%d]:",i,j);
scanf("%d",&A[i][j]);
}
}
printf("Enter the Matrix B\n");
for(i=0;i<r2;i++)
{
for(j=0;j<c2;j++)
{
printf("Enter the element B[%d][%d]:",i,j);
scanf("%d",&B[i][j]);
}
}
printf("Matrix C:\n");
for(i=0;i<r1;i++)
{
for(j=0;j<c2;j++)
{
C[i][j]= 0;
for(k=0;k<c1;k++)
{
C[i][j] += A[i][k] * B[k][j];
}
printf("%d\t",C[i][j]);
}
printf("\n");
}
}

Output
Enter the order of matrices:2 2 2 2
Enter the Matrix A
Enter the element A[0][0]:1
Enter the element A[0][1]:2
Enter the element A[1][0]:3
Enter the element A[1][1]:4
Enter the Matrix B
Enter the element B[0][0]:5
Enter the element B[0][1]:6
Enter the element B[1][0]:7
Enter the element B[1][1]:8
Matrix C:
19 22
43 50

45
Example of Two dimensional Character Array

• Write a program to read name of n persons and display those names.

#include<stdio.h>
#include<string.h>
void main()
{
int n,i,j;
char names[30][30],temp[30];
printf("Enter the value of n:");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("Enter the name:");
scanf("%s",names[i]);
}
printf("Names\n");
for(i=0;i<n;i++)
{
printf("%s\n",names[i]);
}
}
Output
Enter the value of n:4
Enter the name:Sangeeth
Enter the name:Karthi
Enter the name:Poornima
Enter the name:Chandrika
Names
Sangeeth
Karthi
Poornima
Chandrika

• Write a program to read name of n persons and display those name in alphabetical order.

#include<stdio.h>
#include<string.h>
void main()
{
int n,i,j;
char names[30][30],temp[30];
printf("Enter the value of n:");
scanf("%d",&n);
for(i=0;i<n;i++)
46
{
printf("Enter the name:");
scanf("%s",names[i]);
}
for(i=0;i<n-1;i++)
{
for(j=0;j<n-i-1;j++)
{
if(strcmp(names[j],names[j+1])>0)
{
strcpy(temp,names[j]);
strcpy(names[j],names[j+1]);
strcpy(names[j+1],temp);
}
}
}
printf("Names in Ascending order\n");
for(i=0;i<n;i++)
{
printf("%s\n",names[i]);
}
}

Output

Enter the value of n:4


Enter the name:Sangeeth
Enter the name:Karthi
Enter the name:Poornima
Enter the name:Chandrika
Names in Ascending order
Chandrika
Karthi
Poornima
Sangeeth

47
LINEAR SEARCH
Linear search or Sequential search is a method for finding an element within a list. It sequentially
checks each element of the list until a match is found or the whole list has been searched.

48
Program

#include <stdio.h>

int main()
{
int array[100], search, c, n;
printf("Enter number of elements in array\n");
scanf("%d", &n);
printf("Enter %d integer(s)\n", n);
for (c = 0; c < n; c++)
scanf("%d", &array[c]);
printf("Enter a number to search\n");
scanf("%d", &search);
for (c = 0; c < n; c++)
{
if (array[c] == search) /* If required element is found */
{
printf("%d is present at location %d.\n", search, c+1);
break;
}
}
if (c == n)
printf("%d isn't present in the array.\n", search);
return 0;
}

Output
Enter number of elements in array
5
Enter 5 integer(s)
5
6
2
3
4
Enter a number to search
89
89 isn't present in the array.

BUBBLE SORT
Bubble Sort is a simple algorithm which is used to sort a given set of n elements provided in form of
an array with n number of elements. Bubble Sort compares all the element one by one and sort them
based on their values.
49
If the given array has to be sorted in ascending order, then bubble sort will start by comparing the first
element of the array with the second element, if the first element is greater than the second element,
it will swap both the elements, and then move on to compare the second and the third element, and so
on.
If we have total n elements, then we need to repeat this process for n-1 times.
It is known as bubble sort, because with every complete iteration the largest element in the given
array, bubbles up towards the last place or the highest index, just like a water bubble rises up to the
water surface.
Sorting takes place by stepping through all the elements one-by-one and comparing it with the adjacent
element and swapping them if required.
Implementing Bubble Sort Algorithm
Following are the steps involved in bubble sort(for sorting a given array in ascending order):
1. Starting with the first element(index = 0), compare the current element with the next element
of the array.
2. If the current element is greater than the next element of the array, swap them.
3. If the current element is less than the next element, move to the next element. Repeat Step
1.

Let's consider an array with values {5, 1, 6, 2, 4, 3}


Below is a pictorial representation of how bubble sort will sort the given array.

50
So as we can see in the representation above, after the first iteration, 6 is placed at the last index,
which is the correct position for it.
Similarly after the second iteration, 5 will be at the second last index, and so on.

Program
#include <stdio.h>
int main()
{
int arr[100], i, j, n, step, temp;
// ask user for number of elements to be sorted
printf("Enter the number of elements to be sorted: ");
scanf("%d", &n);
// input elements if the array
for(i = 0; i < n; i++)
{
printf("Enter element no. %d: ", i+1);
51
scanf("%d", &arr[i]);
}

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


{
for(j = 0; j < n-i-1; j++)
{
if( arr[j] > arr[j+1])
{
// swap the elements
temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
}
}
}

// print the sorted array


printf("Sorted Array: ");
for(i = 0; i < n; i++)
{
printf("%d ", arr[i]);
}
return 0;
}

Output
Enter the number of elements to be sorted: 5
Enter element no. 1: 8
Enter element no. 2: 9
Enter element no. 3: 6
Enter element no. 4: 7
Enter element no. 5: 1
Sorted Array: 1 6 7 8 9
Although the above logic will sort an unsorted array, it is not efficient because as per the above logic,
the outer for loop will keep on executing for 6 iterations even if the array gets sorted after the second
iteration.

Program to find the average of n numbers using arrays

#include <stdio.h>
int main()
{
int marks[10], i, n, sum = 0, average;

52
printf("Enter number of elements: ");
scanf("%d", &n);

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


{
printf("Enter number%d: ",i+1);
scanf("%d", &marks[i]);

// adding integers entered by the user to the sum


variable
sum += marks[i];
}

average = sum/n;
printf("Average = %d", average);

return 0;
}

Output

Enter n: 5
Enter number1: 45
Enter number2: 35
Enter number3: 38
Enter number4: 31
Enter number5: 49
Average = 39

Exercise Questions
Arrays
1. Write a program in C to find the sum of all elements of the array.
2. Write a program in C to copy the elements of one array into another array.
3. Write a program in C to count a total number of duplicate elements in an array.
4. Write a program in C to count the frequency of each element of an array.
5. Write a program in C to separate odd and even integers in separate arrays.
6. Write a program in C to delete an element at desired position from an array.
7. Write a program in C to find the second smallest element in an array.
8. Write a program in C for addition of two Matrices of same size.
9. Write a program in C to find transpose of a 2 x 2 matrix.
10. Write a program in C to accept two matrices and check whether they are equal.

Strings
1. Write a program in C to find the length of a string without using library function.
2. Write a program in C to print individual characters of string in reverse order.
3. Write a program in C to count the total number of words in a string.
4. Write a program in C to compare two string without using string library functions.
53
5. Write a program in C to count total number of vowel or consonant in a string.
6. Write a program in C to find maximum occurring character in a string.
7. Write a program in C to read a string and sort it using bubble sort.
8. Write a program in C to extract a substring from a given string.
9. Write a program in C to read a sentence and replace lowercase characters by uppercase and vice-
versa.
10. Write a program in C to replace the spaces of a string with a specific character.

54
Module IV
Modular Programming
Modular programming is a software design technique that emphasizes separating the
functionality of a program into independent, interchangeable modules, such that each contains
everything necessary to execute only one aspect of the desired functionality.
There are many advantages to using Modular Software and Programming compared to other
methods.

• Development can be divided: Allows development to be divided by splitting down a program


into smaller programs in order to execute a variety of tasks.
• Readable programs: Helps develop programs that are much easier to read since they can be
enabled as user-defined functions.

• Programming errors are easy to detect: Minimizes the risks of ending up with programming
errors and also makes it easier to spot errors, if any.
• Allows re-use of codes: A program module is capable of being re-used in a program which
minimizes the development of redundant codes
• Improves manageability: Having a program broken into smaller sub-programs allows for
easier management.
• Collaboration: With Modular Programming, programmers can collaborate and work on the
same application.

Function
A function is a group of statements that together perform a task. Every C program has at least one
function, which is main().

Types of Functions

There are two types of function in C programming:

• Standard library functions


• User-defined functions
Standard Library Functions
The standard library functions are built-in functions in C programming. These functions are
defined in header files. For example,

55
• The printf() is a standard library function to send formatted output to the screen (display
output on the screen). This function is defined in the stdio.h header file.
• The sqrt() function calculates the square root of a number. The function is defined in the
math.h header file.
• The strlen() function calculates the length of a given string. The function is defined in the
string.h header file.

User-defined function

User can also create functions as per their own needs. Such functions created by users are
known as user-defined functions.
Advantages of user-defined function

• The program will be easier to understand, maintain and debug.


• Reusable codes that can be used in other programs

• A large program can be divided into smaller modules. Hence, a large project can be divided
among many programmers.

Three parts of a user defined functions are:

1) Function Declaration or Prototype

2) Function Definition

3) Function Call

Function Declaration

A function prototype is simply the declaration of a function that specifies function's name, parameters
and return type. It doesn't contain function body. A function prototype gives information to the
compiler that the function may later be used in the program.

Syntax

return_type function_name( parameter list );

Function Definition

56
A function definition in C programming consists of a function header and a function body. Here are
all the parts of a function:
• Return Type: A function may return a value. The return_type is the data type of the value
the function returns. Some functions perform the desired operations without returning a value.
In this case, the return_type is the keyword void.
• Function Name: The actual name of the function.
• Arguments: When a function is invoked, you pass a value to the parameter. This value is
referred to as actual parameter or argument.
• Function Body: The function body contains a collection of statements that define what the
function does.
Syntax:
return_type function_name( argument list ) {
body of the function
}

Function Call

Control of the program is transferred to the user-defined function by calling it. When a program calls
a function, the program control is transferred to the called function. A called function performs a
defined task and when its return statement is executed or when its function-ending closing brace is
reached, it returns the program control back to the main program.
Syntax:
functionName(parameter list);
Example:
int add(int,int,int); // function declaration
…..
……
int add(int a, int b, int c) // function definition
{
int sum = a+ b + c;
return sum;
}

void main()
{
int x=10,y=20,z=30;
int res = add(x,y,z); // function call
print(“Result=%d”,res);
}

57
#include <stdio.h>
int add(int,int);
int main()
{
int num1,num2;
printf("Enter two numbers : ");
scanf("%d%d",&num1,&num2);
int sum= add(num1,num2);
printf("Sum = %d",sum);
}
int add(int a, int b)
{
int temp=a+b;
return temp;
}

Return Statement

The return statement terminates the execution of a function and returns a value to the calling
function. The program control is transferred to the calling function after the return statement.
In the above example, the value of the sum variable is returned to the main function. The res
variable in the main() function is assigned this value.

Formal and Actual Parameters


There are different ways in which parameter data can be passed into and out of methods and functions.
Let us assume that a function B() is called from another function A(). In this case A is called the “caller
function” and B is called the “called function or callee function”. Also, the arguments which A sends
to B are called actual arguments and the parameters of B are called formal arguments.
• Formal Parameter: A variable and its type as they appear in the prototype of the function or
method.
• Actual Parameter: The variable or expression corresponding to a formal parameter that
appears in the function or method call in the calling environment.
In the above example, x,y and z in the main function are the actual parameter of add function. Formal
parameter of add function are a, b and c.
Pass by Value
In this parameter passing technique, a copy of actual parameter is passed to formal parameter. As a
result, any changes or modification happened to formal parameter won’t reflect back to actual
parameter. This can be explained with an example of swapping program.

58
#include<stdio.h>
int swap(int a,int b)
{
int temp=a;
a= b;
b=temp;
}

void main()
{
int x,y;
printf("Enter the numbers:");
scanf("%d%d",&x,&y);
printf("Before swapping : x=%d\ty=%d\n",x,y);
swap(x,y);
printf("After swapping : x=%d\ty=%d",x,y);
}

Output
Enter the numbers:10 20
Before swapping: x=10 y=20
After swapping : x=10 y=20

In above program we expect the program to swap the value of x and y after calling the function swap
with x and y as actual parameter. But swapping does not place as this uses call by value as parameter
passing technique.

During Swap call, a copy of actual parameters are created and changes are made on that copy. So the
value of x and y does not changes.

After reading the value of x and y

x: 10 y: 20

During swap call a copy is created and passed to formal parameter


x: a:
10 10

y: 20 b: 20

After the swap call, formal parameters get swapped but actual parameter remains the same.

59
x: a:
10 20

y: 20 b: 10

Types of user defined functions


1) No arguments passed and no return value

// function to read two number and print its sum


void add()
{
int a,b,sum;
printf("Enter the values of a & b");
scanf("%d%d",&a,&b);
sum = a+b;
printf("Sum=%d",sum);
}

2) No arguments passed but return value

// function to read two number and return its sum


int add()
{
int a,b,sum;
printf("Enter the values of a & b");
scanf("%d%d",&a,&b);
sum = a+b;
return sum;
}

3) Arguments passed but no return value

// function that takes two arguments and print their sum.


void add(int a,int b)
{
int sum= a + b;
printf("Sum=%d",sum);
}
4) Arguments passed with return value

// function that takes two arguments and print their sum.


int add(int a,int b)
{
return a + b;
}
60
• Write a program to perform arithmetic operations using function

#include<stdio.h>
int add(int a,int b)
{
return a+b;
}
int diff(int a,int b)
{
return a-b;
}
int mul(int a,int b)
{
return a*b;
}
float div(int a,int b)
{
return (float)a/b;
}
int mod(int a,int b)
{
return a%b;
}

void main()
{
int x,y;
printf("Enter the values:");
scanf("%d%d",&x,&y);
printf("Sum=%d\n",add(x,y));
printf("Difference=%d\n",diff(x,y));
printf("Multiply=%d\n",mul(x,y));
printf("Division=%f\n",div(x,y));
printf("Modulo=%d\n",mod(x,y));
}

Output
Enter the values:21 8
Sum=29
Difference=13
Multiply=168
Division=2.625000
Modulo=5

• Write a program to display prime numbers upto a range using function.

61
// function takes an argument n, if n is prime it will return 1 otherwise 0

#include<stdio.h>
int checkPrime(int n)
{
int flag=0,i;
for(i=2;i<=n/2;i++)
{
if(n%i == 0)
{
flag =1;
break;
}
}
if(flag == 0)
return 1;
else
return 0;
}

void main()
{
int n,i;
printf("Enter the range:");
scanf("%d",&n);
for(i=2;i<=n;i++)
{
if(checkPrime(i) == 1)
printf("%d\t",i);
}
}

Output
Enter the range: 25
2 3 5 7 11 13 17 19 23

Recursive Function

A function that calls itself is known as a recursive function. And, this technique is known as recursion.
While using recursion, programmers need to be careful to define an exit condition from the function,
otherwise it will go into an infinite loop. Recursion makes program elegant. However, if performance
is vital, use loops instead as recursion is usually much slower.

62
• Write a program to find factorial of number using recursive function

#include<stdio.h>
int fact(int n)
{
if( n == 0)
return 1;
return n*fact(n-1);
}

void main()
{
int n;
printf("Enter the number:");
scanf("%d",&n);
printf("Factorial=%d",fact(n));
}

Output
Enter the number:5
Factorial=120

• Write a program to find nCr and nPr.

#include<stdio.h>
int fact(int n)
{
if( n == 0)
return 1;
return n*fact(n-1);
}

void main()
{
int n,r;
float C,P;
printf("Enter the numbers:");
scanf("%d%d",&n,&r);
P = (float) fact(n) / fact(n-r);
C = (float)fact(n) / (fact(r) * fact(n-r));
printf("nCr=%f\n",C);
printf("nPr=%f",P);
}

Output

63
Enter the numbers:5 3
nCr=10.000000
nPr=60.000000
• Write a program to find of series 1 + 1/2! + 1/ 3! ..

#include<stdio.h>
int fact(int n)
{
if( n == 0)
return 1;
return n*fact(n-1);
}

void main()
{
int n,i;
float sum;
printf("Enter the limit:");
scanf("%d",&n);
for(i=1;i<=n;i++)
sum = sum + 1.0 / fact(i);
printf("Sum=%f",sum);
}

Output
Enter the limit:5
Sum=1.716667

• Write a recursive function to print Fibonacci series

#include<stdio.h>
int fib(int n)
{
if(n == 1)
return 0;
else if(n == 2)
return 1;
return fib(n-2)+fib(n-1);
}

void main()
{
int n,i;
printf("Enter the limit:");
scanf("%d",&n);
64
for(i=1;i<=n;i++)
printf("%d\t",fib(i));
}

Output
Enter the limit:7
0 1 1 2 3 5 8

• Write a recursive program to print sum of digit of a number

#include<stdio.h>
int sod(int n)
{
if(n<=0)
return 0;
return n%10 + sod(n/10);
}

void main()
{
int n;
printf("Enter the number:");
scanf("%d",&n);
printf("Sum=%d",sod(n));
}
Output
Enter the number:124
Sum=7

• Write a recursive function to find sum of first n natural numbers

#include<stdio.h>
int sum(int n)
{
if(n<=0)
return 0;
return n + sum(n-1);
}
void main()
{
int n;
printf("Enter the number:");
scanf("%d",&n);
printf("Sum=%d",sum(n));
}
Output
Enter the number:5
65
Sum=15

Passing an array as Parameter


Like the value of simple variables, it is also possible to pass the values of an array to a function. To
pass a single dimensional array to a function, it is sufficient to list the name of the array without any
subscripts and the size of the array as arguments
Rules to pass an Array to Function

• The function must be called by passing only the name of the array.
• In function definition, formal parameter must be an array type; the size of the array does not need
to be specified.
• The function prototype must show that the argument is an array.

• Write a function to sort an array.

#include<stdio.h>
int sort(int A[],int n)
{
int i,j,temp;
for(i=0;i<n-1;i++)
{
for(j=0;j<n-i-1;j++)
{
if(A[j]>A[j+1])
{
temp = A[j];
A[j] = A[j+1];
A[j+1]= temp;
}
}
}
}

void main()
{
int A[30];
int i,n;
printf("Enter the limit:");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("Enter the element:");
66
scanf("%d",&A[i]);
}
sort(A,n);
printf("Sorted Array\n");
for(i=0;i<n;i++)
printf("%d\t",A[i]);
}

Output
Enter the limit:5
Enter the element:17
Enter the element:23
Enter the element:5
Enter the element:2
Enter the element:9
Sorted Array
2 5 9 17 23

• Write a program to sort the matrix rowwise.

#include<stdio.h>
int sort(int A[],int n)
{
int i,j,temp;
for(i=0;i<n-1;i++)
{
for(j=0;j<n-i-1;j++)
{
if(A[j]>A[j+1])
{
temp = A[j];
A[j] = A[j+1];
A[j+1]= temp;
}
}
}
}

void main()
{
int A[30][30];
int i,n,m,j;
printf("Enter the order of matrix:");
scanf("%d%d",&m,&n);
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
67
{
printf("Enter the element:");
scanf("%d",&A[i][j]);
}
}
for(i=0;i<m;i++)
{
sort(A[i],n);
for(j=0;j<n;j++)
{
printf("%d\t",A[i][j]);
}
printf("\n");
}
}

Output
Enter the order of matrix:2 4
Enter the element:12
Enter the element:4
Enter the element:25
Enter the element:7
Enter the element:8
Enter the element:5
Enter the element:16
Enter the element:2
4 7 12 25
2 5 8 16

Passing 2 D array as parameter

Note: While passing 2D as parameter we need to mention the max size of element of each row
that is column.

• Write a program to pass a 2 D matrix as parameter and find its sum of all the elements.

#include<stdio.h>
// function that takes a 2 D and its order
int sum(int A[][30],int m,int n)
{
int i,j,sum =0;
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
sum = sum + A[i][j];
}
68
}
printf("Sum=%d",sum);
}

void main()
{
int A[30][30];
int i,n,m,j;
printf("Enter the order of matrix:");
scanf("%d%d",&m,&n);
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
printf("Enter the element:");
scanf("%d",&A[i][j]);
}
}
sum(A,m,n);
}

Output
Enter the order of matrix:2 2
Enter the element:1
Enter the element:2
Enter the element:3
Enter the element:4
Sum=10

SCOPE, VISIBILITY AND LIFETIME OF VARIABLE


In C, not only do all the variables have a data type, they also have a storage class. The following
variable storage classes are most relevant to functions
• Automatic Variables
• External or Global Variables
• Static Variables
• Register Variables

Automatic Variables
Automatic variables are declared inside a function in which they are to be utilized. They are
created when the function is called and destroyed automatically when the function is exited, hence the
name automatic. Automatic variables are therefore private or local to the function in which they are
69
declared. Because of this property, automatic variables are also referred to as local or internal
variables.
A variable declared inside a function without storage class specification is by default an automatic
variable.

void main(){
int num;
----------
----------
}

is same as

void main(){
auto int num;
----------
----------
}
Example
#include<stdio.h>

void func1()
{
int max=10;
printf("Max in func1()=%d\n",max);
}
void func2(){
int max=20;
printf("Max in func2()=%d\n",max);
}
void main(){
int max=30;
func1();
func2();
printf("Max in main()=%d\n",max);
}
Output
Max in func1()=10
Max in func2()=20
Max in main()=30

External Variables

Variables that are both alive and active throughout the entire program are known as external variables.
They are called global variables. Unlike local variables, global variables can be accessed by any
70
function in the program. External variables are declared outside a function

#include<stdio.h>

float pi=3.14; // One way of declaring external variable

float area(int r){


return pi*r*r;
}
float perimeter(int r){
return 2 * pi * r;
}
void main(){
// extern float pi=3.14; Another way of declaring external variable
int r;
float a,p;
printf("Enter the radius:");
scanf("%d",&r);
a=area(r);
p=perimeter(r);
printf("Area=%f\n",a);
printf("Perimeter=%f\n",p);
}

Output
Enter the radius:5
Area=78.500000
Perimeter=31.400002

More example to show the property of global variable.

#include<stdio.h>
int max; // global variable
void func1(){
int max=10; // local variable
printf("Max in func1()=%d\n",max);
}
void func2(){
max=20; // resets max value to 20
printf("Max in func1()=%d\n",max);
}
void main(){
max=40; //set max value to 40
func1();
func2();
printf("Max in main()=%d\n",max);
71
}

Max in func1()=10
Max in func1()=20
Max in main()=20

Why the value of max in main() print as 20? [Hint: main uses global scope of max.]

Static Variables

As the name suggests, the value of static variables persists until the end of the program. A variable
can be declared static using the keyword static like
static int x;
A static variable may be either an internal type or an external type depending on the place of
declaration. Internal static variable are those which are declared inside the function. The score of
internal static variable are similar to auto variables, except that they remain in existence throughout
the remainder of the program. Therefore the internal static variables can be used to retain values
between the function calls.

#include<stdio.h>

void func1(){
static int x=10; //static variable
x++;
printf("x in func1()=%d\n",x);
}
void func2(){
int x=10; // local variable
x++;
printf("x in func2()=%d\n",x);
}
void main(){
func1();
func1();
func2();
func2();
}
Output
x in func1()=11
x in func1()=12
x in func2()=11
72
x in func2()=11

Register Variables

We can tell the compiler that a variable should be kept in one of the machine’s registers instead of
keeping in the memory. Since a register access is fast than a memory access, keep in the frequently
accessed variables in the register will lead to faster execution of programs. This is done as follows

register int count;

Since only a few variables can be places in the register, it is important to carefully select the variables
for these purposes. However C will automatically convert register variables into non register variable
once limit is reached.

Storage Class Where declared Visibility Lifetime


Before all functions in a file
Entire file plus other
(cannot be initialized) extern and
extern files where variable is Global
the file where originally
declared.
declared as global.
Before all the function in a file Only in that file
Static Or OR Global
Inside a function Only in that function
None or auto Until end of
Only in that function
Inside a function function
or block
Register Only in that function Until end of
Inside a function or block
or block function

Structure

A structure is a user defined data type in C/C++. A structure creates a data type that can be used to
group items of possibly different types into a single type. ‘struct’ keyword is used to create a structure.
A structure variable can either be declared with structure declaration or as a separate declaration like
basic types. Consider we want to create the structure of a person with following variable name, age
and address. Then such a structure can be created as
struct Person
{
char name[30];
int age;
char addr[50];
73
}

The general format of a structure definition is as follows


struct structure_name{
data_type member1;
data_type member2;
---------------------
---------------------
};

In defining a structure you may note the following syntax:

• The template is terminated with a semicolon.


• While the entire definition is considered as a statement, each member is declared
independently for its name and type in a separate statement inside the template.

Difference between structure and Array


Array Structure
An array is a collection of related data Structure can have elements of different
elements of same type. types.
An array is derived data type Structure is a programmer defined one
Any array behaves like built in data type. All Structure we have to design and declare a
we have to do is to declare an array variable data structure before the variable of that type
and use it are declared and used.

Declaring structure variable


After defining a structure format we can declare variables of that type. A structure variable
declaration is similar to the declaration of variables of any other data type. It includes the following
elements.
1. The keyword struct
2. The structure tag name (structure name)
3. List of variable names separated by commas.
4. A terminating semicolon.

Example: struct Person p1,p2,p3; // created structure variable for person Structure.

• Write a program to create a structure employee with member variables name, age, bs, da,
hra and tsalary. Total Salary is calculate by the equation tsalary= (1+da+hra)* bs. Read the
values of an employee and display it.

74
#include<stdio.h>
struct Employee{
char name[30];
int age;
float bs;
float da;
float hra;
float tsalary;
};
void main(){
struct Employee e;

printf("Enter the name:");


scanf("%s",e.name);
printf("Enter the age:");
scanf("%d",&e.age);
printf("Enter the basic salary:");
scanf("%f",&e.bs);
printf("Enter the da:");
scanf("%f",&e.da);
printf("Enter the hra:");
scanf("%f",&e.hra);
e.tsalary=(1+e.da+e.hra)*e.bs;

printf("Name=%s\n",e.name);
printf("Age=%d\n",e.age);
printf("Basic Salary=%.2f\n",e.bs);
printf("DA=%.2f\n",e.da);
printf("HRA=%.2f\n",e.hra);
printf("Total Salary=%.2f\n",e.tsalary);
}

Output

Enter the name:Sangeeth


Enter the age:31
Enter the basic salary:10000
Enter the da:12
Enter the hra:7.5
Name=Sangeeth
Age=31
Basic Salary=10000.00
DA=12.00
HRA=7.50
Total Salary=205000.00

75
• Write a program to create a structure Complex with member variable real and img. Perform
addition of two complex numbers using structure variables.

#include<stdio.h>
struct Complex{
int real;
int img;
};

void main(){

struct Complex a,b,c;


printf("Enter the real and img part of a:");
scanf("%d%d",&a.real,&a.img);
printf("Enter the real and img part of b:");
scanf("%d%d",&b.real,&b.img);
c.real = a.real + b.real;
c.img = a.img + b.img;
printf("c = %d + %di\n",c.real,c.img);
}

Output
Enter the real and img part of a:10 20
Enter the real and img part of b:30 40
c = 40 + 60i

Array of Structures

• Declare a structure namely Student to store the details (roll number, name, mark_for_C) of
a student. Then, write a program in C to find the average mark obtained by the students in
a class for the subject Programming in C (using the field mark_for_C). Use array of
structures to store the required data.

#include<stdio.h>
struct Student{
char name[30];
int rollnum;
int mark_for_C;
};

void main(){

struct Student s[30];

76
int i,n,sum=0;
float avg;
printf("Enter the no of Student:");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("Enter the Student name:");
scanf("%s",s[i].name);
printf("Enter the Student rollnum:");
scanf("%d",&s[i].rollnum);
printf("Enter the Student Mark for C:");
scanf("%d",&s[i].mark_for_C);
}
printf("Name\tRoll Number\tMark for C\n");
for(i=0;i<n;i++)
{
printf("%s\t%d\t%d\n",s[i].name,s[i].rollnum,s[i].mark_for_C);
sum = sum + s[i].mark_for_C;
}
avg = sum / (float)n;
printf("Average Mark=%.2f\n",avg);
}

Output
Enter the no of Student:3
Enter the Student name:Sangeeth
Enter the Student rollnum:27
Enter the Student Mark for C:35
Enter the Student name:Pratheesh
Enter the Student rollnum:24
Enter the Student Mark for C:40
Enter the Student name:Poornima
Enter the Student rollnum:26
Enter the Student Mark for C:45
Name Roll Number Mark for C
Sangeeth 27 35
Pratheesh 24 40
Poornima 26 45
Average Mark=40.00

• Write a program to create a structure employee with member variables name, age, bs, da,
hra and tsalary. Total Salary is calculate by the equation tsalary= (1+da+hra)* bs. Read the
values of 3 employees and display details based descending order of tsalary.

#include<stdio.h>
struct Employee{
char name[30];
77
int age;
float bs;
float da;
float hra;
float tsalary;
};
void sort(struct Employee e[],int n)
{
int i,j;
struct Employee t;
for(i=0;i<n-1;i++)
{
for(j=0;j<n-i-1;j++)
{
if(e[j].tsalary < e[j+1].tsalary)
{
t = e[j];
e[j]=e[j+1];
e[j+1]=t;
}
}
}
}
void main(){
struct Employee e[5];
int i;
for(i=0;i<3;i++)
{
printf("Enter the name:");
scanf("%s",e[i].name);
printf("Enter the age:");
scanf("%d",&e[i].age);
printf("Enter the basic salary:");
scanf("%f",&e[i].bs);
printf("Enter the da:");
scanf("%f",&e[i].da);
printf("Enter the hra:");
scanf("%f",&e[i].hra);
e[i].tsalary=(1+e[i].da+e[i].hra)*e[i].bs;
}
sort(e,3);
printf("Name\t Age\tBasic Salary\tDA \t HRA \t Total Salary\n");
for(i=0;i<3;i++)
{
printf("%s\t%d\t%.2f\t",e[i].name,e[i].age,e[i].bs);
printf("%.2f\t%.2f\t%.2f\n",e[i].da,e[i].hra,e[i].tsalary);
}
78
}

Output
Enter the name:Sangeeth
Enter the age:31
Enter the basic salary:14000
Enter the da:6
Enter the hra:7.5
Enter the name:Poornima
Enter the age:28
Enter the basic salary:15000
Enter the da:7.6
Enter the hra:8
Enter the name:Pratheesh
Enter the age:29
Enter the basic salary:15000
Enter the da:8
Enter the hra:9

Name Age Basic Salary DA HRA Total Salary


Pratheesh 29 15000.00 8.00 9.00 270000.00
Poornima 28 15000.00 7.60 8.00 249000.00
Sangeeth 31 14000.00 6.00 7.50 203000.00

Union

A union is a user-defined type similar to struct in C programming. We use the union keyword to
define unions. When a union is defined, it creates a user-defined type. However, no memory is
allocated. To allocate memory for a given union type and work with it, we need to create variables.

Example of Employee Union creation and declartion


union Employee
{
char name[30];
int age;
double salary;
}

union Employee e;

Difference between structure and union

79
Structure Union
struct keyword is used to define a structure union keyword is used to define a union
Members do not share memory in a structure. Members share the memory space in a union
Any member can be retrieved at any time in a Only one member can be accessed at a time
structure in a union.
Several members of a structure can be Only the first member can be initialized.
initialized at once.
Size of the structure is equal to the sum of size Size of the union is equal to the size of the
of the each member. largest member.

Predict the output

#include<stdio.h>
struct Person
{
char pincode[6]; // Size = 6 bytes
int age; // Size = 4 bytes
double salary;// Size = 8 bytes
};
union Employee
{
char pincode[6];
int age;
double salary;
};
void main()
{
struct Person p;
union Employee e;
printf("Size of Structure Person=%d\n",sizeof(p));
printf("Size of Union Employee=%d",sizeof(e));
}

Output
Size of Structure Person=18
Size of Union Employee=8

80
Module V
Pointers
The pointer in C language is a variable which stores the address of another variable. This
variable can be of type int, char, array, function, or any other pointer. The size of the pointer depends
on the architecture. However, in 32-bit architecture the size of a pointer is 2 byte.
Consider the following example to define a pointer which stores the address of an integer.
int n = 10;
int* p = &n; // Variable p of type pointer is pointing to the address of the variable n of type integer.
Declaring a pointer
The pointer in c language can be declared using * (asterisk symbol). It is also known as indirection
pointer used to dereference a pointer.
int *a;//pointer to int
char *c;//pointer to char

Accessing Data through Pointers


Consider the following example:
#include<stdio.h>

void main()
{
int n = 10;
int *p;

p = &n;

printf("Address of n=%u\n",&n);
printf("Value of n=%d\n",n);

printf("Address of p=%u\n",&p);
printf("Value of p=%u\n",p);
printf("Value of *p=%d\n",*p); // *p = value of n;

}
Output
Address of n=6487628
Value of n=10
Address of p=6487616

81
Value of p=6487628
Value of *p=10

Each variables has two properties: address and value. Address of a variable is the memory location
allocated for that variable. Value of a variable is the value stored in the memory location allocated to
them. The address of a variable can be derived using address of (&) operator. In the example above,
the address of n is 6487628 and value is 10.

Variable Name Address Value


n 6487628 10

When p is assigned with &n. p stores the address of n. Thus p points to n. In order to retrieve the value
of n, we can make use of *p.

Pointer Name Address Value Asterisk Value *


p 6487616 6487628 10
Address of variable n Value of n

NULL Pointer
A pointer that is not assigned any value but NULL is known as the NULL pointer. If you don't have
any address to be specified in the pointer at the time of declaration, you can assign NULL value. It
will provide a better approach.

int *p=NULL;

Array Access using Pointers

Write a program to display the content of an array using pointer.


#include<stdio.h>

void main()
{
int A[]={10,20,30,40,50};

82
int i;

int *p = A; //Variable p of type pointer is pointing to the address of an integer array A.

printf("Array Content\n");
for(i=0;i<5;i++)
{
printf("%d\t",*(p+i));
}
}

Output

Array Content
10 20 30 40 50

2) Write a program to read and display an array using pointer.


#include<stdio.h>
#include<malloc.h>
void main()
{
int i,n;
int *p = malloc(30 * sizeof(int)); // equivalent to int p[30];
printf("Enter the size of array:");
scanf("%d",&n);
for(i=0;i<n;i++)
{
scanf("%d",p+i);
}
printf("Array Content\n");
for(i=0;i<n;i++)
{
printf("%d\t",*(p+i));
}
}

Enter the size of array:5


10 15 20 25 30
Array Content
10 15 20 25 30

3) Write a program to sort the content of an array using pointers


#include<stdio.h>
#include<malloc.h>
83
void main()
{
int i,n,temp,j;
int *p = malloc(30 * sizeof(int)); // equivalent to int p[30];
printf("Enter the size of array:");
scanf("%d",&n);
for(i=0;i<n;i++)
{
scanf("%d",p+i);
}
for(i=0;i<n-1;i++)
{
for(j=0;j<n-i-1;j++)
{
if(*(p+j) > *(p+j+1))
{
temp = *(p+j);
*(p+j) = *(p+j+1);
*(p+j+1) = temp;
}
}
}
printf("Array Content\n");
for(i=0;i<n;i++)
{
printf("%d\t",*(p+i));
}
}

Output
Enter the size of array:5
16 7 14 2 5
Array Content
2 5 7 14 16
Pass By Reference
In C programming, it is also possible to pass addresses as arguments to functions. To accept these
addresses in the function definition, we can use pointers. In this method, the address of the actual
parameters is passed to formal parameters. So any change in formal parameters will be reflected in
the actual parameters. Consider the program to swap to two numbers using pass by reference method,
#include<stdio.h>
int swap(int *a,int *b)
{
int temp=*a;
*a= *b;
*b=temp;
84
}

void main()
{
int x,y;
printf("Enter the numbers:");
scanf("%d%d",&x,&y);
printf("Before swapping : x=%d\ty=%d\n",x,y);
swap(&x,&y);
printf("After swapping : x=%d\ty=%d",x,y);
}

Output
Enter the numbers:10 20
Before swapping : x=10 y=20
After swapping : x=20 y=10

Difference between pass by value and pass by reference.

pass by value Pass by reference


In call by value, a copy of actual arguments is In call by reference, the location (address) of
passed to formal arguments of the called function actual arguments is passed to formal arguments of
and any change made to the formal arguments in the called function. This means by accessing the
the called function have no effect on the values of addresses of actual arguments we can alter them
actual arguments in the calling function. within from the called function.
In call by reference, alteration to actual arguments
In call by value, actual arguments will remain is possible within from called function; therefore
safe, they cannot be modified accidentally. the code must handle arguments carefully else
you get unexpected results.

File
A file represents a sequence of bytes, regardless of it being a text file or a binary file. When a program
is terminated, the entire data is lost. Storing in a file will preserve your data even if the program
terminates. It is easy to move the data from one computer to another without any changes. 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 *fp; // *fp – file pointer variable
Types of Files
There are two types of files
85
• Text files
• 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. When you open those files, you'll see all the contents within the file as plain text. It is
easy to edit or delete the contents. They take minimum effort to maintain, are easily readable, and
provide the least security and takes bigger storage space.
2. Binary files
Binary files are mostly the .bin files in the computer. Instead of storing data in plain text, they store it
in the binary form (0's and 1's). They can hold a higher amount of data, are not readable easily, and
provides better security than text files.
File Operations
1) Opening a file:

Opening a file is performed using the fopen() function defined in the stdio.h header file.
The syntax for opening a file in standard I/O is:
FILE *fp
fp = fopen("filename","mode");
File Opening Mode

Sl. No Mode Description

1 r Opens an existing text file for reading purpose.

Opens a text file for writing. If it does not exist, then a new file is
2 w created. Here your program will start writing content from the beginning
of the file.

Opens a text file for writing in appending mode. If it does not exist, then
3 a a new file is created. Here your program will start appending content in
the existing file content.

4 r+ Opens a text file for both reading and writing.

5 Opens a text file for both reading and writing. It first truncates the file
w+
to zero length if it exists, otherwise creates a file if it does not exist.
86
Opens a text file for both reading and writing. It creates the file if it does
6 a+ not exist. The reading will start from the beginning but writing can only
be appended.

File Location
We can provide the relative address of the file location or absolute address of the file. Consider your
working directory is C:\CP\Test\ . Now you want to open a file hello.c in read mode. Two ways to
provide the file location are as given below:
fp = fopen("hello.c","r");
OR
fp = fopen("C:\\CP\\Test\\hello.c","r")
2. Closing a file
The file (both text and binary) should be closed after reading/writing. Closing a file is performed using
the fclose() function.

fclose(fp);
Here, fp is a file pointer associated with the file to be closed.
3. Reading and writing to a file
Sl. No Function Name Description Syntax
1 fgetc To read a character from a file ch = fgetc(fp)
2 fputc To write a character to a file fputc(ch,fp)
3 fscanf To read numbers, string from a file fscanf(fp,"%d",&n)
4 fprintf To write numbers, strings to a file fprintf(fp,"%d",n)
5 fread To read binary content from a file. It Refer Note
is used to read structure content.
6 fwrite To write as binary content to a file. Refer Note
Note:
1) The only difference is that fprint() and fscanf() expects a pointer to the structure FILE.
2) To write into a binary file, you need to use the fwrite() function. The functions take four
arguments:
• Address of data to be written in the disk

87
• Size of data to be written in the disk
• Number of such type of data
• Pointer to the file where you want to write.

fwrite(addressData, sizeData, numbersData, pointerToFile);


3) Function fread() also take 4 arguments similar to the fwrite() function as above.
fread(addressData, sizeData, numbersData, pointerToFile);
feof()
The C library function int feof(FILE *stream) tests the end-of-file indicator for the given stream.
This function returns a non-zero value when End-of-File indicator associated with the stream is set,
else zero is returned.
Random Access to a file
1) rewind()

The rewind() function sets the file pointer at the beginning of the stream. It is useful if you have to
use stream many times.
Syntax: rewind(file pointer)
2) fseek()

If you have many records inside a file and need to access a record at a specific position, you need to
loop through all the records before it to get the record. This will waste a lot of memory and operation
time. An easier way to get to the required data can be achieved using fseek().
fseek(FILE * stream, long int offset, int pos);
The first parameter stream is the pointer to the file. The second parameter is the position of the record
to be found, and the third parameter specifies the location where the offset starts.
Different positions in fseek()
Position Meaning
SEEK_SET Starts the offset from the beginning of the file.
SEEK_END Starts the offset from the end of the file.
SEEK_CUR Starts the offset from the current location of the cursor in the file.
3) ftell()

ftell() in C is used to find out the position of file pointer in the file with respect to starting of the file.
Syntax of ftell() is:

88
ftell(FILE *pointer)

Difference between sequential and random access.


Sequential file access is the method employed in tape drives where the files are access in
a sequential manner. So if you have to get a file in the end of the tape you have to start from the
beginning till it reaches the beginning of the file.
Random access files are similar to the one in Hard Disks and Optical drives, wherever the files
is placed it will go to that particular place and retrieve it.
Accessing data sequentially is much faster than accessing it randomly because of the way in
which the disk hardware works.

Examples Programs
1) Write a program to display the content of a file.

#include<stdio.h>
void main()
{
FILE *fp;
char ch;
fp = fopen("test.txt","r");
while(feof(fp) == 0)
{
ch=fgetc(fp);
printf("%c",ch);
}
fclose(fp);
89
}

Content of test.txt
Hello, Welcome to C Programming Lectures.

Output
Hello, Welcome to C Programming Lectures.

2) Write a program to count numbers of vowels in a given file.

#include<stdio.h>
void main()
{
FILE *fp;
char ch;
int countV=0;
fp = fopen("test.txt","r");
while(feof(fp) == 0)
{
ch=fgetc(fp);
if(ch == 'a' || ch == 'A' || ch=='e'
ch=='E' || ch == 'I' || ch == 'i' ||
ch == 'O' || ch=='o' || ch == 'U' ||
ch == 'u')
{
countV++;
}
}
printf("Count of Vowels=%d",countV);
fclose(fp);
}

Content of test.txt
Hello, Welcome to C Programming Lectures.

Output

Count of Vowels=12

3) Write a program to copy the content of file to another.

#include<stdio.h>
void main()
{
FILE *f1,*f2;
char ch;
f1 = fopen("test.txt","r");
90
f2 = fopen("copy.txt","w");
while(feof(f1) == 0)
{
ch=fgetc(f1);
fputc(ch,f2);
}
printf("Successfully Copied");
fclose(f1);
fclose(f2);
}

Content of test.txt
Hello, Welcome to C Programming Lectures.

Output
Successfully Copied

Content of copy.txt
Hello, Welcome to C Programming Lectures.

4) Write a program to merge the content of two files.

#include<stdio.h>
void main()
{
FILE *f1,*f2,*f3;
char ch;
f1 = fopen("file1.txt","r");
f2 = fopen("file2.txt","r");
f3 = fopen("merge.txt","w");
while(feof(f1) == 0)
{
ch=fgetc(f1);
fputc(ch,f3);
}
while(feof(f2) == 0)
{
ch=fgetc(f2);
fputc(ch,f3);
}
printf("Successfully Merged");
}

Content of file1.txt
Hello, Welcome to C Programming Lectures.

Content of file2.txt
91
C is very easy to learn.

Output
Successfully Merged

Content of merge.txt
Hello, Welcome to C Programming Lectures. C is very easy to learn.

5) Write a program to read numbers from a file and display the largest number.

#include<stdio.h>
void main()
{
FILE *f1;
int large,num;
f1 = fopen("number.txt","r");
fscanf(f1,"%d",&large); // setting first element as largest element
while(feof(f1) == 0)
{
fscanf(f1,"%d",&num);
if(large<num)
{
large= num;
}
}
fclose(f1);
printf("Largest element = %d",large);
}

Content of number.txt
15 21 7 29 36 78 67 56 10

Output

Largest element = 78

6) Consider you are a content writer in Wikipedia. You are the person who write the known
facts about APJ Abdul Kalam. After his death, you need to change all is to was. Write a program
to replace all is’ to was’ to a new file.

#include<stdio.h>
#include<string.h>

void main()
{
92
FILE *f1,*f2;
char str[30];
f1 = fopen("apj.txt","r");
f2 = fopen("new.txt","w");
fscanf(f1,"%s",str);
while(feof(f1) == 0)
{
if(strcmp(str,"is")==0)
fprintf(f2,"was A");
else
fprintf(f2,"%s ",str);
fscanf(f1,"%s",str);
}
fclose(f1);
fclose(f2);
printf("Replaced String Successfully\n");
}

7) Write a program to reverse each content of file to another.

#include<stdio.h>
#include<string.h>

void main()
{
FILE *f1,*f2;
char str[30],rev[30];
int i,j;
f1 = fopen("test.txt","r");
f2 = fopen("new.txt","w");

while(feof(f1) == 0)
{
fscanf(f1,"%s",str);
j=0;
for(i=strlen(str)-1;i>=0;i--)
{
rev[j]=str[i];
j++;
}
rev[j]='\0';
fprintf(f2,"%s ",rev);
}
fclose(f1);
fclose(f2);
}
Content of test.txt
93
Welcome to C programming

Content of new.txt after execution


emocleW ot C gnimmargorp

8) Write a program to copy the content of a file to another in reverse order.

#include<stdio.h>
void main()
{
FILE *f1,*f2;
int count,begin,end;
char ch,i;
f1 = fopen("test.txt","r");
f2 = fopen("new.txt","w");

// Code to find count of characters in a file.


begin = ftell(f1);
fseek(f1, -1, SEEK_END);
end = ftell(f1);
count = end - begin; // Count of characters.
printf("Count of characters=%d",count);

// Copy the content of file in reverse order


i=-1;
while (count != -1)
{
ch = fgetc(f1);
fputc(ch, f2);
i--;
fseek(f1, i, SEEK_END); // shifts the pointer to the previous character
count--;

}
fclose(f1);
fclose(f2);
}

9) Write a program to count number of words and lines in a file.

#include<stdio.h>
#include<string.h>

void main()
{
FILE *f1,*f2;
94
int countW=0,countL=0;
char ch;
f1 = fopen("test.txt","r");

while (feof(f1) == 0 )
{
ch = fgetc(f1);
if(ch == ' ')
countW++;
if(ch == '\n')
countL++;
}
printf("Count of words = %d\n",countW);
printf("Count of Lines = %d",countL);
fclose(f1);
}

Content of test.txt
Welcome to C programming.
C is very easy to learn

Output
Count of words = 4
Count of Lines = 2

10) Write a program to append some data to already existing file.

#include<stdio.h>
void main()
{
FILE *f1;
char str[30];
f1 = fopen("test.txt","a");
printf("Enter the string:");
gets(str);
fprintf(f1,"%s",str);
fclose(f1);
}

11) Write a program to display content of file two times without closing the file.

#include<stdio.h>
void main()
{
FILE *fp;
char ch;
fp = fopen("test.txt","r");
95
while(feof(fp)==0)
{
ch=fgetc(fp);
printf("%c",ch);
}
rewind(fp);
while(feof(fp)==0)
{
ch=fgetc(fp);
printf("%c",ch);
}
fclose(fp);
}

Output
Hello, Welcome to C programming. Hello, Welcome to C programming.

12) Write a program to read the details of “n” Employees with following fields – name, empid
and salary and write the details into a file. Then read details from file and display the name of
employee who has highest salary.

#include<stdio.h>
struct Employee
{
char name[30];
int empid;
double salary;
};
void main()
{
FILE *fp;
struct Employee e[10],res,temp;
int i,n;
fp = fopen("employee.dat","w");
printf("Enter the limit:");
scanf("%d",&n);
printf("Enter the details of Employee\n");
for(i=0;i<n;i++)
{
printf("Name:");
scanf("%s",e[i].name);
printf("EmpId:");
scanf("%d",&e[i].empid);
printf("Salary:");
scanf("%lf",&e[i].salary);
96
fwrite(&e[i],sizeof(e[i]),1,fp);
}
fclose(fp);
fp = fopen("employee.dat","r");
res.salary=-1.0;
while(feof(fp) == 0)
{
fread(&temp,sizeof(temp),1,fp);
if(res.salary < temp.salary)
{
res = temp;
}
}
printf("Name of Employee with highest Salary:%s",res.name);
}
Output
Enter the limit:2
Enter the details of Employee
Name:Sangeeth
EmpId:101
Salary:10000
Name:Poornima
EmpId:102
Salary:20000
Name of Employee with highest Salary:Poornima

97

You might also like