MODULE 5
Structure
struct structure-name
{
datatype Member-name1;
datatype Member-name2;
. OR
.
.
datatype Member-name n;
};
struct structure-name structure-variable;
struct structure-name
{
datatype Member-name1;
datatype Member-name2;
.
.
.
datatype Member-name n;
}
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
{
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;
Single Structure Variable
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>
struct book
{
int Year;
int Id;
float Price;
};
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
printf(“Book1 information=%d, %d,
%f”, b1. Year, b1. Id, b1. Price);
return 0;
}
#include <stdio.h>
int main()
{
Single Structure Variable
in side main ()
struct Point {
int x, y, z;
};
struct Point p1 = { 0, 1, 2 };
struct Point p2 = { 20 };
printf("P1nx = %d, y = %d, z = %dn", p1.x, p1.y, p1.z);
printf("P2nx = %d", p2.x);
return 0;
}
Structure Variables – pointer variable
#include <stdio.h>
struct person
{
int age;
float weight;
};
int main()
{
printf("Displaying:n");
printf("Age: %dn", person1.age);
printf("weight: %f", personPtr->weight);
return 0;
}
struct person *personPtr, person1;
personPtr = &person1;
printf("Enter age: ");
scanf("%d", &person1.age);
printf("Enter weight: ");
scanf("%f", &personPtr->weight);
#include<stdio.h>
struct book
{
char name[20];
int Year;
int Id;
float Price;
};
int main()
{
struct book b[5]; int i;
//run time initialization
printf(“enter information of 20
books”);
for(i=0;i<5;i++)
printf(“enter name”);
scanf(“%s”, b[i].name)
Array of Structure Variable
printf(“enter Year”);
scanf(“%d”, &b[i]. Year)
printf(“enter Id”);
scanf(“%d”, &b[i]. Id)
printf(“enter Price”);
scanf(“%f”, &b[i]. Price)
printf(“display information of all the 20
Books”);
for(i=0;i<5;i++)
printf (“ Book name=%s, Book year=%d,
Book Id=%d, Book Price=%f”, b[i].name,
b[i].Year, b[i].Id, b[i].Price);
return 0;
}
Nested Structures
#include <stdio.h>
#include <string.h>
struct Student {
struct Marks {
int science;
int math;
int language;
};
char name[40];
int id_number;
struct Marks marks;
} s1;
int main() {
s1.marks.science = 92;
s1.marks.math = 97;
s1.marks.language = 89;
strcpy(s1.name, "abc");
s1.id_number = 123;
printf("Student details:n");
printf("nName: %s", s1.name);
printf("nStudent ID: %d", s1.id_number);
printf("nMarks in Science: %d", s1.marks.science);
printf("nMarks in Math: %d", s1.marks.math);
printf("nMarks in Language: %d", s1.marks.language);
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;
char name[20];
float percentage;
void func(struct student record)
{
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
{
//defining a union
char name[32];
float salary;
int workerNo;
} uJob;
int main()
{
printf("size of union = %d bytes", sizeof(uJob));
printf("nsize of structure = %d bytes", sizeof(sJob));
return 0;
}
struct structJob
{
char name[32];
float salary;
int workerNo;
} sJob;
Output
size of union = 32
size of structure = 38
#include <stdio.h>
union Job {
float salary;
int workerNo;
} j;
Accessing Union Members
Output
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 = %.1fn", j.salary);
printf("Number of workers = %d", j.workerNo);
return 0;
}
#include <stdio.h>
#include <string.h>
union student
{
EXAMPLE PROGRAM FOR C UNION:
};
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 examplen");
printf(" Name
printf(" Subject
: %s n", record1.name);
: %s n", record1.subject);
printf(" Percentage : %f nn", record1.percentage);
// assigning values to record2 union variable
printf("Union record2 values examplen");
strcpy(record2.name, "Mani");
printf(" Name : %s n", record2.name);
strcpy(record2.subject, "Physics");
printf(" Subject : %s n", record2.subject);
record2.percentage = 99.50;
printf(" Percentage : %f n", record2.percentage);
return 0;
}
OUTPUT:
Union record1 values example
Name :
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, keywordenum 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");
• WritingMode
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>
int main()
{
int num;
FILE *fptr;
fptr = fopen("C:program.txt","w");
if(fptr == NULL)
{
printf("Enter num: ");
scanf("%d",&num);
fprintf(fptr,"%d",num);
fclose(fptr);
return 0;
}
printf("Error!");
exit(1);
}
Read from a text file
#include <stdio.h>
#include <stdlib.h>
int main()
{
int num;
FILE *fptr;
if ((fptr = fopen("C:program.txt","r")) == NULL)
fscanf(fptr,"%d", &num);
printf("Value of n=%d", num);
fclose(fptr);
return 0;
}
{
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 offile
• It can be used in textfile
• feofReturns 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()
{
FILE *fp = fopen("test.txt", "r");
int ch = getc(fp);
while (ch != EOF)
{
putchar(ch);
ch = getc(fp);
if (feof(fp))
printf("n End of file reached.");
else
printf("n Something went wrong.");
fclose(fp);
return 0;
}
}
Output
This is pop class
Ways of Detecting End of File (Contd..)
#include <stdio.h>
int main () {
FILE *fp;
int c;
fp = fopen("file.txt","r");
if(fp == NULL)
{
perror("Error in opening file");
return(-1);
}
while(1)
{
c = fgetc(fp);
if( feof(fp) )
{
break ;
}
printf("%c", c);
}
fclose(fp);
return(0);
}
Output
This is pop class
Principals of Programming in CModule -5.pdf

Principals of Programming in CModule -5.pdf

  • 1.
    MODULE 5 Structure struct structure-name { datatypeMember-name1; datatype Member-name2; . OR . . datatype Member-name n; }; struct structure-name structure-variable; struct structure-name { datatype Member-name1; datatype Member-name2; . . . datatype Member-name n; } structure-variable;
  • 2.
    Structure A structure isa 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;
  • 4.
    // A variabledeclaration 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 }
  • 5.
    How to initializestructure 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 }
  • 6.
    How to accessstructure 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
  • 7.
    #include<stdio.h> #include<string.h> struct book { 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; Single Structure Variable 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; }
  • 8.
    #include<stdio.h> struct book { int Year; intId; float Price; }; 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 printf(“Book1 information=%d, %d, %f”, b1. Year, b1. Id, b1. Price); return 0; }
  • 9.
    #include <stdio.h> int main() { SingleStructure Variable in side main () struct Point { int x, y, z; }; struct Point p1 = { 0, 1, 2 }; struct Point p2 = { 20 }; printf("P1nx = %d, y = %d, z = %dn", p1.x, p1.y, p1.z); printf("P2nx = %d", p2.x); return 0; }
  • 10.
    Structure Variables –pointer variable #include <stdio.h> struct person { int age; float weight; }; int main() { printf("Displaying:n"); printf("Age: %dn", person1.age); printf("weight: %f", personPtr->weight); return 0; } struct person *personPtr, person1; personPtr = &person1; printf("Enter age: "); scanf("%d", &person1.age); printf("Enter weight: "); scanf("%f", &personPtr->weight);
  • 12.
    #include<stdio.h> struct book { char name[20]; intYear; int Id; float Price; }; int main() { struct book b[5]; int i; //run time initialization printf(“enter information of 20 books”); for(i=0;i<5;i++) printf(“enter name”); scanf(“%s”, b[i].name) Array of Structure Variable printf(“enter Year”); scanf(“%d”, &b[i]. Year) printf(“enter Id”); scanf(“%d”, &b[i]. Id) printf(“enter Price”); scanf(“%f”, &b[i]. Price) printf(“display information of all the 20 Books”); for(i=0;i<5;i++) printf (“ Book name=%s, Book year=%d, Book Id=%d, Book Price=%f”, b[i].name, b[i].Year, b[i].Id, b[i].Price); return 0; }
  • 13.
    Nested Structures #include <stdio.h> #include<string.h> struct Student { struct Marks { int science; int math; int language; }; char name[40]; int id_number; struct Marks marks; } s1; int main() { s1.marks.science = 92; s1.marks.math = 97; s1.marks.language = 89; strcpy(s1.name, "abc"); s1.id_number = 123; printf("Student details:n"); printf("nName: %s", s1.name); printf("nStudent ID: %d", s1.id_number); printf("nMarks in Science: %d", s1.marks.science); printf("nMarks in Math: %d", s1.marks.math); printf("nMarks in Language: %d", s1.marks.language); return 0; }
  • 14.
    Passing struct tofunction 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.
  • 15.
    PASSING STRUCTURE VARIABLETO FUNCTION #include <stdio.h> #include <string.h> struct student { }; int id; char name[20]; float percentage; void func(struct student record) { 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; }
  • 16.
    Unions • Union canbe 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.
  • 17.
    Difference between structureand 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
  • 18.
    Syntax for Declaringa 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
  • 19.
    How is thestructure 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 { //defining a union char name[32]; float salary; int workerNo; } uJob; int main() { printf("size of union = %d bytes", sizeof(uJob)); printf("nsize of structure = %d bytes", sizeof(sJob)); return 0; } struct structJob { char name[32]; float salary; int workerNo; } sJob; Output size of union = 32 size of structure = 38
  • 20.
    #include <stdio.h> union Job{ float salary; int workerNo; } j; Accessing Union Members Output 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 = %.1fn", j.salary); printf("Number of workers = %d", j.workerNo); return 0; }
  • 21.
    #include <stdio.h> #include <string.h> unionstudent { EXAMPLE PROGRAM FOR C UNION: }; 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 examplen"); printf(" Name printf(" Subject : %s n", record1.name); : %s n", record1.subject); printf(" Percentage : %f nn", record1.percentage);
  • 22.
    // assigning valuesto record2 union variable printf("Union record2 values examplen"); strcpy(record2.name, "Mani"); printf(" Name : %s n", record2.name); strcpy(record2.subject, "Physics"); printf(" Subject : %s n", record2.subject); record2.percentage = 99.50; printf(" Percentage : %f n", record2.percentage); return 0; } OUTPUT: Union record1 values example Name : Subject : Percentage : 86.500000; Union record2 values example Name : Mani Subject : Physics Percentage : 99.500000
  • 25.
    Enumeration data type: •An enumeration is a user-defined data type that consists of integral constants. To define an enumeration, keywordenum 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; };
  • 26.
    Declaration of enumeratedvariable enum Boolean {false,true}; enum boolean check; Here, a variable check is declared which is of type enum boolean.
  • 27.
    Example of enumeratedtype #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
  • 28.
    Declaration of enumeratedvariable #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; }
  • 29.
    enumerated variable #include <stdio.h> enummonths{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; }
  • 30.
    Files File: A file representsa 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.
  • 31.
  • 32.
    Different modes: • ReadingMode fp = fopen("hello.txt","r"); • WritingMode fp = fopen("hello.txt","w"); • Append Mode fp = fopen("hello.txt","a");
  • 33.
  • 34.
    Example to Openand close a File #include<stdio.h> int main() { FILE *fp; char ch; fp = fopen("INPUT.txt","r"); fclose(fp); return(0); }
  • 35.
    Write to atext file #include <stdio.h> #include <stdlib.h> int main() { int num; FILE *fptr; fptr = fopen("C:program.txt","w"); if(fptr == NULL) { printf("Enter num: "); scanf("%d",&num); fprintf(fptr,"%d",num); fclose(fptr); return 0; } printf("Error!"); exit(1); }
  • 36.
    Read from atext file #include <stdio.h> #include <stdlib.h> int main() { int num; FILE *fptr; if ((fptr = fopen("C:program.txt","r")) == NULL) fscanf(fptr,"%d", &num); printf("Value of n=%d", num); fclose(fptr); return 0; } { printf("Error! opening file"); exit(1); }
  • 37.
    Ways of DetectingEnd 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
  • 38.
    Ways of DetectingEnd of File (Contd..) In Binary File : • feof function is used to detect the end offile • It can be used in textfile • feofReturns 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)) { --- - --}
  • 39.
    Ways of DetectingEnd of File (Contd..) #include <stdio.h> int main() { FILE *fp = fopen("test.txt", "r"); int ch = getc(fp); while (ch != EOF) { putchar(ch); ch = getc(fp); if (feof(fp)) printf("n End of file reached."); else printf("n Something went wrong."); fclose(fp); return 0; } } Output This is pop class
  • 40.
    Ways of DetectingEnd of File (Contd..) #include <stdio.h> int main () { FILE *fp; int c; fp = fopen("file.txt","r"); if(fp == NULL) { perror("Error in opening file"); return(-1); } while(1) { c = fgetc(fp); if( feof(fp) ) { break ; } printf("%c", c); } fclose(fp); return(0); } Output This is pop class