CP Notes
CP Notes
ON
COMPUTER PROGRAMMING
Ms.K.Sirisha
Asst.Professor
e
UNIT - I
Overview of Computers and Programming - Electronic Computers Then and Now – Computer
Hardware - Computer Software - Algorithm - Flowcharts - Software Development Method –
Applying the Software Development Method.
Types, Operators and Expressions: Variable Names - Data Types and Sizes - Constants -
Declarations - Arithmetic Operators - Relational and Logical Operators - Type Conversions -
Increment and Decrement Operators - Bitwise Operators - Assignment Operators and Expressions -
Conditional Expressions - Precedence and Order of Evaluation.
UNIT - II
Selections Statements – Iteration Statements – Jump Statements- Expression Statements – Block
Statements.
Single Dimensional Arrays – Generating a Pointer to an Array – Passing Single Dimension Arrays to
Functions – Strings – Two Dimensional Arrays – Indexing Pointers – Array Initialization – Variable
Length Arrays
UNIT - III
Pointer Variables – Pointer Operators - Pointer Expressions – Pointers And Arrays – Multiple
Indirection – Initializing Pointers – Pointers to Functions – C‟s Dynamic Allocation Functions –
Problems with Pointers.
Understanding the scope of Functions – Scope Rules – Type Qualifiers – Storage Class Specifiers-
Functions Arguments –The Return Statement.
UNIT - IV
Command line arguments – Recursion – Function Prototypes – Declaring Variable Length Parameter
Lists
K.Sirisha, Asst. Prof., Dept. of CSE, CREC Page 2
Structures – Arrays of Structures – Passing Structures to Functions – Structure Pointers – Arrays and
Structures within Structures – Unions – Bit Fields – Enumerations – typedef
UNIT - V
Reading and Writing Characters – Reading and Writing Strings – Formatted Console I/O – Printf -
Scanf – Standard C Vs Unix File I/O – Streams and Files – File System Basics – Fread and Fwrite –
Fseek and Random Access I/O – Fprintf ( ) and Fscanf( ) – The Standard Streams – The
Preprocessor Directives #define and #include.
Text Books:
1. “The Complete Reference C”- Fourth Edition- Herbert Schildt- McGrawHill Eduction.
2. “The C Programming Language” Second Edition- Brain W. Kernighan- Dennis M. Ritchie-
Prentice Hall-India. (UNIT- I)
References:
1. Programming in C, Second Edition – Pradip Dey, Manas Ghosh, Oxford University Press.
2. “C From Theory to Practice”- George S. Tselikis- Nikolaos D. Tselikas- CRC Press.
3. “Programming with C”- R S Bichkar- University Press.
4. Programming in C and Data Structures, J.R.Hanly, Ashok N. Kamthane and A.Ananda Rao,
Pearson Education. (UNIT-I)
5. Computer Fundamentals and C Programming- Second Edition- P.Chenna Reddy.
Outcomes:
s in designing the solutions for a wide-range of problems
ÿ This is smaller and lighter than the CRT which makes them for use with portable
laptops and palmtops.
ÿ It is also called TFT display [Thin Film Transistors].
ÿ CRT monitors are big and require lot of power where as LCD’s use less power
and occupies less space.
Printers:
ÿ It is a hard copy output device. They can produce text and images on paper. They
can produce both color and black & white prints.
ÿ It can be divided in to two categories.
Impact printers:
ÿ In these printers, there is a mechanical contact between the print head and paper.
ÿ They are having low operating speed and can print on continuous stationary.
ÿ They are having low resolution i.e., print quality is poor. They are very slow and
very noisy.
ÿ The impact printers come in lot of varieties, important two types of printers are
o Dot-Matrix printer
o Drum printer
Utilities:
ÿ These are application programs that help the computer by performing housekeeping functions
like backup, scanning virus, disk de-fragmentation, etc.
ÿ These are helpful programs that ensure the smooth functioning of the computer.
Business Software:
ÿ This type of software is developed based on requirements of a particular business.
ÿ Examples are Inventory Management System, Railway Reservation System, and Hospital
Management System. . . . .
Selection
ÿ We understand that the algorithms written in sequence fashion are not reliable. There must be a
procedure to handle operation failure occurring during execution.
ÿ The selection of statements can be shown as follows
if(condition)
Statement-1;
else
Statement-2;
ÿ The above syntax specifies that if the condition is true , statement-1 will be executed otherwise
statement-2 will be executed.
ÿ In case the operation is unsuccessful. Then sequence of algorithm should be changed/ corrected
in such a way that the system will re-execute until the operation is successful.
Example:
// Person eligibility for vote
Step 1 : start
Step 2 : read age
Step 3 : if age > = 18 then step_4 else step_5
Step 4 : write “person is eligible for vote”
Step 5 : write “ person is not eligible for vote”
Step 6 : stop
Iteration
ÿ In a program, sometimes it is very necessary to perform the same action for a number of times.
ÿ If the same statement is written repetitively, it will increase the program code.
K.Sirisha, Asst. Prof., Dept. of CSE, CREC Page 17
ÿ To avoid this problem, iteration mechanism is applied.
ÿ The statement written in an iteration block is executed for a given number of times based on
certain condition.
Example:
Step 1 : start
Step 2 : read n
Step 3 : repeat step 4 until n>0
Step 4 : (a) r=n mod 10
(b) s=s+r
(c) n=n/10
Step 5 : write s
Step 6 : stop
5. FLOWCHART
Introduction:- flowchart is an alternative technique for solving a problem. Instead of descriptive
steps, we use pictorial representation for every step.
Definition:-
Flowchart is a diagrammatic or pictorial representation of various steps involved I the
Algorithm
∑ A complete flowchart enables us to organize the problem into a plan of actions i.e. it
specifies what comes first, second, third . . . .
∑ Flowchart also represents the flow of data.
∑ It is an easy way to solve the complex problems because it makes the reader to flow the
process quickly from the flowchart incited of going through text.
∑ A flowchart is a set of symbols that indicates various operations in a program.
∑ For every process there is a corresponding symbol in the flowchart.
∑ Once the algorithm is written, its pictorial representation can be done using flowchart
symbol.
Symbol Description
Start/Stop
Decision
Connector
Process
Input/output
Loop
Predefined Process
System Analysis
At this step the developers decide a roadmap of their plan and try to bring up the best software
model suitable for the project. System analysis includes Understanding of software product
limitations, learning system related problems or changes to be done in existing systems beforehand,
identifying and addressing the impact of project on organization and personnel etc. The project
team analyzes the scope of the project and plans the schedule and resources accordingly.
Software Design
Next step is to bring down whole knowledge of requirements and analysis on the desk and design
the software product. The inputs from users and information gathered in requirement gathering
phase are the inputs of this step. The output of this step comes in the form of two designs; logical
design and physical design. Engineers produce meta-data and data dictionaries, logical diagrams,
data-flow diagrams and in some cases pseudo codes.
Coding
This step is also known as programming phase. The implementation of software design starts in
terms of writing program code in the suitable programming language and developing error-free
executable programs efficiently.
Testing
An estimate says that 50% of whole software development process should be tested. Errors may
ruin the software from critical level to its own removal. Software testing is done while coding by
the developers and thorough testing is conducted by testing experts at various levels of code such as
module testing, program testing, product testing, in-house testing and testing the product at user’s
end. Early discovery of errors and their remedy is the key to reliable software.
Integration
Software may need to be integrated with the libraries, databases and other program(s). This stage of
SDLC is involved in the integration of software with outer world entities.
Maintenance
This phase confirms the software operation in terms of more efficiency and less errors. If required,
the users are trained on, or aided with the documentation on how to operate the software and how to
keep the software operational. The software is maintained timely by updating the code according to
the changes taking place in user end environment or technology. This phase may face challenges
from hidden bugs and real-world unidentified problems.
7. Introduction to C:
ÿ ‘C’ is a Structured Programming Language
ÿ It is considered as a middle level language as it supports some of the features of low level
language also.
ÿ ‘C’ is a case sensitive language i.e., upper case letters and lower case letters are distinct.
ÿ It is well suitable for developing application software as well as system software.
ÿ It supports the concept of “Modular Programming”, which means that a larger task is divided in
to a number of sub tasks each subtask is referred to as a “module” or a “function”.
ÿ Due to this modular programming, it is easy to identify and rectifies the errors. Execution speed
also increases.
ÿ ‘C’ language is highly portable. i.e., a ‘C’ program written for one computer can be easily run in
another computer under certain conditions.
ÿ It supports data structures like arrays, pointers, structures and unions.
ÿ The power of ‘C’ is increased due to the support of a number of library (or) inbuilt functions.
ÿ ‘C’ has a special type of operators called “Bitwise” operators.
7.1 History of ‘C’:
Year Language Developer
8. C-Tokens:
These are smallest individual units. They may represent a single character (or) a group of characters
which has a specific meaning.
ÿ The following are the ‘c’ tokens that can be recognized by “C compiler”.
C-Tokens
Data Types
Primary data type User defined data type Derived data type Empty data type
Functions
Charater Enum
Structures
Float
Pointers
Double
K.Sirisha, Asst. Prof., Dept. of CSE, CREC Page 23
Primary
Data Type Size (in bytes) Range
int 2 -32768 to 32767
unsigned int 2 0 to 65535
signed 2 -32768 to 32767
short 2 -32768 to 32767
unsigned short 2 0 to 65535
signed short 2 -32768 to 32767
long 4 -2147483648 to
2147483647
unsigned long 4 0 to 4294967295
signed long 4 -2147483648 to
2147483647
char 1 -128 to 127
unsigned char 1 0 to 255
signed char 1 -128 to 127
float 4 3.4E -38 to 3.4E +38
double 8 1.7E -308 to 1.7E +308
long double 10 34E -4932 to 34E +4932
Note:
ÿ Float is a single precision value. {After decimal 7 digits has been considered}
ÿ Double is a double precision value. {After decimal 14 digits has been considered}
ÿ In-Built data Types are supported by ‘C’ compiler by default.
1. Character (Denoted as "char" in C programming language)
Description: A character denotes any alphabet, digit or special symbol used to represent in
formation and it is used to store a single character.
Storage space: 1 byte
Format: %c
Range of Values: ASCII Character Set.
2. Integer (Denoted as "int" in C programming language)
Description: Integer type is used to store positive and negative integer.
Storage space: 2 bytes.
K.Sirisha, Asst. Prof., Dept. of CSE, CREC Page 24
Format: %d
Range of values: -327687 to +32767.
3. Float point (Denoted as "float" in C programming language)
Description: It is used to store real number, with single precision floating point number (precision of
6 digits after decimal points.)
Storage space: 4 bytes.
Format: %f
Range of values: -3.4*1038 to +3.4*1038.
4. Double (Denoted as "double" in C programming language)
Description: It stores real numbers with double precision. The use of double doesn't guarantee to
double the number of significant digits in our result, but it improves the accuracy of the
arithmetic and reduces the accumulation of rounding errors.
Storage Space: 8 bytes.
Format: %ld
Range of values: -1.7*10308 to +1.7*10308.
void:
ÿ It is a special data type used for
o To specify that a function doesn’t returns any value.
o To specify a function takes no arguments.
o To create generic pointers.
Eg: 1. void print (void)
2. void *ptr
Constants:
ÿ These are fixed values that will not change during the execution of program.
Integer Constant:
An integer constant is an integer valued numbers.
Rules for Constructing Integer Constant:
ÿ It shouldn’t have a decimal point.
ÿ An integer constant must have at least one digit.
ÿ Commas, Blank spaces, special characters can’t be included with in the constants.
ÿ The constant can be preceded by a minus sign if desired.
ÿ The range of integer constants is -32,768 to 32,767
Character Constants:
ÿ A character constant is a single character enclosed in single quotation marks. The Max length of
character constant is “one”. The single character can be either alphabet (or) Digit (or) a special
symbol.
ÿ Eg: ‘a’, ‘1’, ‘?’.
Note: Most computers make use of the “ASCII” {American Standard Code for Information
Interchange”}, character set, in which each individual character is numerically encoded.
ÿ ASCII code is a 7 bit code. ASCII values ranges from 0-127.
Escape Sequences:
ÿ The Escape Sequence characters are used to denote non-graphic characters and other special
characters for a specific operation.
ÿ Some of the Escape Sequence characters are listed.
Escape Sequences Character Meaning
\a Alert a bell character
\n New line {line feed}
\t Horizontal Tab
\b Back Space
\r Carriage return
K.Sirisha, Asst. Prof., Dept. of CSE, CREC Page 27
String Constants:
ÿ A String Constant consists of any number of consecutive characters enclosed in double
quotation marks.
Eg: “ved”, “college”, “ “.
Variable:
ÿ A variable is an identifier that is used to represent a single data item.
ÿ The data may be numerical quantity (or) a character constant.
ÿ The data item must be assigned a value to the variable at some point in the program. Then data
item can be accessed by referring to the variable name
ÿ In other words, a variable is an identifier which changes its value during the execution of the
program.
Rules for Constructing a Variable:
ÿ A variable name is a combination of alphabets, digits and underscore.
ÿ Other than the underscore no special characters is allowed.
ÿ The first character in the variable name must be an alphabet.
ÿ The variable name should not be of keyword.
10. Operators
ÿ An operator is a symbol that informs to the computer to perform a particular task.
ÿ The data items that operators act upon are called “operands”.
ÿ If the operator requires only one operant then it is called “unary operator”. If it requires two
then it is called “Binary Operator”.
ÿ ‘C’ language supports a different set of operators which are listed below.
o Arithmetic Operators
o Relational Operators
o Logical Operators
o Assignment Operators
o Increment / Decrement Operators
o Bit wise Operators
o Unary Operators
o Conditional Operators
o Special Operators
Relational Operators:
ÿ Relational Operators are used to perform comparison between two values.
ÿ These operators’ returns true (1) if the comparison condition is true otherwise false (0).
ÿ The operators used for comparison in ‘C’ are listed below.
perator Description or Action
< less than
<= less than or equal to
> greater than
>= greater than or equal to
== equal to
!= not equal to
Operator purpose
&& Logical AND
|| Logical OR
! Logical NOT
#include<stdio.h>
#include<conio.h>
void main()
{
clrscr();
printf("condition : Return values\n");
printf("\n9>5&&8<10:%5d",9>5&&8<10);
printf("\n10<9&&3>7:%5d",10<9&&3>7);
printf("\n9>6||6<2 :%5d",9>5||8<3);
printf("\n8!=8 :%5d",8!=8);
printf("\n9!=10 :%5d",9!=10);
getch();
}
K.Sirisha, Asst. Prof., Dept. of CSE, CREC Page 31
Assignment Operators:
ÿ This operator is used to assign a constant value (or) the result of an expression to a variable.
ÿ In this operation Right hand side expression is evaluated first and then the result is assigned to
left hand side variable.
Operator Meaning
= Assign Right Hand value to LHS value
+= Value of LHS add to value of RHS and assign it back to the variable in
LHS
Eg: a+=2=> a = a+2
-= Value of RHS variable will be subtracted from the value of LHS and
assign it back to the variable in LHS.
Eg: a-=2 => a = a-2
*= Value of LHS variable will be multiplied to the value of RHS and
Assign it back to the variable in LHS.
Eg: a*=2 => a=a*2
/= Value of LHS variable will be divided by the value of RHS and
Assign it back to the variable in LHS.
Eg: a/=2 => a=a/2
%= The Remainder will be stored back to the LHS after integer, division
Is carried out between the LHS variable and RHS variable.
Eg: a%=2 => a=a%2
>>= Right shift and assign the value to the LHS.
Eg: a>> =2 => a=a>>2.
<<= Left shift and assign the value to the LHS.
Eg: a<<=2 => a=a<<2.
&= Bit wise AND operation and assign the value to the LHS.
Eg: a&=b => a=a&b.
|= Bit wise OR operation and assign the value to LHS.
Eg: a|=b => a=a | b
~= Bit wise complement and assign the value to LHS.
Special Operators:
ÿ In addition to the above operators ‘C’ language supports some special operators like comma
operator, parenthesis for grouping expression, membership operators.
C supports some special operators of interest such as comma operator, sizeof operator.
Comma Operator:
This operator is used to link the related expression together the expression is
separated by the, operator.
e.g.: a=(x=6,y=7,x+y);
This expression first assigns 6 to x and 7 to y then assigns (6+7) to a.
Size of Operator:
Member operator:
These are used to access member of structures and unions.
e.g.:
var member 1;
When var is a structure variable.
var ‡member 2;
When var is pointer to structure variable.
Entry
Condition False
True
If block
Entry
Condition
True False
Using of one if-else statement in another if-else statement is called as nested if-else
control statement.
When a series of decisions are involved, we may have to use more than one if-else
statement in nested form.
Syntax:
if ( Test Condition1)
{
if ( Test Condition2)
{
Statement -1;
}
else
{
Statement -2;
}
}
Entry
True False
Condition1
Condition2 Condition3
True Block Code False Block Code True Block Code False Block Code
{
Statement -1;
}
else if ( Test Condition -2)
{
Statement -2;
}
else if ( Test Condition -3)
{
Statement -3;
}
else
{
default statement;
}
Syntax:
Switch (variable or expression)
{
Case Constantvalue-1: Block -1;
(Or)
Statement-1;
break;
Case Constantvalue-2: Block -2;
(Or)
Statement-2;
break;
Case Constant value-n: Block -n;
(Or)
Statement-n;
break;
default: default – block;
}
(iii) The updation (increment or decrement operations) decides how to make changes in the loop.
∑ The body of the loop may contain either a single statement or multiple statements.
Flowchart:
Syntax:
Initialization Expression;
do
{
Body of the loop
Updation Expression;
} while ( Test Condition);
∑ C supports the “goto” statement to branch unconditionally from one point to another in the
program.
∑ Although it may not be essential to use the “goto” statement in a highly structured language
like “C”, there may be occasions when the use of goto is necessary.
∑ The goto requires a label in order to identify the place where the branch is to be made.
∑ A 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.
∑ The label can be anywhere in the program either before or after the goto label statement.
Syntax:
goto label;
.............
.............
.............
label:
statement;
4. Arrays
The fundamental data types, namely char int, float, and double are used to store only one
value at any given time. Hence these fundamental data types can handle limited amounts of data.
In some cases we need to handle large volume of data in terms of reading, processing and
printing. To process such large amounts of data, we need a powerful data type that would
facilitate efficient storing, accessing and manipulation of data items. For example: If the user
wants to store marks of 100 students. This can be done by creating 100 variables individually
but, this process is rather tedious and impracticable. This type of problem can be handled in C
programming using arrays.
Array:
C Array is a collection of variables belongings to the same data type. You can store group of
data of same data type in an array.
(Or)
An array is collection of homogeneous elements in a single variable.
∑ Array might be belonging to any of the data types
∑ Array size must be a constant value.
∑ Always, adjacent memory locations are used to store array elements in memory.
∑ Individual values are called as elements.
∑ It allocates sequential memory locations.
We can use arrays to represent not only simple lists of values but also tables of data in two or
three or more dimensions.
∑ One – dimensional arrays
∑ Two – dimensional arrays
∑ Multidimensional arrays
∑ The data type specifies the type of element that will be contained in the array, such as int,
float, or char.
∑ The size indicates the maximum number of elements that can be stored inside the array.
For example:
int age[5];
Here, the name of array is age. The size of array is 5, i.e., there are 5 items (elements) of
array age. All elements in an array are of the same type (int, in this case).
Array elements:
Size of array defines the number of elements in an array. Each element of array can be
accessed and used by user according to the need of program.
For example: int age [5];
Array Elements
Syntax:
datatype array_name[size] = { list of values };
You can initialize array in C either one by one or using a single statement as follows:
int age[5]={2,6,34,5,1};
int age[]={2,6,34,5,1};
In this case, the compiler determines the size of array by calculating the number of elements of an
array.
int age[2]=34;
int age[3]=5;
Definition:
A list of items can be given one variable name using two subscripts and such a variable is called
a two–sub scripted variable or a two – dimensional array.
Two – Dimensional arrays can be declared as.
Syntax:
<datatype> <variable-name>[row-size][column-size];
Row-0 89 77 84
Row-1 98 89 80
Row-2 75 70 80
Row-3 60 75 80
Row-4 84 80 75
∑ This initializes the elements of first row to zero and the second row to one.
∑ This initialization is done row by row.
∑ The above statement can be equivalently written as
int table[2][3] ={{0,0,0},{1,1,1}};
int table[2][3] = {
{0,0,0},
{1,1,1}
};
∑ Commas are required after each brace that closes of a row, except in case of last row.
∑ If the values are missing in an initialize, they are automatically set to zero.
Ex: int table [2] [3] = {
{1,1}, 1 1 0
{2} 2 0 0
};
∑ We can also initialize a two – dimensional array in the form of a matrix as shown.
int table[2][3] = {
{
{0,0,0},
{1,1,1}
},
{
{6,6,6},
{7,7,7}
}
};
5. Strings
String is a collection of characters positioned sequentially one after the other, used to represent
names of items, persons, cities, countries and etc. To handle strings there is no direct datatype in c,
instead we have to access them as a normal array of characters. Which is terminated by a null
character ‘\0’, thus a null-terminated string contains the characters that comprise the string followed
by a null. This null character indicates the end of the string.
Strings are always enclosed by double quotes, whereas, character is enclosed by single quotes in
C.
If we declare char arr[20]; means ‘arr’ is an array name with the maximum capacity of 20
characters, it can hold a string with a maximum length of 19 characters and 1 byte for null
character.
Example for C string:
char string[20] = { ‘w’ , ’e’ , ‘l’ , ‘c’ , ‘o’ , ‘m’ , ‘e’ ,’-’ , ‘t’ , ‘o’ ,’-’, ’c’ , ‘r’ , ‘e’ , ‘c’ , ‘\0’}; (or)
char string[20] = “welcome-to-crec ”; (or)
char string [] = “welcome-to-crec ”;
Difference between above declarations are, when we declare char as “string[20]“, 20 bytes of
memory space is allocated for holding the string value.
When we declare char as “string[]”, memory space will be allocated as per the
requirement during execution of the program.
1) strlen( ) Function: strlen( ) function is used to find the length of a character string.
Example: int n;
char st[20] = “Bangalore”;
n = strlen(st);
∑ This will return the length of the string 9 which is assigned to an integer variable n.
∑ Note that the null character “\0‟ available at the end of a string is not counted.
2) strcpy( ) Function: strcpy( ) function copies contents of one string into another string. Syntax
for strcpy function is given below.
Ex : char city[15];
strcpy(city, “BANGALORE”) ;
This will assign the string “BANGALORE” to the character variable city.
Example :
strcat ( str2, str1 ); - str1 is concatenated at the end of str2.
strcat ( str1, str2 ); - str2 is concatenated at the end of str1.
Example:
strncat ( str2, str1, 3 ); – First 3 characters of str1 is concatenated at the end of str2.
strncat ( str1, str2, 3 ); - First 3 characters of str2 is concatenated at the end of str1.
strcmp( ) function is case sensitive. i.e., “A” and “a” are treated as different characters.
Example:
char city[20] = “Madras”;
char town[20] = “Mangalore”;
strcmp(city, town);
This will return an integer value “-10‟ which is the difference in the ASCII values of the first
mismatching letters “D‟ and “N‟.
* Note that the integer value obtained as the difference may be assigned to an integer variable as
follows:
int n;
n = strcmp(city, town);
K.Sirisha, Asst. Prof., Dept. of CSE, CREC Page 62
5) strcmpi() function: strcmpi( ) function in C is same as strcmp() function. But, strcmpi( )
function is not case sensitive. i.e., “A” and “a” are treated as same characters. Whereas, strcmp()
function treats “A” and “a” as different characters.
∑ strcmpi() function is non standard function which may not available in standard library.
∑ Both functions compare two given strings and returns zero if they are same.
∑ If length of string1 < string2, it returns < 0 value. If length of string1 > string2, it returns > 0
value.
Syntax:
int strcmpi ( const char * str1, const char * str2 );
Example:
m=strcmpi(“ DELHI ”, “ delhi ”); m = 0.
Syntax:
char *strlwr(char *string);
strlwr( ) function is non standard function which may not available in standard library in C.
7) strupr() function: strupr( ) function converts a given string into uppercase.
Syntax:
char *strupr(char *string);
strupr( ) function is non standard function which may not available in standard library in C.
This function reverses all the characters on a given string except null character in the last index.
9) strchr() function: strchr( ) function returns pointer to the first occurrence of the character in a
given string.
Syntax:
char *strchr(const char *str, int character);
11) atoi() function: It converts string-value to numeric-value and it converts a numeric-string value
to equivalent integer-value.
Syntax:
int atoi(string);
int arr[5]={ 1, 2, 3, 4, 5 };
Assuming that the base address of arr is 1000 and each integer requires two byte, the five element
will be stored as follows
Here variable arr will give the base address, which is a constant pointer pointing to the
element, arr[0]. Therefore arr is containing the address of arr[0] i.e 1000.
int *p;
Now we can access every element of array arr using p++ to move from one element to another.
NOTE : You cannot decrement a pointer once incremented. p-- won't work.
Pointer to Array
As studied above, we can use a pointer to point to an Array, and then we can use that pointer to
access the array. Lets have an example,
int i;
printf("%d", *p);
p++;
In the above program, the pointer *p will print all the values stored in the array one by one. We can
also use the Base address (a in above case) to act as pointer and print all the values.
A multidimensional array is of form, a[i][j]. Lets see how we can make a pointer point to such an
array. As we know now, name of the array gives its base address. In a[i][j], a will give the base
address of this array, even a+0+0 will also give the base address, that is the address
of a[0][0] element.
Here is the generalized form for using pointer with multidimensional arrays.
*(*(ptr + i) + j)
is same as
a[i][j]
Pointer can also be used to create strings. Pointer variables of char type are treated as string.
This creates a string and stores its address in the pointer variable str. The pointer str now points to
the first character of the string "Hello". Another important thing to note that string created
using char pointer can be assigned a value at runtime.
The content of the string can be printed using printf() and puts().
printf("%s", str);
puts(str);
Notice that str is pointer to the string, it is also name of the string. Therefore we do not need to use
indirection operator *.
Array of Pointers
We can also have array of pointers. Pointers are very helpful in handling character array with rows
of varying length.
char *name[3]={
"Adam",
"chris",
"Deniel"
};
char name[3][20]= {
"Adam",
"chris",
"Deniel"
};
The ‘&’ and ‘*’ operators work together for referencing and de-referencing.
This referencing operator is also called address operator, which gives the address of a
variable, in which location the variable is resided in the memory.
Syntax: &variable-name;
k variable name
For example: int k=10; 10 value
This operator is used to get the value at a given address. For example,*(2020)‡ 10;
The value at address 2020 is 10, this is k’s value
The action of ‘de-referencing operator’ is just contrary to the action of referencing
operator, this is also called ‘indirection operator’ as it changes the direction of control from
location to another location within the program’s memory to access the required data,
Syntax: *addressable _expression;
*&k‡*2020‡10
*&k‡ k ‡10
The reference operator (&) gives the address of ‘k’, whereas de-reference operator (*)
gives value in that address, so finally it is ‘k’ value.
1.1 Declaration:
To differentiate ordinary variables from pointer variable, the pointer variable should
proceed by called “value at address operator”. It returns the value stored at particular address. It
is also called an indirection operator (symbol *).
Pointer variables must be declared with its type in the program as ordinary variables.
Without declaration of a pointer variable we cannot use in the program.
A variable can be declared as a pointer variable and it points to starting byte address of
any data type.
Syntax:
data type *pointer variable;
In the first declaration v is a variable of type integer and p is a pointer variable. v stores value, p
stores address
In the 2nd declaration x is a pointer variable of floating point data type.
Pointer variables are initialized by p=&v, it indicates p holds the starting address of integer
variable v.
int v=20,*p;
1. A pointer variable can be assigned to another pointer variable, if both are pointing to the same
data type.
2. A pointer variable can be assigned a NULL value.
3. A pointer variable cannot be multiplied or divided by a constant.
Example: p*3 or p/3 where p is a pointer variable
If both p1, p2 are pointers to same way then p2-p1 gives the number of elements between p1, p2
main ( )
{
int a=10, b=20;
swap(&a, &b); /* a,b are actual parameters */
printf (“a= %d \t b=%d ”, a ,b);
}
void swap (int *x , int *y) /* x, y are formal parameters */
{
int t;
t = *x;
*x=*y;
*y=t;
}
Output:
a=20 b= 10
Output:
Enter string a: computer
Enter string b: science
Before copy
a=computer and b= science
After copy
a=science and b=science
Pointer can be used with array for efficient programming. The name of an array itself
indicates the stating address of an array or address of first element of an array.
That means array name is the pointer to starting address or first elements of the array. If
A is an array then address of first element can be expressed as &A[0] or A. The Compiler
defines array name as a constant pointer to the first element.
Pointers and arrays are closely related, the array expressions can be taken as pointer
expressions, for example x[i] can be written as *(x+i)
Hence, the expression “array name” without any index gives the address of first element which is
called base-address of array.
Assuming that the base address of arr is 1000 and each integer requires two byte, the five elements
will be stored as follows
Element arr [0] arr [1] arr [2] arr [3] arr [4]
Here variable arr will give the base address, which is a constant pointer pointing to the element,
arr[0]. Therefore arr is containing the address of arr[0] i.e. 1000.
arr is equal to &arr[0] // by default
int *p;
p = arr;
or
p = &arr[0]; //both the statements are equivalent.
Now we can access every element of array arr using p++ to move from one element to
another.
#include<stdio.h>
#include< conio.h>
void disp (int *, int);
main( )
{
int i, a[10],n;
printf (“ enter the size of an array:”);
scanf (“%d”, &n);
printf (“ enter the array elements:”);
for (i=0; i<n; i++)
scanf (“%d”, &a[i]);
disp (a,n);
printf(“ array elements after sorting ” );
for(i=0;i<n;i++)
printf (“%d”, a[i]);
}
void disp(int a[ ], int n)
{
int i,j, temp;
for (i=0; i<n; i++)
for (j=0; j<n; j++)
{
if (a[j] > a[i])
{
temp = a[ j ];
a[ j ] = a[ i ];
a[ i ] = temp;
}
}
}
Output:
Enter the size of an array: 5
Enter the array elements: 20 30 10 50 40
Array elements after sorting: 10 20 30 40 50
Pointer can also be used to create strings. Pointer variables of char type are treated as
string. Pointers are very useful in accessing character arrays. The character strings can be
assigned with a character pointer.
Example:
char array[ ] = “Love India”; //array version
char *str = "Hello";
This creates a string and stores its address in the pointer variable str. The pointer str now
points to the first character of the string "Hello". Another important thing to note that string
created using char pointer can be assigned a value at runtime.
char *str;
str = "hello"; //Legal
The content of the string can be printed using printf() and puts().
printf("%s", str);
puts(str);
Notice that str is pointer to the string, it is also name of the string. Therefore we do not
need to use indirection operator *.
Program: The following program is an example of pointer and character array.
#include<stdio.h>
#include<conio.h>
main()
{
int i;
char *p= “ Love India”;
clrscr();
while (*p! = “\0”)
{
printf (“ %c “, *p);
p++;
}
}
Output:
Love India
An integer operand can be used with a pointer to move it to a point / refer to some other
address in the memory.
In a 16 bit machine, size of all types of pointer, be it int*, float*, char* or double* is
always 2 bytes. But when we perform any arithmetic function like increment on a pointer,
changes occur as per the size of their primitive data type.
65494
int * mptr ; mptr
Assume that it is allotted the memory address 65494 increment value by 1 as follows.
++ and -- operators are used to increment, decrement a ptr and commonly used to move the ptr to
next location. Now the pointer will refer to the next location in the memory with address 65496.
C language automatically adds the size of int type (2 bytes) to move the ptr to next memory location.
mptr = mtpr + 1
= 65494 + 1 * sizeof (int)
= 65494 + 1 * 2
Similarly an integer can be added or subtract to move the pointer to any location in RAM. But the -
resultant address is dependent on the size of data type of ptr.
The step in which the ptr is increased or reduced is called scale factor. Scale factor is nothing but
the size of data type used in a computer.
We know that, the size of
float = 4
char = 1
double = 8 and so on
Example:
float *xp; (assume its address = 63498)
xp = xp + 5;
1.malloc():
The name malloc stands for "memory allocation". It allocates memory of required size
and returns the address of starting byte (base address). In this allocation raw memory, we can
store any type of data such as int, long, float, double, char, etc. So malloc() returns an address
which has no type. That is, it returns ‘void*’ type address called generic address. Unfortunately,
if memory is not available then malloc() or other functions returns NULL value.
Syntax: void* malloc(int num)
Example: pointer=malloc(no of bytes to be allocated);
P=malloc(10);
In the above example, the function malloc() allocates 10 bytes of memory in the RAM and
returns the starting byte address, which is then assigned to ‘p’. Suppose if we are going to store
array of integers then the pointer should be ‘int*’ type. malloc() returns just address which has
no type, that is it returns ‘void*’ type address. So it should be type casted as per our pointer
type.(All malloc(), calloc(), and realloc() functions return-type is void* type)
Example: int *p;
p= (int*)malloc(5*sizeof(int)); //Allocating memory for 5 integers
Accessing dynamic memory:
Accessing this memory is same as accessing elements in the array through pointer.
*(p+0)‡p[0] accesses first location
*(p+1)‡p[1] accesses second location
*(p+2)‡p[2] accesses third location
*(p+ i)‡p[i] accesses i+1th location
2.calloc():
The name calloc stands for "contiguous allocation". The only difference between malloc() and
calloc() is that, malloc() allocates single block of memory whereas calloc() allocates multiple
blocks of memory each of same size and sets all bytes to zero.
The calloc function allocates space for an array of items and it is also like malloc(), but after
allocation of memory, it clears the garbage values by filling zeros in all bytes in the memory.
K.Sirisha, Asst. Prof., Dept. of CSE, CREC Page 79
Syntax: pointer=calloc(int num, int size);
It takes two arguments, first one is number of items to be allocated and second one is size of
the item.
Example: float *p;
p=(float*)calloc(5,sizeof(float)); //allocating memory for 5 float numbers
3.realloc():
The name realloc() stands for “reallocation”. If the previously allocated memory is
insufficient or more than sufficient. Then, you can change memory size previously allocated using
realloc().
It is used to resize (reduce or expand) the memory which is already allocated using
“malloc()” or “calloc()” or “realloc()”. It takes base address of previously allocated memory and
new size which is currently required.
While expanding the memory size using “realloc()”, if the required amount of memory is not
available at the consecutive locations, then allocates memory at another available location, and
copies the existing contents to the newly allocated memory area and then releases the old memory.
If the memory is not available, then it returns null.
Function prototype
The programmer defined function has always precede main. The general for of a function prototype
is
Datatype fun-name(type1 arg1, type2 arg2, type3 arg3 . . . . . . . . . . . type-n arg-n)
Library functions:
They are predefined in the standard library of ‘c’. We need to include the library functions
such as sin(x), cos(x), pow(x), sqrt(n) etc. The code of these functions is not available to the user. So
they can not modify these functions.
User defined functions:
These functions are used need to be developed by the user at the time of program writing.
Functions break large computing tasks into smaller ones, which help in the modular development of
big program.
There are three steps involved in creating and using of User Defined functions.
1. Declaring of function prototype.
2. Defining a function.
Structure chart
¸ The main module is known as a calling module because it has sub modules.
¸ Each of the sub modules is known as a called module.
¸ But because module 1, 2 &3 also have sub modules they are also called modules, they are
both called and calling modules.
¸ The technique used to pass data to a function is known as “parametric passing”.
return (expression):
This statement returns the value of expression to be called function.
E.g: return (a, b)
return (a);
return:
int sum()
{
int a=10,b=20,c;
c=a+b;
return(c);
}
K.Sirisha, Asst. Prof., Dept. of CSE, CREC Page 87
Functions with arguments and with return values:
These are the functions in which parameters are passed from calling function to called
function and the values are returned from called function to calling function.
#include<stdio.h>
int sum(int,int);
void main()
{
int a=10,b=20,c;
c=sum(a,b);
printf("sum of 2 no is %d",c);
}
int sum(int x,int y)
{
int z;
z=x+y;
return(z);
}
Parameter passing techniques:
There are two types of passing parameters to functions
1. Call by value
2. Call by reference
Call by values:
The process of passing the actual values of variables is known as “call by values”.
Call by reference:
The process of calling a function using pointers to pass the address of variables is
known as “call by reference”.
output
enter n value 5
n!=120.
Automatic variable:
ÿ These are declared within which they are used. They are also referred as internal (or) local
variables.
ÿ These variables are created when a function is called, and destroyed automatically when a
function is excited.
ÿ Automatic variables are given only temporary memory space.
ÿ Local variables are given the storage class auto by default. The keyword auto is used to
declare automatic variables.
ÿ The Automatic variables have two distinct advantages.
Advantages:
ÿ The memory space is used economically since it is used only as long as it is needed.
ÿ There local scope prevent from affecting other functions due to inadvertent changes.
Example program for automatic variable
#include<stdio.h>
#include<conio.h>
void main()
{
K.Sirisha, Asst. Prof., Dept. of CSE, CREC Page 90
auto int x,i;
for(i=0;i<=3;i++)
{
x=1;
x++;
printf(“the value of x in iteration%d is : %d”,i,x);
}
getch();
}
Output:
The value of x in iteration1 is :2
The value of x in iteration2 is :2
The value of x in iteration3 is :2
Register variable:
ÿ A register storage class is the same as the auto class with only one difference.
ÿ These variables are stored in CPU registers and gets default initial as “garbage value”. Any
variable which is stored in the CPU registers can be accessed faster than the one which is stored
in memory.
ÿ This is done for effciency
ÿ If a variable is used at many places it is better to declare its storage class as register.
ÿ A good example for frequently used variables in looping counter.
main ( )
{
register int i;
for (i=1; i<=10; i++)
printf(“%d”,i);
}
ÿ Here, even though we have declared the storage class of ‘i’ as register, we are not sure that
the value of ‘i’ would be stored in a CPU register. Because the number of CPU registers is
limited {14 for micro computer} and these are busy in doing some other task. In those situations
it treats them as auto.
ÿ There are some restrictions on register variables. We can’t use register storage class for all
types of variab les. Since, CPU registers are 16 bit registers. They can’t hold float (or) double
K.Sirisha, Asst. Prof., Dept. of CSE, CREC Page 91
963*.values which require 4 & 8 bytes respectively. Even though we use register for float and
double we don’t get any error because they treat as auto.
Static variable:
ÿ As the name suggest that the value of the static variable persists until at the end of the
program i.e., the contents of the variable will be retained.
ÿ A variable can be declared as static by using the keyword “static”.
ÿ A static variable may be either an internal type (or) an external type depending upon the
place of declaration.
ÿ The scope of internal static variable extends up to the end of the function in which they are
defined.
ÿ The internal static variables are similar to automatic variables. The difference between them
is the static variables do not disappear when the function is no longer active. Their values are
persisting(can not be changed).
ÿ If the control comeback to the same function again the static variables have the same value.
Internal static variables can be used to retain values between function call.
ÿ A static variable is initialized only once and it takes default initial value as zero.
ÿ When the program is compiled it will never initialized again.
#include<stdio.h>
#include<conio.h>
void main()
{
int x,i;
clrscr();
for(i=1;i<=3;i++)
{
static x=1;
x++;
printf("the value of x in itration %d is:%d\n",i,x);
}
getch();
}
Output:
External variable:
ÿ Here the variable is both alive and active throughout the entire program. They are also known
as “Global variables”.
ÿ Unlike local variables, global variables can be accessed by any function in the program.
K.Sirisha, Asst. Prof., Dept. of CSE, CREC Page 93
ÿ These variables are defined by using the keyword “extern”.
Eg: main ()
{
extern int i=5;
printf(“%d”,i);
}
ÿ We can also define these variables without using keyword. At that time we declare variables
outside the function.
int x=20;
main()
{
int y;
printf(“%d”,x);
}
ÿ The default initial value of external variable is a “garbage” value.
5.Type qualifiers: The keywords which are used to modify the properties of a variable are called
type qualifiers.
Output:
C:\tc\bin\>sum 10 20 30 40
Sum of numbers=100
Program2:
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[]) // command line arguments
{
if(argc!=5)
{
printf(“Arguments passed through command line “ \ “not equal to 5”);
return 1;
}
printf(“\n Program name : %s \n”, argv[0]);
printf(“1st arg : %s \n”, argv[1]);
printf(“2nd arg : %s \n”, argv[2]);
printf(“3rd arg : %s \n”, argv[3]);
printf(“4th arg : %s \n”, argv[4]);
printf(“5th arg : %s \n”, argv[5]);
K.Sirisha, Asst. Prof., Dept. of CSE, CREC Page 98
return 0;
}
Output:
Program name: test
1st arg: this
2nd arg: is
3rd arg: a
4th arg: program
5th arg: (null)
2. Structures
C Structure is a collection of different data types which are grouped together and each
element in a C structure is called member.
In real life we need to have different data types for ex: To maintain employee
information. We should have information such as name, age, qualification, salary etc. here to
maintain the information of employee dissimilar data types required. Name & qualification are
char data type, age is integer, and salary is float. You can create this information separately but,
better approach will be collection of this information under single name because all these
information are related to person.
Structure is a collection of heterogeneous type of data i.e. different types of data. The
various individual components, in a structure can be accessed and processed separately. A
structure is a collection of variables referenced under a name, providing a convenient means of
keeping related information. A structure declaration forms a template that may be used to create
structure objects.
Difference between C variable, C array and C structure:
∑ A normal C variable can hold only one data of one data type at a time.
∑ An array can hold group of data of same data type.
∑ A structure can hold group of data of different data types
∑ Data types can be int, char, float, double and long double etc.
Features of Structures:
To copy elements of one array to another array of same data type elements are copied one by
one. It is not possible to copy elements at a time. Where as in structure it is possible to copy the
contents of all structure elements of different data types to another structure var of its type using
assignment (=) operator. It is possible because structure elements are stored in successive
memory locations.
Nesting of structures is also possible.
Defining a structure:
‘struct’ keyword is used to define a structure, struct define a new data type which is a
collection of different type of data.
Syntax:
struct structure_name
{
//Statements
};
Example:
struct Book
{
char name[15];
float price;
int pages;
};
Suppose, if we want to access age for variable p1. Then, it can be accessed as:
P1.age;
Eg. Write a program to display student details
#include<stdio.h>
#include<conio.h>
P S1
100 BGS 45 78 47
p p‡name p‡marks1 p‡marks2 p‡marks3
printBook( &Book1 );
printBook( &Book2 );
return 0;
}
Write a program to pass address of structure variable to a user defined and display the
contents.
#include<stdio.h>
#include<conio.h>
struct book
{
char name[23];
char author[25];
int pages;
};
void main()
{
struct book b1={"java","james",998};
show(&b1);
}
show(struct book *b2)
{
clrscr();
printf(" \n %s by %s of %d pages",b2->name,b2->author,b2->pages);
getch();
}
Output:
Java by James of 998 pages
Eg:#include<stdio.h>
void main()
{
struct node
{
int data;
struct node *link;
};
struct node *a,*b,*c;
a->data=10;
b->data=20;
c->data=30;
a->link=b->link=c->link=null;
printf(“a=%d b=%d c=%d”,a->data,b->data,c->data);
getch();
}
A program to declare a self referential structure using dynamic allocation to display the
content of structure
#include<stdio.h>
void main()
{
struct node
{
int data;
struct node *next;
};
struct node *ptr;
3.UNIONS :
ÿ Union is a variable, which is similar to the structure. It contains member of members like
structure but it holds only one object at a time.
ÿ In the structure each member has its own memory location, where as members of union have
same memory location.
ÿ It can accommodate one member at a time in asingle area of storage.
ÿ Union also contains members of type int, float, long, array, pointers,etc..
ÿ It allocates fixed specific bytes of memory for access of data types irrespective of any data
type.
ÿ The union requires bytes that are equal to the number of bytes for target members.
Eg.
ÿ The union contains char, integer, long integer then the number of bytes reserved in the
memory for the union is 4 bytes.
ÿ The difference union and structure is in terms of storage. When we used unions the compiler
allocates a piece of storage that is large enough to hold.
ÿ When union is defined C reserves enough room to store the largest data object in the
construct.
ÿ Union is declared by using union key word.
Syntax:
union union-name
{
member1;
member2;
……..2
member n;
};
union union-variable;
eg:
union result
x y x&y
C provides a number of functions that helps to perform basic file operations; all these
functions are available in stdio library.
Function description
fopen() create a new file or open a existing file
fclose() closes a file
getc() reads a character from a file
putc() writes a character to a file
fscanf() reads a set of data from a file
Opening a file:
C communicates with files using a new data type 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
Syntax: FILE *output_file;
If we want to store data in a file into the secondary memory, we must specify certain things aboutthe
file to the operating system. They include the filename, data structure…
The general format of the function used for opening a file is
Syntax:
*fp = FILE *fopen(const char *filename, const char *mode);
Here filename is the name of the file to be opened and mode specifies the purpose of opening the
file. Mode can be of following types,
*fp is the FILE pointer (FILE *fp), which will hold the reference to the opened(or
created) file.
mode description
r opens a text file in reading mode
w opens or create a text file in writing mode.
a opens a text file in append mode
r+ opens a text file in both reading and writing mode
w+ opens a text file in both reading and writing mode
a+ opens a text file in both reading and writing mode
rb opens a binary file in reading mode
wb opens or create a binary file in writing mode
ab opens a binary file in append mode
rb+ opens a binary file in both reading and writing mode
Return value:
C open function returns NULL in case of failure, and returns a FILE Stream Pointer on success
Example:
#include<stdio.h>
int main()
{
FILE *fp;
fp = fopen(“fileName.txt”, “w”);
return 0;
}
∑ The above example will create file called fileName.txt
∑ The “w” means that the file is being opened for writing, and if the file does not exist then
new file will be created.
Closing a file:
∑ fclose() function is used to releases the memory stream, opened by fopen().
∑ The fclose() function is used to close an already opened 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; it is in the following format.
Syntax:
int fclose( FILE * stream );
Return value:
Here fclose() function closes the file and returns zero on success, or EOF if there is an
error in closing the file. This EOF is a constant defined in the header file stdio.h.
Reading a character from a file and writing a character into a file (getc() and putc() functions):
The getc and putc functions are analogous to getchar and putchar functions and handle one character
at a time. The putc function writes the character contained in character variable c to the file
associated with the pointer fp1. ex putc(c, fpl); similarly getc function is used to read a character
from a file that has been open in read mode. c=getc(fp2).
Program: The following program is an example to read a character from a file and to write a
character into a file
#include<stdio.h>
main()
{
FILE *fl;
char c;
printf(“Data input”);
fl =fopen(“Input.txt”, “w”); /*Open the file Input*/
while((c=getchar())!=EOF) /*get a character from key board*/
putc( c, fl); //write a character to input
fclose(fl); //close the file input
printf(‘Data output”);
fl =fopen(‘INPUT.txt” ,”r”); //Reopen the file input
while((c=getc(fl ))!=EOF)
printf(“%c”, c );
fclose(fl );
Reading a integer from a file and writing a integer into a file ( getw() and putw() functions):
These are integer-oriented functions. They are similar to getc and putc functions and are used to
read and write integer values. These functions would be useful when we deal with only integer data.
The general forms of getw and putw are: putw(integer, fp ); getw(fp);
putw() Example:
#include<stdio.h>
main()
{
FILE *fp;
fp=fopen(“file1.txt”,”w”);
putw(97,fp);
fclose(fp);
}
getw() example:
#include<stdio.h>
main()
{
FILE *fp;
int ch;
fp=fopen(“file1.txt”,”r”);
ch=getw(fp);
printf(“%d”, ch);
fclose(fp);
}
main()
{
struct emp e;
FILE *p,*q;
p = fopen(“one.txt”, “a”);
q = fopen(“one.txt”, “r”);
Output:
Enter text: Welcome
Welcome
ftell():
Functions ftell() and fseek() are important in a program performing file manipulations.
Function ftell() returns the current position of the file pointer in a stream. The return value is 0 or
a positive integer indicating the byte offset from the beginning of an open file. A return value of
-1 indicates an error. Prototype of this function is as shown below:
long int ftell(FILE *fp);
fseek():
This function positions the next I/O operation on an open stream to a new position
relative to the current position.
int fseek(FILE *fp, long int offset, int origin);
Here fp is the file pointer of the stream on which I/O operations are carried on; offset is
the number of bytes to skip over. The offset can be either positive or negative, denting forward
or backward movement in the file. Origin is the position in the stream to which the offset is
applied; this can be one of the following constants:
SEEK_SET: offset is relative to beginning of the file
SEEK_CUR: offset is relative to the current position in the file
SEEK_END: offset is relative to end of the file
Program: The following program is an example of ftell() and fseek().
#include<stdio.h>
main()
{
FILE *fp;
char ch;
fp=fopen(“fileName.txt” ,”r”);
fseek( fp,21 ,SEEK_SET);
ch=fgetc(fp);
while(!feof(fp ))
K.Sirisha, Asst. Prof., Dept. of CSE, CREC Page 121
{
printf(“%c” ,ch);
printf(“%d”, ftell(fp ));
ch= getc(fp );
}
rewind(fp );
while(!feof(fp))
{
printf(“%c” ,ch);
printf(“%d” ,ftell(fp));
ch= fgetc(fp);
}
fclose(fp );
}
Output: 0H1e2l3l4o5 6I7n8dgi10a11
SAMPLE PROJECT 1:
PROJECT NAME: EMPLOYEE RECORD SYSTEMS
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#include <windows.h> ///for windows related functions (not important)
#include <string.h>
/**
function : gotoxy
@param input: x and y coordinates
@param output: moves the cursor in specified position of console
*/
void gotoxy(int x, int y)
{
K.Sirisha, Asst. Prof., Dept. of CSE, CREC Page 122
coord.X = x;
coord.Y = y;
SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE),coord);
}
fp = fopen("EMP.DAT", "rb+");
if(fp == NULL)
{
fp = fopen("EMP.DAT", "wb+");
if(fp == NULL)
{
printf("Cannot open file");
exit(1);
K.Sirisha, Asst. Prof., Dept. of CSE, CREC Page 123
}
}
fwrite(&e,recsize,1,fp);
case '3':
system("cls");
another = 'y';
while(another == 'y')
{
printf("Enter the employee name to modify: ");
scanf("%s", empname);
K.Sirisha, Asst. Prof., Dept. of CSE, CREC Page 125
rewind(fp);
while(fread(&e,recsize,1,fp)==1)
{
if(strcmp(e.name, empname) == 0)
{
printf("\n Enter new name, age and salary: ");
scanf("%s %d %f", e.name, &e.age, &e.bs);
fseek(fp,-recsize, SEEK_CUR);
fwrite(&e,recsize,1,fp);
break;
}
}
printf("\n Modify another record(y/n)");
fflush(stdin);
another = getche();
}
break;
case '4':
system("cls");
another = 'y';
while(another == 'y')
{
printf("\n Enter name of employee to delete: ");
scanf("%s", empname);
ft = fopen("Temp.dat", "wb");
rewind(fp);
while(fread(&e,recsize,1,fp) == 1)
{
if(strcmp(e.name, empname) != 0)
{
fwrite(&e,recsize,1,ft);
}
}
K.Sirisha, Asst. Prof., Dept. of CSE, CREC Page 126
fclose(fp);
fclose(ft);
remove("EMP.DAT");
rename("Temp.dat", "EMP.DAT"); /// rename the temp file to original file name
fp = fopen("EMP.DAT", "rb+");
printf("Delete another record(y/n)");
fflush(stdin);
another = getche();
}
break;
case '5':
fclose(fp); /// close the file
exit(0); /// exit from the program
}
}
return 0;
}
OUTPUT:
1. Add Record
2. List Records
3. Modify Records
4. Delete Records
5. Exit
Your choice: 1
Enter name: sai
Enter age: 24
Enter salary: 15000.00
Add another record(y/n): n
1. Add Record
2. List Records
K.Sirisha, Asst. Prof., Dept. of CSE, CREC Page 127
3. Modify Records
4. Delete Records
5. Exit
Your choice: 2
sai 24 15000.00
1. Add Record
2. List Records
3. Modify Records
4. Delete Records
5. Exit
Your choice: 3
Enter the employee name to modify: sai
Enter new name, age, salary: sai 25 16000.00
Modify another record(y/n): n
1. Add Record
2. List Records
3. Modify Records
4. Delete Records
5. Exit
Your choice: 4
Enter name of employee to delete: sai
Delete another record(y/n): n
1. Add Record
2. List Records
3. Modify Records
4. Delete Records
5. Exit
Your choice: 5