Module -5
Module -5
Structure
struct structure-name
{ struct structure-name
datatype Member-name1; {
datatype Member-name2; datatype Member-name1;
. datatype Member-name2;
OR
. .
. .
datatype Member-name n; .
}; datatype Member-name n;
struct structure-name structure-variable; }
structure-variable;
Structure
A structure is a key word that create user defined data type in C/C++. A
structure creates a data type that can be used to group items of possibly
different types into a single type.
struct address
{
char name[50];
char street[100];
char city[50];
char state[20];
int pin;
} add;
// A variable declaration with structure declaration.
struct Point
{
int x, y;
}
struct Point
{
int x, y;
};
int main()
{
struct Point p1; // The variable p1 is declared like a normal variable
}
How to initialize structure members?
Structure members cannot be initialized with declaration. For example the following C
program fails in compilation.
struct Point
{
int x = 0; // COMPILER ERROR: cannot initialize members here
int y = 0; // COMPILER ERROR: cannot initialize members here
};
Structure members can be initialized using curly braces ‘{}’. For example, following is a
valid initialization.
struct Point
{
int x, y;
};
int main()
{
struct Point p1 = {0, 1}; // ANOTHER METHOD: p1.x=0; p1.y=1
}
How to access structure elements?
Structure members are accessed using dot (.) operator.
#include<stdio.h>
struct Point
{
int x, y;
};
int main()
{
struct Point p1 = {0, 1}; //x=0, y=1
// or can initialize as : p1.x=0; p1.y=1;
// Accessing members of point p1
p1.x = 20;
printf ("x = %d, y = %d", p1.x, p1.y);
return 0;
}
Output:
x = 20, y = 1
#include<stdio.h>
#include<string.h>
struct book Single Structure Variable
{
int Year; char name[20];
int Id;
float Price;
};
int main()
{
struct book b1;
//compile time initialization
b1. Year=2010;
b1. Id=1542;
b1. Price=501.20;
strcpy(b1.name, “Java”); // compile time initialization for string in Structure
printf(“Book1 information=%d, %d, %f”, b1. Year, b1. Id, b1. Price);
return 0; }
#include<stdio.h> Single Structure Variable
struct book
{
int Year; printf(“Book1 information=%d, %d,
int Id; %f”, b1. Year, b1. Id, b1. Price);
float Price; return 0;
}; }
int main()
{
struct book b1;
//run time initialization
printf(“enter Year”);
scanf(“%d”, &b1. Year)
printf(“enter Id”);
scanf(“%d”, &b1. Id)
printf(“enter Price”);
scanf(“%f”, &b1. Price)
Single Structure Variable
#include <stdio.h> in side main ()
int main()
{
struct Point {
int x, y, z;
};
struct Point p1 = { 0, 1, 2 };
struct Point p2 = { 20 };
union union_name
{
datatype field_name;
datatype field_name;
};
Note : Size of the union is the the size of its largest field because
sufficient number of bytes must be reserved
to store the largest sized field.
To access the fields of a union, use dot(.) operator i.e., the variable
name followed by dot operator followed by field name
How is the structure in C different from union? Give example
Let's take an example to demonstrate the difference between unions and structures:
#include <stdio.h>
union unionJob int main()
{ {
//defining a union printf("size of union = %d bytes", sizeof(uJob));
char name[32]; printf("\nsize of structure = %d bytes", sizeof(sJob));
float salary; return 0;
int workerNo; }
} uJob;
struct structJob
{ Output
char name[32];
float salary; size of union = 32
int workerNo; size of structure = 38
} sJob;
#include <stdio.h>
Accessing Union Members
union Job {
float salary;
int workerNo; Output
} j; Salary = 0.0
Number of workers = 100
int main() {
j.salary = 12.3;
strcpy(record2.subject, "Physics");
printf(" Subject : %s \n", record2.subject);
OUTPUT:
record2.percentage = 99.50; Union record1 values example
printf(" Percentage : %f \n", record2.percentage); Name :
return 0; Subject :
} Percentage : 86.500000;
Union record2 values example
Name : Mani
Subject : Physics
Percentage : 99.500000
Enumeration data type:
• An enumeration is a user-defined data type that consists of integral constants. To
define an enumeration, keyword enum is used.
Syntax:
enum enum_name{int_const1, int_const2, int_const3, …. int_constN};
#include <stdio.h>
enum week{ sunday, monday, tuesday, wednesday, thursday,
friday, saturday};
int main()
{
enum week today;
today=wednesday;
printf("%d day",today+1);
return 0;
}
Output 4 day
Declaration of enumerated variable
#include <stdio.h>
enum weekdays{Sunday=1, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday};
int main()
{
enum weekdays w;
w=Monday;
printf("The value of w is %d",w);
return 0;
}
enumerated variable
#include <stdio.h>
enum months{jan=1, feb, march, april, may, june, july, august, september, october,
november, december};
int main()
{
// printing the values of months
for(int i=jan;i<=december;i++)
{
printf("%d, ",i);
}
return 0;
}
Files
File:
• Reading Mode
fp = fopen("hello.txt","r");
• Writing Mode
fp = fopen("hello.txt","w");
• Append Mode
fp = fopen("hello.txt","a");
Functions for file handling
Example to Open and close a File
#include<stdio.h>
int main()
{
FILE *fp;
char ch;
fp = fopen("INPUT.txt","r");
fclose(fp);
return(0);
}
Write to a text file
#include <stdio.h>
#include <stdlib.h> printf("Enter num: ");
scanf("%d",&num);
int main()
{ fprintf(fptr,"%d",num);
int num; fclose(fptr);
FILE *fptr;
return 0;
}
fptr = fopen("C:\\program.txt","w");
if(fptr == NULL)
{
printf("Error!");
exit(1);
}
Read from a text file
#include <stdio.h>
#include <stdlib.h>
fscanf(fptr,"%d", &num);
int main()
{ printf("Value of n=%d", num);
int num; fclose(fptr);
FILE *fptr;
return 0;
if ((fptr = fopen("C:\\program.txt","r")) == NULL) }
{
printf("Error! opening file");
exit(1);
}
Ways of Detecting End of File
In Text File :
In Binary File :
• feof function is used to detect the end of file
• It can be used in text file
• feof Returns TRUE if end of file is reached
Syntax :
int feof(FILE *fp);
int main()
{ if (feof(fp))
FILE *fp = fopen("test.txt", "r"); printf("\n End of file reached.");
else
int ch = getc(fp); printf("\n Something went wrong.");
fclose(fp);
while (ch != EOF)
{ return 0;
putchar(ch); }
ch = getc(fp);
}
Output
This is pop class
Ways of Detecting End of File (Contd..)
#include <stdio.h>
while(1)
{
int main () {
c = fgetc(fp);
FILE *fp;
if( feof(fp) )
int c;
{
break ;
fp = fopen("file.txt","r");
}
if(fp == NULL)
printf("%c", c);
{
}
perror("Error in opening file");
fclose(fp);
return(-1);
}
return(0);
}
Output
This is pop class