You are on page 1of 80

C PROGRAMMING NOTES: NEW COURSE (2013-2016)

BCA 102 PROGRAMMING WITH C


UNIT-1

Program Concept, Characteristics of Programming, Various stages in Program


Development Programming aids Algorithms, Flow Charts - Symbols, Rules for making Flow
chart, Types of flowchart, Advantage & Disadvantage, Pseudocodes, Decision Table,
Programming techniques & tools Programming Techniques – Top down, Bottom up,
Modular, Structured - Features, Merits & Demerits, Comparative study, Programming
Logic- Simple, Branching, Looping, Recursion, Cohesion & Coupling, Programming Testing
& Debugging & their Tools .

UNIT-2

Introduction & features of C, Structure of C program, Variables, Expressions, Identifiers,


Keywords, Data Types, Constants, Operator and expression Operator: Arithmetic, Logical,
Relational, Conditional and Bit wise Operators, Precedence and Associativity of Operators,
Type conversion in expression, Basic input/output and library functions Single character
input/output i.e. getch(), getchar(). getche(), putchar(),Formatted input output i.e. printf()
and scanf(), Library functions - concepts, Mathematical & Character functions.

UNIT-3

If statement, If.....Else statement, Nesting of If....Else Statement, else if ladder, The ?:


operator, goto statement, Switch statement, Compound statement, Loop controls, for, while,
do-while loops, break, continue, goto statement, ARRAYS Single and Multi Dimensional
arrays, Array declaration and initialization of arrays, Strings : declaration, initialization,
functions.

UNIT-4

The need and form of C functions, User defined and library function, Function arguments,
Return values and nesting of function, Recursion, Calling of functions, Array as function
argument, Scope and life of variables - local and global variable, Storage class specified -
auto, extern, static, register.

UNIT-5

Defining structure, Declaration of structure variable, Accessing structure members, Nested


structures, Array of structure, Structure assignment, Structure as function argument,
Function that return structure, Union, pointers, working with text files.

PREPARED BY: SUMIT PUROHIT, ASST. PROF.,AISHWARYA COLLEGE Page 1


C PROGRAMMING NOTES: NEW COURSE (2013-2016)

UNIT-1
Program Concept:
Program: A program strictly a computer program and is a collection of coded instruction to
direct a computer to perform a desired set of operation. The art of making or designing a
program is called programming. The person who writes such programs is called
programmer.
A program can be defined as the combination of algorithm and data structure into single
unit.
Program Library: It is the collection of computer programs. Each and every program in
the library is designed to solve a certain type of problem.
Characteristics of programming: the art of writing or designing the programs to provide
a solution to the well defined problem is called programming. Some characteristics of
programming are like:
1. Accuracy: The programming of a program is based on a certain problem. The
problem must be predefined clearly with specification of requirements. It is expected
from the programmer to design a program that strictly follows these requirements so
the designed program must be accurate to perform the specific task.
2. Efficiency: The program must not spend much time or over use the processor in
executing its coded instructions.
3. Maintainable: It is the ability to change as per the new needs. With very little
modification a program should work for the new needs.
4. Portable: If a program is portable then it can be easily transferred from one
machine to another.
5. Readability: The designed program must contain proper comments to explain the
coded instructions. This will help in understanding and reading the program.
6. Reliability: Program should be reliable that will overcome from the errors to
generate proper or desired output i.e. if there no error in the program then that
program will executed correctly.
7. Robust: The designed program is expected to contains with its functionalities even
at the unexpected errors. It is the art of programming that takes care of all the
possible errors before completing the design. Such program keep on doing their work
even at worst situations.
8. Usable: The designed program must be easy to use. It must be designed with proper
interactive messages so that the user can easily get accustomed to it.
9. Documentation: The usage of comments or remarks to explain the coded
instruction and the modules of the program is called documenting the program.
Such documented program will also help in providing other characteristics of the
programming.
10. Indentation: The coded instruction of the designed program must properly match
with beginning and ending of the structures.

PREPARED BY: SUMIT PUROHIT, ASST. PROF.,AISHWARYA COLLEGE Page 2


C PROGRAMMING NOTES: NEW COURSE (2013-2016)

Stages in program development:


The process of designing the complete program is called program development. The
program development is involved with many stages. The stages of the program
development are also called phases or steps. These stages are as follows:
1. Problem definition: In this phase user’s needs are clearly collected and defined in
the form of problem definition. All the possible views of the users are collected here.
2. Analysis: This phase helps in indentifying the algorithms and data structures based
on the problem definition. There must be good characteristics of programming, need
of data structure, proper names for the identifiers, programs, sub-programs can be
decided at this phase of program development.
3. Identification of output: In this stage format of the output to be presented by the
program can be decided. So the desired format from the use is recorded and framed
out.
4. Design: At this stage purely coding is done. It is necessary that methodology of the
program is decided. Depending on the methodology proper statements are selected
for the design of the program.
5. Validation: In this stage of program development the validity of the coded
instruction or statement is tested. The validity of the statements is tested for the
rules or constraints defined in the problem definition. The coded instruction must
agree with the rules defined by the users. Normally the validity of the statements is
checked before completing the development of the program.
6. Testing: In this stage of program development it is expected to test the complete
program. The testing is said to be complete if the program produces the expected
output for any of the inputs. The possible testing methods used are Functional
Testing (Black Box Testing), Logical Testing (White Box Testing) and
Integrated Testing. In Functional Testing, individually the codes are tested for
a set of input data. The tested code is independent of the other code. The program is
completely checked for all the coded instruction.
In Logical Testing, each and every module is tested independently. The output of
one module may be used as an input to the other module. So this testing helps in
correcting all the modules separately but it can’t test the missing modules of the
program.
In Integrated Testing, the results of all the modules are collected together. All the
modules designed are tested by linking each other. This linking of modules is termed
as integration.
7. Implementation: This is the extension of testing stage of program development.
The program that is tested to the user’s place and installed and implemented there.
The testing is carried at local place of the programmer whereas tested once again
giving the real data of the users.
8. Debugging: The errors found in the program are called bugs. The program with
bugs doesn’t work properly to produce the desired output. Removing these bugs from
the program is called as debugging. During the compilation process the syntax

PREPARED BY: SUMIT PUROHIT, ASST. PROF.,AISHWARYA COLLEGE Page 3


C PROGRAMMING NOTES: NEW COURSE (2013-2016)

errors are removed. Compilation process is nothing but to convert the source
program into executable program. The possible runtime errors are removed during
the validation and testing phases of the program design. The logical errors are
difficult to detect and rectify. Such error removal phase of program development is
called debugging.
9. Documentation: In this phase the manual or instruction booklet of the program is
prepared. The manual helps the user in understanding and using the program. This
will also serve as a guide to the user in the absence of programmer.
10. Maintenance: This phase of program development comes into effect after the use of
the developed program starts. During the program operation the users may come
across many points where they changes for the working program is called as
maintenance phases of the program development.

Programming Aids:
Programming is nothing but designing a program after understanding the problem. The
supporting tools that help in arriving at a good program are called programming aids.
These aids assist the programmer in designing a program. These tools are used before
designing a program. There are three general tools for programming aids, these are:
1. Algorithms
2. Flowcharts
3. Pseudocodes

1. Algorithms: an algorithm is a sequential, finite, non-complex step by step solution,


written in English like statements to solve a problem.
Algorithm Notation: the algorithmic notations are symbolic representation of the formal
steps or operations used to solve a problem that are generally accepted by all. These
notations are like:

 Name and parameters


 Comments
 Variable names
 Assignment Operations
 Input and Output
 Sequential steps
 Selective steps
 Repetitive steps
 Exit / return
 List of elements i.e. array

 Name and parameters: name of the algorithm may be written in capital letters.
The name should start with a character and should not contain in between words.

PREPARED BY: SUMIT PUROHIT, ASST. PROF.,AISHWARYA COLLEGE Page 4


C PROGRAMMING NOTES: NEW COURSE (2013-2016)

The name is chosen according to the problem or functionality. The name may depict
the work done by the algorithm. The name of the algorithm serves the purpose of
start for an algorithm and it is the heading of algorithm.

 Comments: these are necessary to explain the purpose of algorithm. They are also
used to explain the steps used in an algorithm in detail as non-execuatble
statements. They are mentioned in ‘[..]’ square brackets.

 Variable name: the variable names are written in capital letters without any blank
space. Underscore (_) may be used in case of multi word names to the separate the
words. The name should be start with an alphabet.

 Assignment operation: this is used to set the values of a variable for this ‘  ‘
(arrow) symbol is used. A value, constant, another variable or an expression may be
used to set the value.

 Input and Output: ‘Read’ is used to input the value of a variable and ‘Write’ is
used to output of a given variable.

 Sequential steps: the steps are written one after the other usually in separate
lines. If two statements are to be written on the same line they may be separated by
means of a semicolon ‘ ; ’.

 Selective steps: these statements are also called as conditional or branching steps.
They can be written using If Then Else. The branching is based on condition. The
conditions are framed using the relational operators i.e. >(greater than),<(less
than),>=(greater than equal to),<=(less than equal to) and ‘==’ (equal to). For logical
connection of two conditions AND, OR can be used. For negation NOT can be used.

 Repetitive steps: these are known as iterative steps. They can be written between
‘Repeat For’ and ‘[End of For] or ‘Repeat While’ and ‘[End of While]’. Repeat For is
used for the purpose of repeating the statements for fixed number of times where as
Repeat While is used to repeat statements till a condition is true.

Example:
ARITHMETIC_OP (A, B) [A and B are integer values]
Step1: START
Step2: Write ‘Enter the values for A and B:’
Step3: Read A, B
Step4: C  A + B
Step5: Write ‘The Addition is: ‘, C
Step6: D  A - B

PREPARED BY: SUMIT PUROHIT, ASST. PROF.,AISHWARYA COLLEGE Page 5


C PROGRAMMING NOTES: NEW COURSE (2013-2016)

Step7: Write ‘The Subtraction is: ‘, D


Step8: E  A * B
Step9: Write ‘The Multiplication is: ‘, E
Step6: F  A / B
Step7: Write ‘The Division is: ‘, F
Step8: Exit / Stop

2. Flowcharts: these are the pictorial representation to depict the algorithm clearly
the flow of control to arrive at the solution of a problem. The flowcharts are
generally drawn to represent the algorithm of a problem. The steps of algorithms are
then converted in relevant symbols of flowchart. The steps are interconnected by
means of symbols to give the overall representation of the algorithm. Thru which the
flowchart is prepared.

Symbols in Flowchart:
Symbols that are used in preparation of a flowchart are like:
Symbols Name Representation of Example Description
Symbols
This is used to begin
Terminator / C=A+B and terminate the
Ellipse/ Oval process flow.

It is used to take
Read A, B
Parallelogram / input and display
Data Input Output output.
Write A, B

This performs all the


C A+B
Process processing work
F
Decision If Age >=18 This used to test the
conditions in the
T program.

It is used to connect
Connector A 1 a part of flowchart to
another.
This represents the
Directed Arrow Start flow of control.

PREPARED BY: SUMIT PUROHIT, ASST. PROF.,AISHWARYA COLLEGE Page 6


C PROGRAMMING NOTES: NEW COURSE (2013-2016)

Rules for making flowcharts:


1. The flowchart should contain one start and one stop box (terminator).
2. The symbols of the flowchart are always labeled with simple code.
3. The controls flows are always represented by directed arrows.
4. The control flow lines must touch the boundary of any box either while leaving or
entering the box.
5. The control flow line may be horizontal ( left to right or right to left) and vertical (
top to bottom or bottom to top).
6. Only one flow line must be there while entering or leaving the box except condition
(diamond box).

Introduction to programming techniques:


A method used to design the program to solve a problem is called programming technique.
Some programming techniques are available for programming, these are:
1. Top down approach
2. Bottom up approach
3. Unstructured
4. Structured
5. Modular

1. Top down approach: a disciplined approach of decomposing top level to a


hierarchy of understandable lower level modules for better management and
handling is top down technique of programming. The name of technique itself gives
the meaning of this technique. In this programming technique, the main solution is
viewed first. Then in the main solution if there are any parts that are to be solved
are viewed. Then the final solution is obtained.
Characteristics of top down approach:
 Program preparation is stretched to a number of levels.
 Because the technique moves from top to bottom it is a type of specialization.
 Main module can be designed well before without requiring details of complete
design.
 Testing can be done after inserting down level modules one by one.
 Parallel development is possible.
Advantages:
 Parallel development of the program is possible because of independent design of the
modules at different levels.
 Parallel development helps in designing the program at reduced time period.
 Testing and debugging are faster.
 Handling and management of modules are easy.
 Code reliability can be improved.
 The hierarchy of the levels helps in understandable low level modules.

PREPARED BY: SUMIT PUROHIT, ASST. PROF.,AISHWARYA COLLEGE Page 7


C PROGRAMMING NOTES: NEW COURSE (2013-2016)

Disadvantages:
 This is only useful in solving a part of a larger problem.
 This technique is poor for designing larger programs.
 The application developed using this technique can’t be upgraded easily.

2. Bottom up approach:
An approach of generalizing low level functions to an upper level in order to solve
problem is called bottom up approach. This technique of programming is just the
reverse of top down approach. In this technique first the solution of independent sub
programs are designed. Then these solutions are clubbed in main modules to design the
final solution of the problem.
Characteristics of bottom up approach:
 Program preparation starts from designing the sub problems.
 The composition of solution is generalized for main solution.
 The solutions are clubbed in the main coordinating modules.
 Main module can only be designed after the detailed design of sub problems.
 Integration test is performed at the final stage of programming.
 The codes of sub-problems are reusable.
Advantages:
 The details of the sub problem solutions are available in advance in the form of
bottom level modules.
 The individual sub problem solutions are designed with great details.
 The sub solutions obtained are simple.
 The main module is used to link all the sub problem solutions.
 This technique is more general and codes are reusable.
 Testing in this case is simple and test cases can be designed easily.
Disadvantages:
 The application developed using this technique can’t be tested as a whole before the
development of the main solution.
 The sub solutions are added or linked to the main solution without knowing the
details of its coding.
 The integration testing may cause complications because it is done in the later stage
of application development.

3. Unstructured technique:
This is an approach of designing a program simply using series of statements. In such
programming technique every task is solved using series of simple statements only.
Branching and repetitions are achieved thru a ‘goto’ statement. So a technique using ‘goto’
statement is called unstructured technique of programming.
Characteristics:
 Simple statements are used to solve a task.
 The statements used are basic and understandable.

PREPARED BY: SUMIT PUROHIT, ASST. PROF.,AISHWARYA COLLEGE Page 8


C PROGRAMMING NOTES: NEW COURSE (2013-2016)

 This is also known as linear programming.


 Each logic of a program is developed using ‘goto’.
Advantages:
 Program design is simple.
 Simple and straight forward logic.
 Only one ‘goto’ statement is used for branching as well as looping.
Disadvantages:
 There may be abrupt transfer from one point to another.
 Difficult to keep track the logic of the program.
 Excessive use of ‘goto’ statements causes confusion in program flow and may be led
to error formation hence the quality of program is decreases.
 Testing of program consumes lots of time.
 Redesigning of a program is too difficult.
 Program’s logic is messy so difficult to follow.

4. Structured technique:
This is an organized approach of designing a program using control structures like
sequential, selection and iterative to solve all sorts of problems with single entry and single
exit modules.
Characteristics:
 The technique is based on modular, top down design.
 The problem is decomposed into sub-problems.
 Each sub-problem may be decomposed into sub-problems again if required.
 ‘goto’ statement is avoided about to jump from one point to another.
 Unconditional branched are never used about to transfer a control.
 Branching, iterative statements are used.

Advantages:
 Simple to design structured programs.
 Easily modifiable.
 Testing and debugging is easy.
 Programs are well organized.
 Structured programs take less time to design.
 Easy to read and understand.
Disadvantages:
 The logical errors are difficult to remove from the control structure.
 Little carelessness in framing the control structure may lead to logical errors.
 Detailed planning and exercise is required to design the control logic.
 The loop structure may go into infinite loop when the condition used is improper.

PREPARED BY: SUMIT PUROHIT, ASST. PROF.,AISHWARYA COLLEGE Page 9


C PROGRAMMING NOTES: NEW COURSE (2013-2016)

5. Modular technique:
This is an approach of breaking down the original problem into several independent sub-
problems or modules and executing these modules in a sequence.

COMPLEX A B
PROBLEM
BREAK DOWN INTO SEVERAL
SUB-PROBLEMS
C D

Characteristics:
 Modular design increases the programmer’s productivity.
 It allows them to look at the big problem first and thereafter details.
 Several programmers can work on a single, large program and each working on
different module.
 Modules designed for one program can be reused in other programs requiring the
same task.
 The relationship between the modules shows the modular design of the program.
Advantages:
 Focusing is on smallest component of the big problem that is manageable.
 Each module performs a definite function and it is easy to manage.
 The sub-programs make the solution shorter and reduce the bugs.
 Coding, testing and debugging are independent for every module.
 A main module can be linked with sub modules to solve the main problem.
 Meaningful module names identify the task performed by each module.
 The task can be divided among many reusable sub-programs.
Disadvantages:
 The modules designed must be independently checked once.
 The modules must perform specific task.
 Any change in the program will also affect the individual module of the program.
 Because of the linking of modules, the execution of the program takes extra time.

Cohesion and Coupling:


Cohesion: the cohesion of a module is a measure of how well it fits together. A module
should implement a single logical function or should implement a single logical entity.
Cohesion is used to measure strong relationship and responsibilities of a module. Cohesion
is generally expressed as “high cohesion” or “low cohesion”. Modules with high cohesion are

PREPARED BY: SUMIT PUROHIT, ASST. PROF.,AISHWARYA COLLEGE Page 10


C PROGRAMMING NOTES: NEW COURSE (2013-2016)

preferable. High cohesion is associated with several desirable qualities of program. They
include consistency, reusability and understandability.
Low cohesion is associated with undesirable qualities such as difficulty in maintenance,
difficulty in testing, difficulty in reusing and understanding.
Cohesion is more difficult to measure directly because it is measure of meaning of
relationships. Cohesion is reduced when the responsibilities of module have little in
common and the module carries out different operations using unrelated set of data.
The levels of cohesion can be divided into seven levels in the order of worst to best are
like:
 Coincidental
 Logical
 Temporal
 Procedural
 Communicational
 Informational
 Functional

 Coincidental: in this level cohesion no particular relations among operations exist


within a module. The existences of the operations within a module are just
unplanned ones.
 Logical: in this a set of related operations exist with a choice for calling.
 Temporal: in this a series of operations are related with respect to the time of using
such operation. It means the relationship is for sequencing the order of operations.
The operations here typically have strong connections with other parts of the
program.
 Procedural: at this level there exist a series of operations that have something to
do with each other. With such relationship the overall problem is being solved.
 Communicational: at this level there exist a series of operations similar to
procedural cohesion but applied to same data.
 Informational: in this level there exist a group of tasks that work on the same data
model.
 Functional: in this there exists a course of action that accomplishes one clear
function. This is the best level of cohesion.
So to design a program the programmer must try to maximize the cohesion. The modules
whose elements are strongly and fully related to each other are desired. A module should be
highly cohesive.

Coupling: This measures the strength of all relationships between function units. It is the
measure of the interdependence of one module to that of another. The program should have
low coupling. Low coupling minimizes the cause of errors in other modules. The errors in
the other modules are caused because of the change in one module. The reduction in
coupling reduces the complexity of program.

PREPARED BY: SUMIT PUROHIT, ASST. PROF.,AISHWARYA COLLEGE Page 11


C PROGRAMMING NOTES: NEW COURSE (2013-2016)

Types of coupling: Coupling may of following types:


1. No Direct Coupling
2. Normal Coupling
a) Data Coupling
b) Stamp Coupling
c) Control Coupling
3. Common Coupling
4. Content Coupling

1. No Direct Coupling: These are independent modules of a program. They are not
really components of a single program.
2. Normal Coupling: Two modules, X and Y, are normally coupled if X calls Y, Y
returns to X and all information passed between them is by parameters in the call.
a) Data Coupling: Two modules are said to be data coupled if they communicate by
passing parameters. This is the most common type of coupling.
b) Stamp Coupling: Two modules are said to be stamp coupled if they communicate
thru a passed data structure that contains more information than necessary for
them to perform their operations.
c) Control Coupling: Two modules are said to be control coupled if they
communicate with the help of at least one flag.
3. Common Coupling: Two modules are said to be common coupled if both of them
share same global area. This type of coupling is really undesirable. Problem in one
module can affect other module.
Content Coupling: Two modules are content coupled if one module changes a statement
in another, one module references or alters data contained inside another module or one
module branches into another module

Debugging:
The term bug refers to the error in program and the process of removing bug from the
concern program is called debugging. Generally debug is defined as to remove all
malfunction or mistakes from the program.
The errors can be classified as:
1. Syntax error
2. Logical error
3. Data entry error
4. Linker error
5. Runtime error

1. Syntax error: misspell one of the words used in a statement or insertion of comma
at the wrong place, or fail to insert block terminals results in syntax error.
Mistaking in syntax rules is known as syntax error. They are detected while
translating the programs. Error message are displayed by the translator. These are
simply typing errors. These are rectified at the programmer’s end and then the
program is retranslated.

PREPARED BY: SUMIT PUROHIT, ASST. PROF.,AISHWARYA COLLEGE Page 12


C PROGRAMMING NOTES: NEW COURSE (2013-2016)

2. Logical error: These occur at the program’s logic and are the errors that are hard
to detect. They cause more trouble and also cause the program to fail. It is very
difficult for programmer to detect such errors. Generally the translator or compiler
generates some warnings against such errors. Such warnings will help the
programmer to correct the logical errors. The program is generally executed with
such local errors.

3. Data entry errors: The data entry errors are the largest source of errors. These the
errors that occur when wrong data is entered as input to the program.

4. Linker errors: there are the errors that occur during the linking process of
program development. Once the translator converts a source program into object
program after the removal of syntax error the next step is to link the other modules
with the source program. The linker errors are generated when the object modules
to link are not available.

5. Runtime errors: these are the errors that occur when the statements used in the
program are not executed by the processor. If the processor is unable to execute such
statements then run time errors are generated.

Testing:
Checking the execution of a program to completion to solve a problem is called program
testing. The program testing consists of tasks like – test data design, test cases design,
process by hand and process by computer. The program testing needs to select test data
from the input area and to execute the program with the selected test data. Finally the
output is checked for the correctness.
Designing of test data must be good enough to test every possible case with the help of test
cases. Some testing types are as follows:
1. Functional test or black box test: The test data created for this test covers all the
input area to get the expected results.
2. Structural test or white box test: this tests the program logic or program
structure. The program code is studied and the test is carried out to trace each and
every path of the program code.
3. Unit test: Individual function or model of the program is tested for its functionality.
It has to independently perform its functionality to produce desired output for all
possible inputs. This test is easy to perform on individual module.
4. Integration test: As the program may contain number of modules only unit test is
not enough. The modules of the program are normally composed to solve the main
task. The output of one module or the other module or function so the program must
be tested with a combination of all modules or functions. The combined testing for
the testing of the whole program is called integration test.

PREPARED BY: SUMIT PUROHIT, ASST. PROF.,AISHWARYA COLLEGE Page 13


C PROGRAMMING NOTES: NEW COURSE (2013-2016)

UNIT-2
History of C Language
By the late fifties, there were many computer languages into existence. However, none of
them were general purpose. They served better in a particular type of programming
application more than others. Thus, while FORTRAN was more suited for engineering
programming, COBOL was better for business programming. At this stage people started
thinking that instead of learning so many languages for different programming purposes,
why not have single computer languages that can be used for programming any type of
application.
In 1960, to this end, an international committee was constituted which came out with a
language named ALGOL-60. This language could not become popular because it was too
general and highly abstract.
In 1963, a modified ALGOL-60 by reducing its generality and abstractness, a new language,
CPL (Combined Programming Language) was developed at Cambridge University. CPL, too
turned out to be very big and difficult to learn.
In 1967, Martin Richards, at Cambridge University, stripped down some of the complexities
from CPL retaining useful features and created BCPL (Basic CPL). Very soon it was
realized that BCPL was too specific and much too less powerful.
In 1970, Ken Thompson, at AT&T labs., developed a language known by the name B as
another simplification to CPL. B, too, like its predecessors, turned out to be very specific
and limited in application.
In 1972, Ritchie, at AT&T, took the best of the two BCPL and B, and developed the
language C. C was truly a general purpose language, easy to learn and very powerful.
In 1980, Bjarne Stroustrup, at Bell labs., took C to its next phase of evolution, by
incorporating features of Object Oriented programming, reincarnating C into its new avatar
C++. By and large, C remains the mother language for programming even today.

Advantages of C Language
C is often termed as a middle level programming language because it combines the power of
a high level language with the flexibility of a low level language. High-level languages have
lot of built-in features and facilities, which result in high programming efficiency and
productivity. Low-level languages, on the other hand, are designed to give more efficient
programs and better machine efficiency.

C is designed to have a good balance between both extremes. Programs written in C give
relatively high machine efficiency as compared to the high level languages (though not as
good as low level languages). Similarly, C language programs provide relatively high
programming efficiency as compared to the low level languages (though not as high as those
provided by high level languages). Thus, C can be used for a whole range of applications
with equal ease and efficiency.

PREPARED BY: SUMIT PUROHIT, ASST. PROF.,AISHWARYA COLLEGE Page 14


C PROGRAMMING NOTES: NEW COURSE (2013-2016)

There are several features which make C a very suitable language for writing system
programs. These are as follows:
1. C is a machine independent and highly portable language.
2. It is easy to learn as it has only as few as 32 keywords.
3. It has a comprehensive set of operators to tackle business as well as scientific
applications with ease.
4. Users can create their own functions and add them to the C library to perform a
variety of tasks.
5. C language allows manipulation of BITS, BYTES, and ADDRESSES at hardware
level.
6. It has a large library of functions.
C operates on the same data types as the computer, so the codes need very little data
conversion, if at all. Therefore, codes generated are fast and efficient.

Components of C Language
As, with any language, C language also has following language elements:
Character Set, Data Types, Constants, Variables, Keywords, Grammar (Syntax and
semantic)
Character Set
Character set of a language is set of all the symbols used to write in that language. The
characters in C are grouped into four categories:
1. Letters : A - Z or a – z
2. Digits : 0-9
3. Special Symbols : ~ . ' . ! @ # % ^ & * ( ) _ - + = | \ { } [ ]: ;"'<>, . ? /.
4. White spaces : blank space, horizontal tab, carriage return, new
line, form feed.

Data Types
The power of a programming language depends, among other things, on the range of
different types of data it can handle.
Inside a digital computer, at the lowest level, all data and instructions are stored using only
binary digits (0 and 1). Thus, decimal number 65 is stored as its binary equivalent: 0100
0001. Also the character “A” is stored as binary equivalent of 65(A’s ASCII): 0100 0001.
Both the stored values are same but represent different type of values. Actually, the
interpretation of a stored value depends on the type of the variable in which the value is
stored even if it is just 0100 0001 as long as it is stored on the secondary storage device.
Thus, if 0100 0001 is stored in an integer type variable, it will be interpreted to have
integer value 65, whereas, if it is stored in character type of variable, it will represent “A”.
Therefore, the way a value stored in a variable is interpreted is known as its data type. In
other words, data type of a variable is the type of data it can store.
Every computer language has its own set of data types it supports. Also, the size of the data
types (number of bytes necessary to store the value) varies from language to language.
Besides, it is also hardware platform dependent.
The C-data types may be classified into two categories: Primary and Composite data types
as shown below.

PREPARED BY: SUMIT PUROHIT, ASST. PROF.,AISHWARYA COLLEGE Page 15


C PROGRAMMING NOTES: NEW COURSE (2013-2016)

C data types

Primary Data type Composite Data type

void Array
char Pointer
int Structure
float Union
double Enum, etc.

Primary Data Types


There are five primary data types in C language.
1. char : stores a single character belonging to the defined character set of C
language.
2. int : stores signed integers. e.g., positive or negative integers.
3. float : stores real numbers with single precision (precision of six digits after
decimal points).
4. double : stores real numbers with double precision, i.e., twice the storage space
required by float.
5. void : specify no values.
The following table shows the meaning and storage spaces required by various primary
data types.
Data Type Meaning Storage Space Format Range of Values
char A character 1 byte %c ASCII character set
int An integer 2 bytes %d -32768 to +32767

float A single precision 4 bytes %f -3.4*1038 to +3.4*1038


Floating point
number
double A double precision 8 bytes %lf -1.7x10308 to
floating point +1.7*10308
number

void valueless or empty 0 byte - -

In addition to these data types, C also has data type qualifiers – short, long, signed and
unsigned. Thus an integer type data may be defined in C as short int, int, unsigned int,
long int. The range of values and size of these qualified data-types is implementation

PREPARED BY: SUMIT PUROHIT, ASST. PROF.,AISHWARYA COLLEGE Page 16


C PROGRAMMING NOTES: NEW COURSE (2013-2016)

dependent. However, short is smaller than or equal int, which in turn, is smaller than long.
Unsigned int contains larger range since it does not store negative integers.
Composite Data Types
Also known as derived data types, composite data types are derived from the basic data
types. They are 5 in number.

1. Array: Sequence of objects, all of which are of same types and have same name.
e.g.: int num [5];
Reserves a sequence of five locations of 2 bytes, each, for storing integers num[0],
num[1], num[2], num[3] and num[4].
2. Pointer : Used to store the address of any memory location.
3. Structure : Collection of variables of different types. e.g.: A structure of
employee's data, i.e., name, age, salary.
4. Union : Collection of variables of different types sharing common memory space.
5. Enumerated data type : Its members are the constants that are written as identifiers
though they have signed integer values. These constants represent values that can be
assigned to corresponding enumeration variables. Enumeration may be defined as
enum tag { member1, member2 …. member n};
e.g.: enum colors { red, green, blue, cyan};
colors foreground, background;
The first line an enumeration named "colors" which may have any one of the four colors
defined in the curly braces. In the second line, variables of the enumerated data type
"colors” are declared.
Constants
A constant is an entity with fixed value that does not change. It can be stored at a location
in the memory of the computer and can be referenced through that memory address. There
are four basic types of constants in C, viz. integer constants, floating-point constants,
character constants and string constants. Composite types may also have constants.
Integer and floating-point constants represent numbers. They are often referred to
collectively as numeric-type constants.
In specifying constants, following rules must be observed:
Commas and blank spaces cannot be included within the constants
The constant can be preceded by a minus(-) sign if desired.
Value of a constant cannot exceed specified maximum and minimum bounds. For
each type of constant, these bounds will vary from one C-compiler to another.
Constants are the fixed values that remain unchanged during the execution of a
program and are used in assignment statements. Constants can be stored in
variables.
To declare any constant, the syntax is: const datatype var_name = value;
Ex.: const float pi = 22/7; defines a constant named pi whose value remains 22/7
throughout the program in which it is defined.

PREPARED BY: SUMIT PUROHIT, ASST. PROF.,AISHWARYA COLLEGE Page 17


C PROGRAMMING NOTES: NEW COURSE (2013-2016)

In C language, there are five types of constants.


1. Character
2. Integer
3. Real
4. String
5. Logical

Character Constants
A character constant consists of a single character, single digit, or a single special symbol
enclosed within a pair of single inverted commas. The maximum length of a character
constant is one character.
Ex. : ‘a’ is a character constant Ex. : ‘P’ is a character constant
Ex. : ‘7’ is a character constant Ex. : ‘*’ is a character constant

Integer Constants
An integer constant refers to a sequence of digits. There are three types of integers in C
language: decimal, octal, hexadecimal.
Decimal integers : 1, 56, 7657, -34 etc.
Octal integers : 076, -076, 05 etc. (preceded by zero, 0)
Hexadecimal integers : 0x56, -0x5D etc. (preceded by zero, 0x)
No commas or blanks are allowed in integer constants.

Real or floating point Constants


A number with a decimal point and an optional preceding sign represents a real constant.
Ex. 34.8, -655.33, .2, -.56, 7.
Note that 7 is an integer while 7. or 7.0 is real.
Another notation (called scientific notation) for real constants consists of three parts:
i) A sign (+ or 0) preceding the number portion (optional).
ii) A number portion
iii) An exponent portion following the number portion (optional). It starts with E or e
followed by an integer. Which may or may not be preceded by a sign.
Ex. Valid Representations Invalid Representations
+ . 72 12 (no decimal)
+ 72. 7.6 E + 2.2(in exponent decimal point not allowed)
+ 7.6 E + 2 1.2 E9229892(very large exponent)

String Constants
A string constant is a sequence of one or more characters enclosed within a pair of double
quotes (" "). If a single character is enclosed within a pair of double quotes, it will also be
interpreted as a string constant.
e.g.: "Welcome To C Programming \ n"
"a"

PREPARED BY: SUMIT PUROHIT, ASST. PROF.,AISHWARYA COLLEGE Page 18


C PROGRAMMING NOTES: NEW COURSE (2013-2016)

Actually, a string is an array of characters terminated by a NULL character. Thus, “a” is a


string consisting of two characters, viz. ‘a’ and NULL(‘\0’)
Logical Constants
A logical constant can have either true value or false value. In C, a non zero value is treated
as true while 0 is treated as false.
Variables
A variable is an entity whose value can change during program execution. A variable can be
thought of as a symbolic representation of address of the memory space where values can
be stored, accessed and changed.
A specific location or address in the memory is allocated for each variable and the value of
that variable is stored in that location.

Each variable has a name and data-type. All the variables must have their type indicated
so that the compiler can record all the necessary information about them, generate the
appropriate code during translation and allocating required space in memory.
Rules for Constructing Variable Name
a. Variable name may be a combination of alphabets, digits or underscores. Sometimes,
an additional constraint on the number of characters in the name is imposed by
compilers in which case its length should not exceed 8 characters.
b. First character must be an alphabet or an underscore (_).
c. No commas or blank spaces are allowed in a variable name.
d. Among the special symbols, only underscore can be used in a variable name.
e.g.: emp_age, item_4, etc.
e. No word, having a reserved meaning in C can be used for variable name.

Variable Declaration and Assignment of Values


All the variables must be declared before their use. Declaration does two things:
It tells the compiler what the variable name is.
It specifies what type of data the variable will hold.
A variable declaration has the form:
Type-specifier comma-separated-list-of-variables;
Here type-specifier is one of the valid data types. List-of-variables is a comma-
separated list of identifiers representing the program variables.

e.g.: int i, J, K; //creates integer variables i,J and K


b. char ch; //creates a character type variable ch
To assign values to the variable, assignment operator (=) is used. Assignment is of the form
Variable-name = value;
But before assignment, the variable must be declared.
e.g.: int i, j;
j = 5;
It is also possible to assign a value to the variable at the time of declaration.
Type-specifier variable_name = value;

PREPARED BY: SUMIT PUROHIT, ASST. PROF.,AISHWARYA COLLEGE Page 19


C PROGRAMMING NOTES: NEW COURSE (2013-2016)

The process of giving initial values to the variable is known as initialization. More than one
variable can be initialized in one statement using multiple assignment operators.
e.g.: int i = 5; int j, m; j = m = 2;
But there is an exception. Consider the following example:
int i, j = 2, K;
Here the assignment will be
i=0
j=2
k = garbage value (unintialized)
Keywords
Keywords are the words, which have been assigned specific meanings in the context of C
language programs. To avoid problems, keywords should not be used as variable names.
Below is the list of these 32 keywords.

auto double int struct


break else long switch
case enum register typedef

char extern return union


const float short unsigned

continue for signed void

default goto sizeof volatile

do if static while

PREPARED BY: SUMIT PUROHIT, ASST. PROF.,AISHWARYA COLLEGE Page 20


C PROGRAMMING NOTES: NEW COURSE (2013-2016)

Structure of a C Program
Every C program consists of one or more distinct units called functions. Each function has
unique name. One and only one of the constituent functions of a C-program must be named
main(). It is the main function, which is executed. A function may call another function,
which execute and return computed value to the calling function.
Each function has a name, an optional list of input parameters (also called arguments of
the function) with their data-type, a return data-type and a compound statement.
A compound statement is a group of zero or more statements enclosed within curly braces
{}. Compound statements may be nested i.e. one compound statement may exist inside
another one.
A C-statement is a valid C-expression delimited by semi-colon.
The following rules are applicable to all C-statements:
Blank spaces may be inserted between two words to improve the readability of the
statement. However, no blank space is allowed within a word.
Most of the C-compilers are case-sensitive, and hence statements are entered in
small case letters.
C has no specific rules about the position at which different parts of a statements be
written. Not only can a C statement be written anywhere in a line, it can also be
split over multiple lines. That is why it is called free-format language.
A C-statement ends with a semi-colon(;).

Functions
Every C program is structured as an assembly of one or more distinct units called
functions. Each function comprises of a set of valid C statements and is designed to perform
a specific task. Each function is given a unique name for reference purposes and is treated
as a single unit by the C-compiler. A function name is always followed by a pair of
parenthesis, i.e., ( ).
The statements within a function are always enclosed within a pair of braces { }. Every C
program must necessarily contain a special function named main( ). The program execution
always starts with this function. The main function is normally, but not necessarily, located
at the beginning of the program. The group of statements within main( ) are executed
sequentially. When the closing brace of the main function is reached, program execution
stops, and the control is handed back to the operating system.
Whenever a function is called, it returns to the caller the value it is supposed to return.
Schematically, a C-function may be depicted as:

PREPARED BY: SUMIT PUROHIT, ASST. PROF.,AISHWARYA COLLEGE Page 21


C PROGRAMMING NOTES: NEW COURSE (2013-2016)

Returned
List of input parameters
value
Function Name

Int (max of a
Int a, int b
and b
FindMax

The C-program code for this function looks like:


int FindMax(int a, int b)
{
statement1;
statement2;
return (p); //p is the integer value returned by this //function etc.
}

In plain English it reads: function, whose name if FindMax, takes two integer type
arguments, process it some way (i.e. executes the statements contained within) and returns
an integer value to the caller, which can be used by other statements of the program.

Statements
Single C language instruction delimited by a semi-colon is called a statement. Statements
are written in accordance with the grammar of C language. Blank space is inserted between
words to improve the readability. However, no blank spaces are allowed within a word.
Usually all C statements are entered in lower case letters. C is a free form language. There
are no restrictions regarding the format of writing C language statements. The statements
can start and terminate anywhere on the line. They can also be split over multiple lines.
Every C language statement always ends with a semicolon.

A Sample C Language Program


/* Program to print Hello C on the screen */
#include <stdio.h>
main ( )
{
printf ("Hello C");
}

The first line is a comment that explains the purpose of the program.

PREPARED BY: SUMIT PUROHIT, ASST. PROF.,AISHWARYA COLLEGE Page 22


C PROGRAMMING NOTES: NEW COURSE (2013-2016)

#include or any statement beginning with # character, is known as compiler directive. A


compiler directive is a command to compiler to translate the program in a certain way.
These statements are not converted into machine language but only perform some other
task.
A function (as also a variable) must be defined or declared before it is used. This program
uses two functions – main() and printf(). printf() function prints whatever is handed over to
it as input argument. More on printf() later. While main() is a being defined here, printf() is
not. Actually, printf() function is defined in a library file – stdio.h.
#include compiler directive commands the compiler to copy the contents of the specified file
at this line. Thus, #include<stdio.h> will copy the contents of the file stdio.h in its place. As
said earlier this file contains definition of printf() function, its definition (as also any other
definition that file may have) is copied here. Now on, you can use printf() function in the
rest of the program.
The third line is a heading for the function main( ). It takes no arguments.
{ begins the body of the function main().
Printf(“Hello C”); statement prints “Hello C’ on the screen.

} terminates the function main().


Numeric data are stored in the memory in their binary form while the character data has to
be codified as a unique integer and that code number is stored in the internal storage. The
integer equivalents of alphabets are:
Lower case : a-z - 122
Upper case : A-Z - 90

In the above program when characters are displayed in the integer format, the
corresponding ASCII codes are displayed. Similarly when integers are displayed in the
character format, their equivalent character is displayed.

Operators in C language: An operator is a symbol which helps the user to command the
computer to do a certain mathematical or logical manipulations. Operators are used in C
language program to operate on data and variables. C has a rich set of operators. C
programming language provides several operators to perform different kind to operations.
There are operators for assignment, arithmetic functions, logical functions and many more.
These operators generally work on many types of variables or constants, though some are
restricted to work on certain types. Most operators are binary, meaning they take two
operands. A few are unary and only take one operand.
These operators are as follow:

PREPARED BY: SUMIT PUROHIT, ASST. PROF.,AISHWARYA COLLEGE Page 23


C PROGRAMMING NOTES: NEW COURSE (2013-2016)

1. Arithmetic Operators
2. Increment and Decrement Operators
3. Assignment Operators
4. Relational Operators
5. Logical Operators
6. Conditional Operators
7. Bitwise Operators
8. Special Operators

Arithmetic operators: All the basic arithmetic operations can be carried out in C. All the
operators have almost the same meaning as in other languages. Both unary and binary
operations are available in C language. Unary operations operate on a singe operand,
therefore the number 5 when operated by unary – will have the value –5
+ For performing Addition
- For performing Subtraction
/ For performing Division
* For performing Multiplication
% modulo for finding remainder in division operation

Integer Arithmetic
When an arithmetic operation is performed on two whole numbers or integers than such an
operation is called as integer arithmetic. It always gives an integer as the result. Let x = 27
and y = 5 be 2 integer numbers. Then the integer operation leads to the following results.
x + y = 32
x – y = 22
x * y = 115
x%y=2
x/y=5
In integer division the fractional part is truncated.
Floating point arithmetic
When an arithmetic operation is preformed on two real numbers or fraction numbers such
an operation is called floating point arithmetic. The floating point results can be truncated
according to the properties requirement. The remainder operator is not applicable for
floating point arithmetic operands.

Let x = 14.0 and y = 4.0 then


x + y = 18.0
x – y = 10.0
x * y = 56.0
x / y = 3.50

PREPARED BY: SUMIT PUROHIT, ASST. PROF.,AISHWARYA COLLEGE Page 24


C PROGRAMMING NOTES: NEW COURSE (2013-2016)

Mixed mode arithmetic


When one of the operand is real and other is an integer and if the arithmetic operation is
carried out on these 2 operands then it is called as mixed mode arithmetic. If anyone
operand is of real type then the result will always be real thus 15/10.0 = 1.5
2. Increment / Decrement Operator: The increment and decrement operators are one of
the unary operators which are very useful in C language. They are extensively used in for
and while loops. The syntax of the operators is given below
1. ++ variable name
2. variable name++
3. – –variable name
4. variable name– –

The increment operator ++ adds the value 1 to the current value of operand and the
decrement operator – – subtracts the value 1 from the current value of operand. ++variable
name and variable name++ mean the same thing when they form statements
independently, they behave differently when they are used in expression on the right hand
side of an assignment statement.

Consider the following


m = 5;
y = ++m; (prefix)
In this case the value of y and m would be 6
Suppose if we rewrite the above statement as
m = 5;
y = m++; (post fix)
Then the value of y will be 5 and that of m will be 6. A prefix operator first adds 1 to the
operand and then the result is assigned to the variable on the left. On the other hand, a
postfix operator first assigns the value to the variable on the left and then increments the
operand.
3. Assignment Operator: The Assignment Operator evaluates an expression on the right
of the expression and substitutes it to the value or variable on the left of the expression.

Example
x=a+b
Here the value of a + b is evaluated and substituted to the variable x.
In addition, C has a set of shorthand assignment operators of the form.
var oper = exp;
Here var is a variable, exp is an expression and oper is a C binary arithmetic operator. The
operator oper = is known as shorthand assignment operator
Example
x + = 1 is same as x = x + 1
The commonly used shorthand assignment operators are as follows

PREPARED BY: SUMIT PUROHIT, ASST. PROF.,AISHWARYA COLLEGE Page 25


C PROGRAMMING NOTES: NEW COURSE (2013-2016)

Shorthand assignment operators

Statement with simple Statement with


assignment operator shorthand operator
a=a+1 a += 1
a=a–1 a -= 1
a = a * (n+1) a *= (n+1)
a = a / (n+1) a /= (n+1)
a=a%b a %= b

4. Relational Operator: Often it is required to compare the relationship between


operands and bring out a decision and program accordingly. This is when the relational
operator come into picture. C supports the following relational operators.

Operator Meaning
< is less than
<= is less than or equal to
> is greater than
>= is greater than or equal to
== is equal to
!= is not equal to

It is required to compare the marks of 2 students, salary of 2 persons, we can compare them
using relational operators.
A simple relational expression contains only one relational operator and takes the following
form.

exp1 <relational operator> exp2

Where exp1 and exp2 are expressions, which may be simple constants, variables or
combination of them. Given below is a list of examples of relational expressions and
evaluated values.

6.5 <= 25 TRUE


-65 > 0 FALSE
10 < 7 + 5 TRUE

Relational expressions are used in decision making statements of C language such as if,
while and for statements to decide the course of action of a running program.
5. Logical Operator: C has the following logical operators, they compare or evaluate
logical and relational expressions.

PREPARED BY: SUMIT PUROHIT, ASST. PROF.,AISHWARYA COLLEGE Page 26


C PROGRAMMING NOTES: NEW COURSE (2013-2016)

Operator Meaning
&& Logical AND
|| Logical OR
! Logical NOT
Logical AND (&&)
This operator is used to evaluate 2 conditions or expressions with relational operators
simultaneously. If both the expressions to the left and to the right of the logical operator is
true then the whole compound expression is true.
Example
a > b && x = = 10
The expression to the left is a > b and that on the right is x == 10 the whole expression is
true only if both expressions are true i.e., if a is greater than b and x is equal to 10.
Logical OR (||)
The logical OR is used to combine 2 expressions or the condition evaluates to true if any one
of the 2 expressions is true.
Example
a < m || a < n
The expression evaluates to true if any one of them is true or if both of them are true. It
evaluates to true if a is less than either m or n and when a is less than both m and n.
Logical NOT (!)
The logical not operator takes single expression and evaluates to true if the expression is
false and evaluates to false if the expression is true. In other words it just reverses the
value of the expression.
For example
! (x >= y) the NOT expression evaluates to true only if the value of x is neither greater than
or equal to y
6. Conditional Operator or Ternary Operator: The conditional operator consists of 2
symbols the question mark (?) and the colon (:)
The syntax for a ternary operator is as follows
exp1 ? exp2 : exp3

The ternary operator works as follows


exp1 is evaluated first. If the expression is true then exp2 is evaluated & its value becomes
the value of the expression. If exp1 is false, exp3 is evaluated and its value becomes the
value of the expression. Note that only one of the expression is evaluated.

For example
a = 10;
b = 15;
x = (a > b) ? a : b
Here x will be assigned to the value of b. The condition follows that the expression is false
therefore b is assigned to x.

PREPARED BY: SUMIT PUROHIT, ASST. PROF.,AISHWARYA COLLEGE Page 27


C PROGRAMMING NOTES: NEW COURSE (2013-2016)

.
/* Example : to find the maximum value using conditional operator)
#include
void main() //start of the program
{
int i,j,larger; //declaration of variables
printf (“Input 2 integers : ”); //ask the user to input 2 numbers
scanf(“%d %d”,&i, &j); //take the number from standard input and store it
larger = i > j ? i : j; //evaluation using ternary operator
printf(“The largest of two numbers is %d \n”, larger); // print the largest
number
} // end of the program
.
Output
Input 2 integers : 34 45
The largest of two numbers is 45
7. Bitwise Operator: C has a distinction of supporting special operators known as bitwise
operators for manipulation data at bit level. A bitwise operator operates on each bit of data.
Those operators are used for testing, complementing or shifting bits to the right on left.
Bitwise operators may not be applied to a float or double.
Operator Meaning

& Bitwise AND


| Bitwise OR
^ Bitwise Exclusive

<< Shift left

>> Shift right


~ (tilde) One’s complement

8. Special Operator: C supports some special operators of interest such as comma


operator, size of operator etc. The comma operator can be used to link related expressions
together. A comma-linked list of expressions is evaluated left to right and value of right
most expression is the value of the combined expression.
For example the statement
value = (x = 10, y = 5, x + y);
First assigns 10 to x and 5 to y and finally assigns 15 to value. Since comma has the lowest
precedence in operators the parenthesis is necessary. Some examples of comma operator
are
In for loops:
for (n=1, m=10, n <=m; n++,m++)

PREPARED BY: SUMIT PUROHIT, ASST. PROF.,AISHWARYA COLLEGE Page 28


C PROGRAMMING NOTES: NEW COURSE (2013-2016)

In while loops
While (c=getchar(), c != ‘10’)
Exchanging values
t = x, x = y, y = t;
The size of Operator
The operator size of gives the size of the data type or variable in terms of bytes occupied in
the memory. The operand may be a variable, a constant or a data type qualifier.
Example
m = sizeof (sum);
n = sizeof (long int);
k = sizeof (235L);
The size of operator is normally used to determine the lengths of arrays and structures
when their sizes are not known to the programmer.

Type Conversion
It is the process of converting one type into another. In other words converting an
expression of a given type into another is called type casting. There are two ways of
achieving type conversion namely:
1. Automatic conversion or implicit conversion
2. Type casting or explicit conversion
1. Automatic conversion or implicit conversion: this is not done by any
conversion or operators. In other words gets automatically converted to the specific
type which is assigned.
When the type conversion is performed automatically by the compiler without programmers
intervention, such type of conversion is known as implicit type conversion or type
promotion. The compiler converts all operands into the data type of the largest operand.
The sequence of rules that are applied while evaluating expressions are given below:
All short and char are automatically converted to int, then,
1. If either of the operand is of type long double, then others will be converted to long double
and result will be long double.
2. Else, if either of the operand is double, then others are converted to double.
3. Else, if either of the operand is float, then others are converted to float.
4. Else, if either of the operand is unsigned long int, then others will be converted to unsigned
long int.
5. Else, if one of the operand is long int, and the other is unsigned int, then
 If a long int can represent all values of an unsigned int, the unsigned int is
converted to long int.
 Otherwise, both operands are converted to unsigned long int.
6. Else, if either operand is long int then other will be converted to long int.

PREPARED BY: SUMIT PUROHIT, ASST. PROF.,AISHWARYA COLLEGE Page 29


C PROGRAMMING NOTES: NEW COURSE (2013-2016)

7. Else, if either operand is unsigned int then others will be converted to unsigned int.
It should be noted that the final result of expression is converted to type of variable on left
side of assignment operator before assigning value to it.
Also, conversion of float to int causes truncation of fractional part, conversion of double to
float causes rounding of digits and the conversion of long int to int causes dropping of
excess higher order bits.
2. Explicit Type Conversion
The type conversion performed by the programmer by posing the data type of the
expression of specific type is known as explicit type conversion.
The explicit type conversion is also known as type casting.
Type casting in c is done in the following form:
(data_type) expression;
where, data_type is any valid c data type, and expression may be constant, variable or
expression.
For example,
1 x=(int)a+b*d;
The following rules have to be followed while converting the expression from one type to
another to avoid the loss of information:
1. All integer types to be converted to float.
2. All float types to be converted to double.
3. All character types to be converted to integer.
Input output statements in C:
In C language there are two type of input output statements:
1. Unformatted I/O statements
2. Formatted I/O statements

1. Unformatted I/O statements: these are capable of performing I/O operations with
respect to single data form.

(i) Character based I/O functions:


Character based input functions: these are capable of performing input of single
character at a time.
Block - I : getchar(), getc()
Block - II : getche() , getch()

PREPARED BY: SUMIT PUROHIT, ASST. PROF.,AISHWARYA COLLEGE Page 30


C PROGRAMMING NOTES: NEW COURSE (2013-2016)

Block – I V/S Block-II


The I block statements allow us to type as many numbers of characters as user wants. The
input put would be terminated at enter key. An input would perform of only first character
type.
The II block of statements perform input as soon as the user presses first key thus there is
no requirement of enter key to terminate the input.

I/O
STATEMENTS

UNFORMATTE
FORMATTED
D

CHARACTER STRING
printf (for output)
ORIENTED ORIENTED

gets()
INPUT OUTPUT scanf (for input)
(for input)

puts()
getchar() putchar()
(for output)

getc() putc()

getch()

getche()

getchar() – performs input only from keyboard


getc() – used to take input from a file
getc(stdin) – file representation of standard input device (keyboard)
getche() – character typed would be echoed (displayed) on monitor.
getch() – typed character would not be displayed on screen.
Character based output function: The putc() function prints out a character on the
specified file stream.

PREPARED BY: SUMIT PUROHIT, ASST. PROF.,AISHWARYA COLLEGE Page 31


C PROGRAMMING NOTES: NEW COURSE (2013-2016)

#include <stdio.h>
int putc(int c, FILE *stream);

Here c is the character to be written, stored as an integer. The second argument is the file
where the character is going to be printed. If an error occurs, putc() returns EOF;
otherwise, the function returns the written character.
The putchar() is also used to put a character on the screen. The only difference between it
and putc() is that putchar() needs only the first argument, because the standard output is
set as the file stream for putchar().

#include <stdio.h>
int putchar(int c);

Example:
char w = ‘A’;
putchar(w); output = A
putc(w, stdout); A can perform O/P on a file
putchar(w); output=A
putchar(‘A’); output=A
putchar(65); output=A
putchar(‘ ’); error! Must have at least one character
putchar(w + 3); output = D
putchar(‘w’ + 3); output = z
putchar(‘w + 3’); output = error! More than two characters

(ii) String based I/O functions:


String is a stream of characters and it is a feature of ‘C’ language that allows
creating a collection of characters. These functions allow creating such variables
which are capable of string multiple characters at the same time.
Declaration:
char < name of collection> [number of char]
char str[10];
100 101 102 103 104 105 106 107 108 109

(Continuous + Adjacent) = Contiguous manner


String constants should be in “ ” (double quotes).
char str[10]; = “apple”;

100 101 102 103 104 105 106 107 108 109
a p p l e

PREPARED BY: SUMIT PUROHIT, ASST. PROF.,AISHWARYA COLLEGE Page 32


C PROGRAMMING NOTES: NEW COURSE (2013-2016)

In this string variables store the sharing address of collection. Address once
stored can’t be modified.

String based input functions: (gets())


To read character by character from the input we have getc and getchar functions. We can
also read line by line with gets():
char str[10];
gets(str); apple

This allows typing as much number of characters. Input is terminated by enter key and all
characters are taken as input.

gets( str + 3); _ _ _ apple

100 101 102 103 104 105 106 107 108 109
a p p l e

String based output function: (puts())


The puts() function can be used to write a sequence of characters to the standard output
stream.
Char str[10] = “mango”;

100 101 102 103 104 105 106 107 108 109
m a n g o

puts(str) ; output = mango


puts(str + 3) ; output = go
puts(“mango”) ; output = mango
puts(“mango”+3) ; output = go

A constant string is first stored in memory at certain location and its starting address is
represented at its space.

puts(“str”); output = str


puts(“A”); output = A
puts(“ ”); output = SPACE
puts(“ ’A’ ”); output = ‘A’

2. Formatted Input output functions: the functions prinf() and scanf() perform
formatted output and input i.e. they can write and read data in various formats
that are under out control. The prinf() function writes data to the console. The

PREPARED BY: SUMIT PUROHIT, ASST. PROF.,AISHWARYA COLLEGE Page 33


C PROGRAMMING NOTES: NEW COURSE (2013-2016)

scanf() function is its complement and reads data from the console input device
(keyboard).
The prinf() function returns the number of characters written.
printf( control string);
Control string consists of two types of items. The first type is composed of characters that
will be printed on the screen. The second type contains format specifiers that define the
way the subsequent arguments are displayed. A format specifier begins with a percent sugn
(%) is followed by the format code.
Format specifiers
%c Character
%d Signed decimal integer
%i Signed decimal integer
%s String of characters
%f Decimal floating point
%u Unsigned decimal integer
%lf Double
%ld Long signed
%lu Long unsigned

scanf() is used to input data from the standard input device.


scanf( “control string”, address list);

address list: to get address of the variable. We can use ‘&’ operator and this operator is
used as a prefix with any variable name.

PREPARED BY: SUMIT PUROHIT, ASST. PROF.,AISHWARYA COLLEGE Page 34


C PROGRAMMING NOTES: NEW COURSE (2013-2016)

UNIT-3

Control Statements in C : Statements are the instructions given to the computer to


perform any kind of action. Action may be in the form of data movement, decision making
etc. Statements form the smallest executable unit within a C program. Statements are
always terminated by semicolon.
Compound Statement : A compound statement is a grouping of statements in which each
individual statement ends with a semi-colon. The group of statements is called block.
Compound statements are enclosed between the pair of braces ( { } ). The opening brace( { )
signifies the beginning and closing brace ( } ) signifies the end of the block.
Null Statement: Writing only a semicolon indicates a null statement. Thus ‘;’ is a null or
empty statement. This is quite useful when the syntax of the language needs to specify a
statement but the logic of the program does not need any statement. This statement is
generally used in for and while looping statements.
Conditional Statements: Sometimes the program needs to be executed depending upon a
particular condition. C++ provides the following statements for implementing the selection
control structure.
(i) ‘if ’ statement
(ii) ‘if else’ statement
(iii) ‘nested if’ statement
(iv) ‘switch’ statement
(i) ‘if’ statement
syntax of the ‘if’ statement
if (condition)
{
statement(s);
}

From the flowchart it is clear that if the 'if condition' is true, statement 1 is executed;

PREPARED BY: SUMIT PUROHIT, ASST. PROF.,AISHWARYA COLLEGE Page 35


C PROGRAMMING NOTES: NEW COURSE (2013-2016)

otherwise it is skipped. The statement 1 may either be a single or compound statement.

Example 1
(ii) ‘if else’ statement
syntax of the if- else statement
if (condition)
statement1;
else
statement2;
From the above flowchart it is clear that the given condition is evaluated first. If the
condition is true, statement1 is executed, followed by statement3. If the condition
is false, statement2 is executed, followed by statement 3. It should be kept in mind
that statement1 and statement2 can be single or compound statement.

PREPARED BY: SUMIT PUROHIT, ASST. PROF.,AISHWARYA COLLEGE Page 36


C PROGRAMMING NOTES: NEW COURSE (2013-2016)

From the flowchart it is clear that condition 1, condition2, etc. are nested in sequence
until a condition is reached that evaluates to TRUE. Only one statement will be executed. If
condition1 is TRUE, then statement1 is executed. If none of the conditions is TRUE, then
statement 3 is executed. Regardless of which statement is executed, control is passed to the
statement following statement3. Each statement can be single or compound statement.

(iv) switch statement


The if and if-else statements permit two way branching whereas switch statement permits
multiple branching. The syntax of switch statement is:
switch (var / expression)
{
case constant1 : statement1;
break;
case constant2 : statement2;
break;
default : statement3;
}
The execution of switch statement begins with the evaluation of expression. If the values of
expression match with the constant then the statements following this statement execute
sequentially till it executes break. The break statement transfers control to the end of the
switch statement. If the value of expression does not match with any constant, the
statement with default is executed.

Loop Construct
It is also called a Repetitive control structure. Sometimes we require a set of statements to
be executed a number of times by changing the value of one or more variables each time to
obtain a different result. This type of program execution is called looping. C++ provides the
following constructs.

PREPARED BY: SUMIT PUROHIT, ASST. PROF.,AISHWARYA COLLEGE Page 37


C PROGRAMMING NOTES: NEW COURSE (2013-2016)

(i) while loop


(ii) do - while loop
(iii) for loop
(i) While loop:
Syntax of while loop
while (condition)
{
statement(s);
}

The flow diagram indicates that a condition is first evaluated. If the condition is true, the
loop body is executed and the condition is re-evaluated. Hence, the loop body is executed
repeatedly as long as the condition remains true. As soon as the condition becomes false, it
comes out of the loop and goes to the statement next to the ‘while’ loop.

(ii) do-while loop


Syntax of do-while loop
do
{
} while (condition);
The flow diagram indicates that after each execution of the loop body, the condition is true,
the loop body is executed again. If the condition evaluates to false, loop exit occurs and the
next program statement is executed.
Note : the loop body is always executed at least once.
One important difference between the while loop and the do-while loop is the relative
ordering of the conditional test and loop body execution. In the while loop, the loop
repetition test is performed before each execution of the loop body; the loop body is not
executed at all if the initial test fails. In the do-while loop, the loop termination test is
Performed after each execution of the loop body; hence, the loop body is always executed at
least once.

PREPARED BY: SUMIT PUROHIT, ASST. PROF.,AISHWARYA COLLEGE Page 38


C PROGRAMMING NOTES: NEW COURSE (2013-2016)

(iii) For loop


It is a count controlled loop in the sense that the program knows in advance how
many times the loop is to be executed.
syntax of for loop
for (initialization; decision; increment/decrement)
{
statement(s);
}

The flow diagram indicates that in for loop three operations take place:
(i) Initialization of loop control variable
(ii) Testing of loop control variable
(iii) Update the loop control variable either by incrementing or decrementing.
Operation (i) is used to initialize the value. On the other hand, operation (ii) is used to test
whether the condition is true or false. If the condition is true, the program executes the
body of the loop and then the value of loop control variable is updated. Again it checks the
condition and so on. If the condition is true, it gets out of the loop

Jump Statements
The jump statements unconditionally transfer program control within a function.
a) goto statement
b) break statement
c) continue statement
d) exit() function
a) goto statement
syntax of goto statement
goto pgr;


pgr :

PREPARED BY: SUMIT PUROHIT, ASST. PROF.,AISHWARYA COLLEGE Page 39


C PROGRAMMING NOTES: NEW COURSE (2013-2016)

pgr is known as label. It is a user defined identifier. After the execution of goto statement,
the control transfers to the line after label pgr.
Note : It is not a good programming to use goto statement in a program.

b) Break statement
syntax of break statement
The break statement can be used in a switch statement and in any of the loops. It
causes program execution to pass to the next statement following the switch or the
loop.
while (condition)
{
statement 1;
if (condition)
break ;
statement 2;
}
statement 3;
The break statement skips rest of the loop and goes out of the loop.

c) continue statement
The continue statement is used in loops and causes a program to skip the rest of
the body of the loop.
while (condition)
{
statement 1;
If (condition)
continue ;
statement 2;
}
statement 3;
The continue statement skips rest of the loop body and starts a new iteration.

d) exit ( ) function
The execution of a program can be stopped at any point with exit ( ) and a status
code can be informed to the calling program. The general format is
exit (code ) ;
where code is an integer value. The code has a value 0 for correct execution. The value of
the code varies depending upon the operating system. It requires a process.h header file.

PREPARED BY: SUMIT PUROHIT, ASST. PROF.,AISHWARYA COLLEGE Page 40


C PROGRAMMING NOTES: NEW COURSE (2013-2016)

ARRAY
Introduction to Arrays
An array is a group of data items of same data type that share a common name. Ordinary
variables are capable of holding only one value at a time. If we want to store more than one
value at a time in a single variable, we use arrays.

An array is a collective name given to a group of similar variables. Each member in the
group is referred to by its position in the group.

Arrays are allotted the memory in a strictly contiguous fashion. The simplest array is one
dimensional array which is a list of variables of same data type. An array of one
dimensional arrays is called a two dimensional array.

One Dimensional Array


A list of items can be given one variable name using only one subscript and such a variable
is called a one dimensional array.

e.g.: If we want to store a set of five numbers by an array variable number. Then it will
be accomplished in the following way:
int number [5];

This declaration will reserve five contiguous memory locations as shown below:

Number [0] Number [1] Number [2] Number [3] Number [4]

As C performs no bounds checking, care should be taken to ensure that the array indices
are within the declared limits. Also, indexing in C begins from 0 and not from 1.

Array Declaration
Arrays are defined in the same manner as ordinary variables, except that each array name
must be accompanied by the size specification.

The general form of array declaration is:


data-type array-name [size];

data-type specifies the type of array, size is a positive integer number or symbolic constant
that indicates the maximum number of elements that can be stored in the array.
e.g.: float height [50];
This declaration declares an array named height containing 50 elements of type float.

The compiler will interpret first element as height [0]. As in C, the array elements are
induced for 0 to [size-1].

PREPARED BY: SUMIT PUROHIT, ASST. PROF.,AISHWARYA COLLEGE Page 41


C PROGRAMMING NOTES: NEW COURSE (2013-2016)

Array Initialization
The elements of an array can be initialized in the same way as the ordinary variables, when
they are declared. Given below are some examples which show how the arrays are
initialized.
static int num [6] = {2, 4, 5, 45, 12};
static int n [ ] = {2, 4, 5, 45, 12};
static float press [ ] = {12.5, 32.4, -23.7, -11.3};

In these examples note the following points:


(a) Till the array elements are not given any specific values, they contain garbage value.
(b) If the array is initialized where it is declared, its storage class must be either static
or extern. If the storage class is static, all the elements are initialized by 0.
(c) If the array is initialized where it is declared, mentioning the dimension of the array
is optional.

Accessing Elements of an Array


Once an array is declared, individual elements of the array are referred using subscript or
index number. This number specifies the element's position in the array. All the elements of
the array are numbered starting from 0. Thus number [5] is actually the sixth element of
an array.
Entering Data into an Array
It can be explained by the following examples:
main( )
{
int num [6];
int count;
for (count = 0; count < 6; count ++)
{
printf ("\n Enter %d element:" count+1);
scanf ("%d", &num [count]);
}
}

In this example, using the for loop, the process of asking and receiving the marks is
accomplished. When count has the value zero, the scanf( ) statement will cause the value to
be stored at num [0]. This process continues until count has the value greater than 5.

Reading Data from an Array


Consider the program given above. It has entered 6 values in the array num. Now to read
values from this array, we will again use for Loop to access each cell. The given program
segment explains the retrieval of the values from the array.

for (count = 0; count < 6; count ++)


{
printf ("\n %d value =", num [count]);
}

PREPARED BY: SUMIT PUROHIT, ASST. PROF.,AISHWARYA COLLEGE Page 42


C PROGRAMMING NOTES: NEW COURSE (2013-2016)

Memory Representation of Array


Consider the following array declaration:
int arr[8];
16 bytes get immediately reserved in memory because each of the 8 integers would be 2
bytes long and since the array is not being initialized, all eight values present in it would be
garbage values.

Whatever be the initial values, all the array elements would always be present in
contiguous memory location. This arrangement of array elements in memory is shown
below.
Value
12 34 66 -45 23 346 77 98

Address 4002 4004 4006 4008 4010 4012 4014 4016


In C, there is no check to see if the subscript used for an array exceeds the size of the array.
Data entered with a subscript exceeding the array size will simply be placed in memory
outside the array. This will lead to unpredictable results and there will be no error message
to warn you that you are going beyond the array size. So to see to it that you do not reach
beyond the array size is entirely the programmer's botheration and not the compiler's.
Ex. - A program to find average marks obtained by a class of 30 students in a test.
main( )
{
float avg, sum = 0; int i;
int marks [30]; /* array declaration */
fot (i = 0; i < 30; i++)
{
printf ("\n Enter marks: \t");
scanf ("%d", &marks [i]); /* store data in array */
}
for (i = 0; i < 30; i++)
sum = sum + marks [i];
avg = sum / 30;
printf ("\nAverage marks: %f”, avg);
}
Program to read in a one dimensional character array, convert all the
elements to upper case, and then write out the converted array
#include <stdio.h>
# define SIZE 80
main( )
{
char letter [SIZE]; int count;
for (count = 0; count <SIZE; ++ count) /* read in the line */
letter [count] = getchar( );
for (count = 0; count <SIZE; ++ count)
putchar (toupper (letter[count]));
}

PREPARED BY: SUMIT PUROHIT, ASST. PROF.,AISHWARYA COLLEGE Page 43


C PROGRAMMING NOTES: NEW COURSE (2013-2016)

It is sometimes convenient to define an array size in terms of a symbolic constant rather


than a fixed integer quantity. This makes it easier to modify a program that utilizes an
array, since all references to the maximum array size can be altered simply by changing the
value of the symbolic constant.

Strings
Just as a group of integers can be stored in an integer array, group of characters can be
stored in a character array or "strings". The string constant is a one dimensional array of
characters terminated by null character ('\0'). This null character '\0' (ASCII value 0) is
different from 'O' (ASCII value 48).

The terminating null character is important because it is the only way the function that
works with string can know where the string ends.
e.g.: Static char name [ ] = {'K', 'R', 'I', 'S', 'H', '\0'};
This example shows the declaration and initialization of a character array. The array
elements of a character array are stored in contiguous locations with each element
occupying one byte of memory.

K R I S H N A ‘\0’
4001 4002 4003 4004 4005 4006 4007 4009

NOTE: - Contrary to the numeric array where a 5 digit number can be stored in one array
cell, in the character arrays only a single character can be stored in one cell. So in order to
store an array of strings, a 2-dimensional array is required.

As scanf( ) function is not capable of receiving multi word string, such strings should be
entered using gets( ).

Two Dimensional Arrays


It is possible to have an array of more than one dimensions. Two dimensional array (2-D
array) is an array of number of 1-dimensional arrays.

A two dimensional array is also called a matrix. Consider the following table:
Item1 Item 2 Item 3
Sales 1 300 275 365
Sales 2 210 190 325
Sales 3 405 235 240
Sales 4 260 300 380

This is a table of four rows and three columns. Such a table of items can be defined using
two dimensional arrays.

General form of declaring a 2-D array is


data_type array_name [row_size] [colum_size];
e.g.: i) int marks [4] [2];

It will declare an integer array mark of four rows and two columns. An element of this
array can be accessed by the manipulation of both the indices.

PREPARED BY: SUMIT PUROHIT, ASST. PROF.,AISHWARYA COLLEGE Page 44


C PROGRAMMING NOTES: NEW COURSE (2013-2016)

printf ("%d", marks [2] [1]) will print the element present in third row and second column.

Initialization of a 2-Dimensional Array


Two dimensional arrays may be initialized by a list of initial values enclosed in braces
following their declaration.
e.g.: static int table [2] [3] = {0, 0, 0, 1, 1, 1};
initializes the elements of the first row to 0 and the second row to one. The initialization is
done by row.

The aforesaid statement can be equivalently written as


static int table [2] [3] = {{0, 0, 0}, {1, 1, 1}};
by surrounding the elements of each row by braces.

We can also initialize a two dimensional array in the form of a matrix as shown below:
static int table [2] [3] = {{0, 0, 0},
{1, 1, 1}};
The syntax of the above statement. Commas are required after each brace that closes off a
row, except in the case of the last row.

If the values are missing in an initializer, they are automatically set to 0. For instance, the
statement
static int table [2] [3] = {{1, 1},
{2}};
will initialize the first two elements of the first row to one, the first element of the second
row to two, and all the other elements to 0.

When all the elements are to be initialized to 0, the following short cut method may be
used.
static int m [3] [5] = {{0}, {0}, {0}};
The first element of each row is explicitly initialized to 0 while other elements are
automatically initialized to 0.

While initializing an array, it is necessary to mention the second (column) dimension,


whereas the first dimension (row) is optional. Thus, the following declarations are
acceptable.
static int arr [2] [3] = {12, 34, 23, 45, 56, 45};
static int arr [ ] [3] = {12, 34, 23, 45, 56, 45 };

Memory Representation of Two Dimensional Array


In memory, whether it is a one dimensional or a two dimensional array, the array elements
are stored in one continuous chain.

The arrangement of array elements of a two dimensional array of students, which contains
roll numbers in one column and the marks in the other (in memory), is shown below:

PREPARED BY: SUMIT PUROHIT, ASST. PROF.,AISHWARYA COLLEGE Page 45


C PROGRAMMING NOTES: NEW COURSE (2013-2016)

Notation S[0][0] S[0][1] S[1][0] S[1][1] S[2][0] S[2][1] S[3][0] S[3][0]


Value
1234 1234 1234 1234 1234 1234 1234 1234

Address 5002 5004 5006 5008 5010 5012 5014 5016


e.g.: Program that stores roll number and marks obtained by a student side by
side in a matrix
main( )
{
int stud [4] [2];
int i, j;
for (i = 0; i < = 3; i++)
{
printf ("\n Enter roll no. and marks");
scanf ("%d%d", &stud [i] [0], &stud[i] [1]);
}
for (i = 0; i < = 3; i++)
printf ("%d%d\n", stud [i] [0], stud [i] [0];
}
There are two parts to the program, in the first part through a for Loop we read in the
values of roll number and marks, whereas in second part through another for Loop we print
out these values.

Program to print a multiplication table, using two dimensional array.


#define ROWS 5
#define COLUMNS 5
main( )
{
int row, column, product [ROWS] [COLUMNS];
int i, j;
printf ("MULTIPLICATION TABLE \N");
printf (" ");
for (j = 1; j < = COLUMNS; j++)
printf ("%4d", j);
printf ("\n");
for (i = 0; i < ROWS; i++)
{
row = i + 1;
printf ("%2d\n", row);
for (j = 1; j < = COLUMNS; j++)
{
column = j;
product [i] [j] = row *column;
printf ("%4d", product [i] [j]);
}
printf ("\n");
}
}

PREPARED BY: SUMIT PUROHIT, ASST. PROF.,AISHWARYA COLLEGE Page 46


C PROGRAMMING NOTES: NEW COURSE (2013-2016)

output: Multiplication Table


1 2 3 4 5
1 1 2 3 4 5
2 2 4 6 8 10
3 3 6 9 12 15
4 4 8 12 16 20
5 5 10 15 20 25

Multi-dimensional Array
C allows arrays of three or more dimensions. Multi-dimensional arrays are defined in much
the same manner as one-dimensional arrays, except that a separate pair of square brackets
is required for each subscript.

The general form of a multi-dimensional array is


data_type array_name [s1] [s2] [s3] . . . [sm];
e.g.: int survey [3] [5] [12];
float table [5] [4] [5] [3];
Here, survey is a 3-dimensional array declared to contain 180 integer_type elements.
Similarly, table is a 4-dimensional array containing 300 elements of floating point type.

An example of initializing a 4-dimensional array:

static int arr [3] [4] [2] = {{{2, 4}, {7, 8}, {3, 4}, {5, 6},},
{{7, 6}, {3, 4}, {5, 3}, {2, 3}, },
{{8, 9}, {7, 2}, {3, 4}, {6, 1}, }
};

In this example, the outer array has three elements, each of which is a two dimensional
array of four rows, each of which is a one dimensional array of two elements.
e.g.: Sorting an integer array.
# include <stdio.h>
void main( )
{
int arr [5];
int i, j; temp;
printf ("\n Enter the elements of the array:"};
scanf ("%d", & arr [i]);
for (i = 0; i < = 4; i ++);
{
for (J = 0; J < = 3; J ++)
if (arr [J] > arr [J+1])
{
temp = arr [J];
arg [J] = arr [J+1];
arr [J+1] = temp;
}
}
printf ("\ n The Sorted array is:");

PREPARED BY: SUMIT PUROHIT, ASST. PROF.,AISHWARYA COLLEGE Page 47


C PROGRAMMING NOTES: NEW COURSE (2013-2016)

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


printf ("\ t %d", arr [i]);
}

To insert an element into an existing sorted array (Insertion Sort).


# include <stdio.h>
main( )
{
int i, k, y, x [20], n;
for (i = 0; i < 20; i++)
x [ i] = 0;
printf ("\ Enter the number of items to be inserted:\n");
scanf ("%d", &n);
printf ("\n Input %d values \n", n);
for (k = 0; k < n; k++)
{
scanf ("%d", &x [k]);
y = x [x]
for (i = k-1; i > = 0 && y < x [i]; i - -)
x [i+1] = x[i];
x [i+1] = y;

}
printf ("\n The sorted numbers are:");
for (i = 0; i < n; i++)
printf ("\n %d", x [i]);
}

Accept character string and find its length.


NOTE We will solve this question by looping instead of using Library function strlen( ).
# include <stdio.h>
void main( )
{
char name [20];
int i, len;
printf ("\n Enter the name:");
scanf ("%s", name);
for (i = 0; name [i] ! = '\0'; i++);
Len = i - 1;
printf("\n Length of array is % d", len);
}

PREPARED BY: SUMIT PUROHIT, ASST. PROF.,AISHWARYA COLLEGE Page 48


C PROGRAMMING NOTES: NEW COURSE (2013-2016)

UNIT-4

FUNCTION

Introduction to Functions
Functions are the building blocks where every program activity occurs. They are self
contained program segments that carry out some specific, well defined task. Every C
program must have a function. One of the functions must be main( ).

Program execution will always begin by carrying out the instructions in function main( ).
Additional functions will be subordinate to main( ) and also to one another.

C functions can be classified into two categories.


Library functions : Predefined in the standard library of C. Need is just to include the
Library.
User defined functions : They have to be developed by the user at the time of program
writing.

Need of User Defined Functions


If a program is divided into functional parts, then each part may be independently coded
and later combined into a single unit. This approach clearly results in a number of
advantages.
1. It facilitates top-down modular programming.
2. Length of a program can be reduced by using function.
3. Debugging is easier.
4. Reusability of function increases.

The general form of a function is:


data type function_name (type arg1, type arg2, type arg3)
{
statement 1;
:
:
statement n;
}

Before defining the function, it is desired to declare the function along with its prototype. In
function prototype, the return value of function, type, and number of arguments are
specified. The declaration of all functions statement should be first statement in main( ).

The general form of function declaration using ANSI Prototype is


data_type function_name (type1 arg1, type2 arg2 - - - - );
where arg1, arg2. . . are the list of arguments.

Function prototypes are desirable because they facilitate error checking between calls to a
function and corresponding function definition. They also help the compiler to perform
automatic type conversions on function parameters. When a function is called, actual

PREPARED BY: SUMIT PUROHIT, ASST. PROF.,AISHWARYA COLLEGE Page 49


C PROGRAMMING NOTES: NEW COURSE (2013-2016)

arguments are automatically converted to the types in function definition using normal
rules of assignment.

Function Definition
The general form of a function definition is:
data_type function_name (formal argument list)
argument declarations;
{
local variable declarations;
executable statement 1;
executable statement 2;
----------
executable statement n;
return (expression);
}

Where data_type represents the data type of the value which is returned. The type
specification can be omitted if the function returns an integer or a character.

The formal argument list is a comma separated list of variables that receive the values
from main program when a function is called. The identifiers used as formal arguments are
"local" as they are not recognized outside of the function. They are also known as
parameters or formal parameters.

An empty pair of parenthesis must follow the function name if the function definition does
not include any arguments.

The argument declarations follow the first line. Each formal argument must have the same
data type as its corresponding actual argument.

The remainder of the function definition is a compound statement that defines the action to
be taken by the function. It is referred to as the body of the function.

The last statement in the body of function is return (expression);. It is used to return the
computed result, if any, to the calling program.

Calling a Function
A function can be called by specifying its name followed by a list of arguments enclosed in
parentheses and separated by commas. If a function call does not require any arguments,
an empty pair of parenthesis must follow the function name.

The arguments appearing in the function call are referred to as actual arguments, in
contrast to the formal arguments that appear in the first line of function definition.

e.g.: /* Program to find square of given number */


main( )
{
float square (float); /* function prototype dec/n*/

PREPARED BY: SUMIT PUROHIT, ASST. PROF.,AISHWARYA COLLEGE Page 50


C PROGRAMMING NOTES: NEW COURSE (2013-2016)

float a, b;
printf ("\n Enter the number:");
scanf ("%f", &a);
b = square (a); /* calling of function with actual arguments */
printf ("Square of entered no. is = %f" , b);
}

float square(float x) / * function definition with formal argument * /


{
float y; /* Local variable declaration
y = x * x;
return (y);
}
output: Enter the number: 2
Square of the entered number is = 4

The return Statement


Information is returned from the function to the calling portion of the program via return
statement. It causes control to be returned to the point from where the function was
accessed. The return statement can take one of the following forms:
return;
or
return (expression);

In the return (expression); statement, the value of the expression is returned to the calling
of the program.
e.g.: /* Program to convert lower case character to upper case */
# include <stdio.h>
main( )
{
char lower, upper;
char Lower_to_upper (char Lower);
printf ("\n Enter the Lower case character:");
scanf ("%c", & Lower);
upper = Lower_to_upper (lower);
printf ("\n The upper case Equivalent is % c", upper);
}
char lower_to_upper (Char ch)
{
char c2;
c2 = (c1 > = 'a' && c1 < = 'z') ? ('A' + c1 - 'a'): c1;
return (c2);
}

A function can have multiple return statements, each containing different


expressions.
e.g.: int square (x)
int x;

PREPARED BY: SUMIT PUROHIT, ASST. PROF.,AISHWARYA COLLEGE Page 51


C PROGRAMMING NOTES: NEW COURSE (2013-2016)

{
if (x < = 0)
return 0;
else
return (x * x);
}
The absence of return statement indicates that no value is being returned.

Storage Classes
There are two different ways to characterize variables:
i) by data types ii) by storage class

Data types refers to the type of information while storage class refers to the life-time of a
variable and its scope within the program.

A variable in C can have any one of the four storage classes.


1. Automatic variable
2. External variable
3. Static variable
4. Register variable

1. Automatic Variable
The scope of an automatic variable is confined to that function in which it is declared. It is
created when the function is called and destroyed automatically when the function is
exited. Hence the name is Automatic.
By default, a variable declared inside a function without storage class specification is an
automatic variable. Automatic variable values cannot be changed accidently by what
happens in some other functions in the program.
e.g.: main( )
{
int m = 1000;
function 2( );
printf ("%d \n", m);
}
function 1( )
{
int m = 10;
printf ("%d \n", m);
}
function 2( )
{
int m = 100;
function 1( );
printf ("%d \n", m);
}
output: 10
100
1000

PREPARED BY: SUMIT PUROHIT, ASST. PROF.,AISHWARYA COLLEGE Page 52


C PROGRAMMING NOTES: NEW COURSE (2013-2016)

2. External Variable
An external variable is also known as a global variable. It is not confined to a single
function. Its scope extends from the point of definition through the remainder of the
program.

External variables can be accessed from any function that falls within their scope. They are
declared outside a function. If a local variable and a global variable have the same name,
local variable will have precedence over global in the function where it is declared.
e.g.: int count;
main
{
count = 10;
------
-----
-----
}
function ( )
{
int count = 0;
-------
-------
count ++;
}
When the function references the variable count, it will be referencing only its local
variable, not the global one. The value of count in main( ) will not be affected.

e.g.: /* illustration of working of global variable


int x;
main( )
{
x = 10;
printf ("x = %d \n", x);
printf ("x = %d \n", fun1( ));
printf ("x = %d \n", fun2( ));
printf ("x = % d \n", func3( ));
}
fun1( )
{
x = x + 10;
return x;
}
fun2( )
{
int x = 1;
return x;
}
fun3( )
{

PREPARED BY: SUMIT PUROHIT, ASST. PROF.,AISHWARYA COLLEGE Page 53


C PROGRAMMING NOTES: NEW COURSE (2013-2016)

x = x+10;
return (x);
}
output: x = 10
x = 20
x=1
x = 30

External Declaration
In the program segment discussed just previously, the main cannot access the variable y as
it has been declared after the main function. This problem can be solved by declaring the
variable with the storage class extern.

e.g.: main()
{
extern int y; /* external declaration */
--------
}
fun1()
{
extern int y; /* external declaration */
--------
}
int y; /*definition */
The external declaration of y inside the functions informs the compiler that y is an integer
type defined somewhere else in the program.

The extern declaration does not allocate storage space for variable.

3. Static Variable
Static variables are defined within a function in the same manner as automatic variables,
except that the variable declaration must begin with the static storage class designation.
e.g.: static int x; or static float y;

A static variable is initialized only once, when the program is compiled. It is never
initialized again.

A static variable may be either an internal type or an external type, depending on the place
of declaration. Internal static variables are those which are declared inside a function. The
scope of internal static variables extends upto the end of the function in which they are
defined. Therefore, internal static variables are similar to auto variables, except that they
remain in existence (alive) throughout the remaining program. Therefore, internal static
variables can be used to retain values between function calls.

PREPARED BY: SUMIT PUROHIT, ASST. PROF.,AISHWARYA COLLEGE Page 54


C PROGRAMMING NOTES: NEW COURSE (2013-2016)

e.g.: /* Illustration of static variable */


main()
{
int i;
for(i=1; i<=3; i++) stat();
}
stat()
{
static int x = 0;
x = x+1;
printf("x = %d;\t", x);
}
Output: x = 1; x = 2; x = 3;

An external static variable is declared outside of all functions and is available to all the
functions in that program. The difference between a static external variable and a simple
external variable is that the static external variable is available only within the file where
it is defined while the simple external variable can be accessed by other files also.

4. Register Variable
We can tell the compiler that a variable should be kept in one of the machine's registers,
instead of keeping in the memory (where normal variables are stored) since a register
access is much faster than a memory access and keeping the frequently accessed variables
in the register will lead to faster execution of programs. For example, Loop control
variables.

This is done as given below:


register int count;

Since only a few variables can be placed in the register, it is important to carefully select
the variables for this purpose. However, C will automatically convert register variables into
non-register variables once the limit is reached.

PREPARED BY: SUMIT PUROHIT, ASST. PROF.,AISHWARYA COLLEGE Page 55


C PROGRAMMING NOTES: NEW COURSE (2013-2016)

Passing Parameters to Functions

Call by Value
Call by value means sending the values of the arguments to functions. When a single value
is passed to a function via an actual argument, the value of the actual argument is copied
into the function. Therefore, the value of the corresponding formal argument can be altered
within the function, but the value of the actual argument within the calling 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 value.

e.g.: /* A simple C program containing a function that alters the value of its
argument. */
#include <stdio.h>
main()
{
int a = 2;
printf("\na = %d (from main, before calling the function)",a);
modify(a);
printf("\na = %d (from main, after calling the function)",a);
}
modify (int a)
{
a * = 3;
printf("\na = %d (from the function, after being modified)",a);
return;
}
output: a = 2 (from main, before calling the function)
a = 6 (from the function, after being modified)
a = 2 (from main, after calling the function)

The original value of a (i.e.=2) is displayed when main is executed. This value is then
passed to the function modify, where it is multiplied by three and the new value of the
formal argument that is displayed within the function. Finally, the value of a within main
(i.e., the actual argument) is again displayed, after control is transferred back to function
main from function modify.

These results show that a is not altered within main, even though the corresponding value
of a is changed within modify.

Passing an argument by value has certain advantages and disadvantages.


On the positive side, it allows a single valued actual argument to be written as an
expression rather than being restricted to a single variable. Moreover, if the actual
argument is expressed as a single variable, it protects the value of this variable from
alterations within the function.

On the negative side, it prevents information from being transferred back to the calling
portion of the program via arguments. Thus, passing by value is restricted to a one-way
transfer of information.

PREPARED BY: SUMIT PUROHIT, ASST. PROF.,AISHWARYA COLLEGE Page 56


C PROGRAMMING NOTES: NEW COURSE (2013-2016)

Call by Reference
Call by reference means sending the addresses of the arguments to the called function. In
this method the addresses of actual arguments in the calling function are copied into formal
arguments of the called functions. Thus using these addresses we would have an access to
the actual arguments and hence we would be able to manipulate them. Using a call by
reference intelligently, it is possible to make a function return more than one value at a
time, which involves the study of pointer.

Passing Arrays to a Function


Array elements can be passed to a function by calling the function by value, or by reference.
In call by value, we pass values of array elements to the function while in call by reference
we pass the name of array, without any subscript, and the size of array elements to the
function.

e.g.:1. /* passing by call by value * /


int add(int,int); //function prototyping
void main( )
{
int i, j,k;
clrscr();
printf(“\n enter the value for i:”);
scanf(“%d”,&i);
printf(“\n enter the value for j:”);
scanf(“%d”,&j);
k=add(I,j);
printf(“\n addition is:%d”,k);
getch();
}
int add (int a, int b)
{
return a+b;
}

2. /* demonstration of call by reference * /


int add(int *, int *);
void main( )
{
int i, j,k;
clrscr();
printf(“\n enter the value for i:”);
scanf(“%d”,&i);
printf(“\n enter the value for j:”);
scanf(“%d”,&j);
k=add(&i,&j);
printf(“\n addition is:%d”,k);
getch();
}

PREPARED BY: SUMIT PUROHIT, ASST. PROF.,AISHWARYA COLLEGE Page 57


C PROGRAMMING NOTES: NEW COURSE (2013-2016)

int add (int *a, int *b)


{
return *a + *b;

Local and Global variables:


A global variable has a scope thru out the C program. It can be accessed anywhere from any
function.
int i; // global variable declaration
main()
{

}
A local variable on the other hand, is local to it’s container only and can’t be accessed
outside of it’s container.

main()
{
// int a,b,c; // local variable declaration
}

Recursion in Function
Recursion is a process by which a function calls itself repeatedly, until some specified
condition has been satisfied. The process is used for repetitive computation in which each
action is stated in terms of previous result.
In order to solve a problem recursively, two conditions must be satisfied:
1. The problem must be written in recursive form.
2. The problem statement must include a stopping condition.

e.g.: /* To calculate the factorial of an integer recursively * /


# include <stdio.h>
main( )
{
int n;
long int fact (int);
printf ("\n n = ");
scanf ("%d", &n);
printf ("\n n! = % ld" fact (n));
}
long int fact (int n)
{
if (n < = 1)
return 1;

else
return (n * factorial (n-1));
}

PREPARED BY: SUMIT PUROHIT, ASST. PROF.,AISHWARYA COLLEGE Page 58


C PROGRAMMING NOTES: NEW COURSE (2013-2016)

UNIT-5

Structure Definition
A structure is a collection of variables referenced under one name providing a convenient
means of keeping related information together. The structure definition creates a format
that may be used to declare structure variables in a program later on.

The general format of structure definition is as follows:


struct tag_name
{
data_type member1;
data_type member2;
- - - - - - -;
- - - - - - -;
};
The keyword struct declares a structure to hold the details of fields of different datatypes.

At this time, no variable has actually been created. Only a format of a new data type has
been defined.
Consider the following example:
struct addr
{
char name [30];
char street [20];
char city [15];
char state [15];
int pincode;
};
The keyword struct declares a structure to hold the details of fine fields of address, namely,
name, street, city, state, pincode. The first four members are character array and fifth one
is an integer.

Creating Structure Variables


The structure declaration does not actually create variables. Instead, it defines data type
only. For actual use a structure variable needs to be created. This can be done in two ways:
1. Declaration using tagname anywhere in the program.
e.g.: struct book
{
char name [30];
char author [25];
float price;
};
struct book book1, book2;
2. It is also allowed to combine structure declaration and variable declaration in one
statement.

PREPARED BY: SUMIT PUROHIT, ASST. PROF.,AISHWARYA COLLEGE Page 59


C PROGRAMMING NOTES: NEW COURSE (2013-2016)

This declaration is given below:


struct person
{
char * name;
int age;
char *address;
} p1, p2, p3;
While declaring structure variables along with their definition, the use of tag_name
is optional.
struct
{
char *name;
int age;
char *address;
}
p1, p2, p3;

Giving Values to Members


As the members are themselves variables they should be linked to the structure variables.
The Link between a member and a variable is established using member operator '.' which
is also known as dot operator.

This can be explained using following example:


e.g.: / * Program to define a structure and assign value to members * /
struct book
{
char * name;
int pages;
char *author;
};
main( )
{
struct book b1;
printf ("\n Enter Values:");
scanf ("%s %d %s", b1.name, &b1.page, b1.author);
printf ("%s, %d, %s, b1.name, b1.page, b1.author);
}

Structure Initialization
A structure variable can be initialized as any other data type.
main( )
{
static struct
{
int weight;
float height;
}student = {60, 180.75};
}

PREPARED BY: SUMIT PUROHIT, ASST. PROF.,AISHWARYA COLLEGE Page 60


C PROGRAMMING NOTES: NEW COURSE (2013-2016)

This assigns the value 60 to student.weight and 180.75 to student.height. There is a one-to-
one correspondence between the members and their initializing values.

A structure must be declared as static if it is to be initialized inside a function (similar to


arrays). The following statements initialize two structure variables. Here, it is essential to
use a tag name.
main( )
{
struct st_record
{
int weight;
float height;
}
static struct st_record student1 = {60, 180.75};
static struct st_record student2 = {53, 170.60};
- - - - - - -;
- - - - - - -;
}

Another method is to initialize a structure variable outside the function as shown below:
struct st_record / * No static word */
{
int weight;
int height;
}
student1 = {60, 180.75};

main( )
{
static struct st_record student 2 = {53, 170.60}
- - - - - -;
- - - - - -;
}
The initialization of individual structure members within the template is permitted. The
initialization must be done only in the declaration of the actual variables.
Comparison of Structure Variables
Two variables of the same structure type can be compared the same way as ordinary
variables.
If person1 and person2 belong to the same structure, then the following operations are
valid.
Operation Meaning
person1 = person2 Assign person2 to person1.
person1 = = person2 Compare all members of person1 and person2 and return 1 if they are
equal, 0 otherwise.
e.g.: struct class
{
int number;
char name [20];

PREPARED BY: SUMIT PUROHIT, ASST. PROF.,AISHWARYA COLLEGE Page 61


C PROGRAMMING NOTES: NEW COURSE (2013-2016)

float marks;
}
main( )
{
int x;
static struct class student1 = {111, "Ram", 72.50};
static struct class student2 = {222, "Rakesh", 67.00};
static class student 3;
student 3 = student 2;
x = ((student3.number == student.number) && (student3.marks
==student2.marks))? 1:0;
if (x = = 1)
{
printf ("\nStudent2 and Student2 are same \n");
printf ("%d %s %f\n", student3.number,
student3.name,student3.marks);
}
else
printf ("\nStudent2 and Student3 are different\n");
}
Output: Student2 and Student3 are same.
222 Rakesh 67.000000

Arrays of Structures
The most common use of structures is in arrays of structures. To declare an array of
structures, first the structure is defined then an array variable of that structure is declared.
In such a declaration, each element of the array represents a structure variable.
e.g.: struct class student [100];
It defines an array called student which consists of 100 elements of structure named class.

An array of structures is stored inside the memory in the same way as a multi-dimensional
array.

e.g.: / * Program to implement an array of structure * /


struct marks
{
int sub1;
int sub2;
int sub3;
int total;
};
main( )
{
int i;
static struct marks student [3] = {{45, 67, 81, 0}, {75, 53, 69, 0},
{75, 53, 69, 0}, {57, 36, 71, 0}};
static struct marks total;
for (i = 0; i < = 2; i++)

PREPARED BY: SUMIT PUROHIT, ASST. PROF.,AISHWARYA COLLEGE Page 62


C PROGRAMMING NOTES: NEW COURSE (2013-2016)

{
student [i].total = student [i].sub1 + student [i].sub2+student[i] sub3;
total.sub1 = total.sub1 + student [i].sub1;
total.sub2 + = student [i].sub2;
total.sub3 + = student [i].sub3;
total.total = total.total + student [i].total;
}
printf ("STUDENT \t\t TOTAL \n");
for (i = 0; i < = 2; i++)
printf ("Student [%d] \t \t %d \n", i+1, student [i].total);
printf ("\n SUBJECT \t\t %d \n %s \t\t %d \n %s\t\t %d", "Subject1",
total.sub1,
"Subject2", total.sub2. "Subject3", total.sub3);
printf ("\n GRAND TOTAL = \t\t %d \n", total.total.);
}

Array within Structures


Single or multi-dimensional arrays of type int or float can be defined as structure members.
e.g.: struct marks
{
int number;
float subject [3];
}
student [2];
Here the member subject contains three elements, subject [0], subject [1], and subject [2].
These elements can be accessed using appropriate subscripts. For instance, the name
student [1].subject [2];would refer to the marks obtained in the third subject by the second
student.
e.g.: /* Program to implement arrays within a structure. * /
main( )
{
struct marks
{
int sub [3];
int total;
};
static struct marks student [3] = {45, 76, 81, 0, 75, 53, 69, 0, 57,
36, 71,0};
int i, j;
for (i = 0; i < = 2; i++)
{
for(j = 0; j<=2; j++)
{
student [i].total + = student [i].sub[j]
}
}
printf ("STUDENT\t\tTOTAL \n");
for (i = 0; i < = 2; i++)

PREPARED BY: SUMIT PUROHIT, ASST. PROF.,AISHWARYA COLLEGE Page 63


C PROGRAMMING NOTES: NEW COURSE (2013-2016)

printf ("Student [%d]\t\t%d\n", i + 1, student [i].total);


}

Output: Student Total


Student[1] 193
Student[2] 197
Student[3] 164

Structures within Structures


Structures within a structure means nesting of structures. Let us consider the following
structure defined to store information about the salary of employees.
struct salary
{
char name [20];
char department [10];
int basic_pay; int dearness_allowance;
int house_rent_allowance;
int city_allowance;
}employee;
This structure defines name, department, basic pay and three kinds of allowances. All the
items related to allowance can be grouped together and declared under a sub-structure as
shown below:

struct salary
{
char name [2];
char department [10];
struct
{
int dearness;
int house_rent;
int city;
}
allowance;
}employee;

The salary structure contains a member named allowance which itself is a structure with
three members. The members contained in the inner structure, namely, dearness,
house_rent and city can be referred to as:
employee.allowance.dearness
employee.allowance.house_rent
employee.allowance.city

Then inner most members in a nested structure can be accessed by chaining all the
concerned structure variables (from outermost to inner most) with the member using dot
operator.

The following statements are invalid:

PREPARED BY: SUMIT PUROHIT, ASST. PROF.,AISHWARYA COLLEGE Page 64


C PROGRAMMING NOTES: NEW COURSE (2013-2016)

employee.allowance (actual member is missing)


employee.house_rent (inner structure variable is missing)

An inner structure can have more than one variable. The following form of declaration is
legal:
struct salary
{
struct
{
int dearness;
-----
}
allowance, arrears;
}employee [100];

The inner structure has two variables, allowance and arrears. This implies that both of
them have the same structure template.

A base member can be accessed as follows:


employee[1].allowance.dearness
employee[1].arrears.dearness

Tag names can also be used to define inner structures.


e.g.: struct pay
{
int dearness;
int house_rent;
int city;
};
struct salary
{
char name [20];
char department [10];
struct pay allowance; struct pay arrears;
} struct salary employee [100];
The pay template is defined outside the salary template and is used to define the structure
of allowance and arrears inside the salary structure.

It is also permissible to nest more than one type of structures:


struct personal_record
{
struct name_part name;
struct date date_of_birth;
------
------
};
struct personal_record person1;

PREPARED BY: SUMIT PUROHIT, ASST. PROF.,AISHWARYA COLLEGE Page 65


C PROGRAMMING NOTES: NEW COURSE (2013-2016)

The first member of the structure is name, which is of the type struct name_part. Similarly,
other members have their structure types.

Passing Structures to Functions


There are three methods by which the values of a structure can be transferred from one
function to another.

The first method is to pass each member of the structure as an actual argument of the
function call. The actual arguments are then treated independently like ordinary variables.

The second method involves passing of a copy of the entire structure to the called function.
Since the function is working on a copy of the entire structure to the called function,
changes are not reflected in the original structure (in the calling function). It is, therefore,
necessary for the function to return the entire structure back to the calling function.

The third approach employs a concept called pointers to pass the structure as an argument.
In this case, the address location of the structure is passed to the called function. The
function can access indirectly the entire structure and work on it.

The general format of sending a copy of a structure to the called function is:
function_name (structure_variable_name)

The called function takes the following form:


data_type function_name (struct_type st_name)
{
- - - - - -;
------;
return (expression);
}

Note
1. The called function must be declared for its type, appropriate to the data type it is
expected to return. For example, if it is returning a copy of the entire structure, then it
must be declared as struct with an appropriate tag name.
2. The structure variable used as the actual argument and the corresponding formal
argument in the called function must be of the same struct type.
3. The return statement is necessary only when the function is returning some data.
The expression may be any simple variable or structure or an expression using simple
variables.
4. When a function returns a structure, it must be assigned to a structure of identical
type in the calling function.
5. The called function must be declared in calling function for its type, if it is placed
after the calling function.

PREPARED BY: SUMIT PUROHIT, ASST. PROF.,AISHWARYA COLLEGE Page 66


C PROGRAMMING NOTES: NEW COURSE (2013-2016)

e.g.: /* Program showing passing of structure member as function parameters * /


struct stores
{
char name [20];
float price;
int quantity;
};
main( )
{
struct stores update( );
float mul( ), p_increment, value;
int q_increment;
static struct stores item = {"XYZ", 25.75, 12};
printf ("\nInput Increment Values:");
printf ("\nPrice Increment and Quantity Increment\n");
scanf ("%f %d", &p_increment, &q_increment);
item = update item, pincrement, qincrement);
printf ("\nUpdated values of item");
printf ("\nName : %s\n", item.name);
printf ("\nPrice : %f\n", item.price);
printf ("\nQuantity : %d\n", item.quantity);
value = mul (item);
printf ("\nValue of the item: %d\n", value);
}
struct stores update (struct stores product, float p, int q)
{
product.price += p;
product.quantity += q;
return (product);
}
float mul (struct stores stock)
{
return (stock.price *stock.quantity);
}
Output: Input Increment Values: Price Increment and Quantity Increment
10 12
Updated values of item
Name : XYZ
Price : 35.750000
Quantity : 24
Value of the item : 858.000000

In case of structures having numerous structure elements passing these individual


elements would be tedious. In such cases an entire structure can be passed to a function.

PREPARED BY: SUMIT PUROHIT, ASST. PROF.,AISHWARYA COLLEGE Page 67


C PROGRAMMING NOTES: NEW COURSE (2013-2016)

e.g.: /* Program passing entire structure as function parameter. * /


struct emp
{
char empname [25];
char company [25];
int empno;
}
main( )
{
static struct emp emp1 = {"Prashant", “MDU", 101};
display (emp1);
}
display (struct emp e)
{

printf("%s\n%s\n%d",emp.empname,emp.company,emp.empno);
}
Output: Prashant
MDU
101

Union: union is a user defined data type like structure i.e. union can also be treated as a
collection of variables under single name sharing same memory for all the members. All
these variables may contain data items of similar or dissimilar data types. Each member in
the union is called a member or a field.

Syntax:
Union <tag name>
{

Type member1;
Type member2;

};

Example:

Union demo
{
int m;
float x;
char c;

}d;

This declares a variable d of type union demo. The union contains three members, each
with a different data type. however, we can use only one of them at a time. This is due to
the fact that only one location is allocated for a union variable, irrespective of its size.

PREPARED BY: SUMIT PUROHIT, ASST. PROF.,AISHWARYA COLLEGE Page 68


C PROGRAMMING NOTES: NEW COURSE (2013-2016)

100 101 102 103

c
m
x

The compiler allocates a piece of storage that is large enough to hold the largest variable
type in the union.

Difference between structure and union:

Structure Union
1. The keyword struct is used to define 1. The keyword union is used to define a
a structure. union.
2. When a variable is associated with a 2. When a variable is associated with a
structure, the compiler allocates the union, the compiler allocates the memory by
memory for each member. considering the size of the largest member.
3. Each member within a structure is 3. Memory allocated is shared by individual
assigned unique storage area or members of union.
function.
4. Altering the value of a member will 4. Altering the value of any of the member
not affect other members of the will alter other member values.
structure.
5. Individual member can be accessed 5. Only one member can be accessed at a
at a time. time.

POINTER

A pointer is a variable that holds a memory address. This address is the location of another
variable in memory. If one variable contains the address of another variable then the first
variable is said to point to the second.

Pointer variable declaration

A pointer declaration consists of a base type, an * (asterisk) and the variable name.

Syntax:

Type * <variable name>

Where type is the base type of the pointer and may be any valid type. The name of the
pointer variable is specified by the name. The base type of the pointer defines the type of
variable to which pointer will be point. We must note that whenever we declare a pointer
we must make sure that its type is compatible with the type of object to which we want to
point.

PREPARED BY: SUMIT PUROHIT, ASST. PROF.,AISHWARYA COLLEGE Page 69


C PROGRAMMING NOTES: NEW COURSE (2013-2016)

The Pointer Operators


There are two pointer operators; ‘*’ (asterisk) and ‘&’ (ampersand). The & is a unary
operator that returns the memory address of its operand.

int *p,q;
p=&q;
Assume that the variable q uses memory location 2000 to store its value. Also assume that
q has a value of 100. Then after the preceding assignment p will have the value 2000. The
second pointer operator ‘*’ is the complement of ‘&’. It is a unary operator that returns the
value located at the address that follows.

Pointer Arithmetic:
There are only two arithmetic operations can use on pointer- addition and subtraction. For
example P1 be as integer pointer with a current value of 2000. Integers are 2 bytes long
after the expression
P1++ ;

P1 contains 2002 not 2001, the reason for this is that each time P1 is incremented and it
will point to the next integer. The same is true after decrements. For example: P1 has the
value 2000, the expression
P1- -;
Causes P1 to have the value 1998. Each time a pointer is incremented, it points to the
memory location of the next element of its base type. Each time it decremented, it points to
the location of the previous element.

Pointer and Arrays


There is a close relationship between pointer and arrays. For example,
Char str[80], *p1;
p1=str;
here p1 has been set to the address of first array element in string. To access the 5 th
element in string, we could write –
str[4] or *(str + 4)
Both statements will return 5th element. We know arrays start at 0. To access the 5th
element we must use 4 to index str. We also add 4 to the pointer p1 to access the 5 th
element because p1 currently points to the first element of the string.

Arrays of pointers

Pointer can be arrayed like any other data type. The declaration for an integer pointer
array of size 10 is

int *X[10];

to assign the address of an integer variable called var to the 3rd element of the pointer array
then we can write

X[2] = &var;

PREPARED BY: SUMIT PUROHIT, ASST. PROF.,AISHWARYA COLLEGE Page 70


C PROGRAMMING NOTES: NEW COURSE (2013-2016)

To find the value of var we can write * X[2].


Example:

void display_array (int *q[])


{
int a;
for (a=0;a<10;a++)
printf(“%d”,*q[a]);

NULL pointer:
A NULL pointer is defined as a special pointer value that points to nowhere in the
memory.

int *p = NULL;

Here p is a null pointer. This indicates that the pointer variable p does not point to any part
of memory.

Dangling pointer:

Example:

int *a; 100


Garbage Value
int *b; 102
int c = 20; 104 2 0

After declaration the pointer variable a and b do not contain valid addresses so they both
are called dangling pointer.

a = &c;
100
b = &c; 102
104 2 0

After executing these statements the pointer variables a and b contain the address of
integer variable c.
printf(“&a=%u b=%u *a = %d \n”, &a, a,*a);

100 104 20

example: program to add 2 numbers using pointer.


Void main ()

PREPARED BY: SUMIT PUROHIT, ASST. PROF.,AISHWARYA COLLEGE Page 71


C PROGRAMMING NOTES: NEW COURSE (2013-2016)

{
int x=30,y=40,z;
int *ptr1,*ptr2;
ptr1 = &x;
ptr2=&y;
z = *ptr1 + *ptr2;
printf(“%d”,z);
}

Pointer to pointer:
It is possible to make a pointer to point to another variable. A variable which contains
address of a pointer variable is called pointer to a pointer.
int x;
int *ptr1;
int **ptr2;
Example:
x=20;
ptr1 = &x;
ptr2 = &ptr1;

Ptr2 Ptr1 x

Compatibility of pointers:
We should not store the address of a variable into a pointer variable of another data type. at
the time of assigning we should see that the type of variable and type of the pointer
variable should be same or compatible otherwise , it results in compile time error or syntax
error.
We can type cast the pointer. As we convert the type of one variable into type of another
variable using type casting, we can make an assignment between in compatible pointer
types using explicitly type casting. This process of converting the type of a pointer forcibly
to another type is called type casting a pointer.
Incompatible pointer assignment:
int a;
float *b;
b=&a; //error
Valid pointer assignment
int a;
float *b;
b= (float *)&a;

PREPARED BY: SUMIT PUROHIT, ASST. PROF.,AISHWARYA COLLEGE Page 72


C PROGRAMMING NOTES: NEW COURSE (2013-2016)

Void pointer:
A void pointer is a special type of pointer. It can point to any data type and also any pointer
can be assigned to a void pointer. A void pointer is also called universal pointer or generic
pointer.
Example:
Void main()
{
int a=20;
float b=3.14;
void *p;
p=&a;
printf(“a=%d \n”,*((int *)p));
p=&b;
printf(“b=%f \n”, *((float *)p));
}
MEMORY ALLOCATION TECHNIQUES
Memory can be reserved for the variables either during compilation or during execution /
run time. This gives rise to various memory allocation techniques. Memory can be allocated
for variables using two different techniques:
1. Static memory allocation: if the memory is allocated for various variables during
compilation time itself, the allocated memory space can’t be expanded to
accommodate more data or can’t be reduced to accommodate less data. If once size of
the memory allocated is fixed, it can’t be altered even during execution time. This
method of allocating the memory during compilation time is called “static memory
allocation”.
2. Dynamic memory allocation: it is the process of allocating memory during run
time. This allocation technique uses predefined functions to allocate and release
memory for data during execution time. So if there is any unpredictable storage
requirement , then the dynamic allocation technique is used.
Difference between static and dynamic memory allocation:
Static memory allocation Dynamic memory allocation
1. Memory is allocated during compile 1. Memory is allocated during execution
time. time.
2. The size of the memory to be 2. As and when memory is required
allocated is fixed during compilation memory can be allocated. If not
time and can’t be altered during required memory can be deallocated.
execution time.
3. This is used only when the data size 3. This is used for unpredictable
is fixed and known in advance before memory requirement.
processing.
4. Execution is faster 4. execution is slower
5. Memory is allocated either in stack 5. Memory is allocated only in heap
area / data area. area.
Example : array Example : dynamic array, tree, linked list

PREPARED BY: SUMIT PUROHIT, ASST. PROF.,AISHWARYA COLLEGE Page 73


C PROGRAMMING NOTES: NEW COURSE (2013-2016)

Memory map of a program:


A compiled C program creates and uses the following logical distinct regions of memory:-
1. Program memory
2. Global or static
3. Heap
4. Stack

1. Program memory: this is the first region in the memory which is reserved for
various functions such as main (), library and user defined functions. Before
execution all the necessary functions are loaded into this part of the memory.
2. Global or static memory: this is the region where global variable and static
variable are stored. Since the life span of these variables is till the end of the
program so this part of the memory is reserved for these variables till the end of the
program.
3. Heap: in this region the large memory available to the programs only during
execution. This free memory available between stack area and global area is called
heap. If the memory is allocated from this area then the size of heap decreases and
when memory is de-allocated the size of heap increases.
4. Stack: this is the last area in the memory which holds local function calls along with
argument to function if any. The stack memory, heap and global memory together
are called data memory.

Dynamic Memory Allocation:


Dynamic allocation is the means by which a program can obtain memory while it is
running. Global variables are allocated storage at compile time. Non-static, local variables
use the stack. Memory allocated by dynamic allocation function is obtained from heap.
In C language there is dynamic allocation functions - <stdlib.h> or <alloc.h>
1. malloc()
2. calloc()
3. free()
4. realloc()
Using malloc(), calloc(), realloc() functions additional memory space can be allocated
whereas using free() function unwanted space can be deleted.

1. malloc() :this function allows the program to allocate memory explicitly as and
when required. This function allocates a block of memory. The size of the block is the
number of bytes specified in the parameter.
Syntax:
ptr = (data type *) malloc (size);
where ptr = pointer variable
data type = any basic / undefined data type
size = number of bytes required

PREPARED BY: SUMIT PUROHIT, ASST. PROF.,AISHWARYA COLLEGE Page 74


C PROGRAMMING NOTES: NEW COURSE (2013-2016)

on successful execution the function returns the address of first byte of allocated memory. If
specified size of memory is not available this condition is called “overflow of memory”. In
such case, function returns NULL.

#include<conio.h>
#include<alloc.h>
void main()
{
int i, n;
int *p;
printf("enter the number of elements:");
scanf("%d",&n);
p=(int *)malloc(sizeof(int)*n);
if(p==NULL)
{
printf("insufficient memory");
return;
}
printf("enter %d elements \n" , n);
for(i=0;i<n;i++)
scanf("%d",p+i);
printf("the given elements are:\n");
for(i=0;i<n;i++)
printf("%d",*(p + i));
getch();
}

2. calloc() : this function is used to allocate multiple blocks of memory. Calloc stands
for contiguous allocation of multiple blocks and is mainly used to allocate memory
for array. The number of blocks is determined by the first parameter n. The size of
each block is equal o the number of bytes specified in the parameter i.e. size. Thus,
total number of bytes allocated is n * size and all bytes will be initialized to 0.

Syntax:
ptr=(data type *) calloc(n,size);
On successfully allocation, the function returns the address of first byte of allocated
memory. Since address is returned the return type is a void pointer. If specified size of
memory is not available then the condition is called “overflow of memory”. In such case , the
function returns NULL.

3. realloc() : before using this function , the memory should have been allocated using
malloc() or calloc().some times, the allocated memory is not sufficient and we may

PREPARED BY: SUMIT PUROHIT, ASST. PROF.,AISHWARYA COLLEGE Page 75


C PROGRAMMING NOTES: NEW COURSE (2013-2016)

require additional memory space. Sometimes, the allocated memory may be much
larger and we want to reduce the size of allocated memory. In both situations, the
size of allocated memory can be change using realloc() and the process is called
reallocation of memory.

Syntax :
ptr= (data type *) realloc(ptr,size);
#include<conio.h>
#include<alloc.h>
#include<string.h>
void main()
{
char *str;
clrscr();
str=(char*)malloc(10);
printf("%s",strcpy(str,"computer"));
str=(char*)realloc(str,40);
printf("%s",strcpy(str,"this is my first program"));
getch();
}

4. free() : This function is used to de-allocate or free the allocated block of memory
which is allocated by using the function calloc(), malloc() or realloc().
Syntax: free(ptr);
#include<conio.h>
#include<alloc.h>
void main()
{
int *a;
a=(int *)malloc(sizeof(int));
*a=100;
printf("%d",*a);

a=(int *)malloc(sizeof(int));
*a=200;
free(a);
a=NULL;
printf("%d",*a);
getch();

PREPARED BY: SUMIT PUROHIT, ASST. PROF.,AISHWARYA COLLEGE Page 76


C PROGRAMMING NOTES: NEW COURSE (2013-2016)

FILE HANDLING IN C

Main memory of the computing system used to store temporary data that is processed to
produce information. The data store in the system is not permanent. When the system
is switched off we lose the data stored in main memory. it is because of the volatile
nature of the main memory. but most of the time we need to store data permanently for
future use. This data can be permanently stored only on the secondary storage. The
data on the secondary storage can be stored thru file.
File is a format to store data permanently on secondary storage device. In C
programming data can be stored in two file formats- i.e. text and binary.
The standard library stdio.h in C has many input/output functions. The file handling
function are easy to use, powerful and complete. We frequently use the files for storing
data which can be processed by the programs. In order to store data permanently and
retrieve it whenever required we need to use files. The operating system easily keeps
tracks of the things stored on disks. It is nothing but a way of filing data in an easily
accessible way. The major role played by the file system.
File system treats different sets of data as files. Each file is separate from the order.
Along with the data stored within it, the file system includes additional information for
each file like-

the name of the file


the access permission on the file
the time and date creation , access and modification of the file.

Standard streams:

A stream is a collection or sequence of bytes that is moved from main memory and I/O
devices. The standard streams in C are predefined streams. They are automatically opened
whenever the program is executed. There are two types of streams-
1. text stream
2. binary stream

1. Text stream: a text stream is a sequence of characters. Standard C states that a


text stream is organized into lines terminated by a new line character.
2. Binary stream: a binary stream is a sequence of bytes that has a one to one
correspondence to the bytes in the external device. The number of bytes written /
read is the same as the number on the external device.

PREPARED BY: SUMIT PUROHIT, ASST. PROF.,AISHWARYA COLLEGE Page 77


C PROGRAMMING NOTES: NEW COURSE (2013-2016)

The FILE Pointer:

The file pointer is a pointer to a structure type FILE. It points to information that defines
various things about the file, including its name, status and the current position of the
specific file and is used by the associated stream to direct the operation of the I/O functions.
To read / write files, our program needs to use file pointers.

Syntax:
FILE *fp;
Opening a file: The fopen() function opens a stream for use and links a file with that
stream. Then it returns the file pointer associated with that file.

Syntax:

FILE *fp;
fp = fopen (“file name”, “mode”);

Where file name is a pointer to a string of characters that make up a valid file name and
may include a path specification. The string pointed to by mode determines how the file will
be opened.
The fopen() function returns a file pointer.

Example:

FILE *fp;
fp=fopen(“demo”,”w”);

File Opening Modes


mode Meaning
r Open a text file for reading
w Create a text file for writing
a Append to a text file
r+ Open a text file for read / write
w+ Create a text file for read / write
a+ Append or create a text file for read / write

Closing a file:
The fclose() function closes a stream that was opened by fopen(). It writes any data still
remaining in the disk buffer to the file. fclose() also frees the file control block associated
with the streams, making it available for reuse. We may have to close one file before
opening another.

PREPARED BY: SUMIT PUROHIT, ASST. PROF.,AISHWARYA COLLEGE Page 78


C PROGRAMMING NOTES: NEW COURSE (2013-2016)

Syntax: fclose(file pointer);

Input output operations on file:


The important file handling functions that are available in C are:-

Function name Functionality


fopen() Creates a new file for use and also
opens an existing file for use.
fclose() Closes a file which has been opened for
use
getc() Reads a character from file
putc() Writes a character to a file
fprintf() Writes a set of data values to a file
fscanf() Reads a set of data values from a file.
getw() Reads an integer from a file.
putw() Writes an integer to a file.
fseek() Sets the position to a desired point in
the file.
ftell() Gives the current position in the file.
rewind() Sets the position to the beginning of the
file.

getc() and putc() functions:


These are simplest input and output functions. Suppose a file is opened with mode “w” and
file pointer fp1 then we can write
putc(c,fp1);

This will write the character contained in the character variable c to the file associated
with FILE pointer fp1. Similarly getc() is used to read a character from a file that has been
opened in read mode.

C=getc(fp2);

This will read a character from the file whose file pointer is fp2. The file pointer moves by
one character position for every operation of getc() or putc(). The getc() will return an end of
the file marker EOF, when end of file has been reached. Therefore, the reading should be
terminated when EOF is encountered.

PREPARED BY: SUMIT PUROHIT, ASST. PROF.,AISHWARYA COLLEGE Page 79


C PROGRAMMING NOTES: NEW COURSE (2013-2016)

PROGRAM:
#include<stdio.h>
void main()
{
FILE *fp;
char c;
printf("\n data input");
fp=fopen("input","w");
while((c=getchar())!=EOF)
putc(c,fp);
fclose(fp);
printf("\n data output");
fp=fopen("input","r");
while((c=getc(fp))!=EOF)
printf("%c",c);
fclose(fp);
}

PREPARED BY: SUMIT PUROHIT, ASST. PROF.,AISHWARYA COLLEGE Page 80

You might also like