0% found this document useful (0 votes)
2 views

Module -5

The document provides an overview of structures, unions, and enumerations in C/C++, explaining their definitions, syntax, and differences. It includes examples of how to declare, initialize, and access structure members, as well as how to pass structures to functions. Additionally, it covers file handling, including opening, writing, and reading files, along with methods for detecting the end of a file.

Uploaded by

anil-csbs
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Module -5

The document provides an overview of structures, unions, and enumerations in C/C++, explaining their definitions, syntax, and differences. It includes examples of how to declare, initialize, and access structure members, as well as how to pass structures to functions. Additionally, it covers file handling, including opening, writing, and reading files, along with methods for detecting the end of a file.

Uploaded by

anil-csbs
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 41

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;
}

p1; // The variable p1 is declared with 'Point'

// A variable declaration like basic data types

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 };

printf("P1\nx = %d, y = %d, z = %d\n", p1.x, p1.y, p1.z);


printf("P2\nx = %d", p2.x);
return 0;
}
Structure Variables – pointer variable
#include <stdio.h>
struct person printf("Displaying:\n");
{ printf("Age: %d\n", person1.age);
int age; printf("weight: %f", personPtr->weight);
float weight;
}; return 0;
}
int main()
{
struct person *personPtr, person1;
personPtr = &person1;

printf("Enter age: ");


scanf("%d", &person1.age);

printf("Enter weight: ");


scanf("%f", &personPtr->weight);
#include<stdio.h> Array of Structure Variable
struct book
{ printf(“enter Year”);
char name[20]; scanf(“%d”, &b[i]. Year)
int Year; printf(“enter Id”);
int Id; scanf(“%d”, &b[i]. Id)
float Price; printf(“enter Price”);
}; scanf(“%f”, &b[i]. Price)
int main()
{ printf(“display information of all the 20
struct book b[5]; int i; Books”);
//run time initialization
printf(“enter information of 20 for(i=0;i<5;i++)
books”); printf (“ Book name=%s, Book year=%d,
for(i=0;i<5;i++) Book Id=%d, Book Price=%f”, b[i].name,
printf(“enter name”); b[i].Year, b[i].Id, b[i].Price);
scanf(“%s”, b[i].name) return 0;
}
Nested Structures
#include <stdio.h> int main() {
#include <string.h>
s1.marks.science = 92;
struct Student { s1.marks.math = 97;
s1.marks.language = 89;
struct Marks {
int science; strcpy(s1.name, "abc");
s1.id_number = 123;
int math;
int language;
}; printf("Student details:\n");
printf("\nName: %s", s1.name);
printf("\nStudent ID: %d", s1.id_number);
char name[40]; printf("\nMarks in Science: %d", s1.marks.science);
int id_number; printf("\nMarks in Math: %d", s1.marks.math);
struct Marks marks; printf("\nMarks in Language: %d", s1.marks.language);
} s1; return 0;
}
Passing struct to function

A structure can be passed to any function from main function or from


any sub function.
Structure definition will be available within the function only.
It won’t be available to other functions unless it is passed to those
functions by value or by address(reference).
Else, we have to declare structure variable as global variable. That
means, structure variable should be declared outside the main
function. So, this structure will be visible to all the functions in a C
program.
PASSING STRUCTURE VARIABLE TO FUNCTION
#include <stdio.h>
#include <string.h>
struct student
{
int id;
void func(struct student record)
char name[20];
{
float percentage;
printf(" Id is: %d \n", record.id);
}; printf(" Name is: %s \n", record.name);
void func(struct student record); printf(" Percentage is: %f \n",
record.percentage);
}
int main()
{
struct student record;
record.id=1;
strcpy(record.name, "Raju");
record.percentage = 86.5;
func(record); //passing structure variable to function
return 0;
}
Unions

• Union can be defined as a user-defined data type which is a


collection of different variables of different data types in the same
memory location. The union can also be defined as many members,
but only one member can contain a value at a particular point in
time.

• Union is a user-defined data type, but unlike structures, they share


the same memory location.
Difference between structure and union

The main difference between structure and a union is that

• Structs allocate enough space to store all of the fields in the


struct. The first one is stored at the beginning of the struct, the
second is stored after that, and so on.

• Unions only allocate enough space to store the largest field


listed, and all fields are stored at the same space
Syntax for Declaring a C union
Syntax for declaring a union is same as that of declaring a structure
except the keyword struct.

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;

// when j.workerNo is assigned a value, j.salary will no longer hold 12.3 as


union members share memory space.
j.workerNo = 100;

printf("Salary = %.1f\n", j.salary);


printf("Number of workers = %d", j.workerNo);
return 0;
}
EXAMPLE PROGRAM FOR C UNION:
#include <stdio.h>
#include <string.h>
union student
{
char name[20];
char subject[20];
float percentage;
};
int main()
{
union student record1;
union student record2;
// assigning values to record1 union variable
strcpy(record1.name, "Raju");
strcpy(record1.subject, "Maths");
record1.percentage = 86.50;
printf("Union record1 values example\n");
printf(" Name : %s \n", record1.name);
printf(" Subject : %s \n", record1.subject);
printf(" Percentage : %f \n\n", record1.percentage);
// assigning values to record2 union variable
printf("Union record2 values example\n");
strcpy(record2.name, "Mani");
printf(" Name : %s \n", record2.name);

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};

• Here, name of the enumeration is flag. Constants like const1, const2,... ,


constN are values of type flag. By default, const1 is 0, const2 is 1 and so on.
can change default values of enum elements during declaration (if
necessary).
// Changing the default value of enum elements enum suit{
club=0; diamonds=10; hearts=20; spades=3;
};
Declaration of enumerated variable

enum Boolean {false,true};

enum boolean check;

Here, a variable check is declared which is of type enum


boolean.
Example of enumerated type

#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:

 A file represents a sequence of bytes on the disk where a group of


related data is stored.

 File is created for permanent storage of data. It is a ready made


structure.
File Opening Mode Chart
Different modes:

• 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 :

• Special Character EOF denotes the end of File


• As soon as Character is read, End of the File can be detected.
• EOF is defined in stdio.h
• Equivalent value of EOF is -1
Ways of Detecting End of File (Contd..)

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);

Way of Writing feof Function :

Way1: with if statement :


if( feof(fptr) == 1 ) // as if(1) is TRUE printf("End of File");

Way 2 : with While Loop


while(!feof(fptr))
{
--- - --}
Ways of Detecting End of File (Contd..)
#include <stdio.h>

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

You might also like