UNIT 4
Q.1 Explain structure in detail
A structure can be considered as a template used for defining a collection of variables under a single name. Structures help programmers to group elements of different data types into a single logical unit (Unlike arrays which permit a programmer to group only elements of same data type).
- Why Use Structures
• Ordinary variables can hold one piece of information
• arrays can hold a number of pieces of information of the same data type.
For example, suppose you want to store data about a book. You might want to store its name (a string), its price (a float) and number of pages in it (an int).
If data about say 3 such books is to be stored, then we can follow two approaches:
Construct individual arrays, one for storing names, another for storing prices and still another for storing number of pages.
Use a structure variable.
Suppose we want to create a employee database. Then, we can define a structure
Calledemployee with three elements id, name and salary. The syntax of this structure is as
Follows:
Struct employee
{ int id;
Char name[50];
Float salary;
};
Note:
Struct keyword is used to declare structure.
Members of structure are enclosed within opening and closing braces.
Usually structure type declaration appears at the top of the source code file, before any variables or functions are defined or maintained in separate header file.
Declaration of Structure reserves no space.
It is nothing but the “ Template / Map / Shape ” of the structure .
Memory is created , very first time when the variable is created / Instance is created.
- Structure variable declaration:
We can declare the variable of structure in two ways
- Declare the structure inside main function
- Declare the structure outside the main function.
1. Declare the structure inside main function
Following example show you, how structure variable is declared inside main function
Struct employee
{
Int id;
Char name[50];
Float salary;
};
Int main()
{
Struct employee e1, e2;
Return 0;
}
In this example the variable of structure employee is created inside main function that e1 ,e2.
2. Declare the structure outside main function
Following example show you, how structure variable is declared outside the main function
Struct employee
{
Int id;
Char name[50];
Float salary;
}e1,e2;
Q.2 Explain Memory allocation for structure
Memory is allocated to the structure only when we create the variable of structure.
Consider following example
Q.3 Explain Structure Initialization in different ways
1. When we declare a structure, memory is not allocated for un-initialized variable.
2. Let us discuss very familiar example of structure student , we can initialize structure variable
In different ways –
Way 1 : Declare and Initialize
Structstudent
{
Charname[20];
Introll;
Floatmarks;
}std1 = { "Poonam",89,78.3 };
In the above code snippet, we have seen that structure is declared and as soon as after declaration we
Have initialized the structure variable.
Std1 = { "Poonam",89,78.3 }
This is the code for initializing structure variable in C programming
Way 2 : Declaring and Initializing Multiple Variables
Structstudent
{
Charname[20];
Introll;
Floatmarks;
}
Std1 = {"Poonam" ,67, 78.3};
Std2 = {"Vishal",62, 71.3};
In this example, we have declared two structure variables in above code. After declaration of variable we have initialized two variable.
Std1 = {"Poonam" ,67, 78.3};
Std2 = {"Vishal",62, 71.3};
Way 3 : Initializing Single member
Structstudent
{
Intmark1;
Intmark2;
Intmark3;
} sub1={67};
Though there are three members of structure,only one is initialized , Then remaining two members
Are initialized with Zero. If there are variables of other data type then their initial values will be –
Q.4 Explain Data Type Default value if not initialized in different ways
Integer 0
Float 0.00
Char NULL
Way 4 : Initializing inside main
Structstudent
{
Intmark1;
Intmark2;
Intmark3;
};
Voidmain()
{
Structstudent s1 = {89,54,65};
- - - - --
- - - - --
- - - - --
};
When we declare a structure then memory won’t be allocated for the structure. i.e only writing below
Declaration statement will never allocate memory
Structstudent
{
Intmark1;
Intmark2;
Intmark3;
};
We need to initialize structure variable to allocate some memory to the structure.
Structstudent s1 = {89,54,65};
Q.5 Give syntax for declaring structure array give example
Structure is collection of different data type. An object of structure represents a singlerecord in memory, if we want more than one record of structure type, we have tocreate an array of structure or object. As we know, an array is a collection of similartype, therefore an array can be of structure type.
Syntax for declaring structure array
Structstruct-name
{
Datatype var1;
Datatype var2;
- - - - - - - - - -
- - - - - - - - - -
DatatypevarN;
};
Structstruct-name obj [ size ];
Example for declaring structure array
#include<stdio.h>
Struct Employee
{
Int Id;
Char Name[25];
Int Age;
Long Salary;
};
Void main()
{
Inti;
Struct Employee Emp[ 3 ]; //Statement 1
For(i=0;i<3;i++)
{
Printf("\nEnter details of %d Employee",i+1);
Printf("\n\tEnter Employee Id : ");
Scanf("%d",&Emp[i].Id);
Printf("\n\tEnter Employee Name : ");
Scanf("%s",&Emp[i].Name);
Printf("\n\tEnter Employee Age : ");
Scanf("%d",&Emp[i].Age);
Printf("\n\tEnter Employee Salary : ");
Scanf("%ld",&Emp[i].Salary);
}
Printf("\nDetails of Employees");
For(i=0;i<3;i++)
Printf("\n%d\t%s\t%d\t%ld",Emp[i].Id,Emp[i].Name,Emp[i].Age,Emp[i].Salary);
}
Output :
Enter details of 1 Employee
Enter Employee Id : 101
Enter Employee Name : Suresh
Enter Employee Age : 29
Enter Employee Salary : 45000
Enter details of 2 Employee
Enter Employee Id : 102
Enter Employee Name :Mukesh
Enter Employee Age : 31
Enter Employee Salary : 51000
Enter details of 3 Employee
Enter Employee Id : 103
Enter Employee Name : Ramesh
Enter Employee Age : 28
Enter Employee Salary : 47000
Details of Employees
101 Suresh 29 45000
102 Mukesh 31 51000
103 Ramesh 28 47000
In the above example, we are getting and displaying the data of 3 employee using
Array of object. Statement 1 is creating an array of Employee Emp to store the records
Of 3 employees.
Q.6 Explain Array within Structure with example
As we know, structure is collection of different data type. Like normal data type, It can
Also store an array as well.
Syntax for array within structure
Structstruct-name
{
Datatype var1; // normal variable
Datatype array [size]; // array variable
- - - - - - - - - -
- - - - - - - - - -
DatatypevarN;
};
Structstruct-name obj;
Example for array within structure
Struct Student
{
Int Roll;
Char Name[25];
Int Marks[3]; //Statement 1 : array of marks
Int Total;
FloatAvg;
};
Void main()
{
Inti;
Struct Student S;
Printf("\n\nEnter Student Roll : ");
Scanf("%d",&S.Roll);
Printf("\n\nEnter Student Name : ");
Scanf("%s",&S.Name);
S.Total = 0;
For(i=0;i<3;i++)
{
Printf("\n\nEnter Marks %d : ",i+1);
Scanf("%d",&S.Marks[i]);
S.Total = S.Total + S.Marks[i];
}
S.Avg = S.Total / 3;
Printf("\nRoll : %d",S.Roll);
Printf("\nName : %s",S.Name);
Printf("\nTotal : %d",S.Total);
Printf("\nAverage : %f",S.Avg);
}
Output :
Enter Student Roll : 10
Enter Student Name : Kumar
Enter Marks 1 : 78
Enter Marks 2 : 89
Enter Marks 3 : 56
Roll : 10
Name : Kumar
Total : 223
Average : 74.00000
In the above example, we have created an array Marks[ ] inside structure representing
3 marks of a single student.Marks[ ] is now a member of structure student and to
Access Marks[ ] we have used dot operator(.) along with object S.
Q.7 Explain union in detail
Unions are quite similar to the structures in C. Union is also a derived type as
Structure. Union can be defined in same manner as structures just the keyword
Used in defining union in union where keyword used in defining structure was struct.
Union car
{
Char name[50];
Int price;
};
Union variables can be created in similar manner as structure variable.
Union car
{
Char name[50];
Int price;
}c1, c2, *c3;
OR;
Union car
{
Char name[50];
Int price;
};
-------Inside Function-----------
Union car c1, c2, *c3;
In both cases, union variables c1, c2 and union pointer variable c3 of type union
Car is created.
- Memory allocation for union
Like structure memory is allocated to union only when we create the variable of it.
The memory is allocated to union according to the largest data members of the union.
- Accessing members of an union
Array elements are accessed using the Subscript variable , Similarly Union members are accessed using dot [.] operator.
(.) is called as “union member Operator”.
Use this Operator in between “Union variable”&“member name”
Union employee
{
Int id;
Char name[50];
Float salary;
} ;
Void main()
{
Union employee e1= { 1, “ABC”, 50000 };
Printf(“%d”, e. Id);
Printf(“%s”, e. Name);
}
O/P- garbage value, ABC
Q.8 Give some of the functions with example
C fputc() and fgetc()
Writing File :fputc() function
The fputc() function is used to write a single character into file. It outputs a character to a stream.
Syntax:
- Int fputc(int c, FILE *stream)
Example:
- #include <stdio.h>
- Main(){
- FILE *fp;
- Fp = fopen("file1.txt", "w");//opening file
- Fputc('a',fp);//writing single character into file
- Fclose(fp);//closing file
- }
File1.txt
Reading File :fgetc() function
The fgetc() function returns a single character from the file. It gets a character from the stream. It returns EOF at the end of file.
Syntax:
- Int fgetc(FILE *stream)
Example:
- #include<stdio.h>
- #include<conio.h>
- Void main(){
- FILE *fp;
- Char c;
- Clrscr();
- Fp=fopen("myfile.txt","r");
- While((c=fgetc(fp))!=EOF){
- Printf("%c",c);
- }
- Fclose(fp);
- Getch();
- }
Myfile.txt
This is simple text message
Q.9 Write into a file in file handling with examples
Se the code to get the idea how we write into a file
Example Code
#include <stdio.h>
Int main() {
FILE *fp;
Char *filename = "sample.txt";
Char *content = "Hey there! You've successfully created a file with content in c programming language.";
/* open for writing */
Fp = fopen(filename, "w");
If(fp == NULL ) {
Printf("%s: failed to open. \n", filename);
Return -1;
} else {
Printf("%s: opened in write mode.\n", filename);
}
/* Write content to file */
Fprintf(fp, "%s\n", content);
If( !fclose(fp) )
Printf("%s: closed successfully.\n", filename);
Return 0;
}
Output
Sample.txt: opened in write mode.
Sample.txt: closed successfully.
Q.10 Explain Appending into a file in file handling.
Se the code to get the idea how we can append lines into a file.
Make a file (file_append.txt)
This text was already there in the file.
Example Code
#include <stdio.h>
Int main() {
FILE *fp;
Charch;
Char *filename = "file_append.txt";
Char *content = "This text is appeneded later to the file, using C programming.";
/* open for writing */
Fp = fopen(filename, "r");
Printf("\nContents of %s -\n\n", filename);
While ((ch = fgetc(fp) )!= EOF) {
Printf ("%c", ch);
}
Fclose(fp);
Fp = fopen(filename, "a");
/* Write content to file */
Fprintf(fp, "%s\n", content);
Fclose(fp);
Fp = fopen(filename, "r");
Printf("\nContents of %s -\n", filename);
While ((ch = fgetc(fp) )!= EOF) {
Printf ("%c", ch);
}
Fclose(fp);
Return 0;
}
Output
Contents of file_append.txt -
This text was already there in the file.
Appending content to file_append.txt...
Content of file_append.txt after 'append' operation is -
This text was already there in the file.
This text is appeneded later to the file, using C programming.