Professional Documents
Culture Documents
UNIT-2
UNIT-3
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
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.
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
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.
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
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
It is used to connect
Connector A 1 a part of flowchart to
another.
This represents the
Directed Arrow Start flow of control.
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.
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.
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.
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
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.
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.
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.
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.
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.
C data types
void Array
char Pointer
int Structure
float Union
double Enum, etc.
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
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.
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.
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"
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.
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.
do if static while
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:
Returned
List of input parameters
value
Function Name
Int (max of a
Int a, int b
and b
FindMax
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.
The first line is a comment that explains the purpose of the program.
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:
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.
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.
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
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.
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.
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.
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
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.
.
/* 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
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.
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/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()
#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
100 101 102 103 104 105 106 107 108 109
a p p l e
In this string variables store the sharing address of collection. Address once
stored can’t be modified.
This allows typing as much number of characters. Input is terminated by enter key and all
characters are taken as input.
100 101 102 103 104 105 106 107 108 109
a p p l e
100 101 102 103 104 105 106 107 108 109
m a n g o
A constant string is first stored in memory at certain location and its starting address is
represented at its space.
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
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
address list: to get address of the variable. We can use ‘&’ operator and this operator is
used as a prefix with any variable name.
UNIT-3
From the flowchart it is clear that if the 'if condition' is true, statement 1 is executed;
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.
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.
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.
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.
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 :
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.
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.
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.
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].
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 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.
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
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( ).
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.
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.
printf ("%d", marks [2] [1]) will print the element present in third row and second column.
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.
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:
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.
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:");
}
printf ("\n The sorted numbers are:");
for (i = 0; i < n; i++)
printf ("\n %d", x [i]);
}
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.
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( ).
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
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.
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);
}
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);
}
{
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.
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
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.
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.
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.
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.
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.
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.
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.
}
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.
else
return (n * factorial (n-1));
}
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.
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.
Structure Initialization
A structure variable can be initialized as any other data type.
main( )
{
static struct
{
int weight;
float height;
}student = {60, 180.75};
}
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.
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];
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.
{
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.);
}
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.
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.
The first member of the structure is name, which is of the type struct name_part. Similarly,
other members have their structure types.
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)
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.
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.
c
m
x
The compiler allocates a piece of storage that is large enough to hold the largest variable
type in the 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.
A pointer declaration consists of a base type, an * (asterisk) and the variable name.
Syntax:
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.
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.
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;
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:
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
{
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;
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
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.
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
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
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();
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-
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
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”);
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.
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.
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);
}