Unit 5
Unit 5
STRUCTURES
&
FILE PROCESSING
1
outline of structures CONCEPTS
INTRODUCTION OF STRUCTURES
NESTED STRUCTURES
ARRAY OF STRUCTURES
EXAMPLE PROGRAM
2
INTRODUCTION OF STRUCTURES
3
Variables inside the structure are called members of
structure.
4
Declaration of structure
Syntax:
The declaration of the Structure starts with a Key Word called struct and
ends with ;
struct emp
{
int empno;
char ename[20];
float sal;
};
struct emp e1 = { 123,”Kumar”,5000.00};
7
Assessing structure elements
8
EXAMPLE PROGRAM USING
STRUCTURES
Program to read Student Details and Calculate total and
average using structures.
9
Difference b/w array and structure
Array Structure
1 Array is collection of homogeneous Structure is the collection of
data. heterogeneous data.
2 Array data are access using index Structure elements are access using .
operator.
Noornilo Nafees 10
#include<stdio.h> printf("Enter the three subjects marks: \n");
struct stud scanf("%d%d%d",&s.m1,&s.m2,&s.m3);
{ s.tot = s.m1+s.m2+s.m3;
int rno; s.avg = s.tot/3.0;
char sname[20]; printf("Roll Number : %d\n",s.rno);
int m1,m2,m3;
printf("Student Name: %s\n",s.sname);
printf("Total Marks : %d\n",s.tot);
int tot;
printf("Average : %f\n",s.avg);
float avg;
}
};
void main()
{
struct stud s;
printf("Enter the student roll number: \n");
scanf(“%d”,&s.rno);
printf("Enter the student name: \n");
scanf("%s",&s.sname);
11
#include<stdio.h> printf(“number of %s purchased ”,i.itemname);
struct item scanf(“%d”,&i.qty);
{ i.tot_amt = i.rate * i.qty;
int itemno; printf(“Item Number: %d\n”,i.itemno);
char itemname[20]; printf(“Item Name: %s\n”,i.itemname);
float rate; printf(“Rate: %f\n”,i.rate);
int qty; printf(“Number of Items: %d\n”,i.qty);
}; printf(“Total Amount: %f”,i.tot_amt);
Void main() }
{
struct item i;
float tot_amt;
printf(“Enter the Item Number \n”);
scanf(“%d”,&i.itemno);
printf(“Enter the Item Name \n”);
scanf(“%s”,&i.itemname);
printf(“Enter the Rate of the Item \n”);
scanf(“%f”,&i.rate); 12
Example: Array of Structures
#include<stdio.h>
#include<conio.h>
struct stud
{
int regno;
char name[10],grade;
int m1,m2;
float avg,tot;
};
void main()
{
struct stud s[10];
int i,n;
printf("\nEnter the no.of students:");
scanf("%d“,&n);
for(i=0;i<n;i++)
{
printf("\nEnter the student regno,name,m1,m2");
scanf("%d%s%d%d",&s[i].regno,&s[i].name,&s[i].m1,&s[i].m2);
13
s[i].tot=s[i].m1+s[i].m2;
s[i].avg=s[i].tot/2;
if(s[i].m1<35||s[i].m2<35)
s[i].grade='f';
else
{
if(s[i].avg>=75)
s[i].grade=‘A+';
else if(s[i].avg>=60)
s[i].grade='A';
else if(s[i].avg>=50)
s[i].grade='B';
else if(s[i].avg>=35)
s[i].grade='C';
}
}
14
printf("\nSTUDENT MARK LIST\n");
printf("\nREGNO\tNAME\tTOTAL\tAvg\tGRADE");
for(i=0;i<n;i++)
printf("\n%d\t%s\t%f\t%f\t%c",s[i].regno,s[i].name,s[i].tot,s[i].avg,s[i].grade);
getch();
}
Enter the no.of students:2
Enter the student regno,name,m1,m2:
101
Raj
90
98
Enter the student regno,name,m1,m2:
102
kumar
58
68
STUDENT MARK LIST
REGNO NAME TOTAL Avg GRADE
101 Raj 188.000000 94.333336 A+
102 Kumar 126.000000 63.666664 A
15
Nested Structure
• Nested Structure is a structure within another
structure is called Nesting of tructures.
16
#include<stdio.h>
printf("Printing the employee information....\n");
struct address printf("name: %s\nCity: %s\nPincode: %d\nPhone: %d",emp.name,
{ emp.add.city,emp.add.pin,emp.add.phone);
char city[20]; }
int pin;
int phone[14];
};
struct employee
{
char name[20];
struct address add;
};
void main ()
{
struct employee emp;
printf("Enter employee information?\n");
scanf("%s %s %d %s",emp.name,emp.add.city, &emp.add.pin, emp.add.phone)
;
17
Program to calculate employee salary slip
Using array of structures
Solution:
int ecode
char ename[20]
char des[20](Designation should be executive, officer and assistant)
float bs
float hra
float ta
float ma
Float net_salary
18
2. Calculation:
hra: If 10% of basic salary is higher than Rs 2000, than HRA will
Rs 2000.
Else If 10% of basic salary is lower than Rs 2000, then HRA will
10% of Basic Salary
19
// Program to calculate employee salary slip using array of
structures
#include<stdio.h>
#include<conio.h>
struct esal
{
int ecode;
char ename[20];
char des[20];
float bs;
float hra;
float ta;
float ma;
float ns;
};
20
void main()
{
int n,i;
struct esal e[n];
clrscr();
printf(“enter number of employees to calculate salary slip : “);
scanf(“%d”,&n);
for(i=0;i<n;i++)
{
printf(“Enter employee %d code, name, desig,&basic salary:\n”,i);
scanf(“%d%s%s%f”,&e[i].ecode,&e[i].ename,&e[i].des,&e[i].bs);
21
if((e[i].bs*0.1)<2000)
{
e[i].hra=e[i].bs*0.1;
}
else
{
e[i].hra=2000;
}
e[i].ta= e[i].bs*0.25;
if(e[i].des==“executive”)
{
e[i].ma=1000;
}
else if(e[i].des==“officer”)
{
e[i].ma=700;
}
else
{
e[i].ma=500;
} 22
e[i].ns= e[i].bs+ e[i].hra+ e[i].ta+ e[i].ma;
}
printf(“\nEmployee Salary Slip\n***************************);
for(i=0;i<n;i++)
{
printf(“Employee code : %d\n”,e[i].ecode);
printf (“Employee name : %s\”,e[i].ename);
printf (“Deisg: %s\”,e[i].des);
printf(“ Basic Salary : %f\”,e[i].bs);
printf(“ House Rent Allowance : %f”, e[i].hra);
printf(“ Dearness Allowance : %f”, e[i].da);
printf(“ Medical Allowance : %f” ,e[i].ma);
printf(“ Nett Salary : %f”,e[i].ns);
}
getch();
}
23
FILES
• Files are places where data can be stored
permanently.
• In C, each file is simply a sequential stream of
bytes. C imposes no structure on a file.
• A file must first be opened properly before it can
be accessed for reading or writing. When a file is
opened, a stream is associated with the file.
24
• Defining and opening file:
• In order to define and open file we need
– Filename (e.g. sort.c, input.txt)
– Data structure (e.g. FILE)
– Purpose (e.g. Reading, Writing, Appending)
• Filename: String of characters that make up a
valid file name.
• May contain two parts
– Primary
– Optional period with extension
• Examples: a.out, prog.c, temp, text.out
25
• Data Structure:
FILE *fptr1, *fptr2 ;
• The above statement declares that
• fptr1 and fptr2 are pointer variables of type
FILE.
• They will be assigned the address of a file
descriptor, that is, an area of memory that will
be associated with an input or output stream.
26
• Purpose:
• General format for opening file:
• FILE *fp; /*variable fp is pointer to type FILE*/
• fp = fopen(“filename”, “mode”); /*opens file
with name filename , assigns identifier to fp */
• fp
– contains all information about file
– Communication link between system and program
• Various modes of operation on files
– r open file for reading only
– w open file for writing only
– a open file for appending (adding) data 27
• Various modes of operations on files:
• Writing mode
– If the file already exists then contents are deleted,
– Else a new file with specified name is created
• Appending mode
– If the file already exists then the file is opened with contents and
further updated.
– Else new file created
• Reading mode
– If the file already exists then it is opened with contents.
– Else error occurs.
• Ex:
FILE *p1, *p2, *p3;
p1 = fopen(“data”,”r”);
p2= fopen(“results”, w”);
p3= fopen(“results”, a”); 28
• Closing a File:
• File must be closed as soon as all operations on it completed.
• Ensures
– All outstanding information associated with file flushed out
from buffers
– All links to file broken
• If we want to change mode of file, then first close and then open
again.
• Syntax: fclose(file_pointer);
• Example:
FILE *p1, *p2;
p1 = fopen(“INPUT.txt”, “r”);
p2 =fopen(“OUTPUT.txt”, “w”);
……..
……..
fclose(p1); 29
• Input and Output Operations with Files:
• C provides several different functions for
reading/writing in to files.
• Some of them are
• getc() – read a character
• putc() – write a character
• fprintf() – write set of data values
• fscanf() – read set of data values
30
• getc() and putc():
• This function handles one character at a time.
• Syntax: putc(c,fp1);
– c : a character variable
– fp1 : pointer to file opened with mode w
• Syntax: c = getc(fp2);
– c : a character variable
– fp2 : pointer to file opened with mode r
• File pointer moves by one character position
after every getc() and putc()
• getc() returns end-of-file marker EOF when file
end reached 31
#include <stdio.h> //Program for file manipulation using getc()
void main() and putc(); OUTPUT
{
Noornilo Nafees ctrl^z
FILE *f1;
Noornilo Nafees
char c;
f1= fopen(“INPUT”, “w”); /* open file for writing */
while((c=getchar()) != EOF) /*get char from keyboard until CTL-Z*/
putc(c,f1); /*write a character to INPUT */
fclose(f1); /* close INPUT */
f1=fopen(“INPUT”, “r”); /* reopen file */
while((c=getc(f1))!=EOF) /*read character from file INPUT*/
printf(“%c”, c);/* print character to screen */
fclose(f1);
}
32
• fprintf() and fscanf():
• Syntax of fprintf():
fprintf(FILE *fp,"format-string",var-list);
• Syntax of fscanf():
fscanf(FILE *fp,"format-string",var-list);
33
#include<stdio.h> //Program for file manipulation using
void main() fprintf()
{
FILE *fp;
int roll;
char name[25];
float marks;
char ch;
fp = fopen("file.txt","w"); //Statement 1
if(fp == NULL)
{
printf("\nCan't open file or file doesn't exist.");
exit(0);
}
34
do
{
printf("\nEnter Roll : ");
scanf("%d",&roll);
printf("\nEnter Name : ");
scanf("%s",name);
printf("\nEnter Marks : ");
scanf("%f",&marks); fprintf(fp,"%d%s%f",roll,name,marks);
printf("\nDo you want to add another data (y/n) : ");
ch = getche();
}while(ch=='y' || ch=='Y');
printf("\nData written successfully...");
fclose(fp);
}
35
Output :
Enter Roll : 1
Enter Name : Nilo
Enter Marks : 78.53
Do you want to add another data (y/n) : y
Enter Roll : 2
Enter Name : Nafees
Enter Marks : 89.62
Do you want to add another data (y/n) : n
Data written successfully...
36
#include<stdio.h>
void main() //Program for file manipulation using
fscanf()
{
FILE *fp;
char ch;
fp = fopen("file.txt","r"); //Statement 1
if(fp == NULL)
{
printf("\nCan't open file or file doesn't exist.");
exit(0);
}
37
printf("\nData in file...\n");
while((fscanf(fp,"%d%s%f",&roll,name,&marks))!
=EOF) //Statement 2
{
printf("\n%d\t%s\t%f",roll,name,marks);
}
fclose(fp);
}
Output :
Data in file...
1 Nilo 78.53
2 Nafees 89.62 38
Preprocessor
• It is a program that processes the source
program before compilation.
• It operates under the following directives
– File Inclusion
– Macro substitution
– Conditional inclusion
39
File Inclusion
• It is used to include some file that contains
functions or some definitions.
• Syntax:
#include<filename> (or)
#include“filename”
• Eg: #include<stdio.h>
#include “ex.c”
40
Example
#include<stdio.h>
#include<conio.h>
#include "addition.txt"
int main()
{
int a,b;
printf("\nEnter the numbers:");
scanf("%d%d",&a,&b);
printf("The Value is %d",add(a,b));
getch();
}
41
addition.txt
int add(int a,int b)
{
return(a+b);
}
42
Output
43
Example
#include<stdio.h>
#include<conio.h>
#include "fact.c"
void main()
{
int a;
printf("\nEnter the number:");
scanf("%d",&a);
printf("The factorial of %d! is %d",a,rec(a));
getch();
}
44
Macro Substitution
• It is used to define and use integer, string, or
identifier in the source program
• The three forms of macros are
– Simple Macro
– Argumented Macro
– Nested Macro
45
Simple Macro
46
Example
#include<stdio.h>
#include<conio.h>
#define pi 3.14
#define CITY "chennai"
void main()
{
printf("The Value is %f",2*pi);
printf("\nThe Value CITY is %s",CITY);
getch();
}
Output:
The Value is 6.280000
The Value CITY is chennai
47
Argumented Macro
• Eg:
#define cube(n) (n*n*n)
48
Example
#include<stdio.h>
#include<conio.h>
#define cube(n) (n*n*n)
void main()
{
printf("The Value of 3 cube is %d",cube(3));
getch();
}
Output:
The Value of 3 cube is 27
49
Nested Macro
• Eg:
#define a 3
#define sq a*a
50
Example
#include<stdio.h>
#include<conio.h>
#define a 3
#define sq a*a
void main()
{
printf("The Value is %d",sq);
getch();
}
Output:
The Value is 9
51
Conditional Inclusion
• It is used to include some conditional
statements.
52
Example
#include<stdio.h>
#include<conio.h>
#define a 3
#ifdef a
#define c a+5
#endif
void main()
{
printf("\nThe value C is %d",c);
getch();
}
Output:
The value C is 8
53
Storage classes
• Every C variable has a storage class,
• Storage classes determines :
– The part of memory where storage is allocated for variable
– What will be the initial value of the variable if not assigned
– How long the storage allocation continues to exists.
– The scope which specifies the part of the program over which a
variable name is visible
• Categories of storage classes in C:
– Automatic
– External
– Static
– Register
54
Automatic (auto)
• By default, variables in C uses the auto storage class.
• The variables are automatically created when needed and deleted
when they fall out of the scope.
• Ex:
void main()
{ Output
auto int a=10;
{ 30
auto int a=20; 20
{
10
auto int a =30;
printf(“%d”,a);
}
printf(“\n%d”,a);
}
printf(“\n%d”,a);
}
55
Automatic (auto)
• Storage : Memory
• Scope : Within the block in which variable is
defined
• Life : Till the program control is within the
block
• Default value : Un predictable (Garbage Value)
56
External (Global) -extern
• Global variables are accessible from within any block & or remains in existence
for the entire execution of the program.
• Using global variables we can transfer information into a function without using
arguments
• Ex:
void sum();
int a=10,b=5;
void main() Output
{
clrscr(); Added values : 15
sum();
getch();
}
void sum()
{
int c;
c=a+b;
printf(“Added values : %d”,c);
} 57
External - extern
• Storage : Memory
• Scope : Global
• Life : During entire program execution
• Default value : zer0
58
Static variables - static
• Storage: Memory
• Scope : Local to the block in which the variable is defined
• Life : Value of the variables persist between different function calls
• Default value : zer0
• Ex:
void incr();
void main()
Output
{
incr(); 123
incr();
incr();
}
void incr()
{
static int a=1;
printf(“%d\t”,a);
a=a+1;
} 59
Register variables - register
• Register variables are usually stored in memory and
passed back & forth to the processor as needed.
void main()
{
register int counter;
60
}