cs8251 C Material PDF
cs8251 C Material PDF
Features of C Programming
• Easy to learn
• Structured language
• It produces efficient programs.
• It can handle low-level activities.
• It can be compiled on a variety of computer platforms
Usage of C Programming
C programming used to develop the following system programs,
• Operating Systems
• Language Compilers
• Assemblers
• Text Editors
• Print Spoolers
• Network Drivers
• Modern Programs
• Databases
• Language Interpreters
• Utilities
PSNA CET – DEPT. OF CSE – CS8251:C PROGRAMMING – Dr.J.Benadict Raja, ASP/CSE Page 2
Structure of C program
Documentation
– Non Executable statement
- To brief the program details
- Single line comment //
- Multiline comment /* ----------- */
Link section
- To link the header files to the program
- #include<stdio.h>
- #include”c:\tc\bin\myheader.c”
Definition Section
- To define constants Ex: #define pi 3.14
- To define macros Ex: #define cube(x) x*x*x
Global declaration
- The variables declared here is visible to all
- The functions declared here is visible to all
Data Types
S.N. Types and Description
1 Basic Types: They are arithmetic types and consist of the two types: (a) integer types (b)
char types and (c) floating-point types.
2 Enumerated types: They are used to define variables that can only be assigned certain
discrete integer values throughout the program.
Ex:
enum week{Mon, Tue, Wed, Thur, Fri, Sat, Sun};
int main()
{
enum week day;
day = Wed;
printf("%d",day);
return 0;
} // the variable day restricted to accept the enumerated constant listed above
3 The type void: The type specifier void indicates that no value is available.
4 Derived types: They include (a) Pointer types, (b) Array types, (c) Structure types, (d)
Union types and (e) Function types
Integer Types
Type Storage size Value range
Char 1 byte -128 to 127 or 0 to 255
unsigned char 1 byte 0 to 255
signed char 1 byte -128 to 127
int 2 or 4 bytes -32,768 to 32,767 or -2,147,483,648 to 2,147,483,647
unsigned int 2 or 4 bytes 0 to 65,535 or 0 to 4,294,967,295
Short 2 bytes -32,768 to 32,767
unsigned short 2 bytes 0 to 65,535
long 4 bytes -2,147,483,648 to 2,147,483,647
unsigned long 4 bytes 0 to 4,294,967,295
PSNA CET – DEPT. OF CSE – CS8251:C PROGRAMMING – Dr.J.Benadict Raja, ASP/CSE Page 3
Floating-Point Types
Type Storage size Value range Precision
float 4 byte 1.2E-38 to 3.4E+38 6 decimal places
double 8 byte 2.3E-308 to 1.7E+308 15 decimal places
long double 10 byte 3.4E-4932 to 1.1E+4932 19 decimal places
The void Type
Types and Description
1 Function returns as void : A function with no return value has the return type as void.
For example, void exit (int status);
2 Function arguments as void:. A function with no parameter can accept as a void.
For example, int rand(void);
3 Pointers to void A pointer of type void * represents the address of an object, but not its type.
For example, a memory allocation function void *malloc( size_t size );
Storage Classes
A storage class defines the scope (visibility) and life-time of variables and/or functions within a C
Program. These specifiers precede the type that they modify.
Types are,
• auto
• register
• static
• extern
PSNA CET – DEPT. OF CSE – CS8251:C PROGRAMMING – Dr.J.Benadict Raja, ASP/CSE Page 4
In C programming, when static is used on a class data member, it causes only one copy of that
member to be shared by all objects of its class.
#include <stdio.h> /* function definition */ Output :
/* function declaration */ void func( void ) i is 6 and count is 4
void func(void); { i is 7 and count is 3
static int count = 5; /* global variable */ static int i = 5; /* local static i is 8 and count is 2
main() variable */ i is 9 and count is 1
{ i++; i is 10 and count is 0
while(count--) printf("i is %d and count is
{ func(); %d\n", i, count);
} }
return 0;
}
The extern Storage Class
The extern storage class is used to give a reference of a global variable that is visible to ALL the
program files.
When you use 'extern', the variable cannot be initialized
When you have multiple files and you define a global variable or function, which will be used in
other files also, then extern will be used in another file to give reference of defined variable or
function.
The extern modifier is most commonly used when there are two or more files sharing the same
global variables or functions.
First File: main.c Second File: write.c
#include <stdio.h> #include <stdio.h>
int count ; extern int count;
extern void write_extern(); void write_extern(void)
main() {
{ count = 5;
write_extern(); printf("count is %d\n", count);
} }
Here, extern keyword is being used to declare count in the second file where as it has its definition
in the first file, main.c
Constants
Constants ate identifier, which values could not be changed during the program execution.
Types of constants
(1)Integer Literals(constants)
An integer literal can be a decimal (10), octal(010), or hexadecimal(0x10) constant.
(2)Character Constants
Character literals are enclosed in single quotes, e.g., 'x' can be stored in a simple variable of char
type.
A character literal can be a plain character (e.g., 'x'), an escape sequence (e.g., '\t')
(3)Floating-point Literals
A floating-point literal has an integer part, a decimal point, a fractional part, and an exponent part.
You can represent floating point literals either in decimal form or exponential form
(4)String Literals
String literals or constants are enclosed in double quotes "". A string contains characters that are
similar to character literals: plain characters, escape sequences.
Defining Constants
There are two simple ways in C to define constants −
• Using #define preprocessor. Ex: # define a 100
• Using const keyword Ex: const int a=100;
PSNA CET – DEPT. OF CSE – CS8251:C PROGRAMMING – Dr.J.Benadict Raja, ASP/CSE Page 5
Variables
Are identifiers, which values can be changed during the program execution.
Rules: Start with alphabet followed by alphabet or digits, the only allowed special character is
under score.
Keywords
The reserved word of the language, could not be used for other purpose,
Void main int char float double long
Short signed unsigned if else switch case
Default while do for break continue goto
Auto static register extern auto struct sizeof
Operators
An operator is a symbol that tells the compiler to perform specific mathematical or logical
manipulations.
Types of operator:
Arithmetic Operators Relational Operators Logical Operators Bitwise Operators
Assignment Operators Misc Operators
Arithmetic Operators
Operator Description Example
+ Adds two operands A + B will give 30
- Subtracts second operand from the first A - B will give -10
* Multiplies both operands A * B will give 200
/ Divides numerator by de-numerator B / A will give 2
% Gives remainder after an integer division B % A will give 0
++ Increments operator increases integer value by one A++ will give 11
-- Decrements operator decreases integer value by one A-- will give 9
Relational Operators
Assume A= 10 and B=20, then:
== Checks if the values of two operands are equal or not, (A == B) is not true.
!= Checks if the values of two operands are equal or not,. (A != B) is true.
> Checks if the value of left operand is greater than the value of (A > B) is not true.
right operand,.
< Checks if the value of left operand is less than the value of (A < B) is true.
right operand
>= Checks if the value of left operand is greater than or equal to (A >= B) is not true.
the value of right operand.
<= Checks if the value of left operand is less than or equal to the (A <= B) is true.
value of right operand.
Logical Operators
Assume A=2 and B=0
Operator Description Example
&& If both the operands are non-zero, then condition (A && B) is false.
becomes true.
|| If any of the two operands is non-zero, then (A || B) is true.
condition becomes true.
! If a condition is true, then Logical NOT operator !(A && B) is true.
will make false.
PSNA CET – DEPT. OF CSE – CS8251:C PROGRAMMING – Dr.J.Benadict Raja, ASP/CSE Page 6
Bitwise Operators
P q p&q p|q p^q
0 0 0 0 0
0 1 0 1 1
1 1 1 1 0
1 0 0 1 1
1 ~p=0
Assignment Operators
Operator Description Example
= Assigns values from right side operands to left side C = A + B will assign value of
operand A + B into C
+= It adds right operand to the left operand and assign C += A is equivalent to C = C
the result to left operand +A
-= It subtracts right operand from the left operand and C -= A is equivalent to C = C -
assign the result to left operand A
*= It multiplies right operand with the left operand and C *= A is equivalent to C = C
assign the result to left operand *A
/= It divides left operand with the right operand and C /= A is equivalent to C = C /
assign the result to left operand A
%= It takes modulus using two operands and assign the C %= A is equivalent to C = C
result to left operand %A
<<= Left shift AND assignment operator C <<= 2 is same as C = C << 2
>>= Right shift AND assignment operator C >>= 2 is same as C = C >> 2
&= Bitwise AND assignment operator C &= 2 is same as C = C & 2
^= bitwise exclusive OR and assignment operator C ^= 2 is same as C = C ^ 2
|= bitwise inclusive OR and assignment operator C |= 2 is same as C = C | 2
Misc Operators ↦ sizeof & ternary
Operator Description Example
sizeof() Returns the size of an variable. sizeof(a), where a is integer, will return 2.
& Returns the address of an variable. &a; will give actual address of the variable.
* Pointer to a variable. *a; will pointer to a variable.
?: Conditional Expression If Condition is true ? Then value X :
Otherwise value Y
Precedence of operator
Category Operator Associativity
Postfix () [] -> . ++ - - Left to right
Unary + - ! ~ ++ - - (type)* & sizeof Right to left
Multiplicative */% Left to right
Additive +- Left to right
Shift << >> Left to right
Relational < <= > >= Left to right
Equality == != Left to right
Bitwise AND & Left to right
Bitwise XOR ^ Left to right
Bitwise OR | Left to right
Logical AND && Left to right
Logical OR || Left to right
Conditional ?: Right to left
PSNA CET – DEPT. OF CSE – CS8251:C PROGRAMMING – Dr.J.Benadict Raja, ASP/CSE Page 7
Assignment = += -= *= /= %=>>= <<= &= ^= |= Right to left
Comma , Left to right
Decision making statements
In order to write useful programs, we need to check conditions and change the behavior of the
program accordingly.
Alternative execution
A second form of the if statement is “alternative execution”, in which there are two possibilities
and the condition determines which one runs.
Else if ladder
Sometimes there are more than two possibilities and we need more than two branches called
chained conditional:
PSNA CET – DEPT. OF CSE – CS8251:C PROGRAMMING – Dr.J.Benadict Raja, ASP/CSE Page 8
Syntax Flow diagram Example
if(expression1) if( x < y)
{ true statement1(s)} {
else if(expression2) printf('x is less');
{ true statement2(s)} }
else if(expression3) else if(x > y)
{ true statement3(s)} {
else printf('x is greater');
{ false statement(s)} }
else
Each condition is {
checked in order. If the printf(“both are equal”);
first is false, the next is }
checked, and so on.
If x is less than y then print x
If one of them is true, is less and go to end
the corresponding
branch runs and the Otherwise, check x is greater
statement ends. than y print x is greater and go
to end
Even if more than one
condition is true, only Otherwise, print both are
the first true branch equal
runs.
Expressions
1. In programming, an expression is any legal combination of symbols that represents a
value. [Definition from Webopedia]
2. C Programming Provides its own rules of Expression, whether it is legal expression or
illegal expression. For example, in the C language x+5 is a legal expression.
3. Every expression consists of at least one operand and can have one or more operators.
4. Operands are values and Operators are symbols that represent particular actions.
Expression Validity
a+b Valid
++a+b Invalid
a valid
Assignment Statements
Statement used to assign some values,(1) Assignment stmt. (2) Shorthand assignment
PSNA CET – DEPT. OF CSE – CS8251:C PROGRAMMING – Dr.J.Benadict Raja, ASP/CSE Page 9
Switch Statements
For check multiple condition (Alternate to else if ladder)
Syntax Flow diagram Example
switch(expression) switch(choice)
{ {
case 1: case 1:
code block 1 printf(%d”,a+b);
break; break;
case 2: case 2:
code block 2 printf(%d”,a-b);
break; break;
case n: case 3:
code block n printf(%d”,a*b);
break; break;
default: case 4:
code block for default case printf(%d”,a/b);
} break;
default:
If the expression = 1, case 1 printf(“No case is
block runs and break, selected”);
otherwise go and check the }
consecutive cases.
If no one case is matched,
runs the default block.
Looping statements
For execute statement(s) more than 1 time based on the condition
While loop (Entry check loop)
Syntax Flow diagram Example
while(condition) n=3;
{conditional code} s=”Program”;
while(n > 0)
Here, conditional code may be {printf(“%s”,s);
a single statement or a block n = n – 1;
of statements. }
The condition may be any
expression. The loop iterates Initial value for n=3,
while the condition is true.
Condition n>0,
the flow of execution:
1. Determine whether the Every time n is
condition is true or false. reassigned with n-1,
2. If false, exit the while
statement and continue Print the word
execution at the next “program” for three
statement. times (n=3,n=2,n=1) and
3. If the condition is true, run come out from the loop
the body and then go back to
step 1.
PSNA CET – DEPT. OF CSE – CS8251:C PROGRAMMING – Dr.J.Benadict Raja, ASP/CSE Page 10
Do While loop(exit check loop)
Syntax Flow diagram Example
do n=3;
{ conditional code } s=”program”;
while(expression); do{
printf(“%s”,s);
the flow of execution: n = n – 1;
1. Execute conditional code }while(n>0);
2. Determine whether the
condition is true or false. Initial value for n=3,
2. If false, exit the while statement condition n>0,
and continue execution at the next Every time n is
statement. reassigned with n-1,
3. If the condition is true, go back
to step 1. Print the word
“program” for three
times(n=3,n=2,n=1)
and come out from the
loop
PSNA CET – DEPT. OF CSE – CS8251:C PROGRAMMING – Dr.J.Benadict Raja, ASP/CSE Page 11
For Loop
Syntax Flow diagram Example
for(initial value, for(i=0;i<5;i++)
condition; inc/dec) {
{conditional code printf(“%d”,i);
} }
Flow of Execution:
S1:The iterating_var i is initialized with 0, then
initialized, check for the condition and
S2:Then Check for the execute the code,
condition then it is automatically
S3: Execute code incremented by 1
S4:increment/decrement When i is reach the range,
the step value come out from the loop
S5:goto S2 output:
01234
Go to Statement
A non conditional statement, to jump from one block of code to another;
Types: 1) forward goto 2) backward goto
printf(“C program”);
goto XX:
printf(“Lab”);
XX: printf(“completed”);
Input/Output statements
There are some library functions which are available for transferring the information between the
computer and the standard input and output devices.
These functions are available in the header file.
In the above syntax, 'format string' will contain the information that is formatted.
PSNA CET – DEPT. OF CSE – CS8251:C PROGRAMMING – Dr.J.Benadict Raja, ASP/CSE Page 12
Format String Meaning
%d Specify a decimal number
%f Specify a floating point number
%c Specify a character
%s To scan or print a character string. The scanning ends at whitespace.
%o Specify a Octal
%x Specify a hexa decimal value
%l Specify long integer
\n For new line
\t Tab
\r Carriage return
ii) scanf
scanf is used when we enter data by using an input device.
Syntax:
scanf (“format string”, &arg1, &arg2, …..);
Format string consists of the conversion specifier. Arguments can be variables or array name and
represent the address of the variable. Each variable must be preceded by an ampersand (&). Array
names should never begin with an ampersand.
Example:
int avg;
float per;
char grade;
scanf(“%d %f %c”,&avg, &per, &grade):
• scanf works totally opposite to printf. The input is read, interpret using the conversion
specifier and stores it in the given variable.
• The conversion specifier for scanf is the same as printf.
• scanf reads the characters from the input as long as the characters match or it will
terminate. The order of the characters that are entered are not important.
• It requires an enter key in order to accept an input.
iii) getch
This function is used to input a single character. The character is read instantly and it does not
require an enter key to be pressed. The character type is returned but it does not echo on the
screen.
Syntax:
ch=getch();
where, ch - assigned the character that is returned by getch.
iv) putch
this function is a counterpart of getch. Which means that it will display a single character on the
screen. The character that is displayed is returned.
Syntax:
putch(ch);
PSNA CET – DEPT. OF CSE – CS8251:C PROGRAMMING – Dr.J.Benadict Raja, ASP/CSE Page 13
where, ch - the character that is to be printed.
v) getche
This function is used to input a single character. The main difference between getch and getche is
that getche displays the (echoes) the character that we type on the screen.
Syntax:
ch=getche();
vi) getchar
This function is used to input a single character. The enter key is pressed which is followed by the
character that is typed. The character that is entered is echoed.
Syntax:
ch=getchar();
vii) putchar
This function is the other side of getchar. A single character is displayed on the screen.
Syntax:
putchar(ch);
Preprocessor Directives
The task which are carried out before compilation is called preprocessor directives.
Directives Usage Example
#include to paste code of given file into current #include<stdio.h>
file #include”c:\tc\include\conio.h”
#define To define constant or define macros #define pi 3.14
#define cube(x) x*x*x
#ifdef To check anything defined #ifdef pi
#undef To undefined anything #undef pi
#ifndef To check if not defined #ifndef max
#define max 100
#if Use conditional statement before
#else compilation #if expression
#elif conditional codes
#endif #elif expression1
conditional codes
... .. ...
else
conditional codes
PSNA CET – DEPT. OF CSE – CS8251:C PROGRAMMING – Dr.J.Benadict Raja, ASP/CSE Page 14
#endif
Compilation
• User writes a program in C language
(high-level language).
• The preprocessor deals with macro-
processing, augmentation, file
inclusion, language extension, etc.
• The C compiler, compiles the
program and translates it to assembly
program (low-level language).
• An assembler then translates the
assembly program into machine code
(object).
• A linker tool is used to link all the
parts of the program together for
execution (executable machine code).
• A loader loads all of them into
memory and then the program is
executed.
PSNA CET – DEPT. OF CSE – CS8251:C PROGRAMMING – Dr.J.Benadict Raja, ASP/CSE Page 15
UNIT II ARRAYS AND STRINGS 9
Introduction to Arrays: Declaration, Initialization – One dimensional array – Example Program:
Computing Mean, Median and Mode - Two dimensional arrays – Example Program: Matrix
Operations (Addition, Scaling, Determinant and Transpose) - String operations: length, compare,
concatenate, copy – Selection sort, linear and binary search
Arrays:
Array is a derived data type (deriving from the basic types)
Need of the array : to store multiple value on single variable
Characteristics:
The elements of the array should be in same type
The elements are stored in consecutive memory locations
The size of the array is fixed
Declaring Arrays
To declare an array in C, a programmer specifies the type of the elements and the number of
elements required by an array as follows:
type arrayName [ arraySize ];
Ex : int Numbers[10]; // the array Numbers contain ten integers in consecutive locations
// the array index start from 0
Initializing Arrays
Array can be initialized in C either one by one or using a single statement as follows:
int mark[]={58,68,78,88,98}; // integer array with the size of 5
double balance[5] = {1000.0, 2.0, 3.4, 17.0, 50.0};
Accessing Array Elements
An element is accessed by indexing the array name. This is done by placing the index of the
element within square brackets after the name of the array.
Example:
balance[4]=100.0;
Types of Array:
(1) One dimensional array // int mark[9]
(2) Two dimensional array // int matrix[3][3]
(3) Multi dimensional array // int markofclass[60][8][9]
Two-Dimensional Arrays
A two-dimensional array is a list of one-dimensional arrays.
To declare a two-dimensional integer array of size x, y you would write something as follows:
type arrayName [ x ][ y ];
Ex: int a[3][3];
PSNA CET – DEPT. OF CSE – CS8251:C PROGRAMMING – Dr.J.Benadict Raja, ASP/CSE Page 16
Initializing Two-Dimensional Arrays
Two dimensional arrays may be initialized by specifying bracketed values for each row.
Following is an array with 3 rows and each row has 4 columns.
int a[3][4] = {
{0, 1, 2, 3} , /* initializers for row indexed by 0 */
{4, 5, 6, 7} , /* initializers for row indexed by 1 */
{8, 9, 10, 11} /* initializers for row indexed by 2 */
};
Accessing Two-Dimensional Array Elements
An element in 2-dimensional array is accessed by using the subscripts, i.e., row index and column
index of the array.
For example: int val = a[2][3];
Multi-dimensional Arrays
C programming language allows multidimensional arrays. Here is the general form of a
multidimensional array declaration:
type name[size1][size2]...[sizeN];
Example three dimensional integer array:
int markofclass[60][8][9];
// 60 – denote the number of students in the class
// 8 – denote the number of semesters
// 9 – number of subjects per semester
markofclass[0][1][4]; // refers the first students, second semesters 5th subject marks.
Character array:
Like number arrays, we can create character array (called string)
Ex: char name[30]; /* is a 1 Dimensional character array to handle a string
char name[60][30]; /* is 2 Dimensional character array to handle 60 names for a class
initializing and working with character array:
char name[30]=”Deniss”;
printf(“%s”,name); // print the name Deniss
printf(“%c”,name[0]);// print the character D
char name[2][30]={“Deniss”,”Ritchee”};
printf(%s”,name[0]); // print the first name Deniss
Example Program: Matrix operations – Addition
#include <stdio.h> for(i=0;i<m1r;i++)
#define MAXR 10 for(j=0;j<m1c;j++)
#define MAXC 10 scanf("%d",&m1[i][j]);
int main()
{ for(i=0;i<m2r;i++)
int m1[MAXR][MAXC],m2[MAXR][MAXC]; for(j=0;j<m2c;j++)
int m3[MAXR][MAXC]; scanf("%d",&m2[i][j]);
int m1r,m1c,m2r,m2c,i,j;
printf("Enter size of Matrix1"); for(i=0;i<m1r;i++)
scanf("%d %d",&m1r,&m1c); for(j=0;j<m1c;j++)
printf("Enter size of Matrix2"); m3[i][j]=m1[i][j]+m2[i][j];
scanf("%d %d",&m2r,&m2c);
if(m1r!=m2r || m1c!=m2c) for(i=0;i<m1r;i++)
{printf("Size mismatch"); {printf("\n");
return 0; for(j=0;j<m1c;j++)
} printf("%d\t",m3[i][j]);
}
return 0;
}
PSNA CET – DEPT. OF CSE – CS8251:C PROGRAMMING – Dr.J.Benadict Raja, ASP/CSE Page 17
Example Program: Matrix operations - Multiplication
#include <stdio.h>
#define MAXR 10 for(i=0;i<m2r;i++)
#define MAXC 10 for(j=0;j<m2c;j++)
int main() scanf("%d",&m2[i][j]);
{
int m1[MAXR][MAXC],m2[MAXR][MAXC]; for(i=0;i<m1r;++i)
int m3[MAXR][MAXC]; for(j=0;j<m2c;++j)
int m1r,m1c,m2r,m2c,i,j,k; {m3[i][j]=0;
printf("Enter size of Matrix1"); for(k=0;k<m1c;++k)
scanf("%d %d",&m1r,&m1c); m3[i][j]=m3[i][j]+m1[i][k]*m2[k][j];
printf("Enter size of Matrix2"); }
scanf("%d %d",&m2r,&m2c); for(i=0;i<m1r;i++)
if(m1c!=m2r) {printf("\n");
{printf("Size mismatch"); for(j=0;j<m2c;j++)
return 0; printf("%d\t",m3[i][j]);
} }
for(i=0;i<m1r;i++) return 0;
for(j=0;j<m1c;j++) }
scanf("%d",&m1[i][j]);
PSNA CET – DEPT. OF CSE – CS8251:C PROGRAMMING – Dr.J.Benadict Raja, ASP/CSE Page 19
Example Program: Matrix operations - Determinant
#include <stdio.h> int det(int A[100][100], int n)
#include <stdlib.h> {
#include <conio.h> int Minor[100][100];
int i,j,k,c1,c2;
main() int determinant;
{ int c[100];
int A[100][100]; int O=1;
int i,j,k,n,res;
printf("Enter size of the matrix: \n"); if(n == 2)
scanf("%d",&n); {
printf("\nEnter the elements of the determinant = 0;
matrix one by one: \n"); determinant = A[0][0]*A[1][1]-A[0][1]*A[1][0];
for(i = 0 ; i < n ; i++) return determinant;
{ }
for(j = 0 ; j < n ; j++) else
{ {
scanf("%d",&A[i][j]); for(i = 0 ; i < n ; i++)
} {
} c1 = 0, c2 = 0;
for(i = 0 ; i < n ; i++) for(j = 0 ; j < n ; j++)
{ {
for(j = 0 ; j < n ; j++) for(k = 0 ; k < n ; k++)
{ {
printf("%5d",A[i][j]); if(j != 0 && k != i)
} {
printf("\n"); Minor[c1][c2] = A[j][k];
} c2++;
res = det(A,n); if(c2>n-2)
printf("%d",res); {
} c1++;
c2=0;
}
}
}
}
determinant = determinant +
O*(A[0][i]*det(Minor,n-1));
O=-1*O;
}
}
return determinant;
}
PSNA CET – DEPT. OF CSE – CS8251:C PROGRAMMING – Dr.J.Benadict Raja, ASP/CSE Page 20
Selection Sort Linear Search
#include <stdio.h> #include <stdio.h>
int main() int main()
{ {
int array[100], n, c, d, position, swap; int array[100], search, c, n;
printf("Enter number of elements\n"); printf("Enter number of elements in array\n");
scanf("%d", &n); scanf("%d", &n);
printf("Enter %d integers\n", n); printf("Enter %d integer(s)\n", n);
for (c = 0; c < n; c++) for (c = 0; c < n; c++)
scanf("%d", &array[c]); scanf("%d", &array[c]);
for (c = 0; c < (n - 1); c++) printf("Enter a number to search\n");
{ scanf("%d", &search);
position = c; for (c = 0; c < n; c++)
for (d = c + 1; d < n; d++) {
{ if (array[c] == search)
if (array[position] > array[d]) {
position = d; printf("%d is present at location
} %d.\n", search, c+1);
if (position != c) break;
{ }
swap = array[c]; }
array[c] = array[position]; if (c == n)
array[position] = swap; printf("%d isn't present in the
} array.\n", search);
} return 0;
printf("Sorted list in ascending order:\n"); }
for (c = 0; c < n; c++)
printf("%d\n", array[c]);
return 0;
}
Binary Search
#include <stdio.h> while (first <= last) {
int main() if (array[middle] < search)
{ first = middle + 1;
int c, first, last, middle, n, search, array[100]; else if (array[middle] == search) {
printf("Enter number of elements\n"); printf("%d found at location
scanf("%d",&n); %d.\n", search, middle+1);
printf("Enter %d integers\n", n); . break;
for (c = 0; c < n; c++) }
scanf("%d",&array[c]); else
printf("Enter value to find\n"); last = middle - 1;
scanf("%d", &search);
first = 0; middle = (first + last)/2;
last = n - 1; }
middle = (first+last)/2;
if (first > last)
printf("Not found! %d isn't present in the
list.\n", search);
return 0;
}
PSNA CET – DEPT. OF CSE – CS8251:C PROGRAMMING – Dr.J.Benadict Raja, ASP/CSE Page 21
Strings
Strings are one-dimensional array of characters terminated by a null character '\0'.
Declaring a string
char str[30];
Ex: Initializing a string
char str[6] = {'H', 'e', 'l', 'l', 'o', '\0'};
char str[]=”Hello”;
The C compiler automatically places the '\0' at the end of the string when it initializes the array.
Following is the memory presentation of the above defined string in C
PSNA CET – DEPT. OF CSE – CS8251:C PROGRAMMING – Dr.J.Benadict Raja, ASP/CSE Page 22
String Operations
int length(char *str) int compare(char *str1,char *str2)
{ {
int i=0; int i=0;
while(str[i]!='\0') while(str1[i]!='\0' || str2[i]!='\0' )
{i++;} {
return i; if(str1[i]!=str2[i])
} return -1;
i++;
}
int main() return 0;
{ }
int l; int main()
char s1[]="Hello"; {
l=length(s1); int l;
printf("%d",l); char s1[]="Hello",s2[]="Hello";
return 0; l=compare(s1,s2);
} printf("%d",l);
return 0;
}
void concat(char *str1,char *str2) void copy(char *str1,char *str2)
{int i=0,j=0; {int i=0;
while(str1[i]!='\0') while(str2[i]!='\0')
{i++;} {str1[i]=str2[i];
while(str2[j]!='\0') i++;
{str1[i]=str2[j]; }
i++; str1[i]='\0';
j++;} }
str1[i]='\0';
} int main()
{
int main() int l;
{ char s1[]="Hello",s2[]="Helloo";
int l; copy(s1,s2);
char s1[]="Hello",s2[]="Helloo"; printf("%s",s1);
concat(s1,s2); return 0;
printf("%s",s1); }
return 0;
}
PSNA CET – DEPT. OF CSE – CS8251:C PROGRAMMING – Dr.J.Benadict Raja, ASP/CSE Page 23
//Program to print no vowels, consonants, digits and white space in the given string
#include <stdio.h>
int main()
{
char line[150];
int i, vowels=0, consonants=0, digits=0, spaces=0;
printf("Enter a line of string: ");
scanf("%[^\n]",line);
for(i=0; line[i]!='\0'; ++i)
{
if(line[i]=='a' || line[i]=='e' || line[i]=='i' || line[i]=='o' || line[i]=='u')
++vowels;
else if((isalpha(line[i])
++consonants;
else if(isdigit(line[i])
++digits;
else if(line[i]==' ')
++spaces;
}
printf("Vowels: %d",vowels);
printf("\nConsonants: %d",consonants);
printf("\nDigits: %d",digits);
printf("\nWhite spaces: %d", spaces);
}
//Program to print no vowels, consonants, digits and white space in the given string
#include<stdio.h>
#include<string.h>
Void main()
{
int i,j,count;
char str[25][25],temp[25];
puts("How many strings u are going to enter?: ");
scanf("%d",&count);
a) Return type – data type of return value. It can be int, float, double, char, void etc.
b) Function name – name of the function
c) Parameter type list –It is a comma separated list of parameter types. Parameter names are
optional.
Ex: int add(int, int);
or
int add(int x, int y);
FUNCTION DEFINITION
It is also known as function implementation. Every function definition consists of 2 parts:
1. Header of the function
2. Body of the function
PSNA CET – DEPT. OF CSE – CS8251:C PROGRAMMING – Dr.J.Benadict Raja, ASP/CSE Page 25
1. Header of the function
General form:
returntype functionname (parameter list)
FUNCTION CALL:
• A function can be called by using its name & actual parameters.
• It should be terminated by a semicolon ( ; ).
Working of a function
int abc(int, int, int); // Function declaration
void main()
{
int x,y,z;
…..
…..
abc(x,y,z); // Function Call
…
Actual arguments
…
}
Calling function – The function that calls a function is known as a calling function.
Called function – The function that has been called is known as a called function.
Actual arguments – The arguments of the calling function are called as actual arguments.
Formal arguments – The arguments of called function are called as formal arguments.
Steps for function Execution:
PSNA CET – DEPT. OF CSE – CS8251:C PROGRAMMING – Dr.J.Benadict Raja, ASP/CSE Page 26
1. After the execution of the function call statement, the program control is transferred to
the called function.
2. The execution of the calling function is suspended and the called function starts
execution.
3. After the execution of the called function, the program control returns to the calling
function and the calling function resumes its execution.
PSNA CET – DEPT. OF CSE – CS8251:C PROGRAMMING – Dr.J.Benadict Raja, ASP/CSE Page 27
4.5. Built in Functions (Library functions)
Library functions are predefined functions. These functions are already developed by
someone and are available to the user for use.
Declaration:
The declarations of library functions are available in the respective header files. To use a
library function, the corresponding header file must be included.
PSNA CET – DEPT. OF CSE – CS8251:C PROGRAMMING – Dr.J.Benadict Raja, ASP/CSE Page 28
#return address of str2 from
right
15 strset(str1,char) Set all the characters of the string str1=”Hellow”
with given character strset(str1,‘h’);
#str1<-“hhhhhh”
16 strrev(str1) Reverse the contents of string str1=”Hellow”
strrev(str1);
#str1<-“wolleH”
17 strtok(str1,delimeter Tokenizing using delimiter Str1=”Hellow world,hai;”
s) Strtok(str1,” ,;”);
Built-in function (Mathematical functions)
Sno Function Description Example
1 qqrt(no) Return the square root of the sqrt(4) is 2
given no
2 pow(no1,no2) Return the power pow(2,3) is 8
3 floor(real no) Return the next integer(>=) floor(2.1) is 3
4 ceil(real no) Return the previous integer ceil(2.9) is 2
(<=)
5 round(real no) Return next if >.5 round(2.6) is 3
Return previous if <.6 round(2.4) is 2
6 trunc(real no) Return the integer part only trunc(2.6) is 2
trunc(2.4) is 2
7 sin(no) Return sine value of the no sin(0) is 0
8 cos(no) Return the cosine value of the cos(0) is 1
no
9 tan(no) Return the tangent value of the tan(0) is 0
no
10 log(no) Return the natural logarithm of log(2.0) is 0.693147
the given no
11 log10(no) Return base 10 logarithm of the log10(10.0) is 1.0
given no
12 exp(no) Return the exponential value exp(1.) is 2.718282
13 abs(no) Return the absolute value (+ve abs(-10) is 10
value) abs(10) is 10
14 fabs(real no) Return the absolute value (+ve fabs(-10.1) is 10.1
value) fabs(10.1) is 10.1
15 fmod(real no, real no) Return the modulus for floating fmod(13.657, 2.333) is 1.992
point values
RECURSION
A function that calls itself is known as a recursive function.
Advantages
• Reduce unnecessary calling of function.
• Through Recursion one can Solve problems in easy way while its iterative solution is very
big and complex.
Disadvantages
• Recursive solution is always logical and it is very difficult to trace.(debug and
understand).
• In recursive we must have an if statement somewhere to force the function to return
without the recursive call being executed, otherwise the function will never return.
• Recursion takes a lot of stack space, usually not considerable when the program is small
and running on a PC.
PSNA CET – DEPT. OF CSE – CS8251:C PROGRAMMING – Dr.J.Benadict Raja, ASP/CSE Page 29
• Recursion uses more processor time.
Types of Recursion:
1. Direct Recursion: A function call itself for several times
2. Indirect Recursion: Function A calls function B and Function B calls A
POINTERS
Pointer is a variable that stores/points the address of another variable.
The pointer variable might be belonging to any of the data type such as int, float, char, double,
short etc.
• Pointer Syntax : data_type *var_name;
• Example : int *p; char *p;
• Where, * is used to denote that “p” is pointer variable and not a normal variable.
• Normal variable stores the value whereas pointer variable stores the address of the
variable.
• The content of the C pointer always be a whole number i.e. address.
• Always C pointer is initialized to null, i.e. int *p = null.
Advantages
1. Pointers save memory space (using dynamic memory allocation).
2. Faster execution
3. It allows passing of arrays and strings to functions more efficiently.
4. It makes possible to return more than one value from the function.
Pointer Operators
(1)Reference operator (&) - It gives you the address of a variable
(2) Dereference operator (*) – It gets the value from the address
NULL Pointers
It is always a good practice to assign a NULL value to a pointer variable in case you do not have
an exact address to be assigned. This is done at the time of variable declaration. A pointer that is
assigned NULL is called a null pointer.
#include <stdio.h>
PSNA CET – DEPT. OF CSE – CS8251:C PROGRAMMING – Dr.J.Benadict Raja, ASP/CSE Page 31
void main () {
int *ptr = NULL;
printf("The value of ptr is : %x\n", ptr ); // prints 0
}
Pointer Arithmetic
A pointer in c is an address, which is a numeric value. Therefore, you can perform arithmetic
operations on a pointer. There are four arithmetic operators that can be used on pointers:
Operator Purpose Example
++ To increment the current pointer, to int val[5]={10,20,30,40,50};
point the next element in the array int *p=val; // p point the first element
++p; // p point the second element
-- To Decrement the current pointer, to int val[5]={10,20,30,40,50};
point the previous element in the int *p=&val[2]; // p point the third element
array --p; // p point the second element
+ To add a constant to the pointer, to int val[5]={10,20,30,40,50};
point any element in the array int *p=val; // p point the first element
p=p+3; // p point the fourth element
- To add a constant to the pointer, to int val[5]={10,20,30,40,50};
point any element in the array int *p=&val[4]; // p point the fifth element
p=p-3; // p point the second element
Relational To compare two pointers int val[5]={10,20,30,40,50};
operators int *p=val; // p point the first element
while(p <= &val[5])
printf(“%d”,*p++);
PSNA CET – DEPT. OF CSE – CS8251:C PROGRAMMING – Dr.J.Benadict Raja, ASP/CSE Page 32
Function Pointer in C
In C, like normal data pointers (int *, char *, etc), we can have pointers to functions. Following is
a simple example that shows declaration and function call using function pointer.
void fun(int a)
{
printf("Value of a is %d\n", a);
}
int main()
{
void (*fun_ptr)(int) = fun;
fun_ptr(10);
return 0;
}
Function pointer can be used in place of switch case. For example, in below program, user is
asked for a choice between 0 and 2 to do different tasks.
#include <stdio.h>
void add(int a, int b)
{
printf("Addition is %d\n", a+b);
}
void subtract(int a, int b)
{
printf("Subtraction is %d\n", a-b);
}
void multiply(int a, int b)
{
printf("Multiplication is %d\n", a*b);
}
int main()
{
void (*fun_ptr_arr[])(int, int) = {add, subtract, multiply};
unsigned int ch, a = 15, b = 10;
(*fun_ptr_arr[ch])(a, b);
return 0;
}
PSNA CET – DEPT. OF CSE – CS8251:C PROGRAMMING – Dr.J.Benadict Raja, ASP/CSE Page 33
UNIT IV STRUCTURES AND DYNAMIC MEMORY ALLOCATION
Structure ‐ Nested structures – Pointer and Structures – Array of structures – Example Program
using structures and pointers – Self referential structures – Dynamic memory allocation ‐ Singly
linked list ‐typedef
Defining a Structure
Syntax Ex
struct struct_name struct student
{ {
member definition; int rno;
member definition; char name[30];
... char dept[10];
member definition; int mark[3];
}structure_variables; }st;
PSNA CET – DEPT. OF CSE – CS8251:C PROGRAMMING – Dr.J.Benadict Raja, ASP/CSE Page 34
Accessing Structure Members
To access any member of a structure, we use the member access operator (.)
struct student
{
int rno;
char name[30];
char dept[10];
int mark[3]; // Array within structure
};
void main()
{
struct student st;
scanf(“%d %s %s %d %d %d”,
&st.rno,st.name,st.dept,&st.mark[0],&st.mark[1],&st.mark[2]);
printf(“%d %s %s %d %d %d”, st.rno,st.name,st.dept,st.mark[0],st.mark[1],st.mark[2]);
}
Array of Structures
It is possible to create array of variables for structure.
struct student
{
int rno;
char name[30];
char dept[10];
int mark[3]; // Array within structure
};
void main()
{
struct student st[58];
int i;
for(i=0;i<58;i++)
{
scanf(“%d %s %s %d %d %d”,
&st[i].rno,st[i].name,st.dept,&st[i].mark[0],&st[i].mark[1],&st[i].mark[2]);
}
}
When a structure is declared as a member of another structure then it is called structure within
structure or nested structure.
Ex: address is a structure, which used as member of another structure (student).
struct address
{
int dno;
char street[50];
char city[50];
int pin;
};
PSNA CET – DEPT. OF CSE – CS8251:C PROGRAMMING – Dr.J.Benadict Raja, ASP/CSE Page 35
struct student
{
int rno;
char name[30];
char dept[10];
struct address ad; // nested structure
};
void main()
{
struct student st;
scanf(“%d %s %s %d %s %s %d”
&st.rno, st.name, st.dept, &st.ad.dno, st.ad.street, st.ad.city, st.ad.pin);
} // Accessing inner structure member is,
<Outer structure variable> . <inner structure variable> . inner structure member
Pointers to Structures
You can define pointers to structures in very similar way as you define pointer to any other
variable as follows:
struct student st,*stp;
Now, you can store the address of a structure variable in the above defined pointer variable
stp=&st;
To access the members of a structure using a pointer to that structure, you must use the ->
operator as follows:
stp->rno;
PSNA CET – DEPT. OF CSE – CS8251:C PROGRAMMING – Dr.J.Benadict Raja, ASP/CSE Page 36
Difference between Structure and Union
Memory Allocation : Allocating memory location for the variable is called memory allocation.
There are two types of memory allocation,
PSNA CET – DEPT. OF CSE – CS8251:C PROGRAMMING – Dr.J.Benadict Raja, ASP/CSE Page 37
realloc() If the dynamically allocated memory Syntax
is insufficient or more than required, ptr = realloc(ptr, x);
you can change the size of Ex:
previously allocated memory using a=realloc(a,n2); // n2 – new size
realloc() function
free() Dynamically allocated memory Ex:
created with either calloc() or free(a);
malloc() doesn't get freed on their
own. You must explicitly use free()
to release the space
#include <stdio.h>
#include <stdlib.h>
int main()
{
int *ptr, i , n1, n2;
printf("Enter size of array: ");
scanf("%d", &n1);
free(ptr);
return 0;
}
int main()
{
int **matrix;
int row,col;
scanf(“%d %d”,&row,&col);
matrix = (int **)malloc(row * sizeof(int *)); // Allocate row space
for (i=0; i<r; i++)
matrix[i] = (int *)malloc(col * sizeof(int)); // Allocate column space
PSNA CET – DEPT. OF CSE – CS8251:C PROGRAMMING – Dr.J.Benadict Raja, ASP/CSE Page 38
/* Code for free the dynamically allocated memory */
return 0;
}
#include <stdio.h>
#include<stdlib.h>
struct student
{
int rno;
char name[30];
};
int main()
{
struct student *sptr;
int i, n;
printf("Enter number of records: ");
scanf("%d", &n);
struct node
{
int element;
node *next;
}
Applications of Linked Lists
Linked lists are used to implement stacks, queues, graphs, etc.
Polynomial operations
Multilist used for maintain a database.
Node Structure:
struct node
{ int element;
node *next;
node *prev;
}
PSNA CET – DEPT. OF CSE – CS8251:C PROGRAMMING – Dr.J.Benadict Raja, ASP/CSE Page 40
Merits:
List can be traversed forward and backwards.
Easy to delete a node given with that pointer.
Demerits:
More space needed for two pointers forward & backward
PSNA CET – DEPT. OF CSE – CS8251:C PROGRAMMING – Dr.J.Benadict Raja, ASP/CSE Page 41
Linked list implementation:
typedef in C
typedef is a keyword used in C language to assign alternative names to existing data types. Its
mostly used with user defined data types, when names of the data types become slightly
complicated to use in programs. Following is the general syntax for using typedef
Ex:1
typedef int I;
void main()
{
I n; // equal to int n;
}
Ex:2
typedef struct student_detail
{
int rno;
char name[30];
} student;
void main()
{
student st;
}
PSNA CET – DEPT. OF CSE – CS8251:C PROGRAMMING – Dr.J.Benadict Raja, ASP/CSE Page 43
Unit V : File Processing
Files – Types of file processing: Sequential access, Random access – Sequential access file ‐
Example Program: Finding average of numbers stored in sequential access file ‐ Random access file
‐ Example Program: Transaction processing using random access files – Command line arguments
Files: A named storage area, can store data or program in hard disk(secondary memory)
• When a program is terminated, the entire data is lost. Storing in a file will preserve your
data even if the program terminates.
• If you have to enter a large number of data, it will take a lot of time to enter them all.
However, if you have a file containing all the data, you can easily access the contents of
the file using few commands in C.
• You can easily move your data from one computer to another without any changes.
Types of files :
Text file :
• Can handle alphanumeric characters (Text)
• Text files are the normal .txt files that you can easily create using Notepad.
• When you open those files, you'll see all the contents within the file as plain text.
• You can easily edit or delete the contents.
• They take minimum effort to maintain, are easily readable.
Binary files :
• Can handle audio, video , images and text
• Binary files are mostly the .bin files in your computer.
• Instead of storing data in plain text, they store it in the binary form (0's and 1's).
• They can hold higher amount of data, are not readable easily and provides a better security
than text files.
File Operations:
In C, you can perform four major operations on the file, either text or binary:
1. Creation of a new file
2. Opening an existing file
3. Reading from file
4. Writing to a file
5. Moving to a specific location in a file
6. Closing a file
Opening a file is performed using the library function in the "stdio.h" header file: fopen().
PSNA CET – DEPT. OF CSE – CS8251:C PROGRAMMING – Dr.J.Benadict Raja, ASP/CSE Page 44
fp=fopen(<file_name>, <access_mode>);
file_name: That contains the name of the file that you want to access.
access_mode: The access_mode determines the mode in which the file has to be opened
File Modes
File Functions
FILE *fptr;
PSNA CET – DEPT. OF CSE – CS8251:C PROGRAMMING – Dr.J.Benadict Raja, ASP/CSE Page 45
Write an integer to file
int no;
6 getw no=getw(fptr);
Read integer from file
int no;
char name[30];
7 fprintf scanf(“%d %s”,&no,name);
fprintf(fptr,”%d%s”,no,name);
Write the formatted content to the file
int no;
char name[30];
8 fscanf
fscanf(fptr,”%d%s”,&no,name);
Read the formatted content from the file
char name[30];
scanf(“%s”,name);
9 fputs
fputs(fptr, name);
Write the string to the file
char name[30];
10 fgets fgets(fptr,30,name);
Read the 30 byte string from the file
Detects end-of-file marker in a file
feof() which returns non-zero value only if end of file has reached,
otherwise it returns 0.
11 feof
if (feof(fptr))
printf("\n End of file reached.");
PSNA CET – DEPT. OF CSE – CS8251:C PROGRAMMING – Dr.J.Benadict Raja, ASP/CSE Page 46
Example : getc() and putc() Example: getw() and putw()
Write set of character to the file and read the same Finding average of numbers using sequential
and print access file
#include <stdio.h> #include<stdio.h>
int main() int main()
{ {
FILE *fptr; FILE *fptr;
char c; int i,m,n,sum=0;
fptr =fopen("Input.txt", "w"); fptr=fopen("file1.txt","w");
while((c=getchar())!=EOF) for(i=0;i<5;i++)
putc( c, fptr); {
fclose(fptr); scanf("%d",&m);
putw(m,fptr);
fptr =fopen("Input.txt","r"); }
c = getc(fptr); fclose(fptr);
while(!feof(fptr))
{ fptr=fopen("file1.txt","r");
printf("%c", c); for(i=0;i<5;i++)
c = getc(fptr); {
} n=getw(fptr);
fclose(fptr ); sum=sum+n;
return 0; }
printf("\nThe average is %d", sum/5);
}
Sample I/O: fclose(fptr);
Input : C Programming return 0;
Output : C Programming }
Sample I/O:
Input : 10 20 30 40 50
Output : The average is : 30
PSNA CET – DEPT. OF CSE – CS8251:C PROGRAMMING – Dr.J.Benadict Raja, ASP/CSE Page 48
Example: Random Access File Example: Random Access File
Get 5 student data and print particular student Random Access
data Get 5 student record,
Update a particular student record,
Then print all the 5 records
#include <stdio.h> #include <stdio.h>
#include <stdlib.h> #include <stdlib.h>
fclose(fptr);
return 0;
}
PSNA CET – DEPT. OF CSE – CS8251:C PROGRAMMING – Dr.J.Benadict Raja, ASP/CSE Page 49
Command line arguments in C/C++
The most important function of C is main() function. It is mostly defined with a return type of int
and without parameters :
int main() { /* ... */ }
We can also give command-line arguments in C. Command-line arguments are given after the
name of the program in command-line.
To pass command line arguments, we typically define main() with two arguments : first argument
is the number of command line arguments and second is list of command-line arguments.
int main(int argc, char *argv[]) { /* ... */ }
or
int main(int argc, char **argv) { /* ... */ }
argc (ARGument Count) is int and stores number of command-line arguments passed by the
user including the name of the program.
The value of argc should be non negative.
argv(ARGument Vector) is array of character pointers listing all the arguments.
If argc is greater than zero,the array elements from argv[0] to argv[argc-1] will contain pointers
to strings.
Argv[0] is the name of the program , After that till argv[argc-1] every element is command -line
arguments.
C:\tc\bin\add 10 20
PSNA CET – DEPT. OF CSE – CS8251:C PROGRAMMING – Dr.J.Benadict Raja, ASP/CSE Page 50
To write a C Program to add, delete ,display ,Search and exit options for telephone details of
an individual into a telephone directory using random access file.
ALGORITHM:
1. Start.
2. Declare variables, File pointer and phonebook structures.
3. Create menu options.
4. Read the option .
5. Develop procedures for each option.
6. Call the procedure (Add, delete ,display ,Search and exit)for user chosen option.
7. Display the message for operations performed.
8. Stop
#include <stdio.h>
#include <conio.h>
#include <string.h>
struct person
{
char name[20];
long telno;
};
void appendData()
{
FILE *fp;
struct person obj;
clrscr();
fp=fopen("data.txt","ab");
printf("*****Add Record****\n");
printf("Enter Name : ");
scanf("%s",obj.name);
printf("Enter Telephone No. : ");
scanf("%ld",&obj.telno);
fwrite(&obj,sizeof(struct person),1,fp);
fclose(fp);
}
void showAllData(){
FILE *fp;
struct person obj;
clrscr();
fp=fopen("data.txt","rb");
printf("*****Display All Records*****\n");
printf("\n\n\t\tName\t\t\tTelephone No.");
printf("\n\t\t=====\t\t\t==========\n\n");
while(!feof(fp))
{
fread(&obj,sizeof(struct person),1,fp);
if(!feof(fp))
printf("%s %ld\n",obj.name,obj.telno);
}
fclose(fp);
getch();
}
PSNA CET – DEPT. OF CSE – CS8251:C PROGRAMMING – Dr.J.Benadict Raja, ASP/CSE Page 51
void findData()
{
FILE *fp;
struct person obj;
char name[20];
int totrec=0;
clrscr();
fp=fopen("data.txt","rb");
printf("*****Display SpecificRecords*****\n");
printf("\nEnter Name : ");
scanf("%s",&name);
while(!feof(fp))
{
fread(&obj,sizeof(struct person),1,fp);
if(strcmpi(obj.name,name)==0){
printf("\n\nName : %s",obj.name);
printf("\nTelephone No : %ld",obj.telno);
}
}
fclose(fp);
getch();
}
void update()
{
FILE *fp;
struct person obj;
char name[20];
int i=-1;
clrscr();
fp=fopen("data.txt","rb+");
printf("*****Display SpecificRecords*****\n");
printf("\nEnter Name : ");
scanf("%s",&name);
while(!feof(fp))
{ i++;
fread(&obj,sizeof(struct person),1,fp);
if(strcmpi(obj.name,name)==0){
printf("\n\nName : %s",obj.name);
printf("\nTelephone No : %ld",obj.telno);
break;
}
}
printf("\nEnter new no :");
scanf("%ld",&obj.telno);
fseek(fp,(sizeof(struct person)*i),0);
fwrite(&obj,sizeof(struct person),1,fp);
fclose(fp);
getch();
}
PSNA CET – DEPT. OF CSE – CS8251:C PROGRAMMING – Dr.J.Benadict Raja, ASP/CSE Page 52
void main()
{
char choice;
while(1)
{
clrscr();
printf("*****TELEPHONE DIRECTORY*****\n\n");
printf("1) Append Record\n");
printf("2) Find Record\n");
printf("3) Read all record\n");
printf("4) Update record\n");
printf("5) exit\n");
printf("Enter your choice : ");
fflush(stdin);
choice = getche();
switch(choice)
{
case'1' : //call append record
appendData();
break;
case'2' : //call find record
findData();
break;
case'3' : //Read all record
showAllData();
break;
case'4' : //Read all record
update();
break;
case'5' :
exit(1);
}
}
}
PSNA CET – DEPT. OF CSE – CS8251:C PROGRAMMING – Dr.J.Benadict Raja, ASP/CSE Page 53
To write a C Program to Count the number of account holders whose balance is less than
the minimum balance using sequential access file.
ALGORITHM:
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#include <string.h>
#define MINBAL 500
struct Bank_Account
{
char no[10];
char name[20];
int balance;
};
struct Bank_Account acc;
void main()
{
long int pos1,pos2,pos;
FILE *fp;
char *ano,*amt;
char choice;
int type,i=-1,flag=0;
int bal;
do
{
clrscr();
fflush(stdin);
printf("1. Add a New Account Holder\n");
printf("2. Display\n");
printf("3. Deposit or Withdraw\n");
printf("4. Number of Account Holder Whose Balance is less than the Minimum Balance\n");
printf("Enter your choice : ");
choice=getchar();
switch(choice)
{
case '1' :
fflush(stdin);
fp=fopen("acc.dat","ab");
printf("\nEnter the Account Number : ");
gets(acc.no);
printf("\nEnter the Account Holder Name : ");
gets(acc.name);
printf("\nEnter the Initial Amount to deposit : ");
scanf("%d",&acc.balance);
fseek(fp,0,2);
fwrite(&acc,sizeof(acc),1,fp);
fclose(fp);
break;
PSNA CET – DEPT. OF CSE – CS8251:C PROGRAMMING – Dr.J.Benadict Raja, ASP/CSE Page 54
case '2' :
fp=fopen("acc.dat","rb");
printf("\nA/c Number\tA/c Holder Name Balance\n");
while(fread(&acc,sizeof(acc),1,fp)==1)
printf("%-10s\t\t%-20s\t%d\n",acc.no,acc.name,acc.balance);
fclose(fp);
break;
case '3' :
fflush(stdin);
fp=fopen("acc.dat","rb+");
printf("\nEnter the Account Number : ");
gets(ano);
i=-1;
while(!feof(fp))
{ i++;
fread(&acc,sizeof(acc),1,fp);
if(strcmp(acc.no,ano)==0)
{
printf("\nEnter the Type 1 for deposit & 2 for withdraw : ");
scanf("%d",&type);
printf("\nYour Current Balance is : %d",acc.balance);
printf("\nEnter the Amount to transact : ");
scanf("%d",&bal);
if(type==1)
acc.balance=acc.balance+bal;
else
acc.balance= acc.balance-bal;
break;
}
}
fseek(fp,sizeof(acc)*(i),0);
fwrite(&acc,sizeof(acc),1,fp);
fclose(fp);
break;
case '4' :
flag=0;
fp=fopen("acc.dat","rb");
while(fread(&acc,sizeof(acc),1,fp)==1)
{
if(acc.balance<MINBAL)
flag++;
}
printf("\nThe Number of Account Holder whose Balance less than the Minimum Balance :
%d",flag);
fclose(fp);
break;
}
printf("\nPress any key to continue....");
getch();
} while (choice<'5');
}
PSNA CET – DEPT. OF CSE – CS8251:C PROGRAMMING – Dr.J.Benadict Raja, ASP/CSE Page 55