GE6151 Computer Programming Notes
GE6151 Computer Programming Notes
UNIT I
INTRODUCTION
Generation and Classification of Computers- Basic Organization of a Computer Number
System Binary Decimal Conversion Problems. Need for logical analysis and thinking
Algorithm Pseudo code Flow Chart.
Introduction:
A Computer is an electronic machine that accepts data from the user, process the data by
performing calculations and operations and generate the desired output results.
A digital computer uses distinct values (0s and 1s) to represent the data. The computers
that we use at our homes and offices are digital computers.
Analog Computer that represents data as variable across a continuous range of values.
Analog computers are used for measuring parameters that vary continuously in real time
such as temperature.
Characteristics of computer:
Speed:
The computer process the data extremely fast, at the rate of millions of
instructions execute per second.
A computer can perform a huge task in few sec where a human being may take
hours or even days to complete the same task.
Accuracy:
The degree of accuracy of computer is very high and every calculation is
performed with the same accuracy.
For example, the computer can accurately give the result of division of any two
numbers up to 10 decimal places.
Diligence or Endurance:
When used for a longer period of time, the computer does not get tired or fatigued.
Page 1
It can perform long and complex calculations with the same speed and accuracy.
Versatility:
Storage Capability:
Computers are capable of storing huge amount of data and it can be located and
retrieved very quickly.
It uses storage devices such as hard disk to store huge amount of data.
Limitations of a computer:
Computer can only perform tasks that it has been programmed to do.
Computer cannot do any work without instructions from the user.
It executes instructions as specified by the user and does not take its own decision.
History of Computer:
Until the development of the first generation computers based on vacuum tubes, there had been
several developments in the computing technology related to the mechanical computing devices.
1. Calculating machines:
ABACUS were the first mechanical calculating device for counting of large numbers.
The word ABACUS means calculating board.
It consists of bars in horizontal positions on which sets of beads are inserted.
The horizontal bars have 10 beads each, representing units, tens, hundreds, etc.
Page 2
2. Napiers Bones was a mechanical device built for the purpose of multiplication in
1617 AD by an English mathematician John Napier.
3. Slide Rule
Slide rule was developed by an English mathematician Edmund Gunter in the
16the century.
Using the slide rule, one could perform operations like addition, subtraction,
multiplication and division.
It was used extensively till late 1970s.
4. Pascals adding and subtraction machine was developed by Blaise Pascal. It could add and
subtract. The machine consisted of wheels, gears and cylinders.
Page 3
5. Leibnizs multiplication and Dividing machine was a mechanical device that could both
multiply and divide. The German philosopher and mathematician Gottfried Leibnizs built it
around 1673.
6. Punch Card system was developed by Jacquard to control the power loom in 1801. He
invented the punched card reader that could recognize the presence of hole in the punched card
as binary one and the absence of the hole as binary zero. The 0s and 1s are the basis of the
modern digital computer.
Page 4
8. Holleriths punched card tabulating machine was invented by Herman Hollerith. The
machine could read the information from a punched card and process it electronically.
Page 5
Generations of Computers:
Each generation of computer is designed based on a new technological development,
resulting in better, cheaper and smaller computers that are more powerful, faster and
efficient than the previous generation computers.
Currently there are five generation of computer.
First Generation Computers (1940 to 1956):
Hardware technology:
These computers used vacuum tube for circuitry and magnetic drums for memory.
Input devices: punched cards and paper tapes.
Output devices: printouts
Software Technology:
Instructions were written in machine language used 0s and 1s.
These computers could solve one problem at a time.
Computing Speed:
The computation time was in milli seconds.( 1 milli second = 1X10-3 second)
Physical appearance:
The computers were enormous in size and required a large room for installation.
Application:
They were used for scientific applications such as computing device.
Example:
UNIVA( Universal automatic computer,
ENIAC (Electronic numerical integrator and calculator)
EDVAC (Electronic discrete variable automatic computer)
Page 6
The first generation computers used a large number of vacuum tubes and it generated a
lot of heat and it consumes more electricity.
Since these computers used machine language, it was difficult to understand by the
human.
Page 7
Semi conductor memory (RAM and ROM), Hard disk, CD are using for memory.
Input devices: keyboard, mouse and all present input devices.
Output devices: Monitor printer and all present output devices.
Software Technology:
All the present high level languages (C, C++, Java, C#, .Net etc) are the gift of this
generation.
Several new operating systems like MS DOS, MS-WINDOWS developed and also GUI
interface.
Computing Speed:
The computation time was in pico seconds.( 1 pico second = 1X10-12 second)
Physical appearance:
Microprocessors are very small in size, even now days computers are in the size of palm.
Application:
It covers all areas such as personal use, business, space craft, railways and research etc.
Example:
Intel 4004 was the first microprocessor. Now dual core processor etc.
These computers need advanced compiler for converting the high level language into
machine language.
This generation use Super Large Scale Integrated (SLSI) chip that are able to store
millions of components on a single chip.
It requires large memory and speed is extremely high.
The fifth generation computers are based on Artificial Intelligence (AI). They try to
simulate the human way of thinking and reasoning.
Example: Expert System (ES), Natural Language Processing (NLP) , Speech recognition,
voice recognition , robotics etc.
This generation of computer uses parallel processing that allows several instructions to be
executes in parallel, instead f serial execution. The Intel dual core microprocessor uses
parallel processing.
Page 9
Classification of computers:
The computers are broadly classified into four categories based on their sizes and type:
(1)
(2)
(3)
(4)
Microcomputers
Minicomputers
Mainframe computers
Super computers
Microcomputers:
Microcomputers are small, low cost and single user digital computer.
Input, output and CPU are on a single IC chip.
Page 10
Minicomputers are mainly multiprocessors and multi user systems where many
users simultaneously work on the systems. It supports 4-200 users simultaneously.
They have high processing speed and high storage capacity than the micro
computers.
The users can access the minicomputer through their PCs or terminal.
They are used for real time applications in industries, research centers, etc.
PDP 11, IBM 8000 series are some of the widely used mini computers.
Mainframe Computer:
Mainframe computers are large and powerful systems generally used in
centralized databases. These are used to handle huge volumes of data.
These are multi-user and multi-programming and high performance computers.
The user accesses the mainframe computer via a terminal that may be a dumb
terminal.
Highly sophisticated operating systems are needed to control and supervise their
operations.
It is used in research organizations, large industries, large business and
government sectors, banks and ticket reservations etc.
Example: CDC 6600 and IBM ES000 series.
Super Computer:
Super computer is the most powerful of all computers. They are the fastest and
most expensive machines.
Super computers are built by interconnecting thousands of processors that can
work in parallel.
Speed, accuracy, memory capacity higher than all other computers.
It can perform billions of instructions per second ( 1 super computer = 40,000
micro comp)
Weather forecasting, space research, weapons research, atomic research etc are
some of the applications
.Example: IBM Roadrunner, IBM Blue gene and Intel ASCI red.
(3) Data
(4) Users
(1) Hardware:
Hardware consists of the mechanical parts that make up the computer as a
machine.
The devices are required for input, output, storage and processing of the data.
Keyboard, monitor, hard disk, printer, processor and motherboard are some of the
hardware devices.
(2) Software:
Software is the set of instructions that tells the computer about the tasks to be
performed and how these tasks are to be performed.
Program is a set of instructions, written in a language understood by the
computer, to perform specific tasks.
A set of programs and documents are collectively called as software.
(3) Data:
Data are isolated values or raw facts. The data is provided as input to the
computer, which is processed to generate some meaningful information.
(4) Users:
Users are people who write computer programs or interact with the computer.
Programmers, data entry operators, system analysts and computer hardware
engineers fall into this category.
The Input-Process-Output Concept:
A computer is an electronic device that 1) Accepts data, 2) Processes data, 3) Generates output
and 4) stores data. The concept of generating output information from the input data is referred
to as input-process-output concept.
(1) Input : The computer accepts input data from the user via an input device like keyboard.
The input data can be characters, word, text, sound, images, document etc.
(2) Process : The computer processes the input data. For this, it performs some actions on the
data by using the instructions given by the user of the data. The action could be an
arithmetic or logic calculation, editing, modifying a document etc. During processing the
data, instructions and the output are stored temporarily in the computers main memory.
Page 13
(3) Output : Output is the result generated after processing of data. The output may be in the
form of text, sound, image, document etc. The computer may display the output on a
monitor, send output to the printer for printing, play the output etc.
(4) Storage : The input data, instructions and output are stored permanently in the secondary
storage devices like tape or disk. The stored data can be retrieved later, whenever needed.
It interprets the program instructions and performs the arithmetic and logic operations
required for processing of data. Then it sends the processed data or result to the memory.
(a)Arithmetic Logic Unit:
ALU consists of two units Arithmetic unit and Logic unit.
The arithmetic unit performs arithmetic operations on the dat. Some of the
arithmetic operations supported by the arithmetic unit are addition, subtraction,
multiplication and division.
The Logic unit of ALU is responsible for performing logic operations. Logic unit
performs comparisons of numbers, letters and special characters. Logic operations
include testing for greater than, less than or equal to condition.
ALU performs arithmetic and logic operations, and uses registers to hold tha data
that is being processed.
(b)Registers:
Registers store data, instructions, addresses and intermediate results of processing.
Registers are often referred as CPSs working memory.
The data and instructions that require processing must be brought in the registers
of CPU before they a can be processed. For example, if two numbers are to be
added, both numbers are brought in the registers, added and the result is also
placed in a register.
Registers are used for different purposes, with each register serving a specific
purpose. Some of the important registers in CPU are as follows:
Accumulator(ACC) Stores the result of the arithmetic and logic operations.
Instruction Register(IR) contains the current instruction most recently fetched.
Program counter (PC) contains the address of next instruction to be processed.
Memory Address Register(MAR) contains the address of next location in the
memory to be accessed.
Memory Buffer Register (MBR) temporarily stores data from memory or the
data to be sent to memory.
Data Register (DR) stores the operands and any other data.
(c)Control Unit:
Control unit organizes the processing of data and instructions. It acts as a
supervisor and controls and coordinates the activity of the other units of
computer.
CU tells when to fetch the data and instructions, what to do, where to store the
results, the sequencing of events during processing etc.
CU holds the CPUs instruction set, which is a list of all operations that the CPU
can perform.
(3)Memory unit:
Page 15
Number systems:
A number is required for counting or to express the amount of some quantity. It consists of a
group of symbols called digits, which are arranged in a definite manner.
The most widely adopted system is the decimal number system which has ten digits (0, 1, 2
9), the octal system has eight digits (0, 1, 2, ..7), the hexadecimal system has sixteen digits (0,
1 9, A, B, C, D, E, F) and the binary system has only two (0 & 1).
The most widely used number system is the positional number system.
In this system the position of a digit indicates the significance to be attached to that digit.
24
23
22
21
20
2-1
2-2
2-3
2-4
Page 17
(4 * 10-2)
3 in the position
(3 * 10-1)
(8 * 100)
(5 * 101)
(2 * 102)
50 + 8
+ 4 * 10-2
. 3 * 1 / 10 + 4 * 1 / 100
. 0.3
+ 0.04
(258.34)10 = 258.34
OCTAL NUMBER SYSTEM:
The number system with base or radix (8) is known as octal number system. There are
only eight digits i.e. 0, 1,2,3,4,5,6,7.
84
83
82
81
80
8-1
8-2
8-3
8-4
164
163
162
161
160
16-1
16-2
16-3
16-4
Page 18
\ \____________1 x 22 =
\_______________1 x 24 = 16
22
Another example: convert 110112 to decimal
11011
\ \ \ \_________1 x 20 =
\ \ \__________1 x 21 =
\ \_____________1 x 23 =
\______________1 x 24 =
16
27
The method for converting a decimal number to binary is one that can be used to convert from
decimal to any number base. It involves using successive division by the radix until the dividend
reaches 0. At each division, the remainder provides a digit of the converted number, starting with
the least significant digit.
An example of the process: convert 3710 to binary
37 / 2 = 18
remainder 1
Page 19
remainder 0
9/2=4
remainder 1
4/2=2
remainder 0
2/2=1
remainder 0
1/2=0
remainder 1
remainder 1
46 / 2 = 23
remainder 0
23 / 2 = 11
remainder 1
11 / 2 = 5
remainder 1
5/2=2
remainder 1
2/2=1
remainder 0
1/2=0
1011 0101
B
B516
Page 20
B
8
C
6B8C16
To convert a hexadecimal number to a binary number, convert each hexadecimal digit into a
group of 4 binary digits.
Example: Convert the hex number 374F into binary
3
Convert the hex digits to binary
Hexadecimal-to-decimal conversion
One way to find the decimal equivalent of a hexadecimal number is to first convert the
hexadecimal number to binary and then convert from binary to decimal.
Convert the hexadecimal number 1C to decimal:
1C
0001 1100 = 24+ 2 + 2 = 16 +8+4 = 28
Decimal-to-hexadecimal conversion
Page 21
terms of its decimal equivalent is accomplished by multiplying each digit by its weight and
summing the products.
Lets convert octal number 2374 in decimal number.
Weight
8 8 81 80
Octal number 2 37 4
2374 = (2 x 8) + (3 x 8) + (7 x 81) + (4 x 8) =1276
Decimal-to-octal conversion
A method of converting a decimal number to an octal number is the repeated division-by-8
method, which is similar to the method used in the conversion of decimal numbers to binary or to
hexadecimal. Lets convert the decimal number 359 to octal. Each successive division by 8
yields a remainder that becomes a digit in the equivalent octal number. The first remainder
generated is the least significant digit (LSD).
359/8 = 44.875 0.875 x 8 = 7 (LSD)
44 /8 = 5.5 0.5 x 8 = 4
5/8 = 0.625 0.625 x 8 = 5 (MSD)
The number is 547.
Octal-to-binary conversion
Because each octal digit can be represented by a 3-bit binary number, it is very easy to convert
from octal to binary.
Octal/Binary Conversion
Octal Digit 0 1
2
3
4
5
Binary 000 001
010
011
100
101
Lets convert the octal numbers 25 and 140.
Octal Digit 2
5
1
4
0
Binary
010
101
001
100
000
6
110
7
111
Binary-to-octal conversion
Conversion of a binary number to an octal number is the reverse of the octal-to-binary
conversion.
Lets convert the following binary numbers to octal:
110 101
101 111 001
6
5
= 65
5
7
1
= 571
Page 22
Algorithm
Definition:
An algorithm is a finite sequence of step by step, well defined, unambiguous instructions
for solving a particular problem.
Algorithm is an English-like representation of the logic which is used to solve the
problem.
Qualities of good algorithm
The following are the primary factors that judge the quality of the algorithm
Time The good algorithm takes less amount of time for producing the desired result.
Memory The good algorithm takes less amount of memory space to execute.
Accuracy The good algorithm has more accuracy than other.
Example: Algorithm to find the greatest among three numbers
Step 1: Start
Step 2: Read the three numbers A, B, C
Step 3: Compare A and B. If A is greater Perform step 4 else perform step 5
Page 24
Pseudo Code:
The pseudo code is one of another program logic planner tool, used for explaining
algorithm.
The pseudo code is just the algorithm written by using programming language syntaxes.
Preparing a pseudo code:
Pseudo code is written using structured English.
In a pseudo code, some terms are commonly used to represent the various actions. For
example, for inputting data the terms may be (INPUT,GET, READ), for outputting data (
OUTPUT, PRINT, DISPLAY), for calculations ( COMPUTE, CALCULATE), for
incrementing ( INCREMENT),
Page 25
In addition to words like ADD, SUBTRACT, INITIALIZE used for addition, subtraction,
and initialization, respectively.
It use some terms for conditional statements like IF, ELSE, ENDIF and looping
statements like WHILE, DO WHILE etc.
Example: pseudo code for greatest of three numbers
READ a,b,c
IF (a>b) and (a>c) THEN
WRITE a is big
ELSE IF (B>C) THEN
WRITE b is big
ELSE
WRITE c is big
END IF
Example: find sum of first 100 integers
INITIALIZE SUM to zero
INITIALIZE I to zero
DO WHILE (I <100)
INCREMENT I
ADD I to SUM and store in SUM
END DO WHILE
PRINT SUM
STOP
Flow Chart:
A flowchart is diagrammatic representation of the logic for solving a task.
The purpose of drawing a flowchart is to make the logic of the program clearer in a visual
form.
Since flowchart is a diagrammatic representation, it forms a common medium of
communication.
Flow chart symbols:
Basic symbols:
Page 26
It is represented by an oval shape. Every process starts and ends at Some points, so every
flowchart need one start and one end symbol. These blocks should contain simple labels
to indicate the process
Page 27
Connector:
Page 28
Selection(branch) Structure it asks a true/ false question and then selects the next
instructions Based on the answer
Page 29
Page 30
e. Only one flow line should enter a decision symbol, but two or three flow lines, one for each
possible answer, should leave the decision symbol.
h. If the flowchart becomes complex, it is better to use connector symbols to reduce the number
of flow lines. Avoid the intersection of flow lines if you want to make it more effective and
better way of communication.
i. Ensure that the flowchart has a logical start and finish.
j. It is useful to test the validity of the flowchart by passing through it with a simple test data.
Page 31
UNIT II
C PROGRAMMING BASICS
Problem formulation - Problem Solving - Introduction to ' C' programming -fundamentals structure of a 'C' program - compilation and linking processes - Constants, Variables - Data
Types - Expressions using operators in 'C' - Managing Input and Output operations - Decision
Making and Branching - Looping statements - solving simple scientific and statistical problems.
Problem formulation
Before attempting to solve a problem, we need to first formulate or define the problem. It is
important to precisely define the problem we intend to solve.
What makes a good problem definition?
It is precise.
It states the objectives (what is required):
the inputs and their characteristics, including initial conditions
the outputs and their desired characteristics, including goal conditions
the relationships between the inputs and the desired outputs
Problem Solving
Problem Solving is the sequential process of analyzing information related to a given situation
and generating appropriate response options.
There are 6 steps that you should follow in order to solve a problem:
1. Understand the Problem
2. Formulate a Model
3. Develop an Algorithm
4. Write the Program
5. Test the Program
6. Evaluate the Solution
STEP 1: Understand the Problem:
The first step to solving any problem is to make sure that we understand the problem that we are
trying to solve. we need to know:
What format is it in ?
Is anything missing ?
What output information am I trying to produce ?
What do I want the result to look like text, a picture, a graph ?
What am I going to have to compute ?
A Simple Program
The following program is written in the C programming language.
#include<stdio.h>
main()
{
printf("Programmingin C is easy.\n");
}
Fundamentals
(a) Each instruction in a C program is written as a separate statement. Therefore a complete C
program would comprise of a series of statements.
(b) The statements in a program must appear in the same order in which we wish them to be
executed; unless of course the logic of the problem demands a deliberate jump or transfer of
control to a statement, which is out of sequence.
(c) Blank spaces may be inserted between two words to improve the readability of the statement.
However, no blank spaces are allowed within a variable, constant or keyword.
(d)All statements are entered in small case letters.
(e) C has no specific rules for the position at which a statement is to be written. Thats why it is
often called a free-form language.
(f) Every C statement must end with a ;. Thus ; acts as a statement terminator.
Example:
main( )
{
int p, n ;
float r, si ;
p = 1000 ;
n=3;
r = 8.5 ;
si = p * n * r / 100 ;
printf ( "%f" , si ) ;
}
Page 34
main( ) is a collective name given to a set of statements. This name has to be main( ), it cannot
be anything else. All statements that belong to main( ) are enclosed within a pair of braces { } as
shown below.
main( )
{
statement 1 ;
statement 2 ;
statement 3 ;
}
main( ) is a function. Every function has a pair of parentheses ( ) associated with it.
Any variable used in the program must be declared before using it. For example,
int p, n ;
float r, si ;
Any C statement always ends with a ;For example,
float r, si ;
r = 8.5 ;
In the statement,
si = p * n * r / 100 ;
* and/ are the arithmetic operators. The arithmetic operators available in C are +, -, * and /. C is
very rich in operators. There are about 45 operators available in C.
- The general form of printf( ) function is,
printf ( "<format string>", <list of variables> ) ;
<format string> can contain,
%f for printing real values
%d for printing integer values
%c for printing character values
In addition to format specifiers like %f, %d and %c the format string may also contain any
other characters. These characters are printed as they are when the printf( ) is executed.
Following are some examples of usage of printf( ) function:
printf ( "%f", si ) ;
printf ( "%d %d %f %f", p, n, r, si ) ;
printf ( "Simple interest = Rs. %f", si ) ;
printf ( "Prin = %d \nRate = %f", p, r ) ;
The output of the last statement would look like this...
Page 35
Prin = 1000
Rate = 8.5
-\n is called newline and it takes the cursor to the next line.
printf( )outputs the values to the screen whereas scanf( ) receives them from the keyboard.
ampersand (&) before the variables in the scanf( )function is a must. &is an Address of
operator. It gives the location number used by the variable in memory.
Structure of C Program
A C program may contain one or more sections given below.
Documentation section
Preprocessor section
Definition section
i)
Documentation section: It consists a set of comment lines used to specify the name
of program, the author and other details etc.
Comments: Comments are very helpful in identifying the program features and
underlying logic of the program. The lines begins with /* and ending with /* are
Page 36
known as comment lines. These are not executable, the compiler is ignored anything
in between /* and */.
Preprocessor section: It is used to link system library files, for defining the macros
and for defining the conditional inclusion.
ii)
# define A 10 etc.
iii)
Global Declaration section: The variables that are used in more than one function
throughout the program are called global variables and declared outside of all the
function i.e. before main().
iv)
Every C program must have one main() function, which specify the starting of C
program.
void main()
{
}
Functions must return a value and the term void is used to denote that the main
program does not return a value.
Main contains the following two parts.
v)
Declaration Part : This part is used to declare all the variables that are used in the
executable part of the program and these are called local variables.
vi)
Page 37
ii)
iii)
iv)
Constants, Variables:
The alphabets, numbers and special symbols when properly combined form constants,
variables and keywords.
Page 38
A constant is an entity that doesnt change whereas a variable is an entity that may
change.
In any program we typically do lots of calculations. The results of these calculations are
stored in computers memory, the value stored in each location may change the names
given to these locations are called variable names.
Consider the following example.
Here 3 is stored in a memory location and a name x is given to it. Then we are assigning
a new value 5 to the same memory location x. This would overwrite the earlier value 3,
since a memory location can hold only one value at a time.
Since the location whose name is x can hold different values at different times x is known
as a variable. As against this, 3 or 5 do not change, hence are known as constants
Types of C Constants
C constants can be divided into two major categories:
(a)Primary Constants
(b) Secondary Constants
Page 39
+325.34
426.0
-32.76
-48.5792
The exponential form of representation of real constants is usually used if the value of the
constant is either too small or too large.
In exponential form of representation, the real constant is represented in two parts. The
part appearing before e is called mantissa, whereas the part following e is called
exponent.
Following rules must be observed while constructing real constants expressed in exponential
form:
(a)The mantissa part and the exponential part should be separated by a letter e.
(b)The mantissa part may have a positive or negative sign.
(c)Default sign of mantissa part is positive.
(d)The exponent must have at least one digit, which must be apositive or negative
Integer. Default sign is positive.
(e)Range of real constants expressed in exponential form is-3.4e38 to 3.4e38.
Ex.: +3.2e-5
4.1e8
-0.2e+3
-3.2e-5
Rules for Constructing Character Constants
(a) A character constant is a single alphabet, a single digit or a single special symbol
enclosed within single inverted commas. Both the inverted commas should point to the
left.
For example, A is a valid character constant whereas A is not.
(b) The maximum length of a character constant can be 1character.
Ex.: 'A'
'I'
'5'
'='
Page 41
Types of C Variables:
An entity that may vary during program execution is called a variable. Variable names
are names given to locations in memory.
These locations can contain integer, real or character constants. In any language, the
types of variables that it can support depend on the types of constants that it can handle.
This is because a particular type of variable can hold only the same type of constant.
For example, an integer variable can hold only an integer constant, a real variable can
hold only a real constant and a character variable can hold only a character constant.
Rules for Constructing Variable Names:
(a)A variable name is any combination of 1 to 26 alphabets, digits or underscores. Some
compilers allow variable names whose length could be up to 247 characters. Still, it
would be safer to stick to the rule of 31 characters.
(b)The first character in the variable name must be an alphabet or underscore.
(c)No commas or blanks are allowed within a variable name.
(d)No special symbol other than an underscore (as in gross_sal)can be used in a variable
name.
Ex.: si_int
m_hra
pop_e_89
The Programming language C has two main variable types
Local Variables
Global Variables
Local Variables
Local variables scope is confined within the block or function where it is defined. Local
variables must always be defined at the top of a block.
When a local variable is defined - it is not initalised by the system, you must initalise it
yourself.
When execution of the block starts the variable is available, and when the block ends the
variable 'dies'.
int j=10;
i++;
if (j > 0)
{
/* i defined in 'main' can be seen */
printf("i is %d\n",i);
}
if (j > 0)
{
/* 'i' is defined and so local to this block */
int i=100;
printf("i is %d\n",i);
}/* 'i' (value 100) dies here */
printf("i is %d\n",i); /* 'i' (value 5) is now visible.*/
}
This will generate following output
i is 5
i is 100
i is 5
Here ++ is called incremental operator and it increase the value of any integer variable by 1.
Thus i++ is equivalent to i = i + 1;
-- operator also which is called decremental operator and it decrease the value of any integer
variable by 1. Thus i-- is equivalent to i = i - 1;
Global Variables
Global variable is defined at the top of the program file and it can be visible and modified by any
function that may reference it.
Global variables are initalised automatically by the system when you define them.
Data Type
Initializer
int
char
'\0'
float
pointer
NULL
Page 43
If same variable name is being used for global and local variable then local variable takes
preference in its scope. But it is not a good practice to use global variables and local variables
with the same name.
int i=4;
/* Global definition */
main()
{
i++;
/* Global variable */
func();
printf( "Value of i = %d -- main function\n", i );
}
func()
{
int i=10; /* Local definition */
i++;
/* Local variable */
printf( "Value of i = %d -- func() function\n", i );
}
This will produce following result
Value of i = 11 -- func() function
Value of i = 5 -- main function
i in main function is global and will be incremented to 5. i in func is internal and will be
incremented to 11. When control returns to main the internal variable will die and and any
reference to i will be to the global.
Data Types:
Data type is the type of the data that are going to process within the program.
C supports different data types; each data type may have predefined memory
requirement and storage representation.
C Data types: There are four data types in C language. They are,
S.no Types
Data Types
Page 44
INTEGER
These are whole numbers, both positive and negative. Unsigned integers (positive values
only)are supported. In addition, there are short and long integers.
The keyword used to define integers is,
int
An example of an integer value is 32. An example of declaring an integer variable called
sum is,
int sum;
sum = 20;
C offers a variation of the integer data type called short and long integer values. The
intention of providing these variations is to provide integers with different ranges
wherever possible. Short and long integers would usually occupy two and four bytes
respectively.
long variables which hold long integers are declared using the keyword long, as in,
longint i ;
longint abc ;
long integers cause the program to run a bit slower, but the range of values that we can
use is expanded tremendously. The value of a long integer typically can vary from 2147483648 to+2147483647.
short integer variables are declared as,
shortint j ;
shortint height ;
C allows the abbreviation of short int to short and of long int to long. So the
declarations made above can be written as,
long i ;
long abc ;
short j ;
short height ;
Page 45
CHARACTER
These are single characters. The keyword used to define character variables is,
char
Note the assignment of the character A to the variable letter is done by enclosing the
value in single quotes.
Signed and Unsigned chars, both occupying one byte each, but having different ranges.
A signed char is same as an ordinary char and has a range from-128 to +127; whereas,
an unsigned char has a range from 0 to255.
FLOATING POINT
These are numbers which contain fractional parts, both positive and negative. The
keyword used to define float variables is,
float
A float occupies four bytes in memory and can range from -3.4e38to +3.4e38.
If this is insufficient then C offers a double data type that occupies 8 bytes in memory
and has a range from -1.7e308 to+1.7e308.
A variable of type double can be declared as,
double a, population ;
Page 46
If the situation demands usage of real numbers that lie even beyond the range offered by
double data type, then there exists along double that can range from -1.7e4932 to
+1.7e4932.
A long double occupies 10 bytes in memory.
Page 48
Some operators require two operands called binary operators, while other acts upon only
one operand called unary operator.
Operators, functions, constants and variables are combined together to form expressions.
Example: A + B * 5
where,
+, * - operators
A, B - variables
5 constant
A + B * 5 - expression
Types of C operators:
1. Arithmetic operators
2. Assignment operators
3. Relational operators
4. Logical operators
5. Bit wise operators
6. Conditional operators (ternary operators)
7. Increment/decrement operators
8. Special operators
1. Arithmetic operators:
These operators are used to perform mathematical calculations like addition, subtraction,
multiplication, division and modulus.
S.no Operator Operation
1 +
Addition
2 Subtraction
3 *
multiplication
4 /
Division
5 %
Modulus
Example program for C arithmetic operators:
# include <stdio.h>
Page 49
1 void main()
2 {
int a=40,b=20,add,sub,mul,div,mod;
3
add=a+b;
4
sub=a-b;
5
mul=a*b;
6
div=a/b;
7
mod=a%b;
8
printf("Addition of a, b is : %d\n",add);
9
printf("Subtraction of a, b is : %d\n",sub);
10
printf("Multiplication of a, b is : %d\n",mul);
11
printf("Division of a, b is : %d\n",div);
12
printf("Modulus of a, b is : %d\n",mod);
13 }
Example
= sum = 10
+= sum+=10
-= sum = 10
*= sum*=10
Compound assignment operator /+ sum/=10
%= sum%=10
&= sum&=10
^= sum^=10
Explanation
Value 10 is assigned to variable
sum
This is same as sum = sum+10
This is same as sum = sum 10
This is same as sum = sum*10
This is same as sum = sum/10
This is same as sum = sum%10
This is same as sum = sum&10
This is same as sum = sum^10
int Total=0,i;
for(i=0;i<10;i++)
{
Total+=i;
/*This is same as Total = Toatal+i*/
}
printf("Total = %d",Total);
}
Output: Total = 45
3. Relational operators:
These operators are used to find the relation between two variables. That is used to
compare the value of two variables.
Operator Example
>
x>y
<
x<y
>=
x >= y
<=
x <= y
==
x == y
!=
x != y
Output:
m and n are not equal
4. Logical operators:
These operators are used to perform logical operations on the given two variables
Operator Example
&&
x && y
||
x || y
!
x != y)
Example program for logical operators:
1
2
3
4
5
6
7
8
#include <stdio.h>
int main()
{
int m=40,n=20;
if(m>n&&m!=0){
printf("m is greater than n and not equal to 0");
}
}
y
0
1
0
1
x/y
0
1
1
1
x&y
0
0
0
1
x^y
0
1
1
0
Operator Explanation
&
Bitwise AND
|
Bitwise OR
~
Bitwise NOT
^
XOR
<<
Left Shift
>>
Right Shift
#include <stdio.h>
int main()
{
Page 52
int m=40,n=20,AND_opr,OR_opr,XOR_opr;
AND_opr=(m&n);
OR_opr=(m|n);
XOR_opr=(m^n);
printf("AND_opr value = %d\n",AND_opr);
printf("XOR_opr value = %d\n",XOR_opr);
printf("OR_opr value = %d\n",OR_opr);
Output:
AND_opr value = 0
XOR_opr value = 60
OR_opr value = 60
6. Conditional operators:
Conditional operators return one value if condition is true and returns other value when
the condition is false.
This operator is also called as ternary operator
Syntax
: (Condition ? true value : false value);
Example
: (A>100 ? 0 : 1);
Here, if A is greater than 100, 0 is returned else 1 is returned. This is equal to if else
conditional statements.
Example program for conditional / ternary operators:
#include <stdio.h>
int main()
{
int x=1,y;
y=(x==1?2:0);
printf("x value is %d\n",x);
printf("y value is %d",y);
}
Output:x value is 1
y value is 2
Page 53
Operators
&
Description
This is used to get the address of the variable.
Example:
&a will give address of a.
This is used as pointer to a variable.
Example: * a where, * is pointer to the variable a.
Page 54
Size of ()
}
FORMATTERS FOR scanf()
The following characters, after the % character, in a scanf argument, have the following effect.
d
read a decimal integer
o
read an octal value
x
read a hexadecimal value
h
read a short integer
l
read a long integer
f
read a float value
e
read a double value
c
read a single character
s
read a sequence of characters
[...]
read a character string. The characters inside the brackets.
ACCEPTING SINGLE CHARACTERS FROM THE KEYBOARD
Getchar, Putchar
getchar() gets a single character from the keyboard, and putchar() writes a single character from
the keyboard.
Example:
The following program illustrates this,
#include <stdio.h>
main()
{
int i; int ch;
for( i = 1; i<= 5; ++i ) {
ch = getchar();
putchar(ch);
}
}
The program reads five characters (one for each iteration of the for loop) from the keyboard.
Note that getchar() gets a single character from the keyboard, and putchar() writes a single
character (in this case, ch) to the console screen.
In decision control statements ( if else and nested if ), group of statements are executed
when condition is true. If condition is false, then else part statements are executed.
There are 4 types of decision making control statements in C language. They are,
Page 56
if statements
if else statements
nested if statements
If ..else..if ladder
Statement
if
statement
Syntax.
if(condition)
{
Statements;
}
Description
In these type of
statements, if condition
is true, then respective
block of code is
executed.
ifelse
statement
if(condition)
{
Statement1;
Statement2;
}
else
{
Statement3;
Statement4;
}
if(condition1)
{
if (condition2)
{
Statement 2;
}
else
{ statement 3;
}
else
{
if(condition3)
{
Statement 4;
}
else
In these type of
statements, group of
statements are executed
when condition is true.
If condition is false,
then
else
part
statements
are
executed.
nested if
If condition 1 is true
then condition 2 is
checked and statements
are executed.
If
condition1
is false
then else part is
executed.
Page 57
{ statement5;
}
}
If ..else..if if(condition1)
{
ladder
Statement1;
}
else
if(condition2)
{
Statement2;
}
else
if(condition3)
{Statement 3;}
else
Statement4;
The
conditional
expressions
are
evaluated from the top
downward. As soon as
a true condition is
found, the statement
associated with it is
executed, and the rest
of the ladder is
bypassed. If none of the
conditions is true, then
the final else statement
will be executed.
{
printf("m and n are equal");
}
else
{
printf("m and n are not equal");
}
}
Output: m and n are not equal
Example program for C nested if:
In nested if control statement, if condition 1 is true, then condition 2 is checked and
statements are executed if it is true. If condition 2 also gets failure, then else part is executed.
#include <stdio.h>
int main()
{
int m=40,n=20;
if(m!=n)
{
If(m>n)
{
printf("m is greater than n");
}
else
{
printf("m is less than n");
}
else
{
printf("m is equal to n");
}
}
}
Output: m is greater than n
Example program for C if else if ladder:
In this control statement, if condition 1 is false, then condition 2 is checked and statements
are executed if it is true. If condition 2 also gets failure, then else part is executed.
Page 59
#include <stdio.h>
int main()
{
int m=40,n=20;
if(m>n)
{
printf("m is greater than n");
}
elseif(m<n){
printf("m is less than n");
}
else
{
printf("m is equal to n");
}
}
Output:
m is greater than n
Switch case statement
Switch statement is used to execute a block of statements depending on the value of a
variable or an expression.
If the switch value matches with any case value the corresponding case will execute.
If none of the conditions is met then default block will be executed.
Syntax:
switch(expression)
{case constant-expression1 :
statement(s);
break;/* optional */
case constant-expression2 :
statement(s);
break;/* optional */
/* you can have any number of case statements */
default:/* Optional */
statement(s);
}
Page 60
Good
Looping statements
Iteration or looping is a process of repeating the same set of statements again and again
until the specified condition is true.
A loop statement allows to execute a statement or group of statements multiple times.
Page 61
while loop
A while loop statement in C programming language repeatedly executes a block of statement as
long as a given condition is true.
Syntax:
while(condition)
{
statement(s);
}
When the condition becomes false, program control passes to the line immediately
following the loop.
#include<stdio.h>
void main ()
{int a =10;
while( a <20)
{
printf("value of a: %d\n", a);
a++;
}
}
When the above code is compiled and executed, it produces the following result:
value of a: 10
Page 62
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 15
value of a: 16
value of a: 17
value of a: 18
value of a: 19
Do While Loop
The do...while loop in C programming language checks its condition at the bottom of the loop.
A do...while loop is similar to a while loop, except that a do...while loop is guaranteed to execute
at least one time.
Syntax:
do
{
statement(s);
}while( condition );
Notice that the conditional expression appears at the end of the loop, so the statement(s)
in the loop execute once before the condition is tested.
If the condition is true, the flow of control jumps back up to do, and the statement(s) in
the loop execute again. This process repeats until the given condition becomes false.
/* Example */
#include<stdio.h>
void main ()
{
Page 63
int a =10;
do
{printf("value of a: %d\n", a);
a = a +1;
}while( a <20);
}
Result is
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 15
value of a: 16
value of a: 17
value of a: 18
value of a: 19
for loop
A for loop is a repetition control structure that allows you to efficiently write a loop that needs to
execute a specific number of times.
Syntax:
for( initialization ; condition; increment )
{
statement(s);
}
Here is the flow of control in a for loop:
1. The init step is executed first, and only once. This step allows you to declare and initialize any
loop control variables.
2. Next, the condition is evaluated. If it is true, the body of the loop is executed. If it is false, the
body of the loop does not execute and flow of control jumps to the next statement just after the
for loop.
Page 64
3. After the body of the for loop executes, the flow of control jumps back up to the increment
statement. This statement allows you to update any loop control variables.
4. The condition is now evaluated again. If it is true, the loop executes and the process repeats itself
(body of loop, then increment step, and then again condition). After the condition becomes false,
the for loop terminates.
When the above code is compiled and executed, it produces the following result:
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 15
value of a: 16
value of a: 17
value of a: 18
Page 65
value of a: 19
The figure below explains the working of break statement in all three type of loops.
//Example
#include <stdio.h>
main()
{
int i = 1;
while ( i> =10 )
Page 66
{
printf("Hello %d\n", i );
i = i +1;
if(i == 6 )
{
break;
}
}
}
Hello 1
Hello 2
Hello 3
Hello 4
Hello 5
continue Statement
It is sometimes desirable to skip some statements inside the loop or skip 1 iteration of loop. In
such cases, continue statements are used.
Syntax of continue Statement
continue;
Just like break, continue is also used with conditional if statement.
For better understanding of how continue statements works in C programming. Analyze the
figure below which bypasses some code/s inside loops using continue statement.
Page 67
#include
main()
{ int i;
int j = 10;
for(i = 0; i<= j; i ++ )
{
if(i == 5 )
{
continue;
}
printf("Hello %d\n", i );
}
}
goto statement
The goto statement is used to alter the normal sequence of program execution by transferring
control to some other part of the program unconditionally. In its general form, the goto statement
is written as
Syntax:
{
.
go to label;
Page 68
.
.
Label:
Statements;
}
where the label is an identifier that is used to label the target statement to which the
control is transferred. Control may be transferred to anywhere within the current function. The
target statement must be labeled, and a colon must follow the label. Thus the target statement
will appear as
Each labeled statement within the function must have a unique label, i.e., no two statement can
have the same label.
{
root1=(-b+sqrt(d))/(2*a);
root2=(+b+sqrt(d))/(2*a);
printf("The roots of the values are a=%d,b=%d,c=%d,root1=%f,root2=%f\n",a,b,c,root1,root2);
}
else
{
printf("The roots are imaginary");
}
getch();
}
Program for area of triangle
#include<stdio.h>
#include<conio.h>
#include<math.h>
void main()
{
int s,a,b,c;
float area;
clrscr();
printf("Enter the value for a,b,c\n");
scanf("%d%d%d",&a,&b,&c);
s=(a+b+c)/2;
printf("s=%d\n",s);
area=sqrt(s*(s-a)*(s-b)*(s-c));
printf("area of triangle=%f",area);
getch();
}
Scientific problem solving using decision making & looping
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
int main()
{
double a, b, c, d, e, x1, x2;
/* Read input data */
printf("\na = ");
scanf("%lf", &a);
printf("b = ");
Page 70
scanf("%lf", &b);
printf("c = ");
scanf("%lf", &c);
/* Test for a = 0. */
if (a == 0.)
{
printf("\nError: a = 0.\n");
exit(1);
}
/* Perform calculation */
e = b * b - 4. * a * c;
if (e > 0.) // Test for real roots
{
/* Case of real roots */
d = sqrt(e);
x1 = (-b + d) / (2. * a);
x2 = (-b - d) / (2. * a);
printf("\nx1 = %12.3e x2 = %12.3e\n", x1, x2);
}
else
{
/* Case of complex roots */
d = sqrt(-e);
x1 = -b / (2. * a);
x2 = d / (2. * a);
printf("\nx1 = (%12.3e, %12.3e) x2 = (%12.3e, %12.3e)\n",
x1, x2, x1, -x2);
}
return 0;
}
Page 71
In C programming, one of the frequently arising problem is to handle similar types of data. For
example: If the user want to store marks of 100 students. This can be done by creating 100
variable individually but, this process is rather tedious and impracticable. These type of problem
can be handled in C programming using arrays.
An array is a collection of similar data items that are stored under a common name.
A value in an array is identified by index or subscript enclosed in square brackets with
array name.
An array is used to store large amount of data of similar data types.
Example:
int abc[50];
float xyz[20];// It can store 20 floating point items under a common name xyz.
Arrays can be classified into
1. One-dimensional arrays
2. Two dimensional arrays
3. Multi dimensional arrays
1.One Dimensional array (1D Array)
The collection of data items can be stored under a one variable name using only one
subscript; such a variable is called one dimensional array.
Declaration of one-dimensional array:
data_type array_name[array_size];
For example:
int age[5];
Here, the name of array is age. The size of array is 5,i.e., there are 5 items(elements) of array
age. All elements in an array are of the same type (int).
Array elements
Size of array defines the number of elements in an array.
Elements in the age array storage location are shown in figure.
Page 72
Note that, the first element is numbered 0, second element is numbered 1 and so on.
Initialization of one-dimensional array:
The array can be initialized in the following two ways.
1. At Compile time
2. At run time
1. Initialization during compile time
Syntax:
Example:
int a[5];
for (i=0;i<5;i++)
{
printf( enter the values for a[%d],i);
scanf(%d,&a[i]);
}
Example program to find average marks obtained by a class of 30 students in a test.
main( )
{
Page 73
Datatype arrayname[rowsize][columnsize];
Example:
int A[3][3]={11,12,13,14,15,16,17,18,19}
Element 11 can be referred as A[0][0]
Element 12 can be referred as A[0][1]
Element 13 can be referred as A[0][2]
Element 14 can be referred as A[1][0]
Element 15 can be referred as A[1][1] and so on.
Another way to define 2-D array is:
int A[3][3]={
{11,12,13},
{14,15,16},
{17,18,19}
}
The above mentioned method increases the readability of the matrix.
}
3. Multi dimensional array (3D Array)
data_type array_name[d1][d2][d3][d4][dn]; //Where dn is the size of last
dimension.
Example:
int table[5][5][20];
float arr[5][6][5][6][5];
String
The way a group of integers can be stored in an integer array, similarly a group of
characters can be stored in a character array. Character arrays are many a time also called
strings.
Character arrays or strings are used by programming languages to manipulate text such as
words and sentences.
A string constant is a one-dimensional array of characters terminated by a null ( \0 ).
For example,
char name[ ] = { 'H', 'A', 'E', 'S', 'L', 'E', 'R', '\0' } ;
A string is a array of characters. Any group of characters(except the double quote
sign)defined between double quotation marks is a constant string.
Eg: Man is obviously made to think
/* Program to demonstrate printing of a string */
main( )
{
char name[ ] = "Klinsman" ;
inti = 0 ;
while ( i<= 7 )
{
printf ( "%c", name[i] ) ;
i++ ;
}
}
And here is the output...
Klinsman
Page 77
A string variable is any valid C variable name and is always declared as an array.
Eg:
char city[10];
char name[30];
When the compiler assigns a character string to a character array, it automatically supplies a null
character (\0) at the end of the string. Therefore, the size should be equal to the maximum
number of characters in the string plus one.
String operations
String.h header file supports all the string functions in C language. All the string functions are
given below.
S.no String functions Description
1
strcat(str1, str2)
strlen(strl)
strcmp(str1, str2)
Returns 0 if str1 is same as str2. Returns <0 if strl< str2. Returns >0 if
str1 > str2.
strcmpi(str1,str2)
strrev()
strlwr()
strupr()
strset()
10
11
strrchr()
12
strstr(str1, str2)
13
strdup()
14
strncat()
15
strncpy()
16
strtok()
17
strncmp()
18
strncmpi()
19
strnset()
Strlen() function
The strlen() is used to find the length of a string. The input can be a string literal constant
or a character array holding a string or a character pointer pointing to a string.
Syntax : strlen(string);
Example program:
#include<stdio.h>
#include<string.h>
void main()
{
char str[20] = hello;
printf(length of the string is :%d,strlen(str));
printf(length of the string is :%d,strlen(welcome);
}
Page 79
Output is
length of the string is: 5
length of the string is:7
strcpy() function
The strcpy() function copies the source string to the destination string.
Syntax : strcpy(deststring, srcstring);
#include<stdio.h>
#include<string.h>
void main()
{
char str1[20] = hello;
char str2[20];
strcpy(str2,str1);
printf(source string is :%s,str1);
printf(destination string is :%s,str2);
}
Output is
source string is: hello
destination string is:hello
strcat() function
The strcat function concatenates one string with another. It appends a source string to the
destination string.
Syntax : strcat(deststring, srcstring);
#include<stdio.h>
#include<string.h>
void main()
{
char str1[20] = hello;
char str2[20] =world
strcat(str1,str2);
Page 80
void main()
{
char str[20] = hello;
printf(reverse string is :%s,strrev(str));
}
Output is
reverse string is : olleh
strlwr() function
The strlwr function converts all the letters in a string to lowercase.
Syntax : strlwr(string);
Example program:
#include<stdio.h>
#include<string.h>
void main()
{
char str[20] = HELLO;
printf(reverse string is :%s,strlwr(str));
}
Output is
Lower case is : hello
strupr() function
The strupr function converts all the letters in a string to uppercase.
Syntax : strupr(string);
Example program:
#include<stdio.h>
#include<string.h>
void main()
{
char str[20] = hello;
printf(reverse string is :%s,strupr(str));
}
Page 82
Output is
Upper case is : HELLO
strset() function
The strset function sets all characters in a string to a specific character.
Syntax : strset(string, char);
Example program:
#include<stdio.h>
#include<string.h>
void main()
{
char str[20] = hello;
char a=*;
strset(str,a)
puts(str)
}
Output is
*****
strchr() function
The strchr function scans a string in the forward direction for the first occurrence of a
given character. If the character is found, it returns a pointer. If the character is not
found it returns NULL.
Page 83
char str[20]=welcome;
char a=o;
strrchr(str,a);
strstr() function
The strstr function finds the first occurrence of a string in another string. If the string is
found, it returns a pointer. If the string is not found it returns NULL.
Syntax : strstr(string1,string2);
Example :
strcmpi(str1,str2)
strncat(str1,str2,n)
strncpy(str1,str2,n)
strncmp(str1,str2,n)
str1=hello, str2=krishna
n=5
O/P : hellokrish
Sets the first n characters of the strings to str1=apple char =&, n=3
the character
O/P : &&&le
Example program
Page 84
#include<stdio.h>
#include<string.h>
int main ()
{
char str1[12]="Hello";
char str2[12]="World";
char str3[12];
intlen;
/* copy str1 into str3 */
strcpy(str3, str1);
printf("strcpy( str3, str1) : %s\n", str3 );
/* concatenates str1 and str2 */
strcat( str1, str2);
printf("strcat( str1, str2): %s\n", str1 );
/* total lenghth of str1 after concatenation */
len=strlen(str1);
printf("strlen(str1) : %d\n",len);
return0;
}
String Arrays
Strings are declared in C in similar manner as arrays. Only difference is that, strings are
of char type.
Eg: char s[5];
Page 85
Sorting:
Sorting is a technique to rearrange the elements of a list in ascending or descending can be done
on names, numbers and records.
Types of Sorting:
Page 86
Selection sort
Bubble sort
Insertion sort
Merge sort
Quick sort
Shell sort
Radix sort
Selection sort:
In this technique, the first element is selected and compared with all other elements. If
any other element is less than the first element swapping should take place.
By the end of this comparison, the least element most top position in the array. This is
known as pass1.
In pass II, the second element is selected and compared with all other elements.
Swapping takes place if any other element is less than selected element.
Bubble sort
This technique compares last element with the preceding element. If the last element is
less than that of preceding element swapping takes place.
Then the preceding element is compared with that previous element. This process
continuous until the II and I elements are compared with each other. This is known as
pass 1.
Insertion sort
In this method, sorting is done by inserting elements into an existing sorted list.
Initially, the sorted list has only one element. Other elements are gradually added into the
list in the proper position.
Merge sort
In this method, the elements are divided into partitions until each partition has sorted
elements.
Then, these partitions are merged and the elements are properly positioned to get a fully
sorted list.
Quick sort
Page 87
In this method, an element called pivot is identified and that element is fixed in its place
by moving all the elements less than that to its left and all the elements greater than that
to its right.
Shell sort
It generalized as exchanging sort, such as bubble or insertion sorting, by allowing the
comparison and exchange of elements that lie far apart.
Radix sort
In this method, sorting is done based on the place values of the number. In this scheme,
sorting is done on the less-significant digits first.
When all the numbers are sorted on a more significant digit, numbers that have the same
digit in that position but different digits in a less-significant position are already sorted on
the less-significant position.
arr[k]=arr[k+i];
arr[k+i]=tmp;
}
}
}
}
printf("\t**** Shell Sorting ****\n");
for(k=0; k<num; k++)
printf("%d\t",arr[k]);
getch();
return 0;
}
Output:
Enter total no. of elements : 7
Enter 1 number : 8
Enter 2 number : 3
Enter 3 number : 7
Enter 4 number : 9
Enter 5 number : 1
Enter 6 number : 24
Enter 7 number : 2
**** Shell Sorting ****
1 2 3 7 8 9 24
Program to example of bubble sorting
#include<stdio.h>
#include<conio.h>
#define SIZE 7
int main()
{
int i,j,temp;
int arr[ SIZE ];
for(i=0; i<SIZE; i++)
{
printf("Enter Number : ");
scanf("%d",&arr[i]);
}
for(i=0; i<SIZE ; i++)
{
Page 89
min=i;
for(j=i+1; j<SIZE; j++)
if(arr[j]<arr[min])
min=j;
temp=arr[i];
arr[i]=arr[min];
arr[min]=temp;
}
printf("After selection sort the elements:\n");
for(i=0; i<SIZE; i++)
printf("%d\t",arr[i]);
getch();
return 0;
}
Output:Enter element : 21
Enter element : 3
Enter element : 45
Enter element : 87
Enter element : 72
Enter element : 14
Enter element : 54
Enter element : 75
Enter element : 44
Enter element : 5
After selection sort the elements :
3 5 14 21 44 45 54 72 75 87
scanf("%d", &size);
for(i=0; i<size; i++)
{
printf("Enter %d element : ",i+1);
scanf("%d", &arr[i]);
}
for(i=0; i<size; i++)
{
for(j=i-1; j>=0; j--)
{
if(arr[j]>arr[j+1])
{
tmp=arr[j];
arr[j]=arr[j+1];
arr[j+1]=tmp;
}
else
break;
}
}
printf("\n\t------- Insertion sorted elements -------\n\n");
for(i=0; i<size; i++)
printf(" %d",arr[i]);
getch();
return 0;
}
OUTPUT
Enter total no. of elements : 7
Enter 1 number : 8
Enter 2 number : 3
Enter 3 number : 7
Enter 4 number : 9
Enter 5 number : 1
Enter 6 number : 24
Enter 7 number : 2
**** Insertion sorted elements ****
1 2 3 7 8 9 24
#include<stdio.h>
#include<conio.h>
void qsort(int arr[20], int fst, int last);
int main()
{
int arr[30];
int i,size;
printf("Enter total no. of the elements : ");
scanf("%d",&size);
printf("Enter total %d elements : \n",size);
for(i=0; i<size; i++)
scanf("%d",&arr[i]);
qsort(arr,0,size-1);
printf("Quick sorted elements are as : \n");
for(i=0; i<size; i++)
printf("%d\t",arr[i]);
getch();
return 0;
}
void qsort(int arr[20], int fst, int last)
{
int i,j,pivot,tmp;
if(fst<last)
{
pivot=fst;
i=fst;
j=last;
while(i<j)
{
Page 93
int arr[30];
int i,size;
printf("\n\t------- Merge sorting method -------\n\n");
printf("Enter total no. of elements : ");
scanf("%d",&size);
for(i=0; i<size; i++)
{
printf("Enter %d element : ",i+1);
scanf("%d",&arr[i]);
}
part(arr,0,size-1);
printf("\n\t------- Merge sorted elements -------\n\n");
for(i=0; i<size; i++)
printf("%d ",arr[i]);
getch();
return 0;
}
void part(int arr[],int min,int max)
{
int mid;
if(min<max)
{
mid=(min+max)/2;
part(arr,min,mid);
part(arr,mid+1,max);
merge(arr,min,mid,max);
}
}
void merge(int arr[],int min,int mid,int max)
{
int tmp[30];
int i,j,k,m;
j=min;
m=mid+1;
for(i=min; j<=mid && m<=max ; i++)
{
if(arr[j]<=arr[m])
{
tmp[i]=arr[j];
j++;
Page 95
}
else
{
tmp[i]=arr[m];
m++;
}
}
if(j>mid)
{
for(k=m; k<=max; k++)
{
tmp[i]=arr[k];
i++;
}
}
else
{
for(k=j; k<=mid; k++)
{
tmp[i]=arr[k];
i++;
}
}
for(k=min; k<=max; k++)
arr[k]=tmp[k];
}
OUTPUT
-------Merge sorting method---------Enter the number of elements to sort: 5
Enter 1 element
: 65
Enter 2 element
: 87
Enter 3 element
: 35
Enter 4 element
: 21
Enter 5 element
: 10
------------Merge Sorted elements-----------10 21 35 65 87
Page 96
Searching
Searching is a programming technique that determines whether an element or a data item
is present in a list or not.
There are two types of searching
1. Linear search
2. Binary search
1. Linear search:
Linear search is also referred as sequential search, is the simplest searching technique.
The search begins at one end of the list and search for the required element one by one
until the element is found or till the end of the list is reached.
The linear search technique doesnt require that the data items in the list are to be in
sorted order.
/* program to search an element using linear search*/
#include<stdio.h>
#include<conio.h>
void main()
{
int list[20];
int size;
int pos,val,i;
clrscr();
printf("\nenter the size of the list");
scanf("%d",&size);
printf("\nEnter the elements one by one:");
for(i=0;i<size;i++)
{
scanf("%d",&list[i]);
}
printf("\nEnter the value to be searched");
scanf("%d",&val);
pos=-1;
for(i=0;i<size;i++)
{
if(val==list[i])
{
pos=i;
break;
}}
Page 97
if(pos!=-1)
printf("\n the element is found at %d location",pos+1);
else
printf ("\n search failed");
getch();
}
2.Binary search:
The binary search algorithm is one of the most efficient searching techniques, which
requires the list to be sorted in ascending order.
To search for an element in the list, the binary search algorithm splits the list and locates
the middle element of the list.
It is then compared with the search element. If the search element is less than the middle
element, the first part of the list is searched else the second part of the list is searched.
This process continues until the search element is equal to the middle element or the list
consists of only one element that is not equal to the searching element.
/* program to search an element using binary search*/
#include<stdio.h>
#include<conio.h>
void main()
{
int first,last,middle,size,val,pos,i;
int list[20];
printf("\nenter the size of the list");
scanf("%d",&size);
printf("\nEnter the elements one by one in sorted order:");
for(i=0;i<size;i++)
scanf("%d",&list[i]);
printf("\nEnter the value to be searched");
scanf("%d",&val);
pos=-1;
first=0;
last=size-1;
while((first<=last)&&(pos==-1))
{
middle=(first+last)/2;
if(list[middle]==val)
{
Page 98
pos=middle;
break;
}
else if(list[middle]<val)
first=middle+1;
else
last=middle-1;
}
if(pos!=-1)
printf("\n the value found at %d position",pos+1);
else
printf("\n the value not found");
}
Matrix operation:
The program gives an idea to add two matrices.
#include<stdio.h>
#include<conio.h>
void main()
{
int r=0,c=0,j,i,matrix1[100][100],matrix2[100][100],sum[100][100];
clrscr();
printf("Enter the number of rows\n");
scanf("%d",&r);
printf("Enter the number of columns\n");
scanf("%d",&c);
printf("1st matrix values\n");
for(i=0;i<r;i++)
{
printf("Enter the elements in row %d\n",i+1);
for(j=0;j<c;j++)
scanf("%d",&matrix1[i][j]);
}
printf("2nd matrix values\n");
for(i=0;i<r;i++)
{
printf("Enter the elements in row %d\n",i+1);
Page 99
for(j=0;j<c;j++)
scanf("%d",&matrix2[i][j]);
}
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
sum[i][j]=matrix1[i][j]+matrix2[i][j];
}
}
printf("\n1st matrix is\n");
for(i=0;i<r;i++)
{
printf("\n");
for(j=0;j<c;j++)
{
printf("%d\t",matrix1[i][j]);
}
}
printf("\n2nd matrix is\n");
for(i=0;i<r;i++)
{
printf("\n");
for(j=0;j<c;j++)
{
printf("%d\t",matrix2[i][j]);
}
}
printf("\nthe sum is\n");
for(i=0;i<r;i++)
{
printf("\n");
for(j=0;j<c;j++)
{
printf("%d\t",sum[i][j]);
}
}
getch();
}
Page 100
Output:
Enter the number of rows
3
Enter the number of columns
3
1st matrix values
Enter the elements in row 1
1
2
3
Enter the elements in row 2
4
5
6
Enter the elements in row 3
7
8
9
2nd matrix values
Enter the elements in row 1
2
4
5
Enter the elements in row 2
1
2
1
Enter the elements in row 3
3
1
4
1st matrix is
1 2 3
4 5 6
7 8 9
2nd matrix is
Page 101
4
2
1
5
1
4
The sum is
3 6
8
5 7
7
10 9 13
Matrix Multiplication:
#include<stdio.h>
#include<conio.h>
void main()
{
int r1,c1,r2,c2,j,i,matrix1[100][100],matrix2[100][100],mul[100][100],sum=0,k;
clrscr();
printf("Enter the number of rows of 1st matrix\n");
scanf("%d",&r1);
printf("Enter the number of columns of 1st matrix\n");
scanf("%d",&c1);
printf("Enter the number of rows of 2nd matrix\n");
scanf("%d",&r2);
printf("Enter the number of columns of 2nd matrix\n");
scanf("%d",&c2);
if(r1==c2||c1==r2)
{
printf("1st matrix values\n");
for(i=0;i<r1;i++)
{
printf("Enter the elements in row %d\n",i+1);
for(j=0;j<c1;j++)
scanf("%d",&matrix1[i][j]);
}
printf("2nd matrix values\n");
for(i=0;i<r2;i++)
{
printf("Enter the elements in row %d\n",i+1);
for(j=0;j<c2;j++)
scanf("%d",&matrix2[i][j]);
}
Page 102
for(i=0;i<r1;i++)
{
for(j=0;j<c2;j++)
{
for(k=0;k<r2;k++)
{
sum=sum+matrix1[i][k]*matrix2[k][j];
}
mul[i][j]=sum;
sum=0;
}
}
printf("\n1st matrix is\n");
for(i=0;i<r1;i++)
{
printf("\n");
for(j=0;j<c1;j++)
{
printf("%d\t",matrix1[i][j]);
}
}
printf("\n2nd matrix is\n");
for(i=0;i<r2;i++)
{
printf("\n");
for(j=0;j<c2;j++)
{
printf("%d\t",matrix2[i][j]);
}
}
printf("\nthe product is\n");
for(i=0;i<r1;i++)
{
printf("\n");
for(j=0;j<c2;j++)
{
printf("%d\t",mul[i][j]);
}
}
}
Page 103
else
{
printf("The matrices cannot be multiplied\n");
}
getch();
}
Output:
Transpose of a matrix:
#include<stdio.h>
Page 104
#include<conio.h>
void main()
{
int r=0,c=0,j,i,matrix[100][100],transpose[100][100];
clrscr();
printf("Enter the number of rows\n");
scanf("%d",&r);
printf("Enter the number of columns\n");
scanf("%d",&c);
printf("Enter numbers");
for(i=0;i<r;i++)
{
printf("Enter the elements in row %d\n",i+1);
for(j=0;j<c;j++)
scanf("%d",&matrix[i][j]);
}
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
transpose[j][i]=matrix[i][j];
}
}
printf("\nthe matrix is\n");
for(i=0;i<r;i++)
{
printf("\n");
for(j=0;j<c;j++)
{
printf("%d\t",matrix[i][j]);
}
}
printf("\nthe transpose matrix is\n");
for(i=0;i<c;i++)
{
printf("\n");
for(j=0;j<r;j++)
{
printf("%d\t",transpose[i][j]);
}
Page 105
}
getch();
}
Output:
UNIT IV
FUNCTIONS AND POINTERS
Function - definition of function - Declaration of function - Pass by value - Pass by reference Recursion - Pointers - Definition - Initialization - Pointers arithmetic - Pointers and arraysExample Problems.
Functions:
Types of C functions
Basically, there are two types of functions in C on basis of whether it is defined by user or not.
Page 106
Library function
User defined function
Library function
Library functions are the in-built function in C programming system. For example:
main()
- The execution of every C program starts from this main() function.
printf()
- prinf() is used for displaying output in C.
scanf()
- scanf() is used for taking input in C.
Page 107
Function definition
Function definition contains programming codes to perform specific task.
S yn t ax of fu n ct i on defi n i t i on
return_type function_name(type(1) argument(1),..,type(n) argument(n))
{
//body of function
}
Page 108
Arguments that are passed in function call and arguments that are accepted in function
definition should have same data type. For example:
If argument num1 was of int type and num2 was of float type then, argument variable
a should be of type int and b should be of type float,i.e., type of argument during function
call and function definition should be same.
A function can be called with or without an argument.
Return Statement
Return statement is used for returning a value from function definition to calling function.
Page 109
Function declaration:
Every function in C programming should be declared before they are used. These type of
declaration are also called function prototype. Function prototype gives compiler information
about function name, type of arguments to be passed and return type.
Syntax of function prototype
return_type function_name(type(1) argument(1),....,type(n) argument(n));
In the above example, int add(int a, int b); is a function prototype which provides following
information to the compiler:
1. name of the function is add()
2. return type of the function is int.
3. two arguments of type int are passed to function.
Function prototype are not needed if user-definition function is written before main()function.
Function call
Control of the program cannot be transferred to user-defined function unless it is called invoked.
Syntax of function call
function_name(argument(1),....argument(n));
In the above example, function call is made using statement add(num1,num2); frommain(). This
make the control of program jump from that statement to function definition and executes the
codes inside that function.
Page 110
I am in argentina
Eg:3
main( )
{
printf ( "\nI am in main" ) ;
italy( ) ;
printf ( "\nI am finally back in main" ) ;
}
italy( )
{
printf ( "\nI am in italy" ) ;
brazil( ) ;
printf ( "\nI am back in italy" ) ;
}
brazil( )
{
printf ( "\nI am in brazil" ) ;
argentina( ) ;
}
argentina( )
{
printf ( "\nI am in argentina" ) ;
}
Output:
I am in main
I am in italy
I am in brazil
I am in argentina
I am back in Italy
I am finally back in main
Depending up on their inputs (parameters) and outputs (return) functions are classified
into 4 types:
All C functions can be called either with arguments or without arguments in a C program.
These functions may or may not return values to the calling function.
1. C function with arguments (parameters) and with return value
2. C function with arguments (parameters) and without return value
Page 112
syntax
void function();
function();
without arguments and without void function()
return values
{
statements;
}
// function declaration
// function call
// function definition
with arguments
return values
and
// function declaration
// function call
// function definition
// function declaration
// function call
// function definition
Note:
o
o
If the return data type of a function is void, then, it cant return any values to
the calling function.
If the return data type of the function is other than void such as int, float, double
etc, then, it can return values to the calling function.
Page 113
scanf(%d%d,&a,&b);
printsum(a,b);
printf(enter a and b again:);
scanf(%d%d,&a,&b);
printsum(a,b);
}
void printsum(intx,int y)
{
printf(sum is %d,x+y);
}
Output: enter a and b: 4 5
sum is 9
enter a and b again: 6 5
sum is 11
#include<stdio.h>
void printsum(int,int);
// function prototype
void main()
{
inta,b;
printf(enter the value of a and b);
scanf(%d%d,&a,&b);
printsum(a,b);
//function call
}
void printsum(int x, int y) //function definition
{
printf("sum of a and b is %d, x+ y);
}
3.Example program for without arguments & with return value:
#include<stdio.h>
intprintsum();
// function prototype
void main()
{
int sum;
sum=printsum();
//function call
printf("sum is %d, sum);
Page 115
}
int printsum() //function definition
{
inta,b,c;
printf(enter the value of a and b);
scanf(%d%d,&a,&b);
c=a+b;
return (c);
}
Pass by value:
o
o
o
In call by value method, the value of the variable is passed to the function as
parameter.
The value of the actual parameter cannot be modified by formal parameter.
Different Memory is allocated for both actual and formal parameters. Because,
value of actual parameter is copied to formal parameter.
Pass by reference:
o
o
o
In call by reference method, the address of the variable is passed to the function as
parameter.
The value of the actual parameter can be modified by formal parameter.
Same memory is used for both actual and formal parameters since only address is
used by both parameters.
Page 117
#include <stdio.h>
/* function declaration goes here.*/
void swap( int *p1, int *p2 );
int main()
{
int a = 10;
int b = 20;
printf("Before: Value of a = %d and value of b = %d\n", a, b );
swap( &a, &b );
printf("After: Value of a = %d and value of b = %d\n", a, b );
}
void swap( int *p1, int *p2 )
{
int t;
t = *p2;
*p2 = *p1;
*p1 = t;
printf("Value of a (p1) = %d and value of b(p2) = %d\n", *p1, *p2 );
}
Here is the result produced by the above example. Here the values of a and b are changes after
calling swap function.
Before: Value of a = 10 and value of b = 20
Value of a (p1) = 20 and value of b(p2) = 10
After: Value of a = 20 and value of b = 10
Recursion
A function that calls itself is known as recursive function and the process of calling function
itself is known as recursion
//recursion to find the factorial of a number
#include<stdio.h>
int fact(int)
//function prototype
void main()
Page 118
{
int no, factorial;
printf(enter the number);
scanf(%d,&no);
factorial=fact(no);
printf(factorial of %d is %d, no, factorial);
}
int fact(int no)
//function definition
{
if(no==1)
return 1;
else
return no*fact(no-1);
}
Output:
Enter the number 3
Factorial of 3 is 6
Classification of recursion:
Whether the function calls itself directly (i.e. direct recursion) or indirectly (i.e. indirect
recursion)
If any pending operation in return, then it is called non tail recursion. If there is no
pending operation in return, then it is called tail recursion.
According to the pattern of recursive calls(number of recursive call), recursion classified
as
a. Linear recursion it makes only one recursive call
b. Binary recursion it calls itself twice. It use the concept of binary tree
c. n-ary recursion it calls itself N times. N is not a constant number. It depends
upon the parameter.
Direct recursion:
The call for the original function is directly available in the body of the function itself.
A()
{
show ();
}
void show ()
{
printf ("%d",s);
s++;
main();
}
OUTPUT
01234
Tail recursion:
Tail recursion is a special case of recursion in which the last operation of a function is a
recursive call.
In a tail recursive function, there are no pending operations to be performed on return
from a recursive call.
Pointers:
Definition:
Consider the following statement:
Page 122
During execution of the program, the system always associates the name quantity with
the address 5000. To access the value 179 we use either the name quantity or the address
5000.
Since memory addresses are simply numbers, they can be assigned to some variables
which can be stored in memory, like any other variable.
Such variables that hold memory addresses are called pointers. A pointer is, therefore,
nothing but a variable that contains an address which is a location of another variable in
memory.
Syntax
Data_type *var-name;
Ex:
int *ip; /* pointer to an integer */
double *dp; /* pointer to a double */
float *fp; /* pointer to a float */
char *ch /* pointer to a character */
Example program
#include <stdio.h>
int main()
{
int *ptr, q;
q = 50;
/* address of q is assigned to ptr
ptr = &q;
*/
Page 123
Initialization:
Pointer variables contain addresses that belong to a separate data type, which must be declared as
pointers before we use them. The declaration of the pointer variable takes the following form:
data type *pt _name;
This tells the compiler three things about the variable pt _name:
1. The asterisk(*) tells that the variable pt _name.
2. pt _name needs a memory location.
3. pt_name points to a variable of type data type.
Example:
int *p;
float *x;
Once a pointer variable has been declared, it can be made to point to a variable using an
assignment operator such as
p= &quantity;
Before a pointer is initialized it should not be used.
Ensure that the pointer variables always point to the corresponding type of data.
Example:
float a, b;
int x, *p;
p = &a;
b = *p;
This will result in erroneous output because we are trying to assign the address of a float
variable to an integer pointer.
When we declare a pointer to be of int type, the system assumes that any address that a
pointer will hold will point to an integer variable.
Assigning an absolute address to a pointer variable is prohibited. The following is wrong.
int *ptr;
Page 124
.
ptr = 5368;
.
.
A pointer variable can be initialized in its declaration itself. For example,
int x, *p = &x;
is perfectly valid. It declares x as an integer variable and p as a pointer variable and then
initializes p to the address of x.
The statement int *p = &x, x; is not valid.
Float *ptr;
Ptr - 2; //if ptr is 2000 then final value of ptr is 2000-(2*4)=1992.
Int *ptr1;
Ptr1-10; //if ptr is 2000 then final value of ptr1 is 2000 -(10*2)=1980.
Relational (comparison) operation:
A pointer can be compared with a pointer of the same type. It gives Boolean value as the
result.
result =ptr1!= ptr2;
result=p1<p2;
p2=2000 result is 0;
//result =1
//if p1=2000 and p2=2004 result is 1; if p1=2004 and
resultp2==p1;
Illegal pointer operations:
Void pointer is a generic pointer and it can hold address of any type of object.
Void is one of the basic data types available in C .
void *ptr;
int a=10;
float b = 10.2;
ptr = &a; // ptr holds address of integer variable a
ptr =&b // ptr holds address of float variable b
Null pointer:
A Null pointer is a special pointer that does not point anywhere.
It does not hold the address of any object or function. It has numeric value 0.
Page 126
int *ptr=0;
int *ptr=NULL;
When a null pointer is compared with any other pointer the result is always false.
Two null pointers always compare equal.
Dereferencing a null pointer leads to a runtime error.
The name x is defined as a constant pointer pointing to the first element x[0] and therefore value
of x is 1000, the location where x[0] is stored . That is ,
x = &x[0] =1000
x; sum =
0;
printf(Element Value Address \n\n);
while(i< 5)
{
printf( x[%d} %d %u\n, i, *p, p);
sum = sum + *p;
i++, p++;
}
printf(\n Sum = %d \n, sum);
printf(\n &x[0] = %u \n, &x[0]);
printf(\n p = %u \n, p);
}
Output:
Element Value Address
X[0] 5 166
X[1] 9 168
X[2] 6 170
X[3] 3 172
X[4] 7 174
Sum = 55
&x[0] = 166
p = 176
Example Problems:
Example:1
main( )
{
int i = 3 ;
int *j ;
j = &i ;
printf ( "\nAddress of i = %u", &i ) ;
printf ( "\nAddress of i = %u", j ) ;
printf ( "\nAddress of j = %u", &j ) ;
printf ( "\nValue of j = %u", j ) ;
printf ( "\nValue of i = %d", i ) ;
printf ( "\nValue of i = %d", *( &i ) ) ;
printf ( "\nValue of i = %d", *j ) ;
Page 128
}
OUTPUT:
Address of i = 65524
Address of i = 65524
Address of j = 65522
Value of j = 65524
Value of i = 3
Value of i = 3
Value of i = 3
Example:2
main( )
{
int radius ;
float area, perimeter ;
printf ( "\nEnter radius of a circle " ) ;
scanf ( "%d", &radius ) ;
areaperi ( radius, &area, &perimeter ) ;
printf ( "Area = %f", area ) ;
printf ( "\nPerimeter = %f", perimeter ) ;
}
areaperi ( int r, float *a, float *p )
{
*a = 3.14 * r * r ;
*p = 2 * 3.14 * r ;
}
OUTPUT:
Enter radius of a circle 5
Area = 78.500000
Perimeter = 31.400000
Example 3: SWAPPING OF TWO NUMBERS
#include<stdio.h>
#include<conio.h>
void swap(int *,int *);
void swap1(int,int);
void main()
{
int a,b,c,d;
clrscr();
printf("Enter the values of a and b:= ");
scanf("%d %d",&a,&b);
Page 129
Introduction:
C Structure is a collection of different data types (heterogeneous data items) which are grouped
together under a single name and each element in a C structure is called member
Structure Definition:
Unlike arrays, structure must be defined first for their format that may be used later to declare
structure variables. Let us use an example to illustrate the process of structure definition and the
creation of structure variables. Consider a book database consisting of book name, author,
number of pages, and price. We can define a structure to hold this information as follows:
struct book _bank
{
char title[20];
char author[15];
int pages;
float price;
};
The keyword struct declares a structure to hold the details of four data fields, namely title,
author, pages, and price. These fields are called structure elements or members. Each member
may belong to different type of data. book _ bank is the name of the structure and is called the
Page 131
structure tag. The tag name may be used subsequently to declare variables that have the tags
structure.
There are three aspects of working with structures. They are:
1. Defining a structure
2. Declaring structure variables
3. Accessing structure members
Defining a structure:
Keyword struct is used to define a structure. The keyword struct define a new datatype
which is a collection of different type of data.
The general syntax for creating a structure is,
struct structure_name
{
datatype variable1;
datatype variable2;
.
.
datatype variablen;
};
The name of the structure is known as structure tag. The variables inside the structure are known
as structure elements or members.
Eg.
struct book
{
char name[10];
int price;
int pages;
};
Here, book is the name of the structure / structure tag. name, price and pages are known as
structure elements or members.
int pages;
};
void main()
{
struct book b;
b.name=computer;
b.price=300;
b.pages=400;
printf(name is %s,b.name);
printf(price is %d,b.price);
printf(pages is %d,b.pages);
}
Output:
name is computer
price is 300
pages is 400
Arrays
Structures
3. Any array behaves like a built-in 3. But in the case of structure, first we
data types. All we have to do is to have to design and declare a data
declare an array variable and use it. structure before the variable of that
type are declared and used.
4.Array allocates static memory and 4.Structures allocate dynamic memory
uses index / subscript for accessing and uses (.) operator for accessing the
elements of the array.
member of a structure.
};
struct book
{
char name[10];
struct author a;
int price;
int pages;
};
void main()
{
struct book b={computer,allen,weiss,300,400};
printf(name is %s,b.name);
printf(author first name is %s,b.a.first_name);
printf(author last name is %s,b.a.last_name);
printf(price is %d,b.price);
printf(pages is %d,b.pages);
}
Output:
name is computer
pages is allen
author last name is weiss
price is 300
author first name is 400
Structure as function arguments:
We can pass a structure as a function argument in similar way as we pass any other
variable or array.
#include<stdio.h>
void display(struct);
struct book
{
char name[10];
int price;
int pages;
};
void main()
{
struct book b={computer, 300,400};
display(b);
Page 135
}
void display(struct book b)
{
printf(name is %s,b.name);
printf(price is %d,b.price);
printf(pages is %d,b.pages);
}
Output:
name is computer
price is 300
author first name is 400
Pointer to structure:
#include<stdio.h>
struct book
{
char name[10];
int price;
int pages;
};
void main()
{
struct book b={computer, 300,400};
struct book *p=&b;
printf(name is %s,*p.name);
printf(price is %d,*p.price);
printf(pages is %d,*p.pages);
}
Output:
name is computer
price is 300
author first name is 400
typedef and structures:
The keyword typedef is used to give alias name to pre-defined datatypes like int,float as
well as to user-defined datatypes like structure.
#include<stdio.h>
typedef struct book
{
Page 136
char name[10];
int price;
int pages;
};
void main()
{
book b={computer, 300,400};
printf(name is %s,b.name);
printf(price is %d,b.price);
printf(pages is %d,b.pages);
}
Output:
name is computer
price is 300
author first name is 400
Example programs:
1.C program for creating student record:
#include<stdio.h>
#include<conio.h>
struct name
{
char first_name[10];
char last_name[10];
};
typedef struct student
{
int rollno;
struct name a;
int m1,m2,m3;
float percent;
};
void main()
{
student s[20];
int i,n;
printf("enter the number of students:");
scanf("%d",&n);
for(i=0;i<n;i++)
{
Page 137
{
employee e[20];
int i,n;
printf("\n enter the number of employees:");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("\nEnter first name:");
scanf(%s,&e[i].a[i].first_name);
printf("\nEnter last name:");
scanf(%s,&e[i].a[i].last_name);
printf("\nEnter age:");
scanf("%d",&e[i].age);
printf("\nEnter Address:");
scanf(%s,&e[i].address);
printf("\nEnter Salary:");
scanf("%f",&e[i].salary);
}
for(i=0;i<n;i++)
{
printf("First Name of the Employee : %s ", e[i].a[i].first_name);
printf("last Name of the Employee : %s ", e[i].a[i].last_name);
printf("Age of the Employee : %d ", e[i].age);
printf("Address of the Employee : %s ", e[i].address);
printf("Salary of the Employee : %f ", e[i].salary);
}
}
C Union
C Union is also like structure, i.e. collection of different data types which are grouped together.
Each element in a union is called member.
Union and structure in C are same in concepts, except allocating memory for their
members.
Structure allocates storage space for all its members separately.
Whereas, Union allocates one common storage space for all its members
Page 139
We can access only one member of union at a time. We cant access all member values at
the same time in union. But, structure can access all member values at the same time.
This is because; Union allocates one common storage space for all its members.
Whereas Structure allocates storage space for all its members separately.
union tag_name
{
data
type
var_name1; data
type
var_name2; data
type
var_name3; };
Syntax
union tag_name
{
data
type
data
type
data
type
};
Example
union student
{
int
char
float
};
Declaring
union variable
Initializing
union variable
Accessing
union members
report.mark
report.name
report.average
union student
{
mark; int
name[10]; char
average; float
};
var_name1;
var_name2;
var_name3;
mark;
name[10];
average;
report
->
report
->
report -> average
mark
name
float percentage;
};
int main()
{
union student record1;
union student record2;
// assigning values to record1 union variable
strcpy(record1.name, "Raju");
strcpy(record1.subject, "Maths");
record1.percentage = 86.50;
printf("Union record1 values example\n");
printf(" Name
: %s \n", record1.name);
printf(" Subject : %s \n", record1.subject);
printf(" Percentage : %f \n\n", record1.percentage);
// assigning values to record2 union variable
printf("Union record2 values example\n");
strcpy(record2.name, "Mani");
printf(" Name : %s \n", record2.name);
strcpy(record2.subject, "Physics");
printf(" Subject : %s \n", record2.subject);
record2.percentage = 99.50;
printf(" Percentage : %f \n", record2.percentage);
return 0;
}
Output:
Union record1 values example
Name
:
Subject
:
Percentage : 86.500000
Union record2 values example
Page 141
Name
:
Mani
Subject
:
Physics
Percentage : 99.500000
Example program Another way of declaring C union:
In this program, union variable record is declared while declaring union itself as shown in
the below program.
#include <stdio.h>
#include <string.h>
union student
{
char name[20];
char subject[20];
float percentage;
}record; //member created while declaring a union
void main()
{
strcpy(record.name, "Raju");
strcpy(record.subject, "Maths");
record.percentage = 86.50;
printf(" Name
: %s \n", record.name);
printf(" Subject : %s \n", record.subject);
printf(" Percentage : %f \n", record.percentage);
}
Output:
Name
:
Subject
:
Percentage : 86.500000
Difference between structure and union in C:
S.no C Structure
C Union
Structure occupies
memory space.
We can access all members of We can access only one member of union at a time.
higher
Page 142
structure at a time.
Structure example:
struct student
{
int mark;
char name[6];
double average;
};
Union example:
union student
{
int mark;
char name[6];
double average;
};
2B
char
name[6]
6B
double average 8B
Total memory allocation =
2+6+8 = 16 Bytes
Storage classes:
Storage class specifiers in C language tells the compiler where to store a variable, how to
store the variable, what is the initial value of the variable and life time of the variable.
Syntax: storage_specifier data_type variable _name;
There are four storage classes in C:
(a) Automatic storage class
(b) Register storage class
(c) Static storage class
(d) External storage class
S.No. Storage
Specifier
Storage
place
auto
extern
CPU
Memory
CPU
memory
static
CPU
memory
Initial
default
value
Garbage
value
Zero
Zero
/ Scope Life
register
Register
memory
Garbage
value
Sum of Numbers : 5
Static storage class:
Static variables have static (global) life time.
It will be stored in main memory.
It will take both in the local scope and global scope
Its initialized automatically by 0 for static int type and 0.0 for static float type and \0
for char.
If static variable is present inside the local scope, the variable is initialized only once.
The features of a variable defined to have a static storage class are as under:
Storage Memory.
Default initial value Zero.
Scope Local to the block in which the variable is defined.
Life Value of the variable persists between different function calls.
#include<stdio.h>
void fun();
void main(){
int i=0;
for(i=0;i<3;i++)
{
fun();
}
}
void fun()
{
static int a=10;
int b=20;
printf(a = %d,a);
printf(++a = %d,++a);
printf(b = %d,b);
printf(++b = %d,++b);
}
Output:
a =10
++a = 11
b=20
++b=21
a =11
Page 146
++a = 12
b = 20
++b =21
difference between the automatic and static storage classes.
The extern storage class:
A variable that is declared outside any function (i.e. before main function) is by default
an external variable. External variables are also known as global variables.
Global variables remain available throughout the entire program.
The extern storage class specifier cannot be used in the parameter declaration either in the
function declaration or function definition.
The features of a variable whose storage class has been defined as external are as follows:
Storage Memory.
Default initial value Zero.
Scope Global.
Life As long as the programs execution doesnt come to an end.
Eg:
#include<stdio.h>
int num = 75 ;
void display();
void main()
{
printf("Num : %d",num);
display();
}
void display()
{
printf("Num : %d",num);
}
Output:
Num :75
Num :75
Eg:
int i ;
main( )
Page 147
{
printf ( "\ni = %d", i ) ;
increment( ) ;
increment( ) ;
decrement( ) ;
decrement( ) ;
}
increment( )
{
i=i+1;
printf ( "\non incrementing i = %d", i ) ;
}
decrement( )
{
i=i-1;
printf ( "\non decrementing i = %d", i ) ;
}
The output would be:
i=0
on incrementing i = 1
on incrementing i = 2
on decrementing i = 1
on decrementing i = 0
Pre-processor directives:
Translators convert a high level language program into an equivalent machine level
language program. Compiler is not the only translator that works before the execution of a
program.
The preprocessor is another translator that works and processes the source code before it
is given to the compiler. It operates under the control of commands known as preprocessor
directives.
The preprocessor is used to include the header files, macro expansions, conditional
compilation, and line control.
The important points for writing a pre-processor directives are as follows:
1. The pound symbol (#) should be the first character in a source file.
2. A new-line character ends the pre-processor directive.
3. The preprocessor directives can appear anywhere in a program but are generally placed at
the beginning of a program before the main function.
Page 148
b.#undef:
The undef pre-processor directive causes the specified identifier to be no longer defined
as a macro-name.
Syntax: #undef identifier
#include<stdio.h>
#define pi 3.14
#undef pi
void main(){
int rad=5;
float c;
c=pi*r*r;
printf(c=%f,c);
}
Output:
Compilation error undefined symbol pi
2.Source file inclusion directive:
It tells the preprocessor to replace the directive with the content of the file specified in the
directive. it is used to include the header files, which contains the prototypes of the library
functions.
eg. #include<stdio.h>
3.line directive:
The line directive is used to reset the line number and the file name as reported by
_ _LINE_ _ and _ _FILE_ _ macros.
#include<stdio.h>
void main(){
printf(line no is %d, file name is %s,_ _LINE_ _,_ _FILE_ _);
#line 200
printf(line no is %d, file name is %s,_ _LINE_ _,_ _FILE_ _);
#line 100 abc.c
printf(line no is %d, file name is %s,_ _LINE_ _,_ _FILE_ _);
}
Output:
line no is 4, file name is line.c
line no is 200, file name is line.c
line no is 100, file name is abc.c
Page 150
4.error directive:
The error directive causes the preprocessor to generate the customized diagnostic
message and causes the compilation to fail.
#include<stdio.h>
#error this is a customized error
void main(){
printf(hi);
}
Output:
Compilation error
Fatal error.c 2:error directive: this is a customized error
5.pragma directive:
The pragma directive is used to specify the diverse options to the compiler.
Syntax: #pragma token-sequence
Some of the options are:
option
role
-C
Allow nested comments
-CDoes not allow nested comments
-r
Enables the use of register variables
-rSuppresses the use of register variables
#include<stdio.h>
#pragma option -C
void main(){
/*start of outer comment
/*inner comment*/
end of outer comment*/
printf(pragma);
}
Output:pragma
Note:If pragma directive is not used it will show an error.
6.Conditional compilation directive:
Conditional compilation means that a part of a program is compiled only if a certain
condition comes out to be true. Some of the Conditional compilation directives are #if, #ifdef,
#elif,#endif,#else.
#include<stdio.h>
Page 151
#define NUM 11
void main(){
#if((NUM%2)==0)
printf("\nNumber is Even");
#else
printf("\nNumber is Odd");
#endif
}
Output:
Number is odd
7.Null directive:
The null preprocessor directive is a single number sign (#) alone on a line. It has no
effect.
#include <stdio.h>
#
void main(){
puts("Hello, world!");
}
Output: Hello, world!
Page 152