Professional Documents
Culture Documents
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#
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:
• 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.
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:
Algorithm:
Step 1: Initialize X as 0,
Step 2: Increment X by 1,
Step 3: Print X,
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.
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)
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.
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
Int 2 %d
Char 1 %c
Float 4 %f
Double 8 %lf
Page 3
Note: Size of each data types varies based on machines.
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.
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.
\b Backspace
\n New Line
\r Carriage Return
\t Tab (Horizontal)
\v Vertical Tab
\\ Backslash
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.
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
Page 6
scanf() function
The scanf() function is used for input. It reads the input data from the console.
scanf("format string",argument_list);
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
C has many built-in operator types and they are classified as follows:
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.
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;
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
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.
#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
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;
}
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");
}
}
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
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;
}
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:
Page 23
printf("Sum = %d",sum);
}
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);
WHILE DO-WHILE
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);
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
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.
#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]);
}
}
#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]);
}
}
}
#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]);
}
}
}
#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:
#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.
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
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 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");
}
}
#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);
}
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
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];
There are two ways to initialize a two Dimensional arrays during declaration.
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 }
// 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);
}
#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
#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
#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
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.
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]);
}
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.
#include <stdio.h>
int main()
{
int marks[10], i, n, sum = 0, average;
52
printf("Enter number of elements: ");
scanf("%d", &n);
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.
• 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
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
• A large program can be divided into smaller modules. Hence, a large project can be divided
among many programmers.
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
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.
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.
x: 10 y: 20
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
#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
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
#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
#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
#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
#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
• 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.
#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
#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
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
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>
Output
Enter the radius:5
Area=78.500000
Perimeter=31.400002
#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
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.
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
}
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("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
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(){
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(){
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
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.
union Employee e;
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.
#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
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.
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.
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;
void main()
{
int A[]={10,20,30,40,50};
82
int i;
printf("Array Content\n");
for(i=0;i<5;i++)
{
printf("%d\t",*(p+i));
}
}
Output
Array Content
10 20 30 40 50
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
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
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.
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.
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)
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.
#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
#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.
#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");
}
#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
#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");
}
fclose(f1);
fclose(f2);
}
#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
#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