Programming Using C
Programming Using C
Pre-Programming
Techniques
Introduction
Algorithm
Flow Chart
Dry Run
Examples of Algorithm and Flow Chart
Page 1 of 96
Introduction to Computer & Programming
Introduction
A computer is a programmable machine designed to sequentially and automatically carry
out a sequence of arithmetic or logical operations.
1.) Hardware
All the physical parts of the computer are known as “Hardware”.
We can say that all the parts of the computer that have physical existence are known
as hardware.
2.) Software
All the Logical parts of the computer are known as “Software”.
We can say that all the parts of the computer that have logical existence are known
as software.
The software can be divided into 2 parts:
a. Application Software
b. System Software
Page 2 of 96
Concept of Basic types of Software
Software is a set of instructions, programs which enable the computer to perform specified
task.
In other words, software is nothing but binary code instructions which control the
hardware.
The software can be divided into 2 parts:
1. Application Software
2. System Software
Let’s learn deeply:
1. Application Software
Application software on the other hand, performs specific tasks for the computer user.
Application software is a subclass of computer software that employs the capabilities
of a computer directly and thoroughly to a task that the user wishes to perform.
Application software, also known as an application or an "app", is computer
software designed to help the user to perform singular or multiple related specific
tasks.
It helps to solve problems in the real world.
Examples…
enterprise software
accounting software
office suites
graphics software and
media players
2. System Software
System software is a set of programs that manage the resources of a computer system,
so that they are used in an optimal fashion, provide routine services such as copying
data from one file to another and assist in the development of applications programs.
System software consists of programs that assist the computer in the efficient control,
support, development and execution of application programs.
The system software controls the execution of the application software and provides
other support functions such as data storage.
Examples…
Windows XP, 7, 2000, etc…
LINUX / UNIX
DOS
Page 3 of 96
Introduction to Programming & Programming
Language
The Computer language can be divided into 2 categories…
1) Low Level Language
2) High Level Language
3) Middle Level Language
1. Compiler
It checks your whole program at a time and list out all the errors of your program.
2. Interpreter
It checks one line of your program at a time and indicates error at that line.
If you not solving the error of that line the interpreter can’t move on next line.
Page 4 of 96
Flow Chart , Algorithms and Dry Run
Flow Chart
Flow Chart is a diagrammatic representation to get solution of any problem.
Flow Charts are drawn in earlier time to get solution.
In terms of programming language, the Flow charts are used to represent any problems
graphically.
In short, the logic techniques of solving problems are known as “Flow Chart”.
Flow Chart facilitates communication between programmers and business people.
Once the flow chart is drawn, it becomes easy to write the program in High Level Language.
There are several symbols, which are used to draw flowcharts:
1. Terminator/Oval:
This symbol is used to represent the starting and ending
point of “Flow Chart”.
This symbol may contain the words like Start, Begin, Stop, and End Etc.
2. Rectangle:
This symbol is used to represent Process associated with the problem.
This symbol is also used to declare the variables.
3. Input/Output:
This symbol is used to represent All Inputs and Outputs, which are
associated with the flowcharts.
4. Diamond:
This symbol is used to represent the conditions associated
with the flowcharts.
This symbol always contains the conditions or expressions.
5. Flow Lines:
The flow lines are used to indicate the control flow of the flow chart.
Generally the flow of control may be top to bottom or left to right.
6. Connector:
This symbol is used to connect the multiway flow of the control,
and direct the control to the particular point.
Page 5 of 96
Although it looks like a 'Q', the symbol is supposed to look like
a reel of tape.
9. Off-page Connector
It is used to signify a connection to a process held on another sheet
screen.
10. Annotation
It is used to keep data secret from outside world.
11. Display
Indicates a process step where information is displayed to a person
(e.g., PC user, machine operator).
Algorithm
Algorithms are developed on the basis of Flowcharts.
To make a computer do anything, you have to write a computer program.
To write a computer program, you have to tell the computer, step by step, exactly what you
want to do it.
Algorithms are just the textual presentation of the flowchart.
The algorithm is the basic technique used to get the job done.
In short, the step by step representation of any problem is known as algorithms.
Types of Algorithm:
Page 6 of 96
3.) The rent-a-car algorithm
1. Take the shuttle to the rental car place.
2. Rent a car.
3. Follow the directions to get to my house.
4.) The bus algorithm
1. Outside baggage claim, catch bus number 70.
2. Transfer to bus 14 on Main Street.
3. Get off Elm Street.
4. Walk two blocks north to my house.
All four these algorithms accomplish exactly the same goal, but each algorithm does it in
completely different travel time.
You should choose the algorithm based on the circumstances.
Each algorithm has advantages and disadvantages in different situations.
Sorting is one place where a lot of research has been done, because computers spend a lot of
time sorting lists.
There are mainly 5 different algorithms are used for algorithms:
1. Bin sort
2. Bubble sort
3. Merge sort
4. Quick sort
5. Shell sort
By knowing the strengths and weaknesses of the different algorithms, you pick the best one
for the task at hand.
In short, We can say that…
Flow Chart = Graphics
Algorithm= Text
Dry Run
A dry run is a testing process where the effects of a possible failure are intentionally
mitigated.
In computer programming, a dry run is a mental run of a computer program, where the
computer programmer examines the source code one step at a time and determines what it
will do when run.
In theatrical computer science, a dry run is a mental run of an algorithm, sometimes explained
in pseudocode, where the computer scientist examines the algorithm’s procedures one step at
a time.
In both uses, the dry run is frequently assisted by a table with the program or algoritm’s
variables on the top.
The useage of DRY RUN in accetance procedures is meant following:
Page 7 of 96
The firm(which is a subcontractor) must perform a complete test of the system it has to
deliver before the actual acceptance from the contractor side.
Example
1.) Draw a FLOW CHART, create an ALGORITHM and perform
DRY RUN to find SIMPLE INTEREST.
Step 2: Initialize P, R, N
Dry Run:
L1 declares 3 variables, Principal Amount,
Rate, No. of years. After execution P R N Result
Line2 xxx xxx xxx
L2 initialises all three variables with garbage
Line 4 10000 xxx xxx
value.
Line 6 10000 2.5 xxx
L3 ask user to enter PRINCIPAL AMOUNT.
Line 8 10000 2.5 5
L4 assign user input to P variable.
Line 9 SI=10000*2.5*5/100
Page 8 of 96
L5 ask user to enter RATE (per year). Line 10 10000 2.5 5 1250
L6 assign user input to R variable.
L7 ask user to enter NO. OF YEARS.
L8 assign user input to N variable.
L9 performs an action to get Simple Interest.
L10 print Simple Interest.
Ch-2
History & Overview of
C Language
History of C Language
Features of C Language
C Program Structure
Character Set
C Tokens
Hierarchy of Operators
Type Casting
Data Types
Page 9 of 96
History of C Language
C Language has emerged as the most used programming language for software
devlopers.
The language gets name from being the successor to the B language (an interpreter
based language).
It was designed by DENNIS RITCHIE in 1972 as the system language for UNIX
operating system on a PDP-II computer at AT & T Bell laboratories.
At the time of 1960’s the need of programming language was raised for almost
specific purpose.
COBOL was used for commercial purpose and FORTRAN was used for Engineering
and Scientific Purpose etc…
There are some limitations in these types of languages.
To reduce these limitations, a new language called ALGOL was developed and again
to reduce the limitations of ALGOL the language called Combine Programming
Language (CPL) was developed by Cambridge University.
However CPL was hard to learn and difficult to implement, so it was also turned out.
Martin Richards at Cambridge University developed Basic Combined Programming
Language (BCPL) by adding good features in the CPL.
But unfortunately this language was also turned out because of less powerful.
At the same time Ken Thompson was developed the language called B language at
AT & T’s Bell labs.
Dennis Ritchie inherited the features of language called B and BCPL and added some
more features of his own and developed a new language called C.
So, In Nutshell……
C is the Middle level programming language.
Developed By Dennis Ritchie.
In the year 1972.
At the place called AT & T’s Bell labs, in USA.
In beginning C language was not accepted by all programmers and so it was not so
much popular.
Brain Keningham and Dennis Ritchie both made some additions and changes in it and
then published a very successful book named “The C Programming Language”.
Page 10 of 96
ANSI committee has made some standards for it and made chages in C, so it can run
over variety of operating systems like UNIX, DOS, MAC etc… and then approved C
as ANSI-C in 1989, lately ISO committee also approved it in 1990.
Note:
C have both a relatively good programming efficiency and relatively good
machine efficiency.
That’s why it is termed as “Middle Level Language”.
Remember it…
FLEXIBILITY
C is a powerful and flexible language.
C is used for projects as diverse as operating system, word processor, graphics,
spreadsheets and even compilers for other language.
C is a popular language preferred by professional programmers.
As a result, a wide variety of C compilers and helpful accessories are available.
PORTABILITY
C is a portable language.
Portable means that a C program written for one computer system can be run on
another system with little or no modification.
Portability is enhanced by the ANSI standard by C, the set of rules for C compilers.
Page 11 of 96
COMPACTNESS
C is a language of few words, containing only a handful terms, called keywords, which
serve as the base on which the language’s functionality is built.
You might think that a language with more keyword would be more powerful.
This isn’t true. As you will find that it can be programmed to do any task.
REUSABILITY
C is modular, C code can and should be written in routine called functions.
These functions can be reused in other applications or programs.
By passing pieces of information to the function, you can create useful, reusable code.
C Program Structure
C program can be viewed as group of building blocks called functions.
A function is a subroutine that may include one or more statement designed to perform a
specific task.
A C program may contain one or more section as shown here:
Definition Section
This section defines all the symbolic constants. For example PI=3.14. By defining symbolic
constant one can use these symbolic constant instead of constant value.
# define PI 3.14
# define Temp 35
Page 12 of 96
Global Declaration Section
This section contains the declaration of variables which are used by more than one function of
the program.
Character Set
C language allows many characters and symbols.
The characters in C language is divided into 4 parts.
The character set in C language is as follows:
Page 13 of 96
C Tokens
Individual words and punctuation marks are called TOKENS.
Similarly, in a ‘C’ program the smallest individual units are known as ‘C’ tokens.
‘C’ has 6 types of tokens:
1.) K – Keywords
2.) I – Identifiers
3.) S – Special Symbols
4.) C – Constants
5.) O – Operators
6.) S – Strings
Keywords
The keywords are the words auto break case char
whose meaning is already const continue default do
double else enum extern
explained to the c compiler.
float for goto if
The key words are also known
int long register return
as RESERVED WORDS.
short signed sizeof static
There are total 32 keywords struct switch typedef union
available in C. void unsigned volatile while
They are as given here:
Identifiers
Identifiers refer to the names of VARIABLES, FUNCTIONS, and ARRAYS.
These are user-defined names and consist of a sequence of letters, underscore ( _ ) and digits,
with a letter as a first character.
VARIABLES
A variable is the name given to the memory location.
During the execution of program the values of variables may be changed/altered.
We all know that we can’t access the RAM locations directly,
Now what we can do for storing our data?
So, C supports the concepts of Variable…
There are some rules which must be following while defining variable:
1. The variable name must begin with alphabets.
2. The variable name should be meaningful. That means the variable should clearly
indicate the purpose.
3. No special symbols rather than underscore (_) is allowed.
4. The variable name must not be a keyword.
5. No commas or blanks are allowed while defining a variable.
6. The variable name may be combination of alphabets, digits and underscore.
Page 14 of 96
Special Symbols
There are some symbols which are used to define array, function, and etc…
These special symbols are as below:
1.) ( ) - Function Call
2.) [ ] - Array
3.) { } - Definition of Function
4.) < > - Link to Header File
Constants
The Values, which are stored inside the variables, are known as Constants.
During the execution of program the constant remains fixed.
C Supports various types of constant, which are as given below:
1.) Numeric constant
i. Integer Constant
ii. Real Constant
2.) Character Constant
i. Single Character Constant
ii. String Constant
1) Numeric Constant
As its name suggests the numeric constants are made up of digits.
There are 2 types of numeric constants as given below:
i. Integer Constant
There are some rules for defining integer constants.
Rules:
1. An Integer constant must have at least one digit.
2. It must not have a decimal point.
3. It could be either positive or negative.
4. If no sign proceeds, an integer constants assumed is positive.
5. No commas or blanks are allowed within an integer constant.
6. Example: 436,45 10
Page 15 of 96
As its name suggests the character constant always contains one character or no. of
characters.
There are 2 types of character constants.
i. Single Character Constant
There are some rules for defining single character constants.
They are as given below.
Rules:
1) A character constant is either a single alpha bates a single digit or a single special
symbol enclosed within single inverted commas.
2) Example: ‘A’, ‘ ’ , ‘*’
ii. String Constant
The rules of defining string constants are as given below.
Rules:
2) The string constants are always enclosed within double inverted commas.
3) The string constants are just combination of characters, digits, and special
symbols.
4) Example: - “Welcome”, “Hello”
Operators
Operator is a symbol that tells the computer to perform certain mathematical or logical
manipulations.
Operators are just the symbol that can perform manipulations on the data.
C has rich set of operators.
There are several types of operators, they are as given below:
1) Arithmetic Operators
Arithmetic operators are used to perform arithmetic operations on data.
The Arithmetic operators are as given below:
Operator Meaning
+ Addition OR Unary Plus
- Subtraction OR Unary Minus
* Multiplication
/ Division
% Modulo Division
Example: months = days / 30;
2) Assignment Operators
Assignment operators are used to assign a value to the variables.
“=” Sign is used to perform an assignment operation.
Arithmetic assignment operators are also used in combination to simplify the use of both
operators.
Page 16 of 96
The combinations of both operators are known as “Arithmetic Assignment Operators” or
“Short Hand Operators”.
‘C’ has a set of ‘shorthand’ assignment operators of the form
variable operator= expression;
3) Logical Operators
Logical operators are used to combine to or more expressions.
In order to combine two or more the one relational operator, the logical operators are used.
There are 3 logical operators as given below:
Operator Meaning
&& Logical AND
|| Logical OR
! Logical NOT
For example: a > b && x == 100
An expression of this kind, which combines two or more relational expressions, is termed
as a LOGICAL EXPRESSION or a COMPOUND RELATIONAL EXPRESSION.
Like, Simple relation expressions, a LOGICAL EXPRESSION also yield, a value of 1 or
0, according to the TRUTH TABLE.
4) Unary Operators
The unary operators can operand one operand only at a time.
They are just used to increase or decrease the value of operand.
They are always used with integer variable but cannot be used with float variables.
Page 17 of 96
They are listed below:
Increment (++)
Decrement (--)
They are increase / decrease the value of variable by 1,which is by default.
Example: ++m or m++
( ++m is equivalent to m = m+1 OR m+= 1)
6) Conditional Operator
A ternary expression operator pair “ ?: ” is available to construct conditional expressions.
Syntax
Exp1 ? Exp2 : Exp3;
where,, exp1, exp2, exp3 are expressions.
The operator ?: works as follows:
Exp1 is evaluated first.
If it is NON-ZERO (TRUE), then the expression Exp2 is evaluated and becomes
the value of expression.
If Exp1 is FALSE, Exp3 is evaluated and its value becomes the value of the
expression.
Note that only one of the expressions (either Exp2 or Exp3) is evaluated.
It replaces simple if…else loop.
Example…
if (a > b)
x = a; is replaced by x = (a > b) ? a : b;
else
x = b;
Page 18 of 96
7) Bitwise Operators
Some applications require the manipulation of individual bits within a word of memory.
Assembly language or machine language is normally required for operations of this type.
However C contains several special operators that allow such bitwise operations to be
carried out easily and efficient.
These bitwise operators can be divided into three general categories:
1. The one’s complement operator.
2. The logical bitwise operators.
3. The shift operators.
It also contains several operators that combine bitwise operations with ordinary
assignment.
The One’s Complement Operator
The one’s complement operator (~) is a unary operator that causes the bits of its operand to
be inverted (i.e. reversed) so that is become so a so become is.
This operator always precedes its operand. The operand must be an integer type quantity
(including integer, long, short, unsigned, or char).
Linearly the operand will be an unsigned octal or an unsigned hexadecimal quantity,
though this is not a firm requirement.
Suppose int a=16 with 2 byte=16 bit pattern
it will be 00000000 00010000
b=~a
the b will have 16 bit pattern like 11111111 11101111
Page 19 of 96
0 0 0 0 0
Shift Operators
The two bitwise shift operator is shift left (<<) and shift right(>>).
Each operator requires two operands. The first is an integer-type operand that represents
the bit pattern to be shifted.
The second is an unsigned integer that indicates the number of displacements (i.e. whether
the bits in the first operand will be shifted by 1 bit position, 2 bit position, 3 bit positions
and so on).
This value cannot exceed the number of bits associated with the word size of the first
operand.
The left-shift operator causes the left by the bits in the first operand to be shifted to the left
by the number of position indicated by the second operand.
The leftmost bit positions that become vacant will be tilled with us.
A = 01101101 10110111
A<<6 = 0110 1100 0000 = 0x5dc0
All the bits originally assigned to are shifted to the left six places, as the arrows indicate.
The leftmost 6 bits (originally 011011) are lost.
The rightmost 6 bits positions are filled with 00 0000.
The right shift operator causes all the bits in the first operand to be shifted to the right by
the number of positions indicated by the second operand.
The rightmost bits(i.e. the underflow bits) in the original bit pattern will be lost.
If the bit pattern being shifted represents an unsigned integer, then the leftmost bit positions
that become vacant will be filled with 0s.
Hence, the behavior of the right-shift.
When the first operand is an unsigned integer.
A= 0110 1101 1011 0111
A>>6 = 000 0001 1011 0110 = 061bc
We see that all the bits originally assigned to are shifted to the right six places, as the
arrows indicate.
The rightmost 6 bits ( originally 11 011) are lost. The leftmost 6 bits positions are filled
with 00 0000.
8) Special Operators
There are several operators which are used to perform some special task.
Some are listed below:
1. sizeof Operator
Page 20 of 96
2. comma (,) Operator
1. sizeof Operator
The size of a compile time operator and when used with an operand, it returns the number
of
bytes the operand occupies.
The operand may be variable, a constant or a data type qualifies.
M = sizeof(sum);
N= sizeof(long int);
K= sizeof(253L);
The size of operator is normally used to determine the length of array and structures, when
their sizes are not known to the programmer.
It is used to allocate memory space dynamically to variable during execution of a program.
2. Comma(,) Operator
The comma operators are use primarily in conjunction with for statement.
This operator permits two different expressions to upper in situation where only one
expression would ordinarily be used.
For example, it is possible to write
For(expression la, expression lb; expression2; expression3) Statement
Where expression la and lb are the two expressions, separated by the comma operator,
where only one expression would normally appear.
These two expression would typically initialize two separate indices that would be used
simultaneously within the for loop.
Similarly, a for statement might make use of the comma operator in the following manner.
For(expression 1a; expression2;expression3a, expression3b) statement;
Here expression 3a and expression 3b separated by the comma operator, appear in place of
the usual single expression.
In this application the two separate expressions would typically be used to alter the two
different indices used simultaneously within the loop.
For example, one index might count forward while the order counts backward. In for loops.
for(n=1,m=10; n<=m; m++, n++)
Hierarchy of Operators
An arithmetic expression without parenthesis will be evaluated from left to right using the
rules of precedence of operators.
High Priority *, /, %
Low Priority +, -
Ex.
Page 21 of 96
x=9
y=12
z=3 then
ans=x-y/3+3*2-1
Here,,
ans=x-y/3+3*2-1
ans=9-12/3+3*2-1
9 - 12/3 + 3*2 - 1
Page 22 of 96
Increment/Decrement ++ - - R TO L
One’s complement ~ R TO L
Negation ! R TO L
Address of & R TO L
Value of address * R TO L
Type cast (type) R TO L
Size in bytes sizeof R TO L
Multiplication * L TO R
Division / L TO R 3
Modulus % L TO R
Addition + L TO R
4
Subtraction - L TO R
Left Shift << L TO R
5
Right Shift >> L TO R
Less than < L TO R
Less than equal to <= L TO R
6
Greater than > L TO R
Greater than or equal to >= L TO R
Equal to == L TO R
7
Not equal to != L TO R
Bitwise AND & L TO R 8
Bitwise exclusive OR ^ L TO R 9
Bitwise inclusive OR | L TO R 10
Logical AND && L TO R 11
Logical OR || L TO R 12
Conditional ?: R TO L 13
= ,*= ,/=, %=
Assignment +=,-=,&=,|=,^=,!= R TO L 14
<<=,>>=
Comma , R TO L 15
Type Casting
In computer science, type conversion / type casting refers to changing an entity of one data
type to another.
There are two types of conversion;
1. Implicit Conversion
2. Explicit Casting
1.)Implicit Conversion
It works in a way that a variable of data type that is smaller in length, transforming
internally to variable of data type with no longer number length.
It follows below hierarchy:
Page 23 of 96
short int int unsigned int long int unsigned long int float
double long double.
2.)Explicit Casting
It has higher priority then automatic transformation.
General declaration of explicit cast:
Syntax:
(data_type) operand
Operand can be variable or phrase.
Example:
a = (int) c ;
b = (double) d + c ;
Data Types
The predefined identification of any variable is known as “Data type”.
The data type of any variable tells that what kind of values will be stored inside the
variable.
C has rich set of data types.
Basically there are 4 data types, but all data types has some modifiers which helpful to
extend the functionality of data types.
The data types supported by C are as given below:
Keyword Size %
Data Type Range
equivalent (In Bytes) Format
Character char %c -128 to +127
Unsigned
unsigned char %c 0 to 255
Character
signed short int OR 1 byte
Signed Short (8 bits)
short int OR %d -128 to +127
Integer
short
Unsigned Short unsigned short int OR
%d 0 to 255
Integer unsigned short
Signed Integer int OR signed int %d -32,768 to +32,767
2 bytes
unsigned int OR
Unsigned Integer (16 bits) %u 0 to 65,535
unsigned
4 bytes
Signed Long signed long int OR (32 bits) %ld -2,147,483,648 to
Integer long int OR +2,147,483,647
Page 24 of 96
long
Unsigned Long unsigned long OR
%lu 0 to 4,294,967,295
Integer unsigned long
Floating point float %f 3.4E – 38 to 3.4E + 38
Double precision 8 bytes
double %lf 1.7E – 308 to 1.7E + 308
floating point (64 bits)
Extended double
10 bytes 3.4E – 4932 to
precision floating long double %Lf
(80 bits) 1.1E + 4932
point
long double
Conversion double
Page 25 of 96
Ch-3
Various Control
Structure
Introduction
Sequential Control Structure
Selective Control Structure
Iterative Control Structure
Break Statement
Continue Statement
The goto Statement
Page 26 of 96
INTRODUCTION
The term FLOW CONTROL refers to the order in which a programmer’s statements are
executed.
1. Sequential
2. Selection
3. Iterative
The normal flow of control for all program is sequential.
The SELECTION statements allow the programmer to alter the normal sequential flow of
control.
The ITERATIVE statements provide us ability to go back and repeat a set of statements.
#include<stdio.h>
#include<conio.h>
void main()
{
flo at P,R,N,SI;
clr scr() ;
pr int f( “E nt er Pr incipal amount : ”) ;
scanf( “% f”, &P) ;
pr int f( “E nt er Pr incipal amount : ”) ;
scanf( “% f”, &R) ;
pr int f( “E nt er Pr incipal amount : ”) ;
scanf( “% f”, &N) ;
SI=(P*R*N) / 100 ;
pr int f( “\ n\t Simple I nt erest : %.3f”,SI);
get ch() ;
}
Page 27 of 96
SELECTIVE CONTROL STRUCTURE
To perform such things C supports decision making statements that are as given below:
A. if statement
B. switch statement
C. Conditional Operator statement
These statements are purely known as “Decision Making”.
They are also ‘control’ the flow of execution, they are also known as “Control Statement”.
A.) if statement
DECISION MAKING USING ‘IF’ STATEMENT
The if statement is the powerful decision making statement and is used to control the flow of
execution of the statements.
C uses the keyword if to implement the decision control instruction.
It is basically a 2 way decision making statement.
Syntax:
if(test expression)
{
statement block;
}
Example:
/* Program to find check the person is MALE or FEMALE. */
#include<stdio.h>
#include<conio.h> Entry
void main()
{
char code;
clrscr(); Test TRUE
printf(“Enter your gender: ”); Expression
scanf(“%c”,&code);
if(code == ‘M’ || code == ‘m’) Statement - block
printf(“The person is MALE.”); FALSE
if(code == ‘F’ || code == ‘f’ )
printf(“The person is FEMALE.”);
Statement - x
getch();
}
Page 28 of 96
DECISION MAKING USING IF…ELSE STATEMENT
The if else statement is the extension of the simple if statement.
The general form of if…else is as given below: Entry
Syntax:
if(test expression)
{
true-block statements; TRUE FALSE
Test
} Expression
else
{
false-block statements; True statement False statement
} block block
Statement-x;
Example:
/* WAP to check whether you are PASS or FAIL */
Statemet -x
#include<stdio.h>
#include<conio.h>
void main()
{
float per;
clrscr();
printf(“Enter Your Percentage: ”);
scanf(“%f”,&per);
if(per>=40.00)
printf(“You are PASS”);
else
printf(“You are FAIL”);
printf(“You have scored: %.3f”,per);
getch();
}
DECISION MAKING WITH NESTED IF… ELSE STATEMENT
When a one if..else statement is within the another if..else is known as “Nesting of If..Else”.
The general form of the nested if..else is as given below.
Syntax:
if(test expression 1)
{
if(test expression 2)
{
statement 1;
}
else
Page 29 of 96
{
statement 2;
}
}
else
{
statement 3;
}
statement –x;
Example:
/* WAP t o get maximum no. amo ng of given t hree number s. */
Test
Statement -3
Condition-2
Statement -2 Statement -1
Page 30 of 96
Statemet -x
DECISION MAKING WITH ELSE..IF LADDER
Just observe that the program uses the nested if - else.
This leads to three disadvantages:
1) As the No. of conditions are going increased the level of indentation is also
increased.
2) An as a result the program is shifted to the right hand side, and readability of your
program will be decreased.
3) In case of nested if else you must take care about the pair of the ifs and elses.
4) You must take care of the opening braces and closing braces of each & every ifs
and elses.
There is one more way in which we can write the program of multiple conditions, This
involves usage of else if blocks as shown below:
Condition 1
Condition 2
Statement 1
Condition 3
Statement 2
Condition N
Statement 3
Statement N Default
Statement
Statement X
Page 31 of 96
Syntax
if(condition 1)
{
Statement-1;
}
else if (condition 2)
{
Statement-2;
}
else if(condition 3)
{
statement - 3;
}
else if (condition n)
{
Statement-n;
}
else
{
default-statement;
}
statement-x;
Example
Page 32 of 96
pr int f( “\ n\t Second Class.”);
else if(per>=40 && per<50)
pr int f( “\ n\t Pass Class.”) ;
else
pr int f( “\ n\t ***”);
}
As soon as a true condition is found, the statement associated with that condition will be
executed, and then the control will transferred to the statement x.(by skipping the rest of
ladders).
When all the condition become false, then the else portion that is the final else that contains
the default statement will be executed, and the control will transferred at the statement x.
That means the program execution will become faster, when you are using the else…if ladder
instead of more than one ifs. Because after execution of a particular statement, there is not
more conditions are checking, that means skipping the rest of ladder.
Page 33 of 96
Entry
Switch
Expressions
Block 1
Block 2
Default Block
Statement X
Page 34 of 96
The main advantage of switch statement over if is that it leads to more structured
program & the level of indentation is manageable, more so if there are multiple
statements within each case of switch.
Drawback
Drawback is the use of logical operators. That means the logical operators cannot used in
switch..case.
Looping Structures in C
We have already learn about the sequential program and also learn about that how we can
control the flow of program and branching of some of statements of the program.
Now we are going to learn that how to perform the particular task no. of times. That means
how repeat a task without writing a task no. of times.
This thing can be done using the concepts of loop.
To understand the concept of the loop, it is necessary to understand the concept of the
following things:
1) Loop
To perform a particular task no. of times the concepts of loops can be used.
Page 35 of 96
Loops can be of 2 types:
1. Finite Loop
The loop in which the no. of iteration is predefined is known as Finite Loop.
2. Infinite Loop
The loop in which the no. of iteration is not predefined is known as Infinite Loop.
2) Iterations
The meaning of the word “Iteration” is “Repetition”.
3) Counter Variable
The variable which is used to count the no. of iterations is known as counter variable.
In looping the sequence of statements are executed until some conditions for termination of
the body of the loop are satisfied.
Therefore the program loop is made up of 2 statements:
The Body of the loop
The Control statement (A Condition)
Depending on the position of the condition (control statement) in the loop, the loop may be
classified into 2 categories:
1. Entry Controlled loop
2. Exit Controlled loop
There are 3 methods through which some part of the program can be repeated number of
times, they are as given below:
1. The while statement
2. The do…while statement
3. The for statement
Page 36 of 96
If test expression is evaluated to true then and then the body of the loop will be executed,
otherwise the control will transfer to the statement x, which is immediately after the loop.
If the condition is true and the loop will executed, then again the condition will be checked if
the condition is true than the body of the loop will be executed.
This process is continued while the test condition is not evaluated to false.
The flow chart and the example of the while statement is as given below:
In above syntax the do & while are the keywords which defines the loop.
Consider the syntax the condition is not checked at the entry of the loop, but the condition is
on exiting the loop.
According to the syntax, when the control will be reached at the do statement, then the
control will proceeds to the body of the loop. And at last the condition will check.
Now if the condition is true then the control will go at the do statement again and the body of
the loop is executed once again, this process continuous as long as the condition is true.
Page 37 of 96
body of the loop;
}
where,
You can see the initialization of the counter variable is also the part of the loop.
Here the for statement is consisting of 3 parts:
Initialization (i)
Testing (t)
Increment (i)
The initialization of the counter variable is done only once, using an assignment
statement.
The second part is consisting of the conditional statement that is the used to control the loop.
If you want to know the maximum iterations of the loop, then you can identify it using the
conditional expression.
The last part is consisting of the increment or decrement of the counter variable, through
which the value of the counter variable is finally reach at the maximum iterations of the loop.
After executing this increment and decrement of the variable the value of the variable the
new value of the variable is again tested, if the new value of the variable is satisfy the
condition then the body of the loop is again executed. This process is continued till the value
of the counter variable is reached at the maximum value of the variable.
Page 38 of 96
}
}
The nesting of the loop may continue upto any desired level, but our ANSI C Compiler
allows up to 15 levels of the nesting.
The outer loop is for the rows and the inner loop is for the columns.
BREAK STATEMENT
Break statement is useful to exiting prematurely from loop.
Break statement is used to exit from any loop or Switch Case.
• In switch case whenever a break is encountered, it passed the control to the
immediately following statement or case
• Break is used to exit from any loop. After Break, the program will start execution
from the next sentence which is following the loop. Syntax: break;
This statement is used to prematurely stop the execution of the immediately enclosing loop.
Example:
vo id main ()
{
for ( i=1 ;1<=10; i=i+1)
{
pr int f( “ %d”, i) ;
if ( i==5)
break;
}
}
Page 39 of 96
Page 40 of 96
The GOTO statement
The goto statement is used to alter the normal sequence of program execution by transferring
control to some other part of the program.
That means if you want to control the flow of control according to a certain condition then
you can do it with the help of “goto statement”.
Actually this statement is referred to as “goto label”.
C supports the goto statements to branch unconditionally from one point to another in the
program.
The goto requires a label to identify the place where the branch is to be made.
The label is any valid variable name, and must be followed by a colon.
The label is placed immediately before the statement where the control is to be transferred.
Syntax
The label can be nay where in the program either before or after the goto label; statement.
Note that a goto breaks the normal execution of the program.
If the label: is placed before the statement goto label; a loop will be formed and some
statements will be executed repeatedly. And such jump is known as “Backward Jump”.
If the label is placed after the goto label; some statements will be skipped & the jump is
known as a “Forward Jump”.
The most common applications of the goto is as given below:
1. Branching around the statements and group of statements under certain conditions.
2. Jumping it the end of a loop under the certain conditions, thus bypassing the reminder
of the loop during the current pass.
3. Jumping completely out of the loop under the certain conditions, thus terminating the
execution of the loop.
Page 41 of 96
Ch-4
Header Files and
Library Functions
Importance of Header Files
Header Files
Page 42 of 96
Importance of HEADER FILEs
The C language is accompanied by a number of library functions.
ANSI C committee has standardized header files which contain these functions.
Basically header files are the internal built-in function files which are useful for creating any
C program.
The header files also contain other information related to the use of the library functions,
such as symbolic constant definitions.
HEADER FILES
Some of the popular header files are…
stdio.h
conio.h
math.h
string.h
ctype.h
stdio.h
A stream is a source / destination of data that may be associated with a desk or
other peripheral.
character testing & conversion functions.
Functions are as below:
clearerr(); fclose(); feof(); ferror();
fflush(); fgetpos(); fopen(); fread();
freopen(); fseek(); fsetpos(); ftell();
fwrite(); remove(); rename(); rewind();
setbuf(); setvbuf(); tmpfile(); tmpnam();
fprintf(); fscanf(); printf(); scanf();
sprintf(); sscanf(); vfprintf(); vprintf();
vsprintf(); fgetc(); fgets(); fputc();
fputs(); getc(); getchar(); gets();
putc(); putchar(); puts(); ungetc();
perror();
conio.h
Console input/output header file.
Page 43 of 96
Functions are below:
Data type
No. Functions Task
Returned
Gets a character from console but doesn’t
1 getch() int
echo to screen.
Gets a character from console and echoes
2 getche() int
to the screen.
Gets a character from standard input
3 getchar() int
device.
4 clrscr() void Clears text mode window.
5 goto xy() int Positions the cursor in text window.
Sends formatted output to the text window
6 cprintf()
on the screen.
7 textcolor() int Selects a new character color in text mode.
8 textbackground() int Selects a new text background color.
math.h
The header file math.h declares mathematical functions and macros.
The math.h header file is following function included in it:
Functions are as below:
string.h
This header file is used to perform task on character data or for string value.
Functions are as below:
memchr(); memcmp(); memcpy(); memmove(); memset(0;
strcat(); strncat(); strchr(); strcmp(); strncmp();
strcoll(); strcpy(); strncpy(); strcspn(); strerror();
strlen(); strpbrk(); strrchr(); strspn(); strstr();
strtok(); strxfrm(); strupr(); strlwr(); strrev();
ctype.h
This header file is used to declares functions for testing characters.
By using this header file we can perform TESTING and CONVERSION
characters.
Functions are as follow:
isalnum(); isalpha(); iscntrl(); isdigit(); isgraph();
islower(); isprint(); ispunct(); isspace(); isupper();
isxdigit(); tolower(); toupper();
Page 44 of 96
Ch-5
User Defined
Functions
Introduction
Function Definition
Passing & Returning Values to Function
Types of UDF
Recursion
Pointers
Storage Classes
Creating of Library
Page 45 of 96
INTRODUCTION
The C language functions can be categories…
1. Library Functions
2. User Defined Functions
The main difference between Library and UDF is…
1. Library Function:
Not required to be written by the user.
Ex. printf(), scanf() etc…
2. UDF
Has to be developed by the user at the time of writing a program.
However, a UDF can late become a part of the C Program Library.
main() is UDF.
FUNCTION DEFINITION
A function is a…
o block of code
o in sequential manner
o to perform a particular task.
Every C program is collection of functions.
Syntax…
function_name(argument list)
{
variable declarations;
function statements;
-----------------------
-----------------------
return (expression);
}
Page 46 of 96
1) The Function is defined outside the main ( ).
2) The Function can be called from the main() or any other UDF.
3) After executing each of the UDF the control will transfer in the main( ).
4) The function call statement is followed by () and semincolon ( ; ).
5) The Function definition is followed by the ( ).
6) There is no need to specify the name of the variable at the time of prototype of the function.
7) One C program can have more than one UDF.
8) Each and every program has one UDF that is obviously main( ).
9) The functions are executed in order, in which they are called, not in which they are defined.
If you want to understand UDF then you have to understand 3 part of UDF:
Declaration (Prototype) of Function
Calling of Function
Definition of Function
Types of UDF
1) Function without argument without return value.
2) Function with argument without return value.
3) Function with argument with return value.
4) Function without argument with return value.
Page 47 of 96
1) Function without argument without return value
When the function has no argument, it does not receive any data from the calling function.
And when the function does not return any value, the calling function does not receive any
data.
Let’s take one example…
Page 48 of 96
printf(“\n Enter b:”);
scanf(“%d”,&b);
add(a,b); //function call with 2 arguments…(formal argument)
getch( );
}
void add( int a, int b)
{
int c;
c=a+b;
printf(“\n Addition is : %d”,c);
}
Page 49 of 96
In this type the calling function cannot send any argument to the called functions as an
argument.
But the called function can send the value by using a return statement as a response.
This is one type of again a “One way Communication”.
Example
#incclude<stdio.h>
#include<conio.h>
int add(void)
{
int c;
c=add();
getch( );
}
int add( )
{
int a,b,c;
printf(“\n Enter a: “);
scanf(“%d”,&a);
printf(“\n Enter b: “);
scanf(“%d”,&b);
c=a+b;
return ( c );
}
RECURSION
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 on forms of
previous result.
The process is used for repetitive computation in which each action in terms of a previous
result.
Many iterative problems can be written in this form.
In order to solve a problem recursively, two condition must be satisfied.
First, the problem must be written in recursive form and second the problem example, we
wish to calculate the factorial of a positive integer quantity.
We would normally express this problem as n1=1 x 2 x 3 x 4 … x n where n is the
specified positive integer.
However, we can also express in another way, by writing n=1 = n*(n-1).
Page 50 of 96
This is a recursive statement of the problem, in which last expression provides a stopping
condition for the recursion.
When a recursive program is executed the recursive function calls are not executed
immediately.
Rather, they are placed on a stack until the condition that terminates the recursion is
encountered.
The function calls are then executed in reverse order, as they are popped off the stack.
If a recursive function contains local variables, a different set of local variables will be
created during each call.
The name of the local variables, will be cause always be the same, as declared within the
function.
However, the variables will represent a different set of values each time the function is
executed.
Each set of values will be stored on the stack, so that they will be available as the
recursive process “unwinds” i.e. as the various function calls are “popped” off the stack
and executed.
Example…
#include<stdio.h>
#include<conio.h>
int fact(int n)
{
int f;
if(n==1)
return(1);
else
f=n*fact(n-1);
return(f);
}
void main( )
{
int n,m;
clrscr( );
printf(“\n\tEnter any no.: ”);
scanf(“%d”,&n);
m=fact(n);
printf(“\n\tFactorial is %d”,m);
getch( );
Page 51 of 96
}
POINTERS
A pointer is a variable that represents the location of a data item, such as a variable or an
array element. Pointers have a number of useful applications.
Pointer is one kind of variable in which you can store memory information (address) of
its related another variable.
address of x value of x
p
Steps to declare pointer are as follows:
Declare base variable int x;
Declare pointer type variable related to base variable int *p;
Establish relation b/w. base and pointer variable p = &x;
The unary operators & and * is called ADDRESS and INDIRECTION operator to refer
address of that variable and to indicate variable as pointer variable respectively.
Example…
#include<stdio.h>
#include<conio.h>
void main()
{
int x=10,y;
int *ptr;
ptr=&x;
y=*ptr;
printf(“\n\t X: %d”, x);
printf(“\n\t %d refers %d”, &x, x);
printf(“\n\t %d is stored at %d”,*&x, &x);
printf(“\n\t %d refered with %d”, *ptr, &ptr);
printf(“\n\t Y: %d”, y);
*ptr=25;
printf(“\n\t Now X=%d”, x);
getch();
}
The advantages of using pointers are:
1. Function can’t return more than one values but it can modify many pointer
variables and can return more than one variable.
Page 52 of 96
2. In the case of ARRAYS, We can decide the N size array @ runtime by allocating
necessary space.
3. Main advantage: DYNAMIC MEMORY ALLOCATION.
#include <stdio.h>
#include<conio.h>
int sqr(int x);
int main(void)
{
int t=10;
printf("%d is the square of %d", sqr(t), t);
return 0;
}
int sqr(int x)
{
x = x*x;
return(x);
}
Page 53 of 96
Pointers are passed to functions just like any other value.
Of course, you need to declare the parameters as pointer types.
Example…
void swap(int *,int *);
void main()
{
int i, j;
i = 10;
j = 20;
swap(&i, &j); /* pass the addresses of i and j */
printf(“\n\tAfter swapping…”);
printf(“\n\t\t i: %d”, i);
printf(“\n\t\t j: %d”, j);
getch();
}
void swap(int *x, int *y)
{
int temp;
temp = *x; /* save the value at address x */
*x = *y; /* put y into x */
*y = temp; /* put x into y */
}
Note:
C++ allows you to fully automate a call by reference through the use
of reference parameters.
STORAGE CLASSES
In ‘C’ all the variables have data type and storage classes.
It explains the lifetime of the storage associated with the variable.
Variables tell 4 things…
Storage area of variable,
Initial value of variable,
Scope of variable,
Life of variable.
Class
Automatic Register Static External
Properties
A variable A value stored in The variable is External variables
declared without the CPU register initialized only are declared outside
any storage class is can always be once for the all functions, yet
Definition
considered to be accessed faster than program. are available to all
an automatic the one which is Irrespective of the function that wants
variable. stored in memory. multiple function to use them.
Page 54 of 96
calls the value
persists between
multiple calls to
function.
Storage memory CPU registers memory memory
Default garbage value if garbage value if not
Zero (Null) Zero
initial value not initialized initialized
only in the block only in the block only in the block
Scope Global
where it is defined where it is defined where it is defined
the variable is not As long as the
till the block is till the block is destroyed after the program’s
Life
executing. executing. block or function is execution does not
over. end.
Keyword auto register static extern
auto data_type
variable; register data_type static data_type extern data_type
Syntax
OR variable; variable; variable;
data_type variable;
auto int a OR
Example register int a; static int a; extern int a;
int a;
Creating of Memory
We can add UDF to the library.
When we use these UDF in other applications as a library function then we can save
compile time because we have already functions as in compiled form.
We can use these functions as built-in functions in ‘C’.
Let us see an example to make SQUARE function as library file.
Example…
/* square.c */
int square(int val);
{
int temp;
temp = val*val;
return temp;
}
After the compilation of square.c , ‘C’ compiler will create a file square.obj which
will contain all the codes in machine language.
Now add this function to MATH.H by using command…
C:\>tlib maths.lib + c:\square.obj
Page 55 of 96
Now we can use square function as a library file.
Example…
#include<stdio.h>
#include<conio.h>
#include “c:\square.h”
void main()
{
int num,sqr;
clrscr();
printf(“Enter any number to find its square: ”);
scanf(“%d” , &num);
sqr=square(num);
Page 56 of 96
Ch-6
ARRAY
Introduction
Single Dimensional Arrays
Two- Dimensional Arrays
Initialization and working with Array
Passing Array Elements to Function
Use of Pointers in Array
Sorting Numeric and String Arrays
String Function and Operations
Page 57 of 96
Introduction
Up to this chapter, we are learning to store only one value in the variable at a time.
Now suppose you want to store multiple values in the program, at that time you need not
to declare that much variables in your program. C supports the concept of an array.
Using an array, we can store multiple values within one variable.
The concept of an array is used to handle the large amount of data.
Page 58 of 96
Explanation..
Declares the variable named a and can hold 5 values at a same time.
All the values may belong to only one data type that is integer.
Note
Any references to the arrays outside the declared limits would not necessarily
cause an error. Rather it might result in unpredictable results.
The size should be either a numeric constant or a symbolic constant.
Example
/ / A P r o g r a m o f t he s in g le d i me n s io n a l ar r a y… . .
# in c lu d e< st d io . h >
# in c lu d e< co n io . h >
vo id ma in( )
{
int a[5] , i;
fo r ( i= 0 ; i< =5 ; i+ +)
{
scanf( “%d”, &a[ i]) ;
}
fo r ( i= 0 ; i< =5 ; i+ +)
{
pr int f( “\ n%d”,a[ i]) ;
}
getch() ;
}
Page 59 of 96
int No[3][4];
The above variable no can hold total 12 values.
The memory representation of the no variable is as given below:
No[0][0] No[0][1] No[0][2] No[0][3]
No[1][0] No[1][1] No[1][2] No[1][3]
No[2][0] No[2][1] No[2][2] No[2][3]
There is another concept of 2 D character array.
That means you can store only one string in 1 D array of the character data type.
But when you want to store more than one string within one variable at that time 2 D
array of the character data type is used.
for(i=0;i<=2;i++)
Page 60 of 96
{
for(j=0;j<=2;j++)
{
printf("%3d",a[i][j]);
}
printf("\n");
}
getch();
}
Page 61 of 96
PASSING ARRAY ELEMENS TO FUNCTION
An array name can be used as an argument to a function, thus permitting the entire array
to be passed to the function.
The manner in which the array is passed differs mainly.
However, from that of an ordinary variable.
To pass an array to a function, the array mane must appear by itself without brackets or
subscripts as an actual argument within the function call.
The corresponding format argument is written in the same manner, though it must be
declared as an array within the formal argument declaration.
When declaring array as a format argument, the array name is written with a pair of
empty square brackets.
The size of the array is not specified within the format argument declaration.
Example…
int arsum(int * start_here)
{
int ndays = 0;
while (1)
{
ndays += *start_here++;
if (*start_here == 0) break;
}
return ndays;
}
void main()
{
int daze[13] = {31,28,31,30,31,30,31,31,30,31,30,31,0};
int days_in_array;
/* days_in_array = arsum(&daze[0]); */
days_in_array = arsum(daze);
Page 62 of 96
int *ptr;
ptr = &my_array[0]; /* point our pointer at the first integer in our array */
As we stated there, the type of the pointer variable must match the type of the first
element of the array.
In addition, we can use a pointer as a formal parameter of a function which is
designed to manipulate an array. e.g.
Given:
int array[3] = {1, 5, 7};
void a_func(int *p);
Some programmers might prefer to write the function prototype as:
void a_func(int p[]);
which would tend to inform others who might use this function that the function is
designed to manipulate the elements of an array.
for(i=0;i<=9;i++)
{
printf("Enter your No.a[%d]= ",i);
scanf("%d",&a[i]);
}
Page 63 of 96
for(i=0;i<=9;i++)
{
for(j=i+1;j<=9;j++)
{
if(a[i]>a[j])
{
temp=a[i];
a[i]=a[j];
a[j]=temp;
}
}
}
printf("\nAfter sorting. . .");
for(i=0;i<=9;i++)
{
printf("\n%d",a[i]);
}
getch();
}
Page 64 of 96
{
printf(“%s\n” , arr[i]);
}
for(j=0;j<i-1;j--)
{
for(k=j+1;k<I;k++)
{
if( strcmp ( arr[j],arr[k] ) > 0 )
{
strcpy(temp, arr[j]);
strcpy( arr[j], arr[k]);
strcpy( arr[k], temp);
}
}
}
printf(“\n Sorted in Ascending order \n”);
for(i=0;i<5;i++)
{
printf(“\n\t %s”, arr[i]);
}
getch();
}
Page 65 of 96
The strlen() function takes one argument, which is the string you are considering. The
function returns the number of characters of the string.
Here is an example:
#include <stdio.h>
#include <conio.h>
void main()
{
char *School = "Manchester United";
int Length = strlen(School);
clrscr();
printf(“\n\tThe Length of \“%s\” is %d characters.”, School, Length);
getch();
Page 66 of 96
This would produce:
Originally, Make = Ford
After concatenating, Make = Ford Explorer
Page 67 of 96
The strcmp() Function
he strcmp() function compares two strings and returns an integer as a result of its
comparison.
Its syntax is:
int strcmp(const char* S1, const char* S2);
This function takes two strings, S1 and S2 and compares them. It returns …
A negative value if S1 is less than S2
Zero if S1 and S2 are equal
A positive value if S1 is greater than S2
#include <stdio.h>
#include <conio.h>
void main()
{
char *FirstName1 = "Andy";
char *FirstName2 = "Charles";
char *LastName1 = "Stanley";
char *LastName2 = "Stanley";
clrscr();
getch();
}
Page 68 of 96
Ch-7
Structure
Introduction
Declaration and Initialization of Structures
Accessing Structure Members
Memory Allocation
Nested Structure
Arrays of Structure
User Defined Data Types
Pointers of Structure
Structure and Functions
Unions
Page 69 of 96
Introduction
Structure is the collection of elements having different data types.
A structure is a collection of one or more variables types grouped under a single name for
easy manipulation.
The variables in a structure, unlike those in an array, can be of different variable types.
A structure can contain any of C's data types, including arrays and other structures.
Each variable within a structure is called a member of the structure.
where,
The struct keyword defines the structure.
The tag name is the identifier of the structure. This should be meaningful.
Member..1,member..2,member..3 are the members of the structure.
The template of the structure must be enclosed within a curly braces {…} and
terminated by a semicolon (;).
And in the last you can see one variable which is not belongs to a particular data
type. It’s data type is structure.
The structure is the user defined data type. It is not a built in data type.
Page 70 of 96
Example
In the above program you can see that the structure has 2 members.
And can be access by using a structure type variable and member operator.
Memory Allocation
Memory Allocation of structure in C is same as array.
Compiler allocates continuous memory to structure elements in one bunch of memory.
But remember that…
o Memory allocation is done only at the time of declaration of variable of structure
type not at the time of structure declaration.
Page 71 of 96
We have talk about COMPILE TIME ALLOCATION yet.
Now, Let us see about RUN TIME ALLOCATION…
There are some library functions for allocating the memory during the execution
of the program.
These functions are known as MEMORY MANAGEMENT FUNCTIONS.
1.)
malloc()
It reserves a block of memory for specified size.
It returns a pointer type of VOID.
So it can be assigned for any type of pointer.
Syntax:
pointer = (pointer type*) malloc (byte size);
Example:
ptr = (int*) malloc (10 * sizeof(int));
2.) calloc()
It is normally used for requesting runtime memory space for storing ARRAYS,
STRUCTURES, UNIONS, etc…
It allocates multiple blocks of memory storage and each of block are of same size.
Syntax:
pointer = (data type*) calloc (n, element size);
Example:
ptr = (float*) calloc (20, sizeof(float));
Here,
calloc allocates 4 bytes to hold data for 20 records of float type.
When calloc is used, we must be sure that the requested memory
has been allocated successfully.
3.) free()
The function is used for releasing memory spaces used in program.
When memory spaces are not in use, it is programmer’s responsibility to free those
spaces when not needed.
Syntax:
free(pointer);
Example:
free(ptr);
Page 72 of 96
Nested Structure
Nested structures are the structures within structure.
We can create a new structure inside the old structure; the new structure will be called
NESTED STRUCTURE.
Example…
struct stud
{
char *name;
int rno;
float fees;
struct result
{
int mark[5],sum;
float per;
};
};
Arrays of Structure
Arrays can be used to assign structure member and its value comfortably.
It can be declared, then each elements of array represents a structure variable.
Example:
struct College
{
int clgid, clgstars, employee, courses, branches;
char *name;
};
main()
{
typedef struct College;
College CLG[3];
}
Page 73 of 96
Example:
typedef struct
{
int dd;
int mm;
int yyyy;
}DOB;
Here, we can now use DOB as built-in data type in another structure.
Pointers to Structure
It is just like the pointers to built-in data type’s variables.
Example:
struct stud
{
char *name;
int roll;
int std;
float per;
}*s1;
void main()
{
int ans,squr();
clrscr();
printf(“Enter any value: ”);
scanf(“%d”, &sqr.val);
ans=squr(&sqr);
Page 74 of 96
printf(“Square of %d is %d”, sqr.val, ans);
getch();
}
int squr(struct square *s)
{
return (s val * sval);
}
Unions
A union, is a collection of variables of different types, just like a structure.
However, with unions, you can only store information in one field at any one time.
You can picture a union as like a chunk of memory that is used to store variables of
different types.
Once a new value is assigned to a field, the existing data is wiped over with the new
data.
A union can also be viewed as a variable type that can contain many different variables
(like a structure), but only actually holds one of them at a time (not like a structure).
This can save memory if you have a group of data where only one of the types is used at
a time.
The size of a union is equal to the size of its largest data member.
In other words, the C compiler allocates just enough space for the largest member.
This is because only one member can be used at a time, so the size of the largest, is the
most you will need.
Here is an example:
...
union time
{
long simpleDate;
double perciseDate;
}mytime;
To access the fields of a union, use the dot operator(.) just as you would for a structure.
When a value is assigned to one member, the other member(s) get whipped out since they
share the same memory.
Using the example above, the precise time can be accessed like this:
...
printTime( mytime.perciseDate );
...
Here is a sample program to illustrate the use of unions.
#include <stdio.h>
#include <conio.h>
Page 75 of 96
void main()
{
union data
{
char a;
int x;
float f;
} myData;
int mode = 1;
myData.a = 'A';
printf("Here is the Data:\n%c\n%i\n%.3f\n", myData.a, myData.x, myData.f );
myData.x = 42;
mode = 2;
printf("Here is the Data:\n%c\n%i\n%.3f\n", myData.a, myData.x, myData.f );
myData.f = 101.357;
mode = 3;
printf("Here is the Data:\n%c\n%i\n%.3f\n", myData.a, myData.x, myData.f );
if( mode == 1 )
printf("The char is being used\n");
else if( mode == 2 )
printf("The int is being used\n");
else if( mode == 3 )
printf("The float is being used\n");
getch();
}
This little program declares a union with an int, float, and char. It uses each field, and
after each use prints out all the fields (with one ugly printf statement). Here is some
sample output:
Page 76 of 96
0.000
Here is the Data:
1120581321
101.357
The float is being used
Usage
access individual bytes of larger type
variable format input records (coded records)
sharing an area to save storage usage
unions not used nearly as much as structures
sizeof union is size of its biggest member
Unions most often contain different types of structures
Can only initialize first member of union
Can assign (copy) one union variable to another
Can pass union or pointer to union as function arg
Function can return union type
Can define pointers to union type object
Members accessed as unionvar.member or unionptr-$gt;member
Syntax, format and use of tags and declarators like struct, but members overlay each
other, rather than following each other in memory.
Page 77 of 96
Ch-8
File Handling in C
Concept of Data Files
File Handling in C
Opening a File
Reading from a File
Closing a File
Functions: fgets() and fputs()
Functions: fprintf() and fscanf()
Random access using fseek()
ftell()
rewind()
feof()
ferror()
Functions: fwrite() and fread()
File I/O (using TEXT File)
Command Line Arguments
Page 78 of 96
Concept of Data Files
If you work with a computer you work with files. Sometimes those files contain
information about something you are writing - in a word processor, for example.
Sometimes those files contain other information like results of calculations.
Sometimes those files contain results of measurements you took in a laboratory or out
in the field.
In this lesson we are going to examine data files.
There are numerous good reasons why you need to understand some basic ideas about
data files.
The amount of data you can store in a data file on a disk is determined by
the precision of the measurements you take and the number of data points
you want to record.
You may want to write programs that take and store data, and you need to
understand a little bit about file structure when you do that.
In both cases you need to know something about file structure and some details of the
characteristics of data files.
That's what this lesson is about.
File handling in C
A file is a collection of bytes stored on a secondary storage device, which is generally
a disk of some kind.
The collection of bytes may be interpreted, for example, as characters, words, lines,
paragraphs and pages from a textual document; fields and records belonging to a
database; or pixels from a graphical image.
There are two kinds of files that programmers deal with text files and binary files.
C communicates with files using a new datatype called a file pointer.
This type is defined within stdio.h, and written as FILE *.
A file pointer called output_file is declared in a statement like
FILE *output_file;
Opening a File
fopen is used to open a file for read, write or update.
The first statement declares the variable fp as a pointer to the data type FILE.
As stated earlier, File is a structure that is defined in the I/O Library.
The second statement opens the file named filename and assigns an identifier to the
FILE type pointer fp.
fopen() contain the file name and mode (the purpose of opening the file).
r is used to open the file for read only.
w is used to open the file for writing only.
Page 79 of 96
a is used to open the file for appending data to it.
Library: stdio.h
Prototype: FILE *fopen(const char *filename, const char *mode);
Example…
#include <stdio.h>
#include <conio.h>
void main ()
{
FILE *fp;
fp = fopen("data.txt", "r")
if (fp == NULL)
{
printf("\n\n File does not exist, please check!\n");
}
fclose(fp);
}
Closing a File
A file must be closed as soon as all operations on it have been completed.
This would close the file associated with the file pointer.
The input output library supports the function to close a file.
Library: stdio.h
Example
Page 80 of 96
#include <stdio.h>
#include <conio.h>
void main()
{
FILE *myfile;
char c;
myfile = fopen("firstfile.txt", "r");
if (myfile == NULL)
{
printf("File doesn't exist\n");
}
else
{
do
{
c = getc(myfile);
putchar(c);
} while (c != EOF);
}
fclose(myfile);
getch();
}
Example…
#include <stdio.h>
#include <conio.h>
#define MAXLINE 20
void main()
Page 81 of 96
{
char line[MAXLINE];
while (fgets(line, MAXLINE, stdin) != NULL && line[0] != '\n')
{
fputs(line, stdout);
}
getch();
}
where fp id a file pointer associated with a file that has been opened for writing.
The control string is file output specifications list may include variable, constant and
string.
fprintf(f1,%s%d%f”,name,age,7.5);
Here, name is an array variable of type char and age is an int variable
Page 82 of 96
char item[10],filename[10];
printf(“Input filename”);
scanf(“%s”,filename);
fp=fopen(filename,”w”);
printf(“Input inventory datann”0;
printf(“Item namem number price quantityn”);
Example 2
#include <stdio.h>
#include <stdlib.h>
#define MAX 40
void main()
{
FILE *fp;
char words[MAX];
if ((fp = fopen("wordy", "a+")) == NULL)
{
Page 83 of 96
fprintf(stdout,"Can't open \"words\" file.\n");
exit(1);
}
puts("Enter words to add to the file; press the Enter");
puts("key at the beginning of a line to terminate.");
while (gets(words) != NULL && words[0] != '\0')
puts("File contents:");
rewind(fp); /* go back to beginning of file */
while (fscanf(fp,"%s",words) == 1)
puts(words);
if (fclose(fp) != 0)
fprintf(stderr,"Error closing file\n");
getch();
Page 84 of 96
#include <stdio.h>
#include <conio.h>
void main ()
{
FILE * f;
f = fopen ( "myfile.txt" , "w" );
fputs ( "Hello World" , f );
fseek ( f , 6 , SEEK_SET );
fputs ( " India" , f );
fclose ( f );
return 0;
}
ftell()
The function ftell returns the current offset in a stream in relation to the first byte.
Returns the current value of the position indicator of the stream.
For binary streams, the value returned corresponds to the number of bytes from the
beginning of the file.
For text streams, the value is not guaranteed to be the exact number of bytes from the
beginning of the file, but the value returned can still be used to restore the position
indicator to this position using fseek.
Example
/* ftell example : getting size of a file */
#include <stdio.h>
#include <conio.h>
void main ()
{
FILE * pFile;
long size;
pFile = fopen ("myfile.txt","rb");
if (pFile==NULL)
perror ("Error opening file");
else
{
fseek (pFile, 0, SEEK_END);
size=ftell (pFile);
fclose (pFile);
printf ("Size of myfile.txt: %ld bytes.\n",size);
}
getch();
}
Page 85 of 96
rewind()
Set position indicator to the beginning.
void rewind ( FILE * stream );
Sets the position indicator associated with stream to the beginning of the file.
A call to rewind is equivalent to:
fseek ( stream , 0L , SEEK_SET );
Example
/* rewind example */
#include <stdio.h>
#include <conio.h>
void main ()
{
int n;
FILE * pFile;
char buffer [27];
feof()
Checks whether the End-of-File indicator associated with stream is set, returning a value
different from zero if it is.
This indicator is generally set by a previous operation on the stream that reached the End-
of-File.
int feof ( FILE * stream );
Further operations on the stream once the End-of-File has been reached will fail until
either rewind, fseek or fsetpos is successfully called to set the position indicator to a new
value.
Page 86 of 96
Example…
/* feof example: byte counter */
#include <stdio.h>
#include <conio.h>
void main ()
{
FILE * pFile;
long n = 0;
pFile = fopen ("myfile.txt","rb");
if (pFile==NULL) perror ("Error opening file");
else
{
while (!feof(pFile))
{
fgetc (pFile);
n++;
}
fclose (pFile);
printf ("Total number of bytes: %d\n", n-1);
}
getch();
}
ferror()
Checks if the error indicator associated with stream is set, returning a value different
from zero if it is.
This indicator is generaly set by a previous operation on the stream that failed.
int ferror ( FILE * stream );
Example
/* ferror example: writing error */
#include <stdio.h>
#include <conio.h>
void main ()
{
FILE * pFile;
pFile=fopen("myfile.txt","r");
if (pFile==NULL)
perror ("Error opening file");
else
{
fputc ('x',pFile);
Page 87 of 96
if (ferror (pFile))
{
printf ("Error Writing to myfile.txt\n");
}
fclose (pFile);
}
getch();
}
Example
void main ()
{
FILE * pFile;
long lSize;
char * buffer;
size_t result;
Page 88 of 96
if (pFile==NULL) {fputs ("File error",stderr); exit (1);}
// terminate
fclose (pFile);
free (buffer);
getch();
}
fwrite()
Writes an array of count elements, each one with a size of size bytes, from the block of
memory pointed by ptr to the current position in the stream.
The postion indicator of the stream is advanced by the total number of bytes written.
The total amount of bytes written is (size * count).
Syntax
size_t fwrite
(const void * ptr, size_t size, size_t count, FILE * stream);
Parameters
ptr
Pointer to the array of elements to be written.
size
Size in bytes of each element to be written.
count
Number of elements, each one with a size of size bytes.
stream
Pointer to a FILE object that specifies an output stream.
Example
Page 89 of 96
/* fwrite example : write buffer */
#include <stdio.h>
#include <conio.h>
void main ()
{
FILE * pFile;
char buffer[ ] = { 'x' , 'y' , 'z' };
pFile = fopen ( "myfile.bin" , "wb" );
fwrite (buffer , 1 , sizeof(buffer) , pFile );
fclose (pFile);
getch();
}
Page 90 of 96
int main ( int argc, char *argv[ ] )
The integer, argc is the argument count.
It is the number of arguments passed into the program from the command line,
including the name of the program.
The array of character pointers is the listing of all the arguments.
argv[0] is the name of the program, or an empty string if the name is not available.
After that, every element number less than argc is a command line argument.
You can use each argv element just like a string, or use argv as a two dimensional
array.
argv[argc] is a null pointer.
How could this be used? Almost any program that wants its parameters to be set
when it is executed would use this.
One common use is to write a function that takes the name of a file and outputs the
entire text of it onto the screen.
Example…
#include <stdio.h>
#include <conio.h>
void main ( int argc, char *argv[] )
{
if ( argc != 2 ) /* argc should be 2 for correct execution */
{
/* We print argv[0] assuming it is the program name */
printf( "usage: %s filename", argv[0] );
}
else
{
// We assume argv[1] is a filename to open
FILE *file = fopen( argv[1], "r" );
Page 91 of 96
while ( ( x = fgetc( file ) ) != EOF )
{
printf( "%c", x );
}
fclose( file );
}
}
getch();
}
Ch-9 Misc
Type Casting
Typedef
Symbolic Constants
C Preprocessors
Page 92 of 96
Type Casting
Previously, you learned that the value of a variable is stored as a sequence of bits, and the
data type of the variable tells the compiler how to translate those bits into meaningful
values.
Often it is the case that data needs to be converted from one type to another type.
This is called type casting.
It refers to different ways of, implicitly or explicitly, changing an entity of one data
type into another.
This is done to take advantage of certain features of type hierarchies or type
representations.
There are two methods:
o Implicit
o Explicit
1. Implicit Conversion
Implicit type conversion is done automatically by the compiler whenever data from
different types is intermixed.
When a value from one type is assigned to another type, the compiler implicitly converts
the value into a value of the new type.
Example…
short int int unsigned int long int unsigned long int float double long
double.
2. Explicit Conversion
It has higher priority than Implicit Conversion.
Syntax:
(data_type) operand
Operand can be variable or phrase.
Typedef
C provides a feature called “TYPEDEF” that allows user to define an identifier that
would represent an existing data type.
Typedef is used to redefine the name of an existing variable type.
Syntax:
typedef data_type variable;
Advantage:
We can create meaningful data type names for increasing the readability of the
program.
Page 93 of 96
Example:
typedef int dig;
typedef float avg;
Symbolic Constants
Constants defined in the header file are called symbolic constants.
They are also known as MACRO PRE-PROCESSOR.
Constants values are assigned to the variable at beginning of the program.
It can be defined using pre-processor directive #define.
Naming conventions are same as variable names.
Value of Symbolic constants can’t be changed during execution of program.
They are written in CAPS form, just to make difference from other variables.
Features are:
1. Modifiability
2. Understandability
Example:
#define PI 3.14
C Preprocessors
It is a program that processes the source code before it passes through the compiler.
A preprocessor directive begins with a # symbol. Preprocessor directives may be placed
anywhere in the program but are generally placed in the beginning of the program.
The different preprocessor directives are:
1. Macro expansion (#define)
2. File Inclusion (#include)
3. Conditional compilation (#ifdef)
Page 94 of 96
replaces it with the expansion.
Macro expansion makes the program easier to read and modify.
Since the template MAX is used in the program it indicates some maximum
value.
Also any modifications to the value can be made at the definition. Hence the
entire program need not be changed.
Macro with arguments:
#define AREA(x) (3.14*x*x)
Page 95 of 96
#endif
#if TEST>10
#endif
}
Page 96 of 96