Programmong With C
Programmong With C
Programming Fundamentals
1
Structure:
1. Introduction
2. Objectives
3. Presentation of Contents
3.1.1 Compiler
3.1.2 Interpreter
3.1.4 Assemblers
Algorithm Development
4. Summary
2
1. Introduction
program's structure. The coding stage is the translation of the program from flowcharts
necessary. What you are looking for are errors (bugs) in your program and you will
nearly always find some. The most common way to test for errors (often called
debugging or looking for and removing bugs) is to pass the program through a
translator program. The translator program expects the program to follow very rigid
syntactic rules. If this is not so the translator will send you an error message (ie. it will
tell you, by displaying a message on the screen, that you have made a syntax error).
For many languages, the translator examines the entire program at one time and
translates the program into a code that the machine can understand (machine code).
This lesson discusses about various programming language translators. This lesson also
discusses about the concept of problem solving and the various stages of program
detail.
2. Objectives
3
After working through this lesson you should be able to:
3. Presentation of Contents
Machine code i.e. 0’s and 1’s is the only language that a computer understands. People
language and High level languages. With the use of these languages, developers could
think about their programs in human terms rather than the computer terms. But for these
languages we need, translators that converts the humanlike instructions into strings of
numbers i.e. 0’1 and 1’s (machine code) that computers can understand. The most
3.1.1 COMPILER
Compiler is simply a translator. The Compiler takes source language and translates it into
to put ‘;’ at the end of the line, but error messages they get do not help them to find an
error.)
Disadvantages of Compilers
4. It is very difficult to test the program since the compiler execution file gives
5
Advantages of Compilers
3. It saves time since the code is compiled few number of times and executed many
times.
3.1.2 INTERPRETER
and also executes it. The main difference between compiler and interpreter is that
interpreters execute the source program directly and produces the program output, instead
An interpreter performs lexical and syntactic analysis functions just like compiler and
then translates the source program into an internal form. The internal form may also be a
sequence of quadruples. After translating the source program into an internal form,
Formally, an Interpreter is a program that takes program P written in some language and
input x to P. It translates P and runs it on x and than gives a resultant output of P on input
x. Interpreter is a translator plus virtual machine engine. The interpreter runs program “as
Program P
Interpreter Output of P on x
6
Input x to P
languages are particularly well suited to the use of interpreter. Compilers usually generate
calls to library routines to perform function such as I/O and complex conversion
translation. Most of the execution time for the standard program would be consumed by
the standard library routines. These routines would be the same, regardless of whether a
Advantages of Interpreters:
1. The Interpreters are very useful during program development process as program
Disadvantages of Interpreters:
2. The object program is not an optimized one and hence takes more memory and
7
3.1.3 COMPARISON OF COMPILER AND INTERPRETER
Interpreters Compilers
program into some internal form is program into some internal form is
is much slower.
trace of program execution related to the Debugging tools are required for trace
effectively using interpreter as the execution file gives the final result.
traced.
3.1.4. ASSEMBLER
8
An assembler is a translator that translates an Assembly language program into machine
programs translate the low-level language to the machine code. The translation job is
performed either manually or with a program called assembler. In hand assembly, the
programmer uses the set of instructions supplied by the manufacturer. In this case, the
hexadecimal code for the mnemonic instruction is searched from the code sheet. This
assemblers. The program called assembler provides the codes of the mnemonics. This
process is fast and facilitates the user in developing the program speedily. There are two
A One-pass Assembler performs all its functions by reading the source file once.
Any given problem can be solved by using the steps mentioned below. These steps are
called Program development life cycle. It is a systematic approach to solve any problem.
It breaks the jobs of solving a problem into manageable sub jobs in such a manner that
each sub job is successfully completed before moving to the next step. These sub jobs are
Problem Definition/Identification
Program Designing
9
Flow Charting , Decision Table, Decision Trees, Pseudo codes, Algorithm
Development
Program coding
Program Compilation
It is first step to solve any problem. Before doing any thing one must have a proper
understanding of the problem that what is the Problem? One must know what is the
output requirement of the particular problem and what type of input data will be required.
There should be very clear about input data, output formats, reports, execution time
requirement, user interfaces etc. Normally, this entire analysis and facts collection is done
by System Analysts and once the problem is properly understood, they provide the result
10
Fig. 1. Problem Identification and Analysis
For Small projects the programmer itself can do the job of analysts (Problem
Identification and analysis) during this phase System analysts do feasibility tests include
hardware and software feasibility etc. besides above stated jobs. For information
onsite observation and review of manuals, reports etc. Once the problem parts are
11
3.2.2 PROGRAM DESIGNING:
Once the problem is clearly understood its solution procedure is designed and all
alternatives are consulted. All types of input data, output formats and codes are designed
in this phase along with the groups of programmers or sub programmers to complete the
work. The complex or big problem is divided into smaller parts called modules.
Structured approaches like Top-down Approach, Bottom-Up Approach etc. are used for
it. Individual modules can be developed parallely or some times after completion of
previous modules. Team coordination and distribution of modules is also done in this
phase. Modules are easy to manage and if several modules are developed parallely it
takes less time to complete a project. Also error detection is easy in modules.
The main routine is identified and plans for modules are decided in this step. Language
best suited for project development is decided. Designing phase includes modular brake
ups input design, output design, code design and a conceptual plan for program
development.
12
Fig. 2. Program Design
ALGORITHM DEVELOPMENT
13
Fig. 3. Common Symbols of Flow Chart
contains information about what must be done at that point & the arrow shows the ‘flow
of execution’ of the algorithm, i.e., they show the order in which the instructions must be
executed. The purpose of using Flowcharts is to graphically present the logical flow of
data in the system and defining major phases of processing along with the various media
to be used.
a) System flowchart
b) Run flowchart
c) Program flowchart
14
(a) System Flowcharts: System flowchart describes the data flow for a data processing
system. It provides a logical diagram of how the system operates. It represents the flow of
documents and the operations performed in data processing system. It also reflects the
relationship between inputs, processing and outputs. Following are the features of system
flowcharts:
The sources from which data is generated and device used for this purpose
The intermediate and final output prepared and the devices used for their storage.
3. If num % 2 = = 0
6. Stop
15
Fig. 4. System Flowchart
(b) Run Flowchart: Run flowchart is used to represent the logical relationship of
computer routines along with inputs, master files transaction files, and outputs. Fig. 1.5
16
Fig. 5. Run Flowchart
(c) Program Flowcharts: A program flowchart represents, in detail, the various steps to
be performed within the system for transforming the input into output. The various steps
are logical/arithmetic operation, algorithms, etc. It serves as the basis for discussion and
communication between the system analyst and the programmer. Program flowcharts are
17
2. Decision Tables and Decision Trees: Decision tables and trees were developed long
before the widespread use of computers. They not only isolate many conditions and
possible actions but they help ensure that nothing has been overlooked.
(a) Decision Tables: The decision table is a chart with four sections listing all the
logical conditions and actions. In addition, the top section allows space for title,
date, author, system, and comment. These are discussed in more detail in Lesson
2.
(b) Decision Trees: The decision tree defines the conditions as a sequence of left to right
tests. A decision tree helps to show the paths that are possible in a design following an
action or decision by the user. These are discussed in more detail in Lesson 2.
3. Pseudo Codes: Pseudo code is a kind of structured English for describing algorithms.
It allows the designer to focus on the logic of the algorithm without being distracted by
details of language syntax. At the same time, the pseudo code needs to be complete. It
describes the entire logic of the algorithm so that implementation becomes a rote
In general the vocabulary used in the pseudo code should be the vocabulary of the
problem domain, not of the implementation domain. The pseudo code is a narrative for
someone who knows the requirements (problem domain) and is trying to learn how the
solution is organized.
of statements designed in such a manner that on execution the desired output is achieved.
18
It may be written in simple English like language. If it gives correct result then it is
During preparation of any program, firstly algorithm is prepared for it. Then algorithm is
computer program.
Algorithms written in simple English is called ‘Pseudo code’ and written in computer
reverse is not true. An algorithm is very important for any program. If it contains an error
or mistake, one has to recheck the algorithm and restart all process.
Normally the Programming Language for coding the program for any project is decided
in advance. When the algorithm is prepared and tested then it requires implementing
programming language. One must follow the Syntax and grammar of that particular
The names of program, subprogram and variables are chosen such that they are clear and
what steps performed what. Use meaningful variable names and meaningful program
name. Use easy logic for particular problem so that it is clear to all.
19
The process of translating an algorithm into a computer program by using computer
language is known as program coding. Once the program is coded it is handed over to
Compiling the program: After creating the program, it is compiled by compiler (Alt+F9
in C Language) if there is any type of syntax error then compiler shows the listing of
error with line number and if there is no error then it is compiled successfully means
source code converted into object code(machine code). In UNIX, program compiled by
cc abc.c
Linking and execution of Program: after compilation linking is done by linker (Ctrl+F9 in
Program Debugging: Once the program is ready they must be checked for any type of
errors. Normally a program can have following errors: Syntax Errors, Logical Errors and
Execution Errors.
Isolation of errors and removal of errors is known as debugging. You must know that an
error in computer program is known as bugs and the process of detecting and correcting
these errors is called debugging. It is a time consuming step. Syntax errors are easily
located by compiler but logical and execution errors do not. Thus debugging is performed
in this step.
20
Program Testing: After converted algorithm in to programming code. This
programming code called as source code. Source code converted into object code
(Machine code) by compilation process when there is no syntax error in the source code.
If there is any syntax error in the source code then source code does not convert in to
object code. When successfully compiled then source code converted into object code but
still there may be some logical errors which towards to undesired or wrong output. These
errors may cause due to wrong logic used in source code. That is why the program is
For testing a program some sample input data are taken and their output is calculated
manually. The same data are given as input to the program. The output is compared to the
manual output. If the result is OK, there are no logical errors in the program. But if output
is deviate or incorrect, it means there are some logical errors in the program. To locate
these errors in the program one has to go back to Algorithm and flowchart and try to
locate the problem. Correct them, recode the program, recompile it and test it again. The
same steps are repeated until output during resting of program becomes correct.
This is final and last phase of program development life cycle. Software installation
means to install or load the program at user’s site and train the user to use the software.
Provide proper training to the user of software for data entry and getting the output
reports. Some times user may encounter some errors that were not caught during program
testing and debugging. These errors are removed and the software is kept under watch
needs maintenance i.e. there may be some errors discovered by user during day to day
use which need removal and also some times there may be slight changes in user
requirement which can be made time to time. Backups of data files must be taken timely.
In Brief, it may need modification, removal of errors from time to time, reinstallation of
some or full software or data files in case of corruption and some time is may lead to a
charts, pseudo codes, Decision tables, algorithms, flowcharts, program names and their
description, system specifications, program listings, test data files and their fields with
complete details of each program, loading and unloading methods, data entry procedure,
System manual
Operational manual
There are four basic types of program errors. Your objective is to write programs that are
totally free of program errors. Program errors are also referred to as program bugs. Every
programmer, no matter how experienced, writes programs that contain errors. A skilled
programmer, however, can detect, isolate, and correct program errors more quickly than a
22
less skilled programmer. Also, experienced programmers do make fewer programming
errors simply because of their experience. In the beginning you will start off with the “
flat - forehead ” type of programming error. Those are the kind of errors that, when you
do find them, you slam the heel of your hand into your forehead while mumbling, “How
could I make such a silly mistake?” . View each program error as a challenge and learn
from the experience. While there will be fewer errors as you gain experience, those errors
you do make tend to become more sophisticated and harder to isolate and fix.
1. Syntax Errors: The first type of error is a syntax error. The syntax errors are caused
when you do not obey the syntax rules of a language. A common syntax rule you might
semicolon.
2. Logic Errors: Logic errors are those errors that remain after all the semantic and
syntax errors have been removed. Usually, logic errors evident, when the result the
program produces does not match the result your test data suggest it should produce.
Logic errors occur when you implement the algorithm for solving the problem
incorrectly.
The key to fixing logic errors is to be able to reproduce the error consistently. A
repeatable logic error is much easier to track down and fix than an error that appears to be
occurring randomly.
23
3. Semantic Errors: A semantic error occurs when you obey the syntax rules of the
language but are using the statement out of context. For example, a sentence in English is
expected to have a noun and a verb. Consider the sentence “ The dog meowed. ” This
sentence does obey the rules of having a noun and a verb, but the context of the sentence
is out of whack. Dogs do not meow, therefore the context of the statement is incorrect.
The error message, the name ‘i’ does not exist in the current context refers to a type of
semantic error. There may be a variable named i defined somewhere in the program, but
it is not currently in scope. That is, you are trying to use i when it is out of scope.
4. Runtime Errors: If the computer detects and reports an error message during the
execution of the program, we refer to this as a runtime error. In this case, the computer
will stop executing the program, and report the type of error along with its approximate
location. However, the system might misinterpret the problem in many cases and lead
4. Summary
The Compiler takes source language and translates it into an equivalent target language
program.
The main difference between compiler and interpreter is that interpreters execute the
source program directly and produces the program output, instead of translating it into
machine code.
24
Any given problem can be solved by using Program development life cycle. It is a
Problem definition is the first step to solve any problem. Before doing anything one must
Once the problem is clearly understood its solution procedure is designed and all
alternatives are consulted. All types of input data, output formats and codes are designed
in this phase along with the groups of programmers or sub programmers to complete the
work.
Isolation of errors and removal of errors is known as debugging. You must know that an
error in computer program is known as bugs and the process of detecting and correcting
charts, pseudo codes, Decision tables, algorithms, flowcharts, program names and their
description, system specifications, program listings, test data files and their fields with
complete details of each program, loading and unloading methods, data entry procedure,
security, special checks etc. Documentation includes three types of manuals: System
There are four basic types of program errors. These are Syntax Errors, Logic Errors
25
2. Dromey, R.G., “How to Solve it By Computer”, PHI
3. Jeri R. Hanly & Elliot P. Koffman, “Problem Solving and Program Design in C”,
Addison Wesley.
5. Leon, Alexis & Leon, Mathews, “Introduction to Computers”, Leon Tech World
answer.
26
Lesson 2
1
Structure:
1. Introduction
2. Objectives
3. Presentation of Contents
3.1. Flowchart
3.4 Algorithms
4. Summary
2
1. Introduction
In the previous lesson you learn about programming fundamentals and the various
flowcharts, decision tables and algorithms used to solve problems are discussed in
detail. Further, the structured programming concepts are also discussed with their
methodologies i.e. top down and bottom up methodologies are also discussed.
2. Objectives
3. Presentation of Contents
3.1. FLOWCHARTS
representation of the various steps involved in designing a system. Some of the symbols
3
Fig. 1: Common Symbols of Flow Chart
contains information about what must be done at that point & the arrow shows the ‘flow
of execution’ of the algorithm, i.e., they show the order in which the instructions must be
executed. The purpose of using Flowcharts is to graphically present the logical flow of
data in the system and defining major phases of processing along with the various media
to be used.
1. System flowchart
2. Run flowchart
4
3. Program flowchart
The first two types of flowcharts are discussed in lesson 1. In this lesson you will learn
A program flowchart represents, in detail, the various steps to be performed within the
system for transforming the input into output. The various steps are logical/arithmetic
operation, algorithms, etc. It serves as the basis for discussion and communication
between the system analyst and the programmer. Program flowcharts are quite helpful to
flowchart for finding the sum of first five natural numbers (i.e., 1, 2, 3, 4, and 5).
5
Guidelines for Flow Charts
The following are some guidelines that should be followed while drawing flowcharts:
logical order.
2) The flowchart should be clear, neat and easy to follow. There should not be any
3) The usual direction of the flow of a procedure or system is from left to right or top
to bottom.
4) Only one flow line should come out from a process symbol.
or
5) 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.
the number of flow lines. Avoid the intersection of flow lines if you want to make
9) It is useful to test the validity of the flowchart by passing through it with a simple
test data.
2) Effective analysis: With the help of flowchart, problem can be analyzed in more
effective way.
4) Efficient Coding: The flowcharts act as a guide or blueprint during the systems
becomes easy with the help of flowchart. It helps the programmer to put efforts
1) Complex logic: Sometimes, the program logic is quite complicated. In that case,
7
require re-drawing completely.
flowchart becomes a problem. The essentials of what is done can easily be lost in
Example 1: A flowchart to find the sum of first 50 natural numbers is shown in Fig. 3.
Example 2: A flowchart to accept the price of an item and calculate its VAT at 15% is
shown in Fig. 4.
8
Fig. 4. To calculate VAT
9
Example 4: A flowchart that accepts the length and width of a rectangle and calculates
Example 5: A flowchart to find the largest of three numbers A,B and C is shown in Fig.
7.
10
Example 6: A flowchart for computing factorial N (N!), Where N! = 1 ´ 2 ´ 3 ´ …… N is
shown in Fig. 8.
Decision tables and trees were developed long before the widespread use of computers.
They not only isolate many conditions and possible actions but they help ensure that
(a) Decision Tables: The decision table is a chart with four sections listing all the logical
conditions and actions. In addition, the top section allows space for title, date, author,
11
Fig. 9. Decision Table
The Condition Stub contains a list of all the necessary tests in a decision table. In the
lower left-hand corner of the decision table we find the Action Stub where one may
write all the processes desired in a given module. Thus Action Stub contains a list of all
The upper right corner provides the space for the Condition Entry – all possible
permutations of 'yes' and 'no' responses related to the condition stub. The 'yes' and 'no'
possibilities are arranged as a vertical column called rules. Rules are numbered 1,2,3 and
Number of rules = 2^N = 2N where N represents the number of condition and ^ means
exponentiate. Thus a decision table with four conditions has 16 = (24 =2 x 2x 2 x 2 = 16)
rules. One with six conditions has 64 rules and eight conditions yield 256 rules.
The Condition entry contains a list of all yes/no permutations in a decision table. The
lower right corner holds the action entry. X’s or dots/dash indicates whether an action
12
should occur as a consequence of the yes/no entries under condition entry. X’s indicate
an action should occur as a consequence of the yes/no entries under condition entry,
Thus Action entry indicates via dot or X whether something should happen in a decision
table or not.
No discount is allowed
Then discount is 5%
No discount is allowed
13
Fig. 10. Decision Table
(b) Decision Tree: The decision tree defines the conditions as a sequence of left to right
tests. A decision tree helps to show the paths that are possible in a design following an
action or decision by the user. Fig. 11 illustrates the concept of decision tree.
14
Decision tree turns a decision table into a diagram. This tool is read from left to right,
decision results in a fork, and all branches end with an outcome. Fig. 12 illustrates the
decision tree for the book order decision table we saw in Example 7.
Pseudo code is a kind of structured English for describing algorithms. It allows the designer
to focus on the logic of the algorithm without being distracted by details of language syntax.
At the same time, the pseudo code needs to be complete. It describes the entire logic of the
algorithm so that implementation becomes a rote mechanical task of translating line by line
In general the vocabulary used in the pseudo code should be the vocabulary of the problem
domain, not of the implementation domain. The pseudo code is a narrative for someone who
knows the requirements (problem domain) and is trying to learn how the solution is
organized.
15
Example 8: A pseudocode that prompts the user to enter a value and display its square
Step 1: start
Step 6: stop
Example 9: A pseudocode that will accept the length and width and calculate and print
Step 1: start
Step 5: stop
Example 10: A pseudocode that will accept 25 integers and displays the number of
Step 1: start
Step 3: for i 1 to 25
16
Step 3: read num
poscount = poscount +1
else
negcount = negcount +1
endif
Step 5: endfor
3.4 ALGORITHMS
designed in such a manner that on execution the desired output is achieved. It may be
written in simple English like language. If it gives correct result then it is converted into a
preparation of any program, firstly algorithm is prepared for it. Then algorithm is
computer program.
Algorithms written in simple English is called ‘Pseudo code’ and written in computer
reverse is not true. An algorithm is very important for any program. If it contains an error
or mistake, one has to recheck the algorithm and restart all process.
17
First Part tells the purpose of algorithm. It identifies the variables which occur in
algorithms.
a) Input: input part reads the data of a given problem by accepting input.
c) Finiteness: the algorithm must come to end after a finite number of steps.
d) Effectiveness: every step must be accurate and precise. It must be execute with in
description.
Comments
Variable Names
Assignment statement
18
Input/output statement
Conditional instruction
Loop instruction
Comment: Comments are used for clarity and understanding of problem. Each step may
Variable Names: Variable names will use capital letter. Single letter names of variables
used as counters or subscript used as capital letter as well as small letter. e.g.
MAX
COUNT
assignment.
e.g.
19
MAX: = COUNT [5]
statement.
e.g.
Similarly, Message with in quotation marks and data in variables may be output by Write
or Print statement.
e.g.
Write: Message
Or
Conditional instruction: Such statements which choose one process among a few
are:
IF statement
IF-THEN-ELSE
GO TO Step.
SWITCH CASE
e.g.
IF A>B THEN
20
PRINT A
END IF
IFA>B THEN
GOTO STEP 2
END IF
Loop instruction: When there are certain steps required to be executed repeated again
and again up to certain condition, these constructs are called loop constructs. These are:
i. FOR Loop
e.g.
<increment/decrement>
DO
Statements
END FOR
Statements
ENDWHILE
21
iii. REPEAT
Statements
UNTIL <cond.>
Starter & Terminator: Starting an Algorithm we use START and for ending an
algorithm we use STOP or END. But at some times terminate the execution in between
//Algorithm for displaying sum of 50 natural numbers i.e SUM = 1+2+3 ……+50 ,
Step 1: START
Step 2: SUM = 0, I
[SUM variable used for storing sum and I used as counter in loop]
DO
SUM=SUM + I
END FOR
Step 5: STOP
22
// Algorithm for Largest among three numbers. Numbers A,B & C are inputted from
//keyboard.
Step 1: START
IF A>C THEN
PRINT ‘A is greatest’
ELSE
PRINT ‘C is greatest’
PRINT ‘B is greatest’
ELSE
PRINT ‘C is greatest’
[END of IF Structure]
Step 4: STOP
//N is read from Keyboard. Variable M as Counter in For Loop and Variable F used to
Step 1: START
Step 2: READ N
23
Step 4: FOR M=1 TO N STEP 1
DO
F=F*M;
END FOR
Step 5: PRINT F
Step 6: STOP
Example 14: An algorithm and flowchart for finding the average of two numbers. The
Algorithm:
INPUT x
Step 1: START
INPUT y
Step 7: STOP
END
Structured programming techniques assist the programmer in writing effective error free
24
forced programmers to approach programming from the conceptual point of view,
making them design programs before they wrote code. It cleared up spaghetti code and
Experience with programming languages and software development over the years has
shown that applying structured programming concepts helps keep software code
among others.
One of the most important features of structured programming is that all program
structures have only one entry point and one exit point.
There are three main types of control structures in structured programming. These are
25
IF "Condition" is true THEN perform "Procedure 2", ELSE perform "Procedure
3".
"Procedure 4".
26
Fig. 16. (IF-THEN-ELSEIF-THEN-ELSE) control structure.
no longer false (DO-UNTIL). Such structures consist of a loop which takes the
(DO-WHILE) control structure is shown in Fig. 17. Note that the loop condition (in
this case the question "is i < 10?") is tested before proceding with the rest of the
procedures in the loop and that the loop control variable ("i") is incremented at the
end of the loop. If the loop condition is true then the loop is executed. The loop only
terminates when the loop condition is false. If the loop condition is false upon entry to
27
Fig. 17. (DO-WHILE) control structure
Note that the loop condition (in this case the question "is i > 10?") is tested at the end of
the loop. The loop control variable (in this case "i") can be updated anywhere in the loop
and here is incremented just before the loop condition is tested. If the loop condition is
true then the loop is terminated. The loop only repeats when the loop condition is false.
Even if the loop condition is true upon entry to the loop the loop will be executed at least
once.
28
Fig. 18. (DO-UNTIL) control structure.
There are two main types of programming methodogies used to develop programs. These
are Top Down Programming and Bottom Up Programming. Both of these are
discussed below.
of high level tasks that will be called from main(), and recursively splitting each task into
subtasks until a level of complexity is attained that permits the definition of reasonably
29
In top down programming the higher-level functions are implemented in terms of the
lower-level functions.
Top-down program design is useful for defining the overall structure of a program, and
the dependencies between functions. Usually, the functions are first implemented as
interfaces only, with do-nothing internals (also called “dummy” internals). This allows
the program to run without any real utility, and individual functions can be written and
tested within a working skeleton program. Thus, the entire program shell is laid out at the
start, and the function internals are subsequently built and debugged one-at-a-time.
A key limitation of top-down design is that the resulting functions tend to be problem-
specific (i.e., specific to the program at hand). They tend to be non-reusable, and the top-
programming is as follows
2) It is easier to test segments of solutions, rather than the entire solution at once.
This method allows one to test the solution of each sub-problem separately until
3) It is often possible to simplify the logical steps of each sub-problem, so that when
taken as a whole, the entire solution has less complex logic and hence easier to
develop.
4) Simplified solution takes less time to develop and will be more readable.
30
Bottom-up Programming : The bottom-up approach to program design is to identify
various components that will be required by the program, and to build them in isolation
Assuming the appropriate argument types are known, the function interfaces can be
An advantage of bottom-up design is that the resulting modules are often more generic
than those designed in a top-down approach. They tend to be less tied to the program at
hand and more amenable to reuse. In the best-case, a bottom-up component can be
The disadvanatge of bottom-up program design is that it does not give a clear indication
of how the individual program elements should be merged together. It does not present
the “big picture”, the overall structure of the program with its dependencies and function-
call hierarchy. In addition, because components are developed in isolation, they often
require the writing of drivers to permit testing and debugging. These drivers are small test
programs that allow one to check the response of a component to various inputs. Writing
Top-down and bottom-up program design are complementary and practical design tends
to use both strategies, working at both ends until they meet in the middle. Top-down
design composes the overall program structure and call hierarchy, and bottom-up design
31
Example 15: A hotel wants to have a room booking system. When a guest arrives the
receptionist would be able to see which rooms are free and allocate one to the guest.
When the guest leaves, the room would be marked as free again. Each day the cleaners
would be given a list of the rooms that are in use. At any time the receptionist would be
able to use the room number to find the name and home address of a guest, or could
search the room system for a named guest. A top-down design diagram in Fig. 19 shows
4. Summary
Flowcharts are of three types, System flowchart, Run flowchart and Program flowchart.
32
The decision table is a chart with four sections listing all the logical conditions and
actions.
The decision tree defines the conditions as a sequence of left to right tests and helps to
Pseudo code is a kind of structured English for describing algorithms and allows the designer
to focus on the logic of the algorithm without being distracted by details of language syntax.
Structured programming techniques assist the programmer in writing effective error free
programs.
One important feature of structured programming is that all program structures have only
There are three main types of control structures used in structured programming. These
There are two main types of programming methodogies used to develop programs. These
In top down programming the higher-level functions are implemented in terms of the
lower-level functions.
build them in isolation from any design of the overall program structure.
33
1. Suggested Reading/Reference Material
3. Jeri R. Hanly & Elliot P. Koffman, “Problem Solving and Program Design in C”,
Addison Wesley.
5. Leon, Alexis & Leon, Mathews, “Introduction to Computers”, Leon Tech World
1. What is Flow Chart? List out the Symbol used to draw Flow Chart.
4. What is a flow chart? Draw a flow chart to read ten integers and print the sum of
5. Draw a flow chart to read ten integer values and print the sum of squares of the
values.
6. Draw a flow chart to read ten positive integers and print how many are multiples
of 2.
8. Draw a flowchart for finding the sum of ‘n’ numbers starting from 1?
34
9. Draw a flowchart to find maximum and minimum of the given three input
numbers
10. Define the flow chart? Draw a flow chart for finding roots of a quadratic equation
11. Define Algorithm? What are the characteristics that any algorithm should satisfy?
12. What is an algorithm? Write an algorithm to read five integers and find out if the
13. What is an algorithm? Write an algorithm to find out if a given number is a prime.
14. Write an algorithm to find out all the factors of a given positive integer.
15. Write an algorithm to read ten positive integers and find out how many are perfect
squares (such as 49, 81).You may assume that the input values read are in the
range 1 to 10000.
16. A utility company charges its customers based on their monthly utilization in
terms of units as follows: Description charge: First 100 units Rs.10 per unit, Next
200 units Rs. 9 per unit, Next 200 units Rs.8 per unit, Next units Rs.7 per unit
.Write an Algorithm and flowchart that reads monthly units of a customer and
17. Write a pseudocode that will create a conversion table to convert degrees Celsius
to degree Fahrenheit. Prompt the user to enter the temperature in degree Celsius
20. Explain why a top-down design approach is sometimes used to solve problems.
35
Lesson 3.
1
Structure:
1. Introduction
2. Objectives
3. Presentation of Contents
3.1 Overview of C
3.1.1 History of C
3.1.2 Characteristics of C
2
1. Introduction
language is a language that is used to interact with the computer or computing machine.
early 1970s by Ken Thompson and Dennis Ritchie for use on the UNIX operating
system. It is one of the most widely used general purpose programming languages. C is
very efficient and is the most popular programming language for writing system
software. C is a medium level language (some refers it as a high level language). But
compatibility with computer, this language uses a compiler or simply a translator which
2. Objectives
3. Presentation of Contents
3
3.1 OVERVIEW OF C
Before starting C Language you must know what Language is. Language is a medium by
which one person can communicate with other person as shown in Fig 1.
But problem arises when Person A knows Hindi only and Person B knows English only.
Now, person A wants to communicate with computer. But computer understand only
machine language (binary language o’s or I’s language). Machine language is very
difficult to understand for us. So we will have to learn programming language like C,
Pascal, Fortran etc. for making program for computer. These languages are easier to learn
as compare to machine language. But, now computer does not understand these
programming languages. For this we uses the intermediate or language translator i.e.
4
Fig. 3. Communication b/w Person and Computer via Compiler
Laboratories of USA in 1972. It was developed and written by a man named Dennis
technologies. Its compact size , precision, accuracy and adaptability make it a famous
tool for writing operating systems, compilers, commercial and business data processing
applications.
5
Fig. 4. Comparison of Basic elements b/w English and C Language
The basic elements shown in Fig. 4 used to construct simple C statements. These elements
include the C character set, keywords and identifiers, constants, data types, variables, arrays,
declarations, expressions and statements. These basic elements are used to construct more
3.1.1 HISTORY OF C
The C programming language was developed in the years 1969 to 1973, although the first
published description did not appear until the book The C Programming Language"
written by Brian Kernighan and Dennis Ritchie was published in 1978. The early
6
versions of the C language were strongly influenced by a language called BCPL which
The early development of C was closely linked to the development of the Unix operating
system. Large portions of the code of the Unix operating system were eventually written
into the design of the C language. The modest hardware available to the Unix developers
was also reflected in the language design, most notably the use of separate library
functions for operations such as input and output. Until the early 1980s the language was
1980s also saw a rapid growth in the use of C on such systems. C compilers were known
to be small.
As early as 1982 it became clear that the informal description of the language in
Kernighan & Ritchie's book was not good enough. ANSI established a committee known
as X3J11 in 1983. This committee produced a report defining the language at the end of
1989. The report was known as X3.159 but the standard was soon taken over by ISO with
the designation ISO/IEC 9899-1990. This version of the language is known as ANSI-C to
distinguish it from the earlier version of the language described by Kernighan and
Ritchie. The earlier version of the language is known as K&R C. C++ and Objective-C
are different languages developed from C. The GNU C compiler, often known by the
command that invokes it, gcc , is public domain software available for both Unix and
MSDOS based systems. It supports a version of the language close to the ANSI standard.
7
The different milestones in C’s development as a language are listed below:
3.1.2 CHARACTERISTICS OF C
1. Low Level Features: C Programming provides various low level features that are
2. Portability: This is the one of the most preferable feature of the C language. As
discussed earlier C language uses compilers which brings its portability. The
systems.
in which software is break down into separate parts, called modules. C Program
program
8
4. More Efficient: It is more efficient language and simpler to use. It is an ideal
called as extendibility.
6. Flexibility: ‘C’ language has right number of reverse words which allows the
the programmers.
7. Other Key Features: The following are some more features of C language.
C is a relatively small language. C's small, unambitious feature set is a real advantage.
There’s less to learn, but it can also be a disadvantage, since it doesn't do everything for
in assembly language, you'll probably find C very natural and comfortable if you haven't
programmed in assembly language, you may be frustrated by C's lack of certain higher-
level features. If you write a C program simply and succinctly, it is likely to result in a
succinct, efficient machine language executable. If you find that the executable program
9
resulting from a C program is not efficient, it's probably because of something silly you
did, not because of something the compiler did behind your back which you have no
control over.
A programming language is a tool, and no tool can perform every task unaided. In the
same way, C does not have built-in features to perform every function that you might
C imposes relatively few built-in ways of doing things on the programmer. Some
common tasks, such as manipulating strings, allocating memory, and doing input/output
(I/O), are performed by calling on library functions. Other tasks which you might want to
windows or other user-interface elements, or doing color graphics, are not defined by the
prototype.
prototype.
10
8. Right delimiter (‘}’) which marks the end of function main ( ).
9. Definition of function declared above the main ( ) function and called in the main
( ) function.
Program 1.
#define SIZE 10
void main( )
int a[SIZE];
if (x%2= =0)
else
11
printf(“Enterd no. is ODD”);
1. Program’s Name, Author’s Name and Objectives: Program start with program name
and author’s name. It also describes the purpose of the program in one or two lines for better
documentation.
Starts with ‘// ‘(double back slash) and end upto end of line.
Start with ‘/*’ and end with ‘*/’ it contains more than one line as part of comment.
directives. A preprocessor directives start with a symbol hash(#) . Directives are instructions
#include<stdio.h>instructs the compiler to insert the stdio.h (header file) file in the source
4. Declaration of Global Variables: There are mainly two types of variables: Local &
Global. Global variables and functions are defined and declared outside the main function.
12
5. Function Main ( ): Every Program in C have at least one function i.e. main( ). Program
execution start with the first statement of the main( ) and end with the last statement of the
main ( ).
6. Left (‘{‘) and Right (‘}’) Delimiter or Curly Braces : Left brace indicates the beginning
of the function and Right brace indicates the end of function. The left brace(‘{‘) along with
the right braces (‘}’) enclose the entire body of executable statements and functions.
sequence of declarations and statements which performs a specific task and provides the
results to the main program which calls the function. Declaration of function tells about
function: name of function, return type of function , no. of arguments and their types.
8. Body of Statement and Functions: In between left brace (‘{‘) and right brace(‘}’) in
9. Called Functions: These perform a specific task. In the above program void check(int
function includes the statement of check( ) that represent the task of check( ) function
performed.
3.3. ELEMENTS OF C
The following sections and subsections discusses about the various elements of C
language.
13
3.3.1 THE C CHARACTER SET
C uses:
uppercase letters A to Z,
lowercase letters a to z,
digits 0 to 9 and
special symbols
! *+\”< #) = ; } >
^ ( ],{ ?&-[ :‘ /%
Anyone can use both uppercase and lowercase letters. But uppercase and
lowercase letters are distinct. e.g. AGE and age are not same.
Any identifier can start with underscore character, though this is not a good
programming practice.
14
Valid identifiers are:
nd
2 , “y”, ship-no, flag error
Keywords are certain reserved words that have standard, predefined meanings in C.
These keywords can be used only for their intended purpose, they cannot be used as
3.3.3 CONSTANTS
Constant in C refers to fixed values that do not change during the Program execution.
15
e.g.
Integer Constant
Character Constant
String Constant
Floating-point constant
As the name suggests integer & Floating point constants represent numbers. They are
An integer constant refers to a sequence of digits. There are three types of integers:
Decimal
Octal and
Hexadecimal
16
Octal Integer Constant can consist of any combination of digits 0 through 7 with a
leading o. e.g. :
Hexadecimal Integer Constant must begin with either 0x or 0X. It can then be followed
Floating Point Constant is a base-10 number that contains either a decimal point or an
exponent (or both). Floating point Constant represent in exponential form like:
If an exponent is present, its effect is to shift the location of the decimal point to the right
Each character constant has its equivalent ASCII value like ‘A’ has
17
String Constant consist of any number of consecutive characters enclosed in double
“A” and ‘a’ are not same. Firtst one is string constant and later one is character constant.
3.3.4 VARIABLES
A Variable is a name given to a variety of values or we can say variable is a name that
represents a storage location in the computer memory. The information which is stored at
e.g. variable x starting value is 10 shown in Fig. 5 and later some statement value is 20
shown in Fig. 6 so we can say x value vary from 10 to 20.(Changeable during various
part of program)
int x;
x=10;
------
------
18
Fig. 5. Variable X in Memory with value 10
-------
-------
-------
x=20
data type. In ‘C’ language all variables must be declared before they appear in executable
19
e.g
int x,y, z;
float p,q,r;
Thus x, y, z are declared to be integer type variables, p, q, r are floating point variables
The programmer can also write above declarations in the following manner:
int x;
int y;
int Z;
float p;
float q;
float r;
C supports different types of data, each of which may be represented differently within
the computer’s memory. There are three type of data types shown in Fig. 7:
20
Fig. 7. Types of Data Type
Primitive or built in data types: it is further divided in two parts shown in Fig. 8:
1. Integral type
Integral Types includes integer and character type data types and Floating point type
1. Integer types: An integer occupies one word space and the size of the word
varies with the machine, the storage of integer is totally dependent on the
computer. E.g. a 16 bit word length , size of integer is limited to the range from
-215 to 215-1 i.e. -32768 to +32767. on the other hand for a 32 bit word length the
size is from -231 to 231-1 i.e. -2147483648 to 2147483647. in C, there are three
classes in which integer can be stored. These are short int, int and long int for
both signed and unsigned forms. A short int may require less space than an
21
ordinary int or it may require the same memory space as that required by an
ordinary int.
2. Floating point types: When floating point or real numbers are stored in 32 bits
there are 6 bits of precision. In C, floating point numbers are denoted by the
keyword float. If a float number cannot provide sufficient accuracy, the number is
type requires 1 byte memory. The range of signed char is from -128 to 127
22
Data Types
Type Size (in bytes) Range
unsigned char 1 0-255
char 1 -128 to 127
unsigned short 2 0 to 65535
short 2 -32768 to 32767
unsigned int 2 0 to 65535
int 2 -32768 to 32767
unsigned long 4 0 to 4294967295
long 4 -2147483648 to 2147483647
float 4 3.4E-38 to 3.4E+38
double 8 1.7E-308 to 1.7e+308
long double 10 3.4E-4932 to 1.1E+4932
C also uses some combinations of these characters such as \t, \n to represent special
conditions such as horizontal tab and newline respectively. These character combinations
are called escape sequences. Each escape sequence represents a single character, although
\n Newline
\t Horizaontal tab
\v vertical tab
\b backspace
\a bell
\r carriage return
\f form feed
\0 NULL
23
\”” double quotation mark
\? Question mark
\\ backslash
3.6 C INSTRUCTIONS
Input Data- Scanf Function : It is used to input any type of data from keyboard.
Syntax:
Output Data- Printf Function : It is used to output any type of data on Screen/Printer.
Syntax:
24
Example 1: Which of the following are valid variable name and why
3. interestPaid // valid
5. age12 // valid
7. name_of_author //valid
2. string1=”123” // no error
operators in left
4. area=3.14*r*r // no error
Int i=3;
int j=4,k,l;
float a,b;
k=i / j * j;
25
l=j / i * i;
a=i / j * j;
b=j / i * i;
OUTPUT:
0.000000
3.000000
#include<stdio.h>
#include<conio.h>
void main()
int numi;
float numf;
char ch;
char str[20];
clrscr();
26
scanf("%d",&numi);
scanf("%f",&numf);
fflush(stdin);
scanf("%c",&ch);
scanf("%s",&str);
is=%s",numi,numf,ch,str);
getch();
OUTPUT:
float is=10.500000
character is=x
string is=india.
27
Program 2: A Program to show octal and hexadecimal representation of decimal
numbers
#include<conio.h>
void main()
int num;
clrscr();
scanf("%d",&num);
getch();
OUTPUT:
12345
28
Program 3: A Program to show format specifier in input and output.
#include<conio.h>
void main()
int numi;
float numf;
clrscr();
scanf("%2d",&numi);
fflush(stdin);
scanf("%3f",&numf);
getch();
OUTPUT:
29
10
10.5
4. Summary
There are various C standards: Kernighan & Ritchie (K&R) C standard; ANSI
ANSI C and ISO C are the most popular C standards. Most popular compilers
C character set consists of letters, digits, special characters and white space
characters.
Identifier refers to the name of an object. It can be a variable name, a label name, a
Keyword cannot form a valid identifier name. The meaning of keyword is predefined
30
Every identifier (except label name) needs to be declared before its use. They can be
The declaration statement introduces the name of an identifier along with its data type
Data types are categorized as: basic data types, derived data types and user-defined
data types.
The declaration statement can optionally have type qualifiers or type modifiers or
both.
C program should have at least one function. A function named main is always
required.
31
1. Gottfried, Byron S., “Programming with C”, Tata McGraw Hill
4. Jeri R. Hanly & Elliot P. Koffman, “Problem Solving and Program Design in C”,
Addison Wesley.
1. What is identifier? What are the rules for the naming identifiers?
6. What is data type? Explain different types of data type available in c with example.
32
Lesson 4:
1
Structure:
1. Introduction
2. Objectives
3. Presentation of Contents
3.1 Operators
4. Summary
2
1. Introduction
In the last lesson, you have learned about the history of C language and its importance.
Further, you have also learned about the basic elements of C language and the structure
of a typical program in C language. You know that the processing of data is essential part
and binary operators, assignment operators, bit wise operators, relational operators and
logical operators.
2. Objectives
3. Presentation of Contents
3.1 OPERATORS
Operators are those which operate on operands and form a expression. The data items on
which operators act upon are called operands. Binary operators (e.g. + operator) requires
3
two operands while Unary (++ Operator) require only one operand.
1. Arithmetic Operators
2. Relational Operators
3. Logical Operators
4. Assignment Operator
6. Conditional Operator
Operators Function
+ additions
- subtraction
* multiplication
/ division
The modulus operator requires that both operands be integers & the second
operand be nonzero.
4
The division operator (/) requires that the second operand be nonzero.
If division operation is carried out with two floating- point numbers, or with one
floating-point number. & one integer, the result will be a floating-point quotient.
x+y 30
x-y 10
x*y 200
x/y 2
x %y 0
If one or both operands represent negative values, then the addition, subtraction,
multiplication and division operations will result in values whose signs are
In case of % operator when one of the operands is negative then the sign of first
a) Conversion: Operands that differ in type may undergo type conversion before the
5
expression takes on its final value. The final result has highest precision possible,
consistent with data types of the operands. The following rules apply when
Expression Result
5/2 2
5/2.0 2.5
5.0/2 2.5
5.0/2.0 2.5
5/2 2 2
5/2.0 2.5 2
5.0/2 2.5 2
5.0/2.0 2.5 2
5/2 2 2.0
6
5.0/2.0 2.5 2.5
• If one operand is a floating point type and the other is a char or an int, the
char/int will be converted to the floating point type of the other operand and the
result will be expressed as such. So, an operation between an int and a double will
result in double.
• If both operands are floating-point types with different precisions, the lower-
precision operand will be converted to the precision of the other operand and the
type if desired. The ‘C’ programmer has the choice of explicitly cast one type of
operand in to another type of operand and this may be accomplished using what is
called the casting operator. The name of data type to which the conversion is to be
made is enclosed in parentheses and placed directly to the left of the value to be
converted; the word “cast” never is actually used. The example of type casting is
as follows:
int a=17;
float b;
b=(float)a+ 11.0;
The cast operator converts the value of int a to its equivalent float representation
7
before the addition of 11.0 is carried out. The cast operator can be used on a
(float)(a+4)
2. Unary Operators: ‘C’ includes a class of operators that act upon a single operand to
produce a new value. Such operators are known as unary operators. Unary operators
usually precede their single operands, though some unary operators are written after
their operands.
The most common unary operator is unary minus, where a minus sign precedes a
e.g.
-5,-10, -20(numbers)
x=-y(variable) Of all the arithmetic operators, the unary minus has the
y=x+z* -b;
in the above expression, evaluation commences with the unary minus, which
negates the value of b. Then z is multiplied by –b, and finally the addition takes
place. The result is stored in the variable y. So, the use of parentheses to separate
8
the two adjacent operators and avoid possible confusion.
Y=x+z*(-b);
If the operator used before operand, then the value of operand will be altered before
it is used for its intended purpose within the program. If, however the operator used
after the operand then the value of the operand will be changed after it is used.
Another unary operator is the sizeof operator. This operator returns the size of its
e.g.
int x;
float y;
9
sizeof (y); // it will return 4
Relational operators are symbols that are used to test the relationship between two
Operator Description
!= not equal to
== Equality operator
Let us understand operations of these relational operators with the help of an example:
5>=4
10
(5>9)
Here, true or false represents logical interpretation and they have values 1 and 0
respectively.
There are two logical operators in C language, they are and, or. They are represented by
|| OR (Logical OR)
The result of a logical AND (&&) operation will be true only if both operands are true,
whereas the result of a logical OR ( || ) operation will be true if either operand is true or if
11
z==’w’ also true because (‘w’==’w’) both expression are true so final result is true.
In this case first expression (x<==6) is false and second expression is (z==’w’) is
true. One is false and one is true so according to Logical AND(&&) final result is
false
In this case first expression (x<==6) is false and second expression is (z==’w’) is
true. One is false and one is true so according to Logical OR (||) final result is
true.
There are several different assignment operators in C. All of them are used to form
assignment expression, which assign the value of an expression to an identifier. The most
commonly used assignment operator is =. The assignment expressions that make use of
Identifier = expression
Assignment operator = and the equality operator == are distinctly different. The
operator is used to compare two expressions have the same value. These two operators
12
cannot be used in place of one another.
allowed in ‘C’.
In such situations, the assignments are carried out from right to left.
This will cause the integer value 10 to be assigned to both x and y. Similarly,
x=y=10.5 will cause the integer value 10 to be assigned to both x and y, truncation
occurs when the floating point value 10.5 is assigned to the integer variable y.
‘C’ also contains the additional assignment operators. These are also called short hand
+= , -= , *= , /=, &=, %=
As we know that computers understand only binary number system for processing and
13
8 bit = 1 byte
This numbering system has a base two. The base two consists of two digits 0 and 1. in
this system, starting from right side, the place value of each bit is an increasing order of
power 2.
e.g.
32 16 8 4 2 1 (place value)
1 0 1 0 0 1 (binary value)
1 +0 +0 +8 +0 +32
41/2 20 1
20/2 10 0
10/2 5 0
5/2 2 1
14
2/2 1 0
1/2 0 1
Starting from the bottom, collect all remainder 101001 is the binary equivalent of decimal
no 41.
- ones compliment
| inclusive or of bits
1. The Compliment Operator (-) : This operator change all 1’s to 0 and all 0’s to I.
2. The Left Shift Operator (<<): This operator shifts the bits to left by a specified
e.g
int x=8;
15
3. The Right Shift Operator (>>) : This operator shifts the bits to Right by a specified
e.g
int x=8;
4. The AND Operator (&) : This operator compares two operands bit by bit and if both
bits are 1’s the result is 1 otherwise in all other cases the result is zero.
e.g.
x y x&y
0 0 0
0 1 0
1 0 0
1 1 1
16
Application of and (&) operator
--------------
5. The Inclusive OR Operator (|) : This operator compares two operands bit by bit and
if either of the corresponding bit is 1 the result is 1 otherwise the result is zero.
e.g.
x y x|y
0 0 0
0 1 1
1 0 1
1 1 1
--------------
17
00010111 Decimal no. 23
6. The Exclusive OR Operator (^) : This operator compare two operands bit by bit and
if one and only of the corresponding bit is 1, the result is 1, otherwise the result is 0.
e.g.
x y x^y
0 0 0
0 1 1
1 0 1
1 1 0
--------------
18
It is discussed in detail in Lesson 5.
Precedence refers to the definite order in which the operands are evaluated. Associativity
specifies the order in which several operators with equal precedence are evaluated, either
from right to left or from left to right. Where several operators appear in a line, they equal
Structure member,
19
Logical OR || Left to Right
&=, |=, ^=
The operators within C are grouped hierarchically according to their order of evaluation
known as precedence. Obviously operations with a higher precedence are carried out
before operations having a lower precedence. The natural order can be altered by making
use of parentheses.
The operators *, / and % have higher precedence than + and -. In other words,
multiplication, division and remainder operations will be carried out before addition and
subtraction.
Another important point to consider is the order in which consecutive operations within
the same precedence group are carried out. This is known as associativity. Within each of
the precedence groups described above, the associativity is left to right. In other sense,
consecutive addition and subtraction operations are carried out from left to right, as are
e.g.
Let
20
a=5, b=10, c=15;
a+b/c+b*c-a
(i) 5+10/15+10*15-5
In the given expression, /, * have higher precedence than + and -. But / and * have the
same precedence level. Then we see their associativity and associativity of that level is
left to right means which operator appears first from the left evaluate first. So division is
(ii) 5+0+10*15-5 (10/15=0 because both are integer and result will be integer) after
(iv) 5+150-5
150
Library functions carry out various commonly used operations or calculations. A library
function is accessed simply by writing the function name, followed by a list of arguments
that represent information being passed to the function. The arguments must be enclosed
names or more complex expressions. The parentheses must be present, even if there are
21
no arguments. This information is generally stored in special files supplied with the
compiler. Thus, the required information can be obtained simply by accessing these
# include <filename>
You can see rest of the library functions available in C in Help topic of ‘C’.
The C language provides several functions that give different levels of input and output
capability. These functions are, in most cases, implemented as routines that call lower
The input and output functions in C are built around the concept of a set of standard data
streams being connected from each executing program to the basic input/output devices.
These standard data streams or files are opened by the operating system and are available
to every C to use without having to open or close the files. These standard files or streams
are called:
22
- stdin : connected to the keyboard
The input/output functions fall into two categories, Formatted display and read
Formatted output converts the internal binary representation of the data to ASCII
characters which are written to the output file. Formatted input reads characters from the
input file and converts them to internal form. Formatted I/O can be either "Free" format
follows.
Syntax:
Where format specifier is a list of format specifiers indicating the format and type of
data to be read from the keyboard and stored in the corresponding address. There must
be the same number of format specifiers and addresses as there are input fields.
scanf returns the number of input fields successfully scanned, converted, and stored. The
return value does not include scanned fields that were not stored.
%[*][width][F|N|h|l|L] type
23
1 Percent(%): it marks the beginning of format specifications.
2 Asterisk (‘*’) : it called and optional suppression character. It will read the
next input filed but input field will not be stored at address of the argument. It
number of character that will be inputted from the current input filed. It may
5 Argument type modifier: the h, l, L are optional argument type modifier. ‘h’
indicates short int. ‘l’ modifies integer and floating point quantities if the type
is int it makes is long int. if the type is float then it specifies it double. ‘L’
24
u unsigned Decimal Pointer to unsigned int integer
e.g.
resp.
&x); /*read not more than 5 digits of integer type value and store at address of x. */
25
scanf(“%c”,&ch); //read a character and store at address of ch.
Long %ld or %D or %I
float %f
double %lf
float %e
float %g
26
double %le or %E or %G
Hexadecimal
int %x or %i
long %x or %lx or %I
Octal
int %o or %i
long %O or %lo or %I
Syntax:
Where format is composed of literal text, escape sequences used as carriage control, and
format specifiers for conversion of data in the arguments to a display format. This
function returns the number of characters printed.
printf() returns the number of bytes output. In the event of error, printf returns EOF.
%[flags][width][.precision][F|N|h|l|L] type
27
2 Flags: it specifies parameters for output justification (left or right), decimal
5 Input size modifiers (N, F, H, l, L): they mean the same as scanf() function wih
minor difference.
28
% none % character
FLAGS:
space right justified, it will omit ‘+’ show ‘-’ if value is negative.
Width specifer: In scanf() there is only one type of width specifier(n). in the printf()
e.g.
int x=578;
printf(“%8d”,x); // bbbbb578(no of character less than width so left out places filled
with blanks.)
printf(“%2d”,x); // 578 (no of character more than width so all character will be
displayed.)
29
printf(“%*d”,8,x); // bbbbb578 (* specifies the width specifier which is given just
input/output transfers the internal binary representation of the data directly between
memory and the file. The most commonly used unformatted input/output functions are as
follows:
1. puts Function: It displays a string literal or a stored character string on the screen. The
function automatically carriage returns and line feeds at the end of the display. The string
#include "stdio.h"
int main()
char name[30];
gets(name);
printf("\nHello ");
30
puts(name);
return 0;
2. gets Function: It reads characters from the keyboard and stores them in a passed
character array. The reading of keyboard is terminated when the '\n' (RETURN/ENTER)
key is pressed.
On success, gets() returns the string argument s; it returns NULL on end-of-file or error.
e.g.
#include "stdio.h"
int main()
char name[30];
gets(name);
printf("\nHello %s",name);
return 0;
31
On success, putchar() returns the character c. On error, putchar() returns EOF.
4. putch Function: It writes the character directly to the screen. This function is
On success, putch returns the characer printed, c. On error, it returns EOF. e.g.
#include "stdio.h"
int main()
int c;
c = 'A';
putchar(c);
putch(c);
return 0;
OUTPUT
AA
32
getchar() reads a single character the from the input data stream; but does not
return the character to the program until the '\n' (RETURN/ENTER) key is
pressed.
getch() reads, without echoing, a single character from the keyboard and
compilers.
getche() reads, with echo, a single character from the keyboard and immediately
e.g.
#include "stdio.h"
int main()
int ch;
printf("\nContinue(Y/N)?");
ch = getchar();
return 0;
OUTPUT
33
Program 1: Write a Program to show operators and expression
#include<stdio.h>
#include<conio.h>
void main()
int num1,num2,sum,sub,mul,div,rem;
clrscr();
scanf("%d%d",&num1,&num2);
sum=num1+num2;
sub=num1-num2;
mul=num1*num2;
div=num1/num2;
rem=num1%num2;
getch();
OUTPUT:
34
3
sum=13
sub=7
mul=30
div=3
rem=1
i) x+y // 8
ii) x–y // 2
iii) x*y // 15
iv) x/y // 1
v) x%y // 2
Example 2. Solve the following expression if x=5, y=3, z=2, where x ,y and z are
integers:
i) x*y/z–z; // 5
ii) (x/z)*y–y; // 3
iii) x+y*z–y; // 8
35
i) 19<=15 // false
v) 11+8==13+6 // true
a)
Int x;
X = 4;
OUTPUT:
b)
36
int x,y,z;
x=4;
y=6;
z=++x + y++;
OUTPUT:
11
c)
int x ,y;
x=3;
printf(“y= %d\n”,y);
printf(“x= %d\n”,x);
OUTPUT:
216
37
d)
int x ,y;
x=3;
printf(“y= %d”,y);
printf(“x= %d”,x);
OUTPUT:
27
4. Summary
themselves.
Simple expressions have only one operator whereas compound expressions contain more
38
In a compound expression, if operators of different precedence appear together, then
The type of result of the binary operator will also be the common type.
Explicit type conversion is done with the help of a type cast operator.
4. Jeri R. Hanly & Elliot P. Koffman, “Problem Solving and Program Design in C”,
Addison Wesley.
India, 2010.
Design
39
6. Self Assessment Questions
3. What are postfix and prefix increment and decrement operators? Illustrate with
example.
and associativity.
7. What are bit wise operators? Explain any three bitwise operators with example.
40
Lesson 5:
Control Statements
1
Structure:
1. Introduction
2. Objectives
3. Presentation of Contents
3.2.1. IF Statement
3.2.1.1. Simple IF
3.2.1.2. IF…ELSE
3.4. Repetition/Looping
2
3.5 Jumping Out From Loop or Block (BREAK Statement)
4. Summary
1. Introduction
So far you have learnt that instructions are executed sequentially in the program. Each
instruction is executed once and only once sequentially. Programs do not change or alter
the order of execution. However, most programs require that a group of instructions be
changed order of its execution. This is known as branching and when this branching based
on any condition then it is called conditional branching and when not based on any
2. Objectives
repetition.
3. Understand the use and working of selection statements such as IF-THEN, IF-
3
4. Understand the use and working of repetition statements such as WHILE, DO-
3. Presentation of Contents
Selection: In a selection structure certain instructions will only be carried out IF a certain
Repetition: In a repetition structure certain instructions will be repeatedly carried out until
false (DO-UNTIL). Such structures consist of a loop which takes the program back to the
MAKING STATEMENTS
1. If statement
4
3. Conditional operator statement
3.2.1. IF STATEMENT
1. Simple if
2. if...else
4. else if ladder
3.2.1.1. SIMPLE IF
Statement will execute if the given expression is true. If the user wants to add more than one
Syntax:
if (expression)
statement;
statement;
e.g.
1 #include <stdio.h>
5
2 main()
3 {
4 int x;
6 scanf(“%d”, &x);
7 if(x = = 10)
10 }
OUTPUT:
Enter value of x 10
The value is ok
Explanation: line no. 7 if expression (x==10) is true then statement 8 is print in response
to if statement and after that statement 9 will be printed. If we want to run more than one
statement run in response to if statement then we have to enclosed the statements in curly
braces.
3.2.1.2. IF…ELSE
condition evaluated to true then statement no. 1 and 2 is run and if condition evaluates to
6
Syntax:
----
----
if(Expression)
statement 1;
statement 2;
else
statement 3;
statement 4;
statement 5;
----
----
e.g.
1. #include <stdio.h>
2. main()
3. {
4. char sex;
7
6. scanf(“%c”, &sex);
7. if(sex= =’m’)
8. {
11. }
12. else
13. {
15. printf(“FEMALE\n");
16. }
18. }
OUPUT:
First Run
Explanation: in the first run of the program when user enters value ‘m’ then the condition
is true and in response to condition evaluates to true statement no. 9 & 10 is executed and
In the second run of program when user enters value ‘f’ then the condition is evaluates to
8
false and in response to condition evaluates to false statement no. 14 & 15 is executed and
And statement no.17 executes in both run because this statement is the other statement of
When a clause of the if statement may itself contain another if statement then this construct
Syntax:
----
----
If(Expression or condition)
if(Expression or condition)
---
---
else
---
---
9
}
else
Statement x;
Statement y;
Statement z;
e.g. if salary of female is greater than or equal to 5000 then a bonus of Rs. 500 is added to
the salary. In this case two condition will be included. first which check male or female
and second which check salary greater than or equal to 5000 or not.
e.g.
1. #include <stdio.h>
2. main()
3. {
5. char sex;
6. int bonus=0;
10
7. printf(“Enter sex ‘m’ for male and ‘f’ for female”);
8. scanf(“%c”, &sex);
9. printf(“Enter salary”);
12. {
14. {
15. bonus=500;
16. gross=salary+bonus;
17. }
18. else
19. {
20. gross=salary+bonus;
21. }
22. else
23. {
24. gross=salary+bonus;
25. }
26.
28. }
OUTPUT:
11
First Run
Enter sex ‘m’ for male and ‘f’ for female m [First Condition false then
is added.
Second Run
Enter sex ‘m’ for male and ‘f’ for female f [First Condition true but second
bonus 0 is added
NOTE: It is very important to be sure which else clause goes with which if clause. The
rule is that each else matches the nearest if preceding it which has not already been
matched by an else. Addition of braces prevents any association between the if statement
within the braces and the else clause outside them. Even where braces are not necessary,
12
When a clause of the else statement may itself contain if statement and inner else further
Syntax:
----
----
If(Expression or condtion)
Statement x;
Statement y;
else
if(Expression)
---
---
else
if(Expression)
13
---
---
else
So On…
Statement z;
The switch statement uses when we have more than two alternate to a particular problem.
It choses a particular group of statements from several available groups. The selection is
based upon the expression that is included within the switch statement.
Syntax:
---
---
switch (expression)
14
{
case constant :
statement ;
statement;
----
break;
case constant :
statement ;
statement;
----
break;
------
------
------
default:
statement ;
statement;
----
statement x;
Where
15
Expression may be of integer type and also of char type because individual characters
Case Label must be a constant value and unique within a given switch statement and
precede with colon symbol. There are as many as cases. Last case is default means when
Each alternative or case is composed of a group of one or more individual statements. For
each alternative (case), the first statement within the group must be preceded by one or
more case labels. The case labels identify the different groups of statements and
distinguish them from one another. Last statement of each case except default is a break
statement. When a particular case match, all the statement of matched case is executed and
control goes to the next statement immediate after the switch case statement i.e statement
Thus, the switch statement is in effect an extension of the familiar if…else statement.
Rather than permitting maximum of only two branches, the switch statement permits
e.g.
char ch;
printf(“Enter a character”);
scanf(“%c”,&ch);
16
switch(ch)
case ’a’
printf(“vowel a”);
break;
case ‘e’ :
printf(“vowel e”);
break;
case ‘i’ :
printf(“vowel i”);
break;
case’ o’ :
printf(“vowel o”);
break;
case ‘u’ :
printf(“vowel u”);
break;
default:
statement”);
17
OUTPUT:
First Run
Vowel e
Second Run
Vowel o
Syntax:
evaluated and this becomes the value of the conditional expression. If expression 1 is false,
then expression 3 is evaluated and this becomes the value of the conditional expression
18
The expression (i<1) is evaluated first, if it is true the entire conditional expression takes
on the value 0. Otherwise, the entire conditional expression takes on the value 200.
The goto statement is used to alter the normal sequence of program execution by
transferring control to some other part of the program. But it is not good practice to use
goto statement for programming. As much extent we will not use it.
Syntax:
goto label;
Label is an identifier used to label the target statement to which control will be transferred.
Control may be transferred to any other statement within the program. The target statement
must be labeled, and the label must be followed by a colon. Thus the target statement will
appear as
Label : statement ;
#include<stdio.h>
#include<conio.h>
void main()
int num;
19
clrscr();
scanf("%d",&num);
if(num%2==0)
printf("\nNo is EVEN");
else
printf("\nNo. is ODD");
getch();
OUTPUT:
No. is ODD
#include<stdio.h>
#include<conio.h>
void main()
int year;
20
clrscr();
scanf("%d",&year);
if(((year%4==0)&&(year%100!=0))||(year%400==0))
else
getch();
OUTPUT:
1996
#include<stdio.h>
#include<conio.h>
#include<math.h>
21
void main()
int num,root=0;
clrscr();
scanf("%d",&num);
root=sqrt(num);
if((num-root*root)==0)
else
getch();
OUTPUT:
144
22
Program 8: Program of calculator by switch statement
#include<stdio.h>
#include<conio.h>
void main()
int a,b;
int ch;
clrscr();
scanf("%d%d",&a,&b);
printf("*******************Menu**************\n");
printf("****** 4.Multiplication*************\n");
scanf("%d",&ch);
23
switch(ch)
case 1:
printf("Addition=%d",a+b);
break;
case 2:
printf("Subtraction=%d",a-b);
break;
case 3:
printf("Division=%d",a/b);
break;
case 4:
printf("Multiplication=%d",a*b);
break;
case 5:
printf("Remainder=%d",a%b);
break;
case 6:
exit(0);
24
break;
default:
printf("invalid choice\n");
getch();
OUTPUT:
10
*******************Menu**************
****** 4.Multiplication*************
press from 1 to 6
3.4. REPETITION/LOOPING
25
Most programs, however, require that a group of instructions be executed repeatedly means
more than one time, until some logical condition has been satisfied. This is known as looping
or repetition. Most of the programs require that a logical test be carried out at some particular
Type of Loop:
The while loop is used to carry out looping operations. Every loop has three things.
Syntax:
---
---
26
{
statement;
statement x;
NOTE: while loop is entry controlled loop because condition check at entry point of loop.
Without satisfying the condition control can not enter in the body of loop.
All variables used in the test expression of the while statement must be initialized at some
point before the while loop is reached. In addition, the body of the loop must do something to
change the value of the variable used in the expression being tested. Otherwise the condition
would remain true and the loop would never terminate. This situation, known as an infinite
First of all loop counter i is declared and initialized with value 1. The value of the test
expression enclosed in parentheses is evaluated. If the result is true, then the program
statement (the body of the loop) is executed. The statement may be a compound statement.
Then the test expression, which may be just as complex as any of those found in if statement is
evaluated again. If it is again true, the statement is executed once more. This process continues
until the test expression becomes false. At that point, the loop is terminated immediately, and
program execution continues with the statement x (if any) following the while loop. If there
27
are no more statements, the program terminates.
e.g.
include<stdio.h>
main( )
int x=1;
while(x<=5)
x++;
OUTPUT:
line number 1
line number 2
line number 3
line number 4
line number 5
NOTE: If x were initialized to a value of 6, the condition in the while loop becomes false to
begin with , and the body of the loop would not be executed at all. It is clear, then, that the
while statement employs a loop pre-test. The loop condition is tested before each iteration, and
28
therefore before the loop is entered at all. If the condition initially fails, the loop is skipped
There is another way to use while loop, instead of incrementing the value of variables inside
the loop, you can also decrement it. For example, if you want to print the line number of test
program in reverse order then test expression changes and the program is as follows:
include<stdio.h>
main( )
int x=5;
while(x>=1)
x- -;
OUTPUT:
line number 5
line number 4
line number 3
line number 2
29
line number 1
There is an option for test expression in while loop, instead of giving some constant value
to test variable you can even given it some variable also. The value of this variable can be
input from the user interactively e.g. if the user wants to calculate the average of numbers,
but ‘how many numbers?’ this number can be input from the user itself and then this
If the test expression involves two variables and joined with ‘&&’ or ‘||’ operator
#include <stdio.h>
main( )
int x=1;
int a=4;
x++;
The loop executes only while x is less than 6 and a is greater than 3. If at least one of these
conditions becomes false, the loop terminates. If at least one of the conditions is false when the
30
The value of a is not changed in the loop, but the value of x is incremented in a way that will
make the loop terminate eventually. If the value of a is less than or equal to 3, then the initial
The do… while loop differs from the while loop in entry or exit. That is the condition is not
tested until the body of the loop has been executed once. In the while loop, by contrast, the test
is made on entry to the loop rather than at the end. The effect is that even if the condition is
false when the do-while loop is first encountered, the body of the loop is executed at least
once. If the condition is false after the first iteration, the loop terminates. If the first iteration
Syntax:
---
---
do
statement;
statement x;
31
}
NOTE: do-while loop is exit controlled loop because condition check at exit point of loop.
Control can enter into the body of loop without satisfying the condition at the very first
e.g.
#include<stdio.h>
main( )
int x=1;
do
x++;
} while(x<=5);
OUTPUT:
line number 1
line number 2
line number 3
line number 4
32
line number 5
NOTE: In above example , if variable x=6 means expression (x<=5) evaluate to false at
the beginning of loop. Yet, statement printf(“line number %d \n”,x) will be executed once
and loop terminates and continue with next statement after the loop.
The for loop is the most commonly used loop in 'C'. This loop includes an expression that
specifies an initial value for loop counter, another expression determines whether or not the
loop is continued and the third expression that increment or decrement the loop counter.
Syntax:
statement ;
statement;
---
---
33
iteration of the loop and determines whether the loop should continue or be termi-
nated.
exp3 = modifier expression (increment/ decrement loop counter), changes the value
of the variable used in the test. This expression is executed at the end of each
NOTE: The three loops expressions are separated by two semicolons. No semicolon
e.g.
include<stdio.h>
main( )
int x;
for(x=1;x<=5;x++)
OUTPUT:
line number 1
line number 2
line number 3
34
line number 4
line number 5
NOTE: The first expression of the for loop can be omitted if the variable is initialized
outside the loop. If one or more expressions are omitted from the for loop, the two
semicolons still must appear, even if they are not preceded or followed by anything.
e.g.
#include<stdio.h>
main( )
int x;
x=1;
x++;
Loops can be nested or embedded within another. The inner and outer loops need not be
generated by the same type of control structure. It is essential, however that one loop be
35
completely embedded within the other there can be no overlap. Each loop must be
#include<stdio.h>
#include<conio.h>
void main()
int i,j;
clrscr();
for(i=2;i<=5;i++)
printf("table of %d:\n\n",i);
for(j=1;j<=10;j++)
printf("%d\t",i*j);
printf("\n\n\n\n");
getch( );
OUTPUT:
table of 2:
36
2 4 6 8 10 12 14 16 18 20
table of 3:
3 6 9 12 15 18 21 24 27 30
table of 4:
4 8 12 16 20 24 28 32 36 40
table of 5:
5 10 15 20 25 30 35 40 45 50
Explanation: In this program firstly, outer for loop will be executed, if the expression (test) is
“table of 2:”
then inner loop will be executed. Inner loop will be executed till the test expression of inner
“2 4 6 8 10 12 14 16 18 20”
Then if the expression is false, the pointer again goes to outer loop and then it will re execute
the next iteration and so on. For nested loops any other loop structures could also have been
selected.
The break statement is used to force fully terminate loops or to exit from a switch or any block
of code. It can be used within a while, a do-while, for or a switch statement. The format is
simple as
break;
without any embedded expression or statements. The break statement causes a transfer of
37
control out of the entire block of code, to the first statement following the block of code. If
a break statement is included in a while, in do while or in for loop, then control will
immediately be transferred out of the loop when the break statement is encountered. Thus
provides a convenient way to terminate the loop if an error or other irregular condition is
#include <stdio.h>
main()
int x;
x=1;
while(x<=10)
if (x==5)
loop
printf(“%d ”,x);
x++;
38
printf(“\nnext statement after while loop”);
OUTPUT:
1 2 3 4
The continue statement is used to bypass the remainder of the current pass through a loop.
The loop does not terminate when a continue statement is encountered, instead the
remaining loop statements are skipped and the computation proceeds directly to the next
pass through the loop. It can also be included within a while, do while or a for statement as
Syntax: continue;
39
Program 17: Program to show binary conversion of decimal integer
#include<stdio.h>
#include<conio.h>
void main()
int num;
int a[15],i;
clrscr();
40
scanf("%d",&num);
i=0;
while(num>=1)
a[i]=num%2;
num=num/2;
i++;
for(i=i-1;i>=0;i--)
printf("%d",a[i]);
getch();
OUTPUT:
12345
11000000111001
41
Program 18: Program to Compute and print Armstrong no.
e.g. 153
#include<stdio.h>
#include<conio.h>
void main()
int n,sum=0,num,r;
clrscr();
for(n=1;n<=500;n++)
num=n;
while(num)
r=num%10;
sum=sum+r*r*r;
num=num/10;
42
}
if(n==sum)
printf("%d \t",n);
sum=0;
getch();
OUTPUT:
e.g 6 whose proper divisors are 1, 2, 3 whose sum is 6 equal to original number so 6 is
perfect number
#include<stdio.h>
#include<conio.h>
43
void main()
int num,i,sum=1;
clrscr();
printf("Enter number:\n");
scanf("%d",&num);
for(i=2;i<=num/2;i++)
if(num%i!=0)
continue;
sum=sum+i;
if(sum==num)
else
getch();
44
OUTPUT:
Enter number:
No 6 is a perfect number
#include<stdio.h>
#include<conio.h>
void main()
long num[50],num1,num2,n,m,i,j;
clrscr();
printf("Enter number\n");
scanf("%ld",&n);
num[1]=num[2]=1;
for(i=3;i<=n;i++)
num[i]=num[i-2]+num[i-1];
45
printf("%ld ",num[i]);
getch();
OUTPUT:
Enter number
1 1 2 3 5 8 13
#include<stdio.h>
#include<conio.h>
#include<math.h>
void main()
long num,r,dup;
unsigned size=0;
clrscr();
46
scanf("%ld",&num);
dup=num;
while(dup)
r=dup%10;
size++;
dup=dup/10;
dup=num;
while(size)
r=dup/pow(10,--size);
switch(r)
case 0:
printf("zero ");
break;
case 1:
47
printf("one ");
break;
case 2:
printf("two ");
break;
case 3:
printf("three ");
break;
case 4:
printf("four ");
break;
case 5:
printf("five ");
break;
case 6:
printf("six ");
break;
case 7:
48
printf("seven ");
break;
case 8:
printf("eight ");
break;
case 9:
printf("nine ");
break;
default:
break;
dup=dup-r*pow(10,size);
getch();
OUTPUT:
12458
49
one two four five eight
#include<stdio.h>
#include<conio.h>
void main()
float fah;
int cel;
clrscr();
for(cel=40;cel<=50;cel++)
fah=1.8*cel+32;
printf("%5d %30.2f\n",cel,fah);
getch();
OUTPUT:
50
Celsius Temp. Fahrenheit Temp.
40 104.00
41 105.80
42 107.60
43 109.40
44 111.20
45 113.00
46 114.80
47 116.60
48 118.40
49 120.20
50 122.00
#include<stdio.h>
#include<conio.h>
void main()
{ int first,last,i,j,flag=0;
clrscr();
51
printf("Enter first no.");
scanf("%d",&first);
scanf("%d",&last);
for(i=first;i<=last;i++)
{ flag=0;
for(j=i-1;j>=2;j--)
if(i%j==0)
flag=1;
break;
if(flag==1)
continue;
52
else;
printf("prime=%d\n",i);
getch();
OUTPUT:
prime=2
prime=3
prime=5
prime=7
prime=11
prime=13
prime=17
prime=19
prime=23
53
sum=1/2 + 2/3 + 3/4.......+(n-1)/n.
#include<stdio.h>
#include<conio.h>
#include<math.h>
void main()
int i,n;
float sum,f;
clrscr();
scanf("%d",&n);
sum=0.0;
for(i=2;i<=n;i++)
f=(float)(i-1)/i;
sum=sum+f;
54
getch();
OUTPUT:
Enter value of n
#include<stdio.h>
#include<conio.h>
void main()
long num,rev=0;
int rem;
clrscr();
scanf("%ld",&num);
while(num)
55
{
rem=num%10;
rev=rev*10+rem;
num=num/10;
getch();
OUTPUT:
32319
Program 26: Program to print a number in a reverse and sum up its digits
#include<stdio.h>
#include<conio.h>
void main()
56
long num,num1,rem,sum=0;
clrscr();
scanf("%ld",&num);
num1=num;
while(num)
rem=num%10;
sum=sum+rem;
num=num/10;
printf("%ld",rem);
printf("\n\n");
sum=0;
for(;num1>0;)
rem=num1%10;
57
sum=sum+rem;
num1=num1/10;
printf("%ld",rem);
getch();
OUTPUT:
54321
Sum of Digits=15
54321
Sum of Digits=15
i) If ( x == y || y < z )
z= ( x * y ) / z;
58
else
z= ( x + y ) - z;
printf(“z=%d”, z);
OUTPUT:
Z=2
printf(“ it is OK”);
else
OUTPUT:
it is NOT OK
printf(“ Ok”);
else
59
{
printf(“NOT OK”);
OUTPUT:
OK
i) main( )
If(x = y)
ii) main ( )
Answer: No error
iii) main( )
int x = 5;
60
if x >= 3
i) main()
int i=10;
while(i=20)
ii) main()
int i;
i=10;
while(i<=5)
printf(“%d”,i);
i++;
OUTPUT: loop will not execute because of condition false at very first time.
61
iii) main()
int i;
i=10;
do
printf(“%d”,i);
i++;
while(i<=5);
OUTPUT: loop will execute once due to condition check after loop body.
iv) main()
int i;
for(i=1;i<=5;i++)
printf(“%d”,i);
OUTPUT: loop will not execute because of condition false at very first time like while loop.
v) main()
62
int i=0;
for( ; i ; )
Semi colon( ;)
i) x = x + 1;
ii) x + = 1;
iii) x + +;
iv) x = + 1;
Answer: iv x =+1
4. Summary
There are three ways for taking decisions in a program. First way is to use the if-else
statement, second way is to use the conditional operators and third way is to use the switch
63
statement.
The default scope of the if statement is only the next statement. So, to execute more than
An if block need not always be associated with an else block. However, an else block is
If the outcome of an if-else ladder is only one of two answers then the ladder should be
In C every test expression is evaluated in terms of zero and non-zero values. A zero value
Assignment statements used with conditional operators must be enclosed within a pair of
parenthesis.
The three types of loops available in C are for, while, and do-while.
A continue statement skips the execution of the statements after it and takes the control to
A do-while loop is used to ensure that the statements within the loop are executed at least
once.
4. Jeri R. Hanly & Elliot P. Koffman, “Problem Solving and Program Design in C”,
Addison Wesley.
64
5. Yashwant Kanetker, “Let us C”, BPB
India, 2010.
‘C’.
65
15. What is skipping a part of loop explain with example.
17. What is infinte loop (endless loop)? How we can avoid or prevent an infinite loop
situation.
66
Lesson 6:
Functions
1
Structure:
1. Introduction
2. Objectives
3. Presentation of Contents
4. Summary
1. INTRODUCTION
If a big problem is divided into various small problems then it is easy to solve small problem
than a big problem. In the previous lessons, you have seen how to declare identifiers, how to
In this lesson, you will learn how to group these components in a function so that these
broken down into a number of smaller, self-contained components, each of which has some
2
unique, identifiable purpose. Thus a C program can be modularized through the intelligent use
of such functions. You will also learn about the advantages of using functions, how to declare,
define and call them. You will be familiarized with the methods of increasing flexibility of a
C supports the use of library functions, which are used to carry out a number of commonly
used operations. C also allows programmers to define their own functions for carrying out
various tasks.
2. Objectives
2. Create C functions.
3. Presentation of Contents
Function is a self-contained set of instruction that carries out some specific well-defined task.
Every C program contains one or more functions. Main( ) function is must for every program
because execution begin with the first statement of main( ) function and execution end with
the last statement of main( ) function so we can say that main( ) function is very important
3
Every C function has three components:
i) Function Declaration
Function prototypes are usually written at the beginning of a program, ahead of any programmer
where :
Formal arguments are optional arguments. If want to use then specifies them.
e.g.
void fun4( );
A function definition has two principal components: the first line (including the argument
declarations) and the body of the function. The first line of a function contains the type
specification of the value returned by the function, followed by the function name and
4
optionally a set of arguments, separated by commas and enclosed in parentheses. Each
argument is preceded by its associated type declaration. In general terms, the first line and
---
statement;
---
return statement;
e.g.
int z;
z=x+y;
return z;
float z;
5
z=x+y;
return z;
int z;
z=x+y;
return z;
d) void fun4()
A function can be called or accessed by specifying its name followed by a list of arguments
enclosed in parentheses and separated by commas. If the function call does not require any
arguments, an empty pair of parentheses must follow the name of the function. In general
e.g.
6
float c=10.5,d=20.6,s2;
s1=fun1(a,b);
s2=fun2(c,d);
s3=fun3(a,b);
fun4( );
Points to be noted: The following points must be noted about the functions.
1) The definitions of functions may appear in any order in a program file because they
4) Once the function has been executed, control will be returned to the point from which
information is passed to the function and from functions information is returned via
6) It is not necessary that every function must return information, there are some
functions also which do not return any information then return type will be void e.g.
7
3.2. FORMAL ARGUMENTS/ PARAMETERS
They receive information/value from the calling function(from actual parameters) of the
program. They are also known as parameters or formal parameters as shown in Fig. 1.
1) Actual Parameters: These are passed from the calling function to the called function.
The names of actual parameters and formal parameters may be either same or different
but their data type should be same. Information is returned from the called function to
the calling function of the program via the return statement shown in Fig 1. The return
statement also causes control to be returned to the point from which the function was
accessed.
#include <stdio.h>
main()
int x,y,s=0;
int sum(int, int); /*function declaration: argument name is optional but data type
is must */
8
int c;
c=a+b;
return c;
value.
function call. However, if function definition precedes the first function call, there is
e.g
Program 2: Program in which definition of the function precedes the first call
#include<stdio.h>
#include<conio.h>
9
void swap( int x, int y) // function definition precede the function call
int z;
z=x;
x=y;
y=z;
void main( )
int a,b;
clrscr( );
a=10;
b=20;
swap(a,b);
getch( );
OUTPUT:
10
value of x after swap:20
NOTE: Function Swap(int x, int y); precede the function call so there is no need to include
1. Pass/call by value
2. Pass/call by reference
1. Pass/ Call By Value : When value is passed to a function via an actual argument, the
value of the actual argument is copied into the formal argument. Therefore, the value of
the corresponding formal argument can be altered within the called function, but the value
of the actual argument within the calling function/routine will not change. This procedure
for passing the value of an argument to a function is known as passing by value or call by
#include <stdio.h>
#include<conio.h>
main( )
11
int x=10;
clrscr( );
change(x);
getch( );
return 0;
void change(int y)
y=y+3;
OUTPUT:
12
Fig 2. Showing call by value
Points to Note:
(i) Function returns no value and passes no argument: In the following function no
void main()
13
{
----
(ii) Function returns value: In the following function value is returned by the function.
void main( )
{ -----
-----
-----
-----
float c;
c=a+b;
return (c);
via an actual argument, the reference (address) the actual argument is copied into the
formal argument. Therefore, the formal argument can altered the value of the actual
14
argument within the calling function/routine. This procedure for passing the reference of
receiving the reference/ address of actual argument, function has to need pointer as formal
argument because pointer can store reference or address. So before discuss any more
a) Pointer: The memory address of a variable is a constant value. The address can be
assigned to another variable as shown in Fig. 3. A variable that stores the address of
pointer is just like another variable that stores data; pointer holds memory address of a
variable.
Pointers have their area of application. They have used to access elements of array,
pass argument to a function by reference rather than value in order to modify the
original value of actual argument. Pass string to function, create data structure like list,
Pointer declaration :
Data-type * pointer-name;
Where
indirection operator
e.g.
int *ptr1;
float *ptr2;
15
double *ptr3;
void *ptr4;
Pointer always take 2 bytes in memory regardless of its type (int, float, double
Pointer contain address of variable which have the same data type as of
e.g.
----
----
int x;
x=10;
Int *ptr1;
Ptr1=&x;
16
printf(“%u”,&ptr1); // it will print address of ptr1 (i.e. 5510)
----
----
Fig 4. Showing pointer ptr1 which store the address of int variable x.
NOTE: here ‘*’ operator called as ‘value at address operator’ means a pointer ptr1 which
So we can access value of a variable directly by variable name and indirectly by pointer.
Now, we are coming back to our topic call by reference shown in Fig. 5.
#include <stdio.h>
#include<conio.h>
main( )
int x=10;
17
clrscr( );
getch( );
return 0;
void change(int *y) //funct. Def., pointer instead of simple variable as formal
argument
OUTPUT:
18
Fig. 5. Showing call by reference
Recursion is a process by which a function calls itself repeatedly, until some specified
condition has been satisfied. The process is used for repetitive computations in which each
action is stated in terms of a precious result. In order to solve a problem recursively, two
conditions must be satisfied. The problem must be written in a recursive form, and the
problem statement must include a stopping condition. The best example of recursion is
calculation of factorial of an integer quantity, in which the same procedure is repeating itself.
#include <stdio.h>
void main( )
int num;
19
long int x;
printf(“Enter number”);
x=fact(num);
if(p <=1)
return(1);
else
return(p *fact(p-1));
The point to be noted here is that the function ‘fact’ calls itself recursively, with an actual
argument (n-1) that decrease in value for each successive call. The recursive calls terminate
When a recursive program is executed, the recursive function calls are not executed
immediately. Instead of it, they are placed on a stack until the condition that terminates the
recursion is encountered. The function calls are then executed in reverse order, as they are
The use of recursion is not necessarily the best way to approach a problem, even though the
20
Advantage of Recursion: Some of the advantages of recursion are as follows.
2. The computer may run out of memory if the recursive calls are not checked.
4. Recursion may result in non-terminating iterations if proper precautions are not taken.
C Library functions are inbuilt functions in C Language. Function prototype and data
definitions of these functions are written in their respective header file. For example: If you
want to use printf() function, the header file <stdio.h> should be included.
There are many library functions available in C programming to help the programmer to write
a good efficient program. Suppose, you want to find the square root of a number. You can
write your own piece of code to find square root but, this process is time consuming and the
code you have written may not be the most efficient process to find square root. But, in C
programming you can find the square root by just using sqrt() function which is defined under
21
Program 6: Program to show the use of library function sqrt( ).
#include <stdio.h>
#include <math.h>
int main(){
float num,root;
scanf("%f",&num);
return 0;
Adding Function to Library: One way to provide the necessary library functions
declarations is to write them explicitly. C provides us a way by placing the required library
function declarations in special files called header files. The header files also contain other
information related to the use of the library functions such as symbolic constant definitions.
The required header files must be merged with the source program during the compilation
process. This is accomplished by placing one or more #include statements at the beginning of
the source program. The following five steps are used to add function to the library and then
Step 1 : write a function which you want to add in library and save in a file says sum.c.
e.g
22
int z;
z=x+y;
return z;
Step 2 : Compile the sum.c file. A new file is created sum.obj in which object code is created.
Step 3 : add the function to library by giving the command at command prompt by using dos
shell.
Here ‘math.lib’ is a library file. ‘+’ is denoted, file is added in library and
e.g
or
int sum(int,int);
Step 5 : to use the function present in the library as follows shown in Program 6.
23
#include<stdio.h>
#include “c:\tc\sum.h”
void main()
int a,b;
scanf(“%d%d”,&a,&b);
Printf(“\nsum=%d”,c);
OUTPUT:
Enter a & b
10
50
sum=60
#include<stdio.h>
#include<conio.h>
#include<math.h>
24
void main()
float x;
int n;
clrscr();
scanf("%f%d",&x,&n);
if(power (x,n))
printf("%.2f\n",power(x,n));
else
printf("Exponent is negative\n");
getch();
if(n<0)
return 0;
25
if(n==0)
return 1.0;
else
return(x*power(x,n-1));
OUTPUT:
125.00
i) main()
float a=16.5;
char ch=’D’;
fun1(a, ch);
26
printf(“\n %f %c”, a, ch);
ii) main()
fun1(&x,&y);
printf(“\n %d %d”,x,y);
a=a+a;
b=b+b;
Answer: Error, Data type of arguments is not matched. Addresses are passed from
main function as actual argument and formal arguments are not of pointer type they
iii) main()
27
{
fun1(a,b);
printf(“\n %d %d”,a,b);
printf(“\n %d %d”,x,y);
iv) main()
fun1(a,b);
printf(“\n %d %d”,a,b);
void fun1(x, y)
int x;
int y;
28
{
printf(“\n %d %d”,x,y);
i) main( )
main( );
OUTPUT:
Program will be in infinite loop because main( ) function call itself and no condition `
specified here which jumped out from this from infinite loop.
ii) main( )
int i=45,c;
c=check(i);
29
printf(“\n %d”,c);
check(int ch)
if(ch>=45)
return 100;
else
return
(10*10);
OUTPUT:
100
iii) main()
fun1(&i,&j);
30
*x = *x * *x ;
*y = *y * *y;
OUTPUT:
36 9
iv) main()
fun1(&i, j);
printf(“\n %d %d”, i, j );
*x = *x * *x ;
y=y *y;
OUTPUT:
36 3
31
4. Summary
Functions are categorized as: (a) user-defined functions and (b) library functions.
User-defined functions are defined by the user at the time of writing a program and are also
There are three aspects of working with user-defined functions: (a) function declaration, (b)
Every function definition consists of two parts: (a) header of the function and (b) body of the
function.
A function with no input–output does not accept any input and does not return any result.
The execution of a C program always begins with the function main. It need not to be called
explicitly.
Functions whose return type is void are known as void functions. void functions do not return
any value.
While calling a function, the expressions that appear within the parentheses of a function call
are known as actual arguments, and the variables declared in the parameter list in the header
32
The return statement is to return the result of computations done in the called function and/or
There are two forms of return statement: (a) return; and (b) return expression;.
Depending upon whether values or addresses are passed as arguments to a function, the
argument passing methods in C language are classified as: (a) pass by value and (b) pass by
reference/address.
If arguments are passed by value, the changes made in the values of formal parameters inside
the called function are not reflected back to the calling function.
If the arguments are passed by reference/address, the changes made in the values pointed to
by the formal parameters in the called function are reflected back to the calling function.
A function can return only one value by using the return statement but it can indirectly return
type.
Function calling itself is called recursive function and the process is known as recursion.
A pointer to a function, commonly known as the function pointer, is a variable that points to
Library functions or pre-defined functions are the functions whose functionality has already
33
5. Suggested Reading/Reference Material
4. Jeri R. Hanly & Elliot P. Koffman, “Problem Solving and Program Design in C”,
Addison Wesley.
2. Why we need user defined function? What is difference between user-defined function
4. How do you pass argument to a function? Explain two method of passing arguments
to function.
argument.
34
10. Should the number of parameters in the function prototype be always equal to the
11. Why the parameters given within a function prototypes are called ”dummy”
parameters?
35
Lesson 7:
Storage classes in C
1
Structure:
1. Introduction
2. Objectives
3. Presentation of Contents
3.3. Scope
4. Summary
1. Introduction
In the previous lessons, you have learned how to declare variables of different data types, as
well as to initialize and use those variables. It has been assumed that you can access variables
from anywhere. Now, the question is: Can we declare variables that are accessible only to
2
certain portions of a program? In this lesson you will learn about the scope and storage classes
of data in C.
2. Objectives
3. Presentation of Contents
The storage class of a variable specifies the lifetime and visibility of a variable. Variables
posses ‘storage class’ and ‘storage class specifier’. Storage class specifies the visibility and
scope of variable and storage class specifier indicates storage class specification. There are
four specifiers and corresponding storage classes that can be used in C language
3
3.1.1. AUTOMATIC OR AUTO STORAGE CLASS
An auto variable is defined and accessed with in a function. The auto specifier indicates that
the memory location of a variable is temporary. In other words, a variable's reserved space in
the memory can be erased or relocated when the variable is out of its scope. Only variables
with block scope can be declared with the auto specifier. The auto keyword is rarely used.
Storage : Memory
Lifetime : Till the control remains within the block in which it is defined.
#include<stdio.h>
void main()
a=10;
printf(“%d”,a);
Output:
4
10
The word register is borrowed from the world of computer hardware. Each computer has a
certain number of registers to hold data and perform arithmetic or logical calculations.
Because registers are located within the CPU, it's much quicker to access a register than a
memory location. Therefore, storing variables in registers may help to speed up the program.
The C language provides the register specifier. This specifier is applied to variables when it is
However, the register specifier only gives the compiler a suggestion. In other words, a
variable specified by the register keyword is not guaranteed to be stored in a register. The
compiler can ignore the suggestion if there is no register available, or if some other
It's illegal to take the address of a variable that is declared with the register specifier because
In the following lines of code, the integer variable i is declared with the register specifier:
int main()
register int i;
...
5
for (i=0; i<MAX_NUM; i++){
/* some statements */
...
return 0;
The declaration of i suggests that the compiler store the variable in a register. Because i is
intensively used in for loop, storing i in a register may increase the speed of the code.
Lifetime : Till the control remains within the block in which it is defined.
#include<stdio.h>
void main()
register int a;
a=10;
6
printf(“%d”,a);
Output:
10
The static specifier can be applied to variables with either block scope or program scope.
When a variable within a function is declared with the static specifier, the variable has a
permanent duration. In other words, the memory storage allocated for the variable is not
destroyed when the scope of the variable is exited, the value of the variable is maintained
outside the scope, and if execution ever returns to the scope of the variable, the last value
stored in the variable is still there. The various features this class are
Storage : Memory
For example, in the following lines of code the integer variable i has temporary duration by
default. But the other integer variable, j, has permanent duration due to the storage class
specifier static.
int main()
7
int i; /* block scope and temporary duration */
return 0;
The following program shows the effect of the static specifier on variables.
#include <stdio.h>
return (x + y);
main()
int i, j;
8
i, j, add_two(i, j));
return 0;
OUTPUT
The purpose of the above program is to call a function to add two integers and then print out
the result returned by the function on the screen. The function is called several times. A
counter is set to keep track of how many times the function has been called.
The programs of Fig. 1. shows the working of static storage class in comparison with auto
9
storage class
Fig. 1. Showing working of static storage class in comparison with auto storage class
A variable with program scope is visible through all source files that make up an executable
But how can a global variable declared in file A, be seen in file B? In other words, how does
the compiler know that the variable used in file B is actually the same variable declared in file
A?
Use the extern specifier provided by the C language to allude to a global variable defined
elsewhere. In this case, we declare a global variable in file A, and then declare the variable
10
For instance, suppose you have two global int variables, y and z, that are defined in one file,
and then, in another file, you may have the following declarations:
int main()
return 0;
Here, there are two integer variables, y and z, that are declared with the extern specifier,
outside and inside the main() function, respectively. When the compiler sees the two
declarations, it knows that the declarations are actually allusions to the global variables y and
Storage : Memory
Scope : Global
11
3.1.5. THE STORAGE CLASS MODIFIERS
C provides two storage class modifiers that can be used to indicate to the C compiler how
1. The const Modifier: If you declare a variable with the const modifier, the content of
the variable cannot be changed after it is initialized. For instance, the following
expression indicates to the compiler that Pi is a variable whose value should not be
changed
Similarly, the value of the character array str1 declared in the following statement
You can also declare a pointer variable with the const modifier so that an object
pointed to by the pointer cannot be changed. For example, consider the following
After the initialization, you cannot change the content of the string pointed to by the
pointer ptr_str.
2. The volatile Modifier: To declare a variable whose value can be changed without any
explicit assignment statement in the program. For instance, you might declare a global
12
variable that contains characters entered by the user. The address of the variable is
passed to a device register that accepts characters from the keyboard. However, when
the C compiler optimizes your program automatically, it intends to not update the
value held by the variable unless the variable is on the left side of an assignment
operator (=). In other words, the value of the variable is likely not changed even
To ask the compiler to turn off certain optimizations on a variable, you can declare the
variable with the volatile specifier. For instance, in the following lines of code, a
variable, keyboard_ch, declared with the volatile specifier, tells the compiler not to
optimize any expressions of the variable because the value saved by the variable may
void read_keyboard()
A variable has a definite lifetime. Lifetime of a variable is period during which its value and
Lifetime of local variable is limited to the period of execution of the function in which it
Visibility or scope of a variable specifies the area or portion of the program where it can
be accessed. Visibility of variable depends on its storage class and storage class specifier.
e.g.
#include<stdio.h>
void main( )
----
----
void fun1( )
storage class specifier: every strorage class of a variable tells four thing about variable i.e
initial value: initial value, whether it is initialized with garbage value or any other value
14
visibility or scope: area or portion of the program where it can be accessed.
3.3. SCOPE
The scope of an identifier is a region of the program within which the identifier is visible (i.e.
it can be used). In C language, the following four types of scopes are defined, which
1. Block Scope
2. Function Scope
3. Program Scope
4. File scope
In the complete program, there might be variables that have to be shared by all the functions.
On the other hand, the use of some other variables may be limited to only certain functions.
That is, the visibility of those variables is limited, and values assigned to those variables are
Limiting the scope of variables is very useful when several programmers are working on
different pieces of the same program. If they limit the scope of their variables to their pieces
of code, they do not have to worry about conflicting with variables of the same name used by
In C, you can declare a variable and indicate its visibility level by designating its scope. Thus,
variables with local scope can only be accessed within the block in which they are declared.
15
1. Block Scope: A block refers to any sets of statements enclosed in braces ({ and }). A
variable declared within a block has block scope. Thus, the variable is active and
accessible from its declaration point to the end of the block. Sometimes, block scope is
For example, the variable i declared within the block of the following main function has
block scope:
int main()
return 0;
Nested Block Scope: You can also declare variables within a nested block. If a
variable declared in the outer block shares the same name with one of the variables in
the inner block, the variable within the outer block is hidden by the one within the
#include <stdio.h>
16
main()
return 0;
OUTPUT
i= 0, j=10
i= 1, j= 9
i= 2, j= 8
i= 3, j= 7
i= 4, j= 6
i= 5, j= 5
i= 6, j= 4
17
i= 7, j= 3
i= 8, j= 2
i= 9, j= 1
i=10, j= 0
There are two nested blocks in Program 1. The integer variable i declared is visible within
the outer block enclosed by the braces ({ and }). Another two integer variables, i and j, are
visible only within the inner block. Although the integer variable i within the outer block
has the same name as one of the integer variables within the inner block, the two integer
variables cannot be accessed at the same time due to their different scopes.
2. Function Scope: Function scope indicates that a variable is active and visible from the
beginning to the end of a function. In C, only the goto label has function scope. For
example, the goto label, start, shown in the following code portion has function scope:
int main()
18
.
return 0;
Here the label start is visible from the beginning to the end of the main( ) function.
Therefore, there should not be more than one label having the same name within the
main( ) function.
3. Program Scope: A variable is said to have program scope when it is declared outside
a function. Variables with program scope are also called global variables, which are
visible among different files. These files are the entire source files that make up an
executable program. Note that a global variable is declared with an initializer outside a
int main()
19
return 0;
Here the int variable x and the float variable y have program scope.
#include <stdio.h>
void function_1()
main()
function_1();
/* a nested block */
function_1();
20
return 0;
OUTPUT
From function_1:
x=1234, y=1.234567
x=4321, y=1.234567
From function_1:
x=1234, y=1.234567
x=4321, y=7.654321
4. File Scope: A global variable declared with the static specifier is said to have file
scope. A variable with file scope is visible from its declaration point to the end of
the file. Here the file refers to the program file that contains the source code. Most
large programs consist of several program files. The following lines of code show
int main()
21
int i; /* block scope */
return 0;
Here the int variable y and the float variable z both have file scope.
i) main()
long x ;
x = 5;
Answer: No Error
ii) main()
char ch=201;
printf(“\n ch=%d”,ch);
}
22
Answer: Error, it will print undesired value because char ‘s range is -128 to 127
i) main()
if(count!=0)
main();
Output:
Count=6
Count=5
Count=4
Count=3
Count=2
Count=1
ii) main()
int i , j;
23
j = fun1( i );
fun1(int x)
int b=3;
p+=x;
return (p+x+b);
Output:
13
18
4. Summary
The scope of an identifier is a region of the program within which the identifier is visible
24
There are four types of scopes, namely file scope or global scope, block scope or local
Two identifiers have the same scope if and only if their scopes terminate at the same
point.
The keyword extern provides a method for declaring an identifier without defining it.
It is not allowed to define an identifier more than once in the same scope.
One definition rule states that each object must have only one definition in a scope.
It is possible to define an identifier with the same name more than once if the definitions
Lifetime of an object is the portion of the program execution during which the storage is
There are four storage classes, namely auto, register, static and extern.
By default, a variable with block scope has an auto duration, and its memory storage is
temporary.
A variable declared with the static specifier has permanent memory storage, even though
the function in which the variable is declared has been called and the function scope has
exited.
25
A variable declared with the register specifier may be stored in a register to speed up the
performance of a program; however, the compiler can ignore the specifier if there is no
You can also allude to a global variable defined elsewhere by using the extern specifier
4. Jeri R. Hanly & Elliot P. Koffman, “Problem Solving and Program Design in C”,
Addison Wesley.
India, 2010.
Auto
Static
Extern
Register
6. Give the main feature of global variable. Describe its lifetime and visibility.
7. Can a global variable be hidden by a local variable with block scope? Why do you
program?
9. When you declare a variable with the extern specifier, do you define the variable
10. Given the following code portion, which variables are global variables, and which
int x = 0;
float y = 0.0;
int myFunction()
int i, j;
float y;
...
27
{
int x, y;
...
...
11. When two variables with the same name are defined, how does the compiler know
12. Identify the storage class of each declaration in the following code portion:
int i = 0;
static int x;
extern float y;
int myFunction()
int i, j;
extern float z;
register long s;
...
28
const char ch_str[ ] = "The const specifier";
15. Compile and run the following program. What do you get on the screen, and why?
#include <stdio.h>
int main()
int i;
int x = 0;
static int y = 0;
return 0;
29
Lesson 8:
Arrays
1
Structure:
1. Introduction
2. Objectives
3. Presentation of Contents
4. Summary
1. Introduction
As we know that variable are used to store one value at a time means a variable stores only
single value at a time. In case of storing say 100 values, it is a very difficult task to store 100
2
different variable names with their values. Arrays are the solution to this problem. Arrays are
nothing but a single name to a whole group of similar type of data. The position in terms of
arrays is known as subscript. Each subscript must be expressed as a non-negative integer. The
In this lesson, we will discuss two important data types – array and pointer – which come
under the category of derived data types as we have studied earlier in Unit 1. One more
reason why we should read array and pointers is that the concept of array and pointer are
similar to each other. In fact the identifier of an array is equivalent to the address of its first
element, like a pointer is equivalent to the address of the first element that it points to, so in
fact they are similar. In the first half of the lesson we have discussed the methods of
initialization and declaration of arrays, further we have given the use of array in function,
and also defined the multidimensional arrays. All the topics are given with suitable
examples.
2. Objectives
3
3. Presentation of Contents
Arrays are defined in much the same manner as ordinary variables except that each array
name must be followed by a size specification. Arrays are of two types, One-Dimensional
Arrays and Multidimensional Arrays. For a one-dimensional array, the size is specified
by a positive integer expression enclosed in single square brackets. When two or more
An array is a collection of data storage locations, each of which holds the same type of
data. These storage areas are called elements. Arrays are used to handle large amounts of
data. An array can be thought of as a collection of numbered boxes each containing one
data item. The number associated with the box is the index of the item. To access a
particular item the index of the box associated with the item is used to access the
appropriate box. The index must be an integer and indicates the position of the element in
the array. Thus the elements of an array are ordered by the index. Array subscripts start
If the name of the array is arr, then arr[0] is the name of the element that is in position 0,
arr[1] is the name of the element that is in position 1, etc. In general, the ith element is in
position i – 1. So if the array has n elements, their names are arr[0], arr[1], arr[2], . . . ,
arr[n – 1].
Syntax:
4
e.g.
NOTE: The array’s size can be defined in terms of a symbolic constant rather than a fixed
integer quantity.
An array can be initialized like other variable. Following are the methods of initializing an
array. e.g.
int a[ ] = {10,20,30,40,50};
int a[5]={10,20,30}; //In this case a[3] and a[4] that are not initialized and are
5
3.2.2. PROCESSING ONE DIMENSIONAL ARRAY
One dimensional array is a collection of finite number of elements of same data type. Each
element of array has a unique index or subscript starting from 0 and ending at n-1. The
subscript denotes the elements of array. The elements of array are accessed by specifying
the name of the array, beginning square bracket, subscript (index) and closing square
bracket.
int a[5];
The values in the array can be stored by using one of the following methods.
a[0]=10;
a[1]=25;
a[2]=35;
a[3]=55;
a[4]=15;
or
int a[5]={10,25,35,55,15};
or
for(i=0;i<5;i++)
scanf(“%d”,a[i]);
6
Fig. 2 Declaration and initialization of array in memory
After storing the values in the array, these can be accessed. Suppose you want to show the
value of 3rd element then the following statement will display the required element.
#include<stdio.h>
#include<conio.h>
void main( )
int n1,n2,n3,n4,n5,n6,n7,n8,n9,n10;
int m[10],I;
clrscr( );
printf(“Enter 10 numbers\n”);
scanf(“%d%d%d%d%d%d%d%d%d%d”,&n1,&n2,&n3,&n4,&n5,&n6,&n7,&n8,&n9,&n
Printf(“%d %d %d %d %d %d %d %d %d %d”,n1,n2,n3,n4,n5,n6,n7
7
for(i=0;i<10;i++)
for(i=0;i<10;i++)
getch( );
First part of the program reads 10 numbers from keyboard in 10 different variables naming n1,
n2 up to n10 and similarly display them without an array. And in second part of the program,
above stated works of reading numbers done by using an array. It is easier than first part of
work.
Array with more than one subscript is known as multidimensional array. The following syntax
Syntax:
8
An array with two subscript called as two dimensional array. A two dimensional array is a
grid containing rows and columns, in which each element is uniquely specified by means of its
int a[2] [3]. //first subscript represents row and second subscript represent columns
An array can be initialized like other variable. Following are the methods of initializing
int a[2] [3]={10,20,30,40,50,60}; // Declares an array of two rows and three columns.
At the time of initialization, the size of array can be omitted. When size will be
int a[ ] [ ] = {
}; // end of initialization
9
Fig. 4 Declaration and initialization of two dimensional array in memory
where
a[0][0]=10
a[0][1]=20
a[0][2]=30
a[1][0]=40
a[1][1]=50
a[1][2]=60
Value of the elements of the two dimensional array are accessed by specifying the name of
int a[2][3];
The values in the array can be stored by using one of the following methods.
a[0][0]=10
a[0][1]=20
a[0][2]=30
10
a[1][0]=40
a[1][1]=50
a[1][2]=60
or
or
for(i=0;i<2;i++)
for(j=0;j<3;j++)
scanf(“%d”,a[i] [j]);
After storing the values in the array, these can be accessed. Suppose you want to show the
value of 2nd row and 2nd column then the following statement will display the required
element.
11
#include<stdio.h>
#include<conio.h>
void main( )
int a[2][3],i,j;
clrscr();
printf(“Elements of array\n”);
for(i=0;i<2;i++)
for(j=0;j<3;j++)
12
getch();
#include<stdio.h>
#include<conio.h>
void main()
int a[5][5],b[5][5],c[5][5],i,j,row,col;
clrscr();
scanf("%d%d",&row,&col);
for(i=0;i<row;i++)
for(j=0;j<col;j++)
scanf("%d",&a[i][j]);
scanf("%d%d",&row,&col);
13
for(i=0;i<row;i++)
for(j=0;j<col;j++)
scanf("%d",&b[i][j]);
for(i=0;i<row;i++)
for(j=0;j<col;j++)
c[i][j]=a[i][j]+b[i][j];
for(i=0;i<row;i++)
for(j=0;j<col;j++)
printf("%d ",c[i][j]);
printf("\n");
getch();
14
OUTPUT:
10
20
30
40
10
20
30
40
15
elements of c matrix are
20 40
60 80
An array name can be used as an argument to a function, thus permitting the entire array to be
passed to the function. An array is itself a pointer. The name of the array points to the address
of the first array element. Hence all array are passed by reference rather than by value. Being
an address, no ampersand(&) precedes array name when used as actual array name.
#include<stdio.h>
#include<conio.h>
void rev(int x ,int number[]); //function declaration includes array as formal argument.
void main( )
int i,j,n;
int num[25];
clrscr( );
16
scanf(“%d”,&n);
for(i=0;i<n;i++)
scanf(“%d”,&num[i]);
rev(n,num);
for(i=0;i<n;i++)
printf(“%d\n”,num[i]);
getch( );
int a,b,temp;
for(a=0,b=x-1;a<b;a++,b- -)
temp=number[a];
number[a]=number[b];
number[b]=temp;
OUTPUT:
10
17
5
15
25
25
15
10
The dynamic array is an array data structure which can be resized during runtime which
means elements can be added and removed. You can see in the given example that we
prompt the user to enter the number of elements that you want to set into the array.
The expression (int*)malloc(n*sizeof (int)) stores the number of elements in the memory.
The malloc is basically used for memory allocation. By using for loop, the variable i reads
the elements from the memory and displays the required array.
#include <stdlib.h>
#include <stdio.h>
#include <conio.h>
18
int main() {
int* array;
int n, i;
scanf("%d", &n);
scanf("%d", &array[i]);
getch();
return 0;
the string will be stored within one element of the array. For example,
19
char name[ ]= {‘I’,‘N’,‘D’,’I’,’A’,‘\0’};
Each character in the array takes one byte of memory and the last character is always ‘\0’.
The terminating null is important, because it is the only way the functions that work with a
string can know where the string ends. In facts, a string which is not terminated by a ‘\0’ is
In this declaration ‘\0’ is not necessary. C inserts the null character automatically. Let us
# include <stdio.h>
main()
int i;
for(i=0;i<5;i++)
}
20
OUTPUT:
INDIA.
With the help of null character this program can be written in the following manner:
#include <stdio.h>
main()
int i ;
for(i=0;name[i]!=’\0’;i++)
OUTPUT:
INDIA
#include<stdio.h>
main()
21
char name[20];
scanf(“%s”, name);
OUTPUT:
Bharat kumar
It will print the same string as entered from the user. The length of string should not exceed the
dimension of the character array. This is because the C compiler doesn’t perform bounds
#include<stdio.h>
#include<conio.h>
void main()
int a[5][5],m,n,i,j;
22
clrscr();
scanf("%d%d",&m,&n);
for(i=0;i<m;i++)
for(j=0;j<n;j++)
scanf("%d",&a[i][j]);
for(i=0;i<m;i++)
for(j=0;j<n;j++)
printf("%d ",a[i][j]);
printf("\n");
printf("Transpose of a matrix:\n");
for(i=0;i<n;i++)
for(j=0;j<m;j++)
23
printf("%d ",a[j][i]);
printf("\n");
getch();
OUTPUT:
123
24
456
Transpose of a matrix:
14
25
36
#include<stdio.h>
#include<conio.h>
void main()
int x[10][10],y[10][10],z[10][10];
int r,c,m,n,j;
clrscr();
scanf("%d%d",&r,&c);
if(r!=c)
25
printf("Cols of first matrix must equal to rows of second matrix\n");
exit();
for(m=0;m<r;m++)
for(n=0;n<c;n++)
scanf("%d",&x[m][n]);
for(m=0;m<r;m++)
for(n=0;n<c;n++)
scanf("%d",&y[m][n]);
for(m=0;m<r;m++)
for(n=0;n<c;n++)
for(j=0;j<c;j++)
26
}
for(m=0;m<r;m++)
for(n=0;n<c;n++)
printf("%8d",z[m][n]);
printf("\n");
getch();
OUTPUT:
27
4
11 14
15 22
i) main()
int i, a[5];
28
for(i=0; i<5; i++)
printf(“%d” , a[ i ] );
ii) main()
int i;
for(i=0;i<5;i++);
a[i]*=a[i];
printf(“%d”,a[i]);
iii) main()
int array[26],i;
for(i=0;i<=25;i++)
29
array[i]=’A’+i; // it adds A’s ascii value i.e.65 and
value of i
printf (“\n %d %c \n”, array[i], array[i]); /* it will print ascii value and
character */
OUTPUT: it shows the ascii value and its corresponding character from 65 to 90
4. Summary
An array is used to store homogeneous data, i.e. data of the same type.
All the elements of an array have the same name, i.e. the array name. They are
distinguished on the basis of their locations in the array. Locations are specified by
30
The array name refers to the address of the first element of the array and is a constant
object.
In C language, multi-dimensional arrays are stored in the memory by using row major
order of storage.
4. Jeri R. Hanly & Elliot P. Koffman, “Problem Solving and Program Design in C”,
Addison Wesley.
1. What are the limitations of an ordinary variable? How are these removed with an
array?
5. Write a program that will compute the length of a given character string.
31
6. Write a program that will count the number of occurrences of a specified character
7. Write a program to read two matrices A and B and print the following:
10. What is a dynamic array? How it is created? Give typical example of a dynamic
array.
main( )
int m[ ] = { 2,3,4,5,6 }
int x, y =0;
y=y+m[x];
32
Lesson 9:
Strings
1
Structure:
1. Introduction
2. Objectives
3. Presentation of Contents
4. Summary
2
1. Introduction
In the last lesson you learned how to use arrays to collect variables of the same type. You also
learned that a character string is actually a character array ended with a null character \0. In this
lesson you'll learn more about strings and C functions that can be used to manipulate strings.
Strings are often needed to be manipulated by programmer according to the need of a problem.
All string manipulation can be done manually by the programmer but, this makes programming
complex and large. To solve this, the C supports a large number of string handling functions.
There are numerous functions defined in "string.h" header file for reading, writing, copying,
2. Objectives
3. Presentation of Contents
3
3.1. STRING HANDLING
Definition: A string is a character array terminated by a null character (\0). For instance, a
character array, array_ch, declared in the following statement, is considered a character string:
In C, the null character can be used to mark the end of a string, or to return logical FALSE. C
A series of characters enclosed in double quotes ("") is called a string constant. The C compiler
can automatically add a null character (\0) at the end of a string constant to indicate the end of
the string.
Here the array arr_str is treated as a character array. However, if you add a null character (\0)
Here the array arr_str is expanded to hold seven elements; the last element contains a null
character. Now, the character array arr_str is considered a character string because of the null
The compiler can automatically append a null character (\0) to the end of the array, and treat the
character array as a character string. Note that the size of the array is specified to hold up to
seven elements, although the string constant has only six characters enclosed in double quotes.
You can declare an unsized character array if you want the compiler to calculate the total number
A string constant is a series of characters enclosed in double quotes (" "). On the other hand, a
When a character variable ch1 and a character array str1 are initialized with the same character,
5
1 byte is reserved for the character variable ch1, and two bytes are allocated for the character
array str1. The reason that an extra byte is needed for str1 is that the compiler has to append a
Another important thing is that a string is interpreted as a char pointer. Therefore, you can assign
char *ptr_str;
In C, there are several functions you can use for string reading or writing. Some of these
1. The gets() Function : The gets() function can be used to read characters from the
#include <stdio.h>
Here the characters read from the standard input stream are stored in the character array
identified by s. The gets() function stops reading, and appends a null character \0 to the
6
2. The puts() Function: The puts() function can be used to write characters to the standard
output stream (that is, stdout). The syntax for the puts() function is
#include <stdio.h>
Here s refers to the character array that contains a string. The puts() function writes the
string to the stdout. If the function is successful, it returns 0. Otherwise, a nonzero value
is returned. The puts() function appends a newline character to replace the null character
Both the gets() and puts() functions require the header file stdio.h. In the following
#include <stdio.h>
main()
char str[80];
gets( str );
i = 0;
while (str[i])
{
7
if ((str[i] >= `a') && (str[i] <= `z'))
++i;
puts( str );
return 0;
OUTPUT
This is a string.
THIS IS A STRING.
The above program accepts a string of characters entered from the keyboard and then
converts all lowercase characters to uppercase ones. Finally, the modified string is put
3. Using %s with the printf() Function : You have used the printf() function in many
programs in earlier lessons. Further, you also know that many format specifiers can be
8
used with the printf() function to specify different display formats for numbers of various
types. Similarly, you can use the string format specifier, %s, with the printf() function to
4. The scanf() Function : The scanf() function provides another way to read strings from
the standard input stream. The formats of arguments to the scanf() function are quite
similar to those used in the printf() function. The syntax for the scanf() function is
#include <stdio.h>
Here various format specifiers can be included inside the format string referenced by the
char pointer variable format. If the scanf() function concludes successfully, it returns the
number of data items read from the stdin. If an error occurs, the scanf() function returns
EOF (end-of-file).
Note that using the string format specifier %s causes the scanf() function to read
characters until a space, a newline, a tab, a vertical tab, or a form feed is encountered.
Characters read by the scanf() function are stored into an array referenced by the
corresponding argument. The array should be big enough to store the input characters.
The following program shows how to use various format specifiers with the scanf()
function.
9
Program 2. A program that uses the scanf() function with various format specifiers.
#include <stdio.h>
main()
char str[80];
int x, y;
float z;
scanf("%f", &z);
printf("Enter a string:\n");
scanf("%s", str);
return 0;
OUTPUT
10 12345
1.234567
10
Enter a string:
string
10 12345
1.234567
String
Strings are often needed to be manipulated by programmer according to the need of a problem.
All string manipulation can be done manually by the programmer but, this makes programming
complex and large. To solve this, the C supports a large number of string handling functions.
There are numerous functions defined in "string.h" header file. Few commonly used string
11
strupr() Converts string to uppercase
1. The strlen() Function : This function is used to know how many bytes are taken by a
string, This means it measures the length of a string. The syntax for the strlen() function
is
#include <string.h>
Here s is a char pointer variable. The return value from the function is the number of
bytes. size_t is a data type defined in the string.h header file. Note that string.h has to be
included in your program before you can call the strlen() function.
The following program shows the use of strlen() function to measure string lengths.
#include <stdio.h>
12
#include <string.h>
main()
strlen(ptr_str));
return 0;
OUTPUT
NOTE: The strlen() function does not count the null characters appended to the two string
13
2. Copying Strings with strcpy() : This function is used to copy a string from one array to
another. You can copy each item of the first array to the corresponding element in the
second array, or you can simply call the C function strcpy(). The syntax for the strcpy()
function is
#include <string.h>
Here the content of the string src is copied to the array referenced by dest. The strcpy()
function returns the value of src if it is successful. The header file string.h must be
The following program shows how to copy a string from one array to another by either
#include <stdio.h>
#include <string.h>
main()
char str2[15];
char str3[15];
int i;
14
/* with strcpy() */
strcpy(str2, str1);
/* without strcpy() */
str3[i] = str1[i];
str3[i] = `\0';
return 0;
OUTPUT
3. Concatenates (joins) two strings with strcat(): This function concatenates the strings. It
does not concatenate two strings together and give you a third, new string; what it really
does is append one string onto the end of another. For example,
15
printf("%s\n", string5);
strcat(string5, string6);
printf("%s\n", string5);
The first call to printf function prints ``Hello, '', and the second one prints ``Hello,
world!'', indicating that the contents of string6 have been tacked on to the end of string5.
Notice that we declared string5 with extra space, to make room for the appended
characters.
4. Compares two string with strcmp() : This function compares two strings, and returns 0
if they are identical, or a negative number if the first string is alphabetically ``less than''
the second string, or a positive number if the first string is ``greater.'' The meaning of one
string to be ``less than'' another is that it would come first in a dictionary or telephone
if(strcmp(string3, string4) == 0)
These lines of code will print ``strings are different''. Notice that strcmp does not return a
16
The dynamic string is an array data structure which can be resized during runtime which means
characters can be added and removed. As you have seen in case of dynamic arrays, in the given
example, we prompt the user to enter the number of elements that you want to set into the array.
characters. By using for loop, the variable i reads the characters from the memory and displays
#include <stdlib.h>
#include <stdio.h>
#include <conio.h>
int main()
int* array;
int n, i;
scanf("%d", &n);
scanf("%c", &array[i]);
getch();
return 0;
#include<stdio.h>
#include<string.h>
#define MAX_STRING_LEN 80
int main() {
char S1[MAX_STRING_LEN];
char S2[MAX_STRING_LEN];
int i, l, res;
printf("String1:\t");
scanf("%s",S1);
printf("String2:\t");
scanf("%s",S2);
res = strcmp(S1,S2);
printf("strcmp(%sS1,%sS2) = %d\n",S1,S2,res);
18
Program 7: Program to Copy Strings
#include<stdio.h>
#include<string.h>
#define MAX_STRING_LEN 80
int main() {
char* S1 = "AAAAAAAAAA";
char* S2 = "BBBBBBBBBB";
int i, l;
/* assign S1 to S2 */
S2 = S1;
/* change S1 */
S1[3] = 0;
printf("S1:\t%s\n",S1);
printf("S2:\t%s\n",S2);
#include<stdio.h>
#include<string.h>
#define MAX_STRING_LEN 80
19
int main() {
char* S1 = "AAAAAAAAAA";
char* S2 = "AAAAAAAAAA";
cmp2 = strcmp(S1,S2);
printf("S1:\t%s\n",S1);
printf("S2:\t%s\n",S2);
printf("S1 == S2:\t%d\n",cmp1);
printf("strcmp(S1,S2):\t%d\n",cmp2);
S2 = S1;
cmp4 = strcmp(S1,S2);
printf("\nafter assignment\n");
printf("S1:\t%s\n",S1);
printf("S2:\t%s\n",S2);
printf("S1 == S2:\t%d\n",cmp3);
printf("strcmp(S1,S2):\t%d\n",cmp4);
#include<string.h>
20
#include<stdio.h>
#define MAX_STRING_LENGTH 80
int main() {
char S1[MAX_STRING_LENGTH];
char S2[MAX_STRING_LENGTH];
strcat(S1,S2);
printf("S1:\t");
scanf("%s",S1);
printf("S2:\t");
scanf("%s",S2);
strcat(S1,S2);
printf("\nafter strcat(S1,S2)\n");
printf("S1:\t%s\n",S1);
printf("S2:\t%s\n",S2);
You can also create and use two dimensional Arrays of characters. Let us first consider an example
of 2D array of character.
21
Program 10. A program to show 2D array of character
#include <stdio.h>
#include<conio.h>
main()
int i, flag, a;
char name[10];
clrscr();
scanf("%s",&name);
flag=0;
for(i=0;i<=5;i++)
a = strcmp(&sample[i][0],name);
if(a== 0)
flag =1;
break;
22
}
if(flag==0)
printf("Wrong candidate");
getch();
OUTPUT:
First Run:
ghansham
Second Run:
bharat
Wrong candidate
The program shows how the two dimensional character array has been initialized. The order of the
23
subscripts in the array declaration is important. The first subscript gives the number of names in the
array, while the second subscript gives the length of each item in the array.
4. Summary
A string literal is a sequence of zero or more characters enclosed within double quotes.
Due to this additional null character, a string constant takes 1 byte more than the number of
In C language, string type is not separately available and character pointers are used to
represent a string.
The type of string literal constants is const char*. The constant pointer refers to the address
Strings can be read from the keyboard by using scanf and gets functions.
The scanf function is used for reading single-word strings while the gets function can be used
Strings are printed on the screen by using printf and puts functions.
24
The printf function does not place a new line character after printing the string but
the puts function places a new line character after printing the string.
The C string library provides a rich set of functionality to manipulate strings in the form of
Real-time applications often require storage and processing of a number of strings at a time.
A list of strings can be stored by using an array of strings or by using an array of character
pointers.
The main function can also take string inputs from the command line. The arguments given
to the function main from the command line are known as command line arguments.
4. Jeri R. Hanly & Elliot P. Koffman, “Problem Solving and Program Design in C”,
Addison Wesley.
25
6. Self Assessment Questions
2. What is string terminator? What is its purpose explain its importance with example.
i) strcpy( )
ii) strcat( )
iii) strlen( )
iv) strcmp( )
5. What are the main differences between a string constant and a character constant?
6. Does the gets() function save the newline character from the standard input stream?
9. Given a char pointer variable ptr_ch, are the following statements legal?
i. *ptr_ch = `a';
26
10. Can the puts() function print out the null character in a character array?
11. Which format specifier do you use with the scanf() function to read in a string, and which
Write a program to copy the string from str1 to another array, called str2.
13. Write a program to measure the length of a string by evaluating the elements in the
character array one by one. To prove you get the right result, you can use the strlen()
14. Write program that convert all uppercase characters to their lowercase counterparts.
15. Write a program that uses the scanf() function to read in two integers entered by the user,
adds the two integers, and then prints out the sum on the screen.
27
Post Graduate Diploma in Computer Science and Applications
1. INTRODUCTION
2. OBJECTIVE
3. CONTENTS
4.EXAMPLE PROGRAMS
5. SUMMARY
6. SUGGESTED READINGS
In C, variables are used to hold data values during the execution of a program. Every variable,
when declared occupies certain memory location. Pointer variable stores the memory address of
any type of variable. It is denoted by, asterisk (*), symbol. With pointers, one can manipulate
memory addresses. It is possible to access and display the address of a memory location of
variable using the pointers. Pointers are also used for the allocation of me ory during run time,
also known as dynamic memory allocation. Dynamic memory allocation is essential for handling
various data structures like, structures, trees, linked lists, stacks, most important, being arrays.
Another use of pointers is command-line arguments. Command line arguments are passed to
programs and stored in an array of pointers.
2. OBJECTIVE
Most of the computer language learners feel that the pointer is a puzzling topic and very difficult
to understand. However, the pointer enables fast and straightforward execution of a program.
With pointers, memory is used most efficiently. Pointers reduce length and the complexity of the
programs.They increase the execution speed and thus reduce the program execution time. C
gives more importance to punters because of their flexible and dynamic nature.Hence, it
becomes important to learn the operation and applications of pointers.Thus, the real power of C
lies in te proper use of pointers. In this lesson, pointers and their usage is described in detail. It
also describes the various operations that can be performed on a pointer variable. How the
pointers can be used to handle functions, arrays and strings is also explained.
A pointer is a variable that represents the location of a data item, such as a variable or anarray
element. Pointers are used frequently in C, as they have a number of useful applications.For
example, pointers can be used to pass information back and forth between a functionand its
reference point. Pointers provide a way to return multiple data items from a functionvia function
arguments to be specified as arguments to a given function.Pointers are also closely associated
with arrays and therefore provide an alternate way toaccess individual array elements.
Within the computer’s memory, every stored data item occupies one or more adjacent memory
cells. The number of memory cells required to store a data item depends on the type of dataitem.
For example, a single character will be stored in 1 byte of memory integer usuallyrequires two
adjacent bytes, a floating point number may require four adjacent bytes.
Suppose V is a variable that represents some particular data item. The compiler will
automaticallyassign memory cells for this data item. The data item can be accessed if we know
thelocation of the first memory cell. The address of V’s memory location can be determined
bythe expression &V, where & is a unary operator, called the address operator, that evaluatesthe
address of its operand.Now let us assign the address of V to another variable, PV. Thus,
PV = & V
This new variable is called a pointer to V, since it “Points” to the location where V is stored
inmemory. PV represents V’s address, not its value. Thus, PV iscalled pointer variable.The data
item represented by V can be accessed by the expression *PV where * is a unaryoperator, that
operates only on a pointer variable. Therefore, PV and V both represent thesame data item.
Furthermore, PV = &V and U = PV, then U and V will bothrepresent the same values i.e., the
value of V will indirectly be assigned to U.
Since pointer variables contain addresses that belong to a separate data type, they must
bedeclared as pointers before we use them. The declaration of a pointer variable takes
thefollowing form:
This tells the compiler three things about the variable Pt_name.
For Example :
int * P ;
declares the variable P as a pointer variable that points to an integer data type. and
float * y ;
Once pointer variable has been declared, it can be made to point to a variable using anassignment
statement such as
P = & quantity ;
which causes P to point to quantity. P contains the address of quantity. This is known aspointer
initialization.
After declaring a pointer, pointer is assigned a value, so that it can point to a particular variable.
eg. int * P ;
inti ;
P=&i;
This is called assignment expression in which pointer variable P is holding the address of i.
Like other variables, pointer variables can be used in expressions. Pointer variables can be
incremented, decremented, assigned to and compared with other variables using relational
operators. However, multiplication and division cannot be performed on pointer variables. For
example, if P1 and P2are properly declared and initialized pointers, then the following
statements are valid.
1) Y = * P1 ;
2) Sum = Sum + * P1 ;
3) Z = S - * P2 / * P1 ;
4) * P2 = * P2 + 10 ;
Sum =Sum + *P2 ;P1 ++ ;- -P2 ;P1 > P2; P1 = = P2; P1 ! = P2are all allowed expressions.
3.1.3POINTER ARITHMATIC
eg. if
inti ;
int j ;
int * P , * q ;
i = 5 , j = 10 ;
eg. * j = * i + * j ;
*j=*j-*i;
* i = * i ** j ;
3.2TYPES OF POINTERS
1. Void pointer or generic pointer: It is a special type of pointer that can be pointed at objects
of any data type. A void pointer is declared like a normal pointer, using the void keyword as
the pointer’s type.Pointers defined using specific data type cannot hold the address of the
some other type of variable i.e., it is incorrect to assign the address of an integer variable to a
pointer of type float.
The pointer defined in this manner do not have any type associated with them and can hold
the address of any type of variable.
void *v;
int *i;
intivar;
charchvar;
floatfvar;
v = &ivar; // valid
v = &chvar; //valid
v = &fvar; // valid
i = &ivar; //valid
i = &chvar; //invalid
i = &fvar; //invalid
2. Null Pointer: It is always a good practice to assign a NULL value to a pointer variable in
case you do not have exact address to be assigned. This is done at the time of variable
declaration. A pointer that is assigned NULL is called a null pointer.The NULL pointer is a
constant with a value of zero defined in several standard libraries. The following program
exemplifies a NULL pointer:
#include <stdio.h>
int main ()
{
int *ptr = NULL;
printf("The value of ptr is : %x\n", ptr );
return 0;
}
When the above code is compiled and executed, it produces following result:
The value of ptr is 0.
On most of the operating systems, programs are not permitted to access memory at address 0
because that memory is reserved by the operating system. However, the memory address 0 has
special significance; it signals that the pointer is not intended to point to an accessible memory
location. But by convention, if a pointer contains the null (zero) value, itis assumed to point to
nothing.
3. Dangling pointer: If any pointer is pointing the memory address of any variable but after
some variable has been deleted from that memory location while pointer is still pointing to
such memory location. Such pointer is known as dangling pointer and this problem is known
as dangling pointer problem.
For example:
#include<stdio.h>
int *call();
void main(){
int *ptr;
ptr=call();
fflush(stdin);
printf("%d",*ptr);
}
int * call()
(
int x=25;
++x;
return &x;
}
#include<stdio.h>
int *call();
void main(){
int *ptr;
ptr=call();
fflush(stdin);
printf("%d",*ptr);
}
int * call(){
return &x;
}
Output: 26
4. Constant pointer-A constant pointer is a pointer that cannot change the address its holding.
In other words, we can say that once a constant pointer points to a variable then it cannot
point to any other variable.A constant pointer is declared as follows :
int * constptr;
#include<stdio.h>
int main(void)
ptr = &var2;
printf("%d\n", *ptr);
return 0;
}
In the above example, two variables var1 and var2 are declared.A constant pointer ‘ptr’ was
declared and made to point var1. Pointerptr is made to point var2.Finally, we try to print the
value ptr is pointing to.So,an address to a constant pointer is assigned and then address is
changed by assigning the address of some other variable to the same constant pointer.
A block of memory may be allocated using the function malloc(). The malloc() function
reservesa block of memory of specified size and returns a pointer of type void. This means that
we canassign it to any type of pointer. It takes the following form;
ptr is a pointer of type cast type. The malloc() returns a pointer (of cast type) to an area of
Using this statement, a memory space equivalent to “100 times the sizeof an int” bytes is reserved
and the address of the first byte of the memory allocated is assignedto the pointer X of type int.the
malloc() allocates a block of adjacent bytes. The allocation can fail if the space
in the heap is not sufficient to satisfy the request. If it foils, it returns a NULL. It
shouldtherefore,be checked whether the allocation is successful before using the memory
pointer.
When an array is declared, the compiler allocates a base address and sufficient amount ofstorage
to contain all the elements of the array in contiguous memory locations. The baseaddress is the
location of the first element (index 0) of the array. The compiler also defines thearray name as a
constant pointer to the first element suppose we declare an array X asfollows :
static int X [ 6 ] = { 1, 2, 3, 4, 5, 6 } ;
Suppose the base address of X is 1000 and assuming that each integer requires two bytes,the five
elements will be stored as follows :
VALUE 1 2 3 4 5 6
The name X is defined as a constant pointer pointing to the first clement,x[0] and therefore the
value of X is 1000, the location whose X[0] is stored. That is,
If we declare P as an integer pointer, then we can make the pointer P to point to the array X
P=X;
This is equivalent to P = & X[0] ;Now we can access every value of x using P++ to move from
one element to another. Therelationship between P and X is :
The address of an element is calculated using its index and the scale factor of the data type.
For instance,
When an array is passed to a function as an argument, only the address of the first element ofthe
array is passed, but not the actual values of the array elements. The function uses thisaddress for
manipulating the array elements. Similarly, we can pass the address of a variableas an argument
to a function in the normal fashion.
When we pass addresses to a function, the parameters receiving the addresses should bepointers.
The process of calling function using pointers to pass the address of variable isknown as call by
reference. The function which is called by reference can change the value ofthe variable used in
the call.
eg.
main ( )
int X ;
X = 40 ;
change ( & X ) ;
printf ( “ %d”, X ) ;
change ( int * P )
* P = * P + 10 ;
}
When the function change is called, the address of the variable X, not its value, is passed intothe
function change ( ). Inside change ( ), the variable P is declared as a pointer and thereforeP is the
address of the variable X. The statement,
* P = * P + 10 ;
means add 10 to the value stored at address P. Since P represents the address of X, thevalue of X
is changed from 50. Therefore, the output of the program will be 50 not 40.Thus, call by
reference provides a mechanism by which the function can change the storedvalues in the calling
function.
A function like a variable, has an address location in the memory. It is therefore, possible
todeclare a pointer to a function, which can then be used as an argument in another function.
Apointer to a function is declared as follows:
type ( * fp) ( ) ;
This tells the compiler that fp is a pointer to a function which returns type value.
We can make a function pointer to point to a specific function by simply assigning the name
ofthe function to the pointer.
For example,
P1 = mul ;
declare P1 as a pointer to a function and mul as a function and then make P1 to point to
thefunction mul. To call the function mul, we may now use the pointer P1 with the list
ofparameters.
That is,
(*P1) (x,y)
is equivalent to mul ( x,y )
The way functions return an int, a float, a double or any other data type, it can even return
apointer. However, to make a function return a pointer it has to be explicitly mentioned in
thecalling function as well as in the function declaration. The following program illustrates this:
main ( )
int * P ;
int * fun ( ) ;
P = fun ;
int * fun ( )
inti = 20;
return (& i) ;
In this program, function fun( ) is declared as pointer returning function can return the addressof
integer type value and in the body of the function fun ( ) we are returning the address ofinteger
type variable i into P which is also integer type pointer.
The way there can be an array of integersor an array of floats, similarly there can be an array
ofpointers. Since, a pointer variable always contain an address, an array of pointers would
benothing but collection of addresses. The addresses present in the array of pointers can
beaddresses of isolated variables or addresses of array elements or any other addresses. Allrules
that apply to an ordinary array apply to the array of pointers as well. For example,
main ( )
int * arra [ 4 ];
31
19
71
char str[5]=”great”;
The C compiler automatically inserts a null character ‘\0’ at the end of the string. In C, strings
can also be created using pointer variables of type char. For example,
The above statement creates a string for the literal and then stores its address in the pointer
variable str. The pointer str now points to the first character of the string “great”. The siring
pointer can also be assigned value at the run time as ;
char *str1;
str1=”great”;
Similarly, to print the content of the string C provides puts function other than printf as follows:
printf(“%s”, str1);
puts(str1);
Since, str1 is not only the name of the string bur also the pointer to it, the indirection operator *
is not used to access the string.
4.EXAMPLE PROGRAMS
#include <stdio.h>
int main()
{
int first, second, *p, *q, sum;
printf("Entertwo integers to add\n");
scanf("%d%d", &first, &second);
p = &first;
q = &second;
sum = *p + *q;
printf("Sum of entered numbers = %d\n",sum);
return 0;
OUTPUT:
#include <stdio.h>
#define SIZE 10
inti;
printf( "%4d", a[ i ] );
bubbleSort( a, SIZE );
printf( "\nData items in ascending order\n" );
printf( "%4d", a[ i ] );
OUTPUT:
2 6 4 8 10 12 89 68 45 37
2 4 6 8 10 12 37 45 68 89
#include <stdio.h>
inti; /* counter */
} /* end for */
} /* end for */
} /* end for */
} /* end main */
OUTPUT:
b[ 0 ] = 10
b[ 1 ] = 20
b[ 2 ] = 30
b[ 3 ] = 40
*( b + 0 ) = 10
*( b + 1 ) = 20
*( b + 2 ) = 30
*( b + 3 ) = 40
bPtr[ 0 ] = 10
bPtr[ 1 ] = 20
bPtr[ 2 ] = 30
bPtr[ 3 ] = 40
Pointer/offset notation
*( bPtr + 0 ) = 10
*( bPtr + 1 ) = 20
*( bPtr + 2 ) = 30
*( bPtr + 3 ) = 40
#include <stdio.h>
char string1[ 10 ];
char string3[ 10 ];
return 0;
}
#include <stdio.h>
#define SIZE 10
/* initialize array a */
if ( order == 1 ) {
} /* end if */
} /* end else */
} /* end for */
OUTPUT:
2 6 4 8 10 12 89 68 45 37
2 4 6 8 10 12 37 45 68 89
2 6 4 8 10 12 89 68 45 37
89 68 45 37 12 10 8 6 4 2
5. SUMMARY
1. Pointers are used to store the address of a variable. It is not correct to store the address of
one type of variable into a pointer variable of the other type. Also, a pointer variable
cannot contain the value of a variable.
2. When we pass a parameter by address, the corresponding formal parameter must be a
pointer variable.
3. When an array is passed as an argument, to a function, a pointer is actually passed. Such
arrays must be declared in the header function with proper size.
4. If we increment a pointer, it will point to the next byte in memory.
5. Allocation of the memory at the run time, known as dynamic memory allocation can be
easily done using pointers.
6. Pointers can not be operated upon by relational and conditional operators. Multiplication
and division operations are also not allowed on a pointer.
6. SUGGESTED REAGINGS
1. INTRODUCTION
2. OBJECTIVE
3. CONTENTS
3.1 STRUCTURES
3.2 DEFINING A STRUCTURE
3.2.1 Declaring structure variables
3.2.2 Initializing Structures
3.3 NESTED STRUCTURES
3.4 ARRAYS OF STRUCTURES
3.5 PASSING STRUCTURES TO FUNCTIONS
3.6 UNIONS
3.6.1 Accessing Members of a union
A variable stores a single value for a data type. An array however, is a collection of
elements of similar types. In real life, we need to have different data types, to maintain
information about books in the library we should have information like, title, author,
edition ,price and so on. Thus, to, maintain the information about the books, dissimilar
data types are required. Title and author being character types, edition being integer type
and price being float type. All these data types cannot be handled in a single array. Thus,
multiple arrays of different types, one for each type may be declared. This, will lead to a
cumbersome program. To tackle the need for mixed data type problems, C has an
efficient feature called structure. A structure is a collection of one or more variables of
different data types, grouped together under the same name. It is a user-defined data type
because the user can decide the data type to be included in the body of the structure. By
using structures it is possible to group variables, arrays, pointers and even structures. Like
structures are unions. These also contain elements of different types. However unlike
arrays and structures, members of a union share same memory locations. Thus, union
permits several different data items to be stored in the same portion of memory at
different times.
2. OBJECTIVE
Unlike arrays, individual elements in structures can differ in type. Thus, a single structure
may contain integer, character, and floating point elements. Pointers, arrays and other
structures can also be included as structure elements. The individual elements of a
structure are referred to as members of a structure. Through this lesson, we will learn
how structures are defined, and how individual structure members are accessed and
processed within a program. Relationship between pointers, functions, and arrays is also
presented. We will also examine the concepts of nested structures, that is, structure
elements are structures themselves. Closely related to structures are unions. Unions also
contain members of different types. They differ from structures in storage that all the
members share the same storage area. This lesson also explains the concept of unions and
their usage.
3.1STRUCTURES
Arrays can be used to represent a group of data items that belong to the same type, such
as int or float. However, to represent a collection of data items of different types using a
single name, a constructed data type known as structure, is used. A structure can be seen
as analogous to record, which is used to handle logically related data items. Structures
provide an efficient mechanism to handle real-world data.
For example, to represent a book record in a library, various attributes that can be used
are: title, author, publisher, price, edition, date of publication etc. All these attributes are
dissimilar, for example, title, author, publisher are strings, price, edition and date of
publication are integers. To handle multiple records for books either five different arrays,
each to handle the corresponding entry for all the books can be used or we can create a
structure named books with title, author, publisher, price, edition date of publication as
attributes in a single data item.
3.2DEFINING A STRUCTURE
A structure allows for the storage, in contiguous areas of memory, of associated data
items.A structure is one of a group of language constructs that allow the programmer to
compose his/her own data types A structure is a template for a new data type whose
format is defined by the programmer..Unlike arrays, structures must be defined first for
their format that may be used later to declare structure variables.The general form of a
structure template is:
structtag
{
Data type Member1_name;
Data type Member2_name;
------ ;
------;
}variable_name;
Wherestruct is a keyword, that declares a structure with name tag to hold the details of
the member fields, tag is optional and only needs to be present if no variable is present.
The members are variables declared as any C supported data type or composed data
type. A structure is a set of values that can be referenced collectively through a variable
name. The components of a structure are referred to as members of a structure. A
structure differs from an array in that members can be of different data types. The name
of the structure is the tag. The tag is optional when avariable is present and
the variable is optional when the tag is present.Following structure is used to represent
the above mentioned book record
structbook_rec
{
char title[25];
char author[20];
char publisher[20];
int price,
int edition;
int date;
};
A structure template does not occupy any memory space and does not have an address, it
is simply a description of a new data type.
Three variables of the above data type person would be declared as follows:
Thus, structure variable declaration includes,the struct keyword, structure tag name, list
of variable names and a terminating semicolon.Each one of these variables has four
members as specified by the template.
The other way to declare the same is:
struct Person
{
charlast_name[20];
charfirst_name[16];
int age;
double salary;
} frank, tom, jack;
To access individual members of a structure, the ‘dot operator’ or the ‘period operator’ is
used to connect a variable name with an element in the structure. For example,
frank.last_name
is the variable representing the last name of frank and can be treated like any ordinary
variable. The composed name is treated as a variable with the type of the member
variable.Each member of a structure is in a contiguous memory location in relationship to
its previous member and next member.
The sizeof operator in C is used to evaluate the number of bytes used to hold all the
members of the structure. The size of structure person can be evaluated using the
following expression:
sizeof(struct person)
Similarly,
sizeof(frank)
will generate the same result 46, as frank is a structure variable of type struct person.
sizeof function will generate the total number of bytes required by the array of the same
structure type. For example, if arr_person is a 10 element array of type struct person,
rhesizeof operator will generate result as 460(10*46).
The following C program shows structure definition, variable declaration and accessing
of the structure members.
struct person
{
charlast_name[20];
charfirst_name[16];
int age;
int salary;
};
main()
{
struct person frank;
printf(“Enter the details of frank”);
scanf(“%s %s %d %d”,frank.last_name, frank.firat_name, &frank.age,
&frank.salary);
printf(“Details of person is “);
printf(“(“Last name is %s \n First name is %s\n Age is %d\n Salary is
%d\n”,frank.last_name,frank.firat_name, frank.age, frank.salary;
}
3.2.2Initializing Structures
Structures can be initialized when the template is created, if a variable of the structure
type is declared with the template creation.
Likewise, any number of variables of given structure type can be initialized.However, the
order of values enclosed in braces while initializing must match the order of members in
the structure definition.
Values are assigned to individual members of the structure by using the structure variable
name connected with the structure member name.
employ.age = 35;
The dot (.) operator is used to provide the connection between variable name and member
name. When referencing a particular member of a structure, the resulting type of that
expression is that of the member being referenced. The value of one structure variable
can be assigned to another structure variable of the same type.
The above assignment is a valid statement. The data stored in employ2 would be stored
in employ1, because objects of like type can be assigned to one another. Structure
variables cannot be compared through a relational operator. The following example
attempts to compare two structure variables of the same type.
The above code is invalid, each member of the structure must be compared in order to
establish equality or non-equality.
3.3NESTED STRUCTURES
struct Vital
{
intage,height,weight;
};
struct Home
{
char f_name[12],l_name[20],city[20],state[3] ,zip_code[11];
};
struct Person
{
Vital emp;
Home place;
} employ;
The above example shows a structure person, whose members, Home and Vital are
structures themselves with 5 and 3 members respectively. In order to access a member of
one of the nested structures, the dot operator is used until the lowest member is reached
in the structure hierarchy. For example, to access height of emp, following statement is
valid.
employ.emp.age
However, employ.zip_code is an invalid reference as it misses out the inner level member
reference.
3.4ARRAYS OF STRUCTURES
Like any other data type in C, a variable of a structure type can be arrayed. For example,
to create a database of vital statistics of 100 persons, we may need to create a structure
vital having 2 members and then create an array stats of 100 members, each member of
which is a structure itself.
struct vital
{
int height;
int weight;
} stats[100];
The above declaration would allow for the storage of 100 items of type vital. Each item
will have height and weight as its membersSincestats isan array, the usual array accessing
methods are used to access individual elements and the dot (.) operator is used to access
members. Any specific item could be referenced as:
stats[index].height
stats[index].weight
For example to print the height and weight of 2nd element, the statement used is,
printf(“ The height and weight of the 2nd element are %d %d”, stats[1].height,
stats[1].weight);
Here, index is the usual array accessing index.In C, single or multi-dimensional arrays
can also be used as structure members. The above structure vital can be modified as:
struct vital
{
int weight;
int height;
intsal_mnth[12];
}stats[100];
In this, we have added a new membersal_mnth, an array to hold the salary for all the
months in a year. To print the salary for the month of aprilfor employee number
23,following statement can be used.
3. Using pointers to pass the address location of the structures to the function as
argument. The function can access indirectly the entire structure and work on it.
This method is more efficient as compared to the second method mentioned
above.
3.6 UNIONS
A union is an aggregate variable that can declare several data types, but only store the
value of one variable at any one time. Each data type shares the same area of memory.
This can save memory if you have a group of data where only one of the types is used at
a time. . The declaration of a union is similar to that of a structure:
union [union_tag]
{
data_type variable_1;
data_type variable_2;
data_type variable_3;
.
.
.
} [union_variable_name];
union Data
{
int y;
charstr[6];
float x;
double t;
} var;
The union variable var is given eight(8) bytes of storage; all the elements start at the
same address in memory; the compiler gives the amount of storage needed by the largest
data type, in this case double which is eight bytes.
To access a member of a union the dot operator is used the same as with structures.
var.x = 123.45;
var.str=abc;
var.y=12;
are all valid statements. During accessing, only that member can be accessed whose value
is currently stored. For example, if after making the above declarations, the following
statement is invalid:
printf(“%f”,var.x);
as the storage is currently allocated to the variable var.y. When a different member is
assigned a new value, the new value replaces the previous value assigned to a member.
Unions can also be initialized when the corresponding variable is declared. However,
unlike structures, it can only be initialized with value of the type as of the first union
member. For example:
is valid as initialized value is of type int, which is same as of the first defined member
type y. Other members can be initialized either by assigning values or reading values
from the keyboard.For example:
#include <stdio.h>
intmain()
{
union data
{
char a;
int x;
float f;
} myData;
int mode = 1;
myData.a = 'A';
printf("Here is the Data:\n%c\n%i\n%.3f\n", myData.a, myData.x, myData.f );
myData.x = 42;
mode = 2;
printf("Here is the Data:\n%c\n%i\n%.3f\n", myData.a, myData.x, myData.f );
myData.f = 101.357;
mode = 3;
printf("Here is the Data:\n%c\n%i\n%.3f\n", myData.a, myData.x, myData.f );
if( mode == 1 )
printf("The char is being used\n");
else if( mode == 2 )
printf("The int is being used\n");
else if( mode == 3 )
printf("The float is being used\n");
return 0;
}
The above example program declares a union with an int, float, and char. It uses each
field, and after each use prints out all the fields. Here is some sample output:
Here is the Data:
A
577
0.000
Here is the Data:
*
42
0.000
Here is the Data:
1120581321
101.357
The float is being used
There can be different outputs for this program. Clearly the data in the unused fields is
just garbage. This happens because different types are treated differently by the
computer. So if one type is set, the memory is not going to be in the format of the other
types. Also mode is used to keep track of the type.
OUTPUT:
Enter information for 1st distance
Enter feet:12
Enter inch:3.45
OUTPUT:
Enter information of students:
For roll number 1
Enter name: Tom
Enter marks: 98
OUTPUT:
Enter integer
5
Enter number
6
Displaying
6 5
4. SUMMARY
1. A structure is used to store dissimilar data items. All the elements of a structure are
stored in contiguous memory locations.
2. Members of a structure can be accessed using dot (.) operator through a structure
variable. Structure elements can be accessed through a pointer to a structure using arrow
(- >) operator.
3. All elements of a structure variable can be assigned to another structure variable using
assignment variable using assignment operator (=). However, it is not possible to
compare two structure variables.
4. When structures are nested, a member must be qualified with all levels of the
structures nesting it
5. Array of structure can be created. Usual array indexing techniques are used to access
the members of the structure, but the dot operator will be used to access individual
member elements of the structure array.
6. A union is just like structures except that members of union share same memory
locations. A union can store only one member at a time.
7. A union can be initialized only withdata that matches only with the type of the first
data type.
5. SUGGESTED READINGS
1. Ashok. K. Kamthane,”Programming in C”, Pearson ed.
2. YashwantKanethkar, “Let Us C”, BPB Publications
3.E. Balaguruswamy,” Programming in ANSI C”, Tata Mc- Graw Hill
4.Byron Gottfried,” Programming with C”, Tata Mc- Graw Hill