Question 1: Write a programme to illustrate the different ways of declaration and initialization of structure variable by storing information of three student
Solution:
#include <conio.h>
#include <stdio.h>
#include <string.h>
int main()
{
//Different ways of declaring structure variable
struct info
{
int sno;
char name[20];
char add[20];
} s1, s2;
//Different ways of initialising structure varibles
struct info stu1 = {1, "ajay", "dehradun"};
struct info stu2, stu3;
stu2.sno = 2;
//stu2.name="rashmi";//wrong
strcpy(stu2.name, "rashmi");
strcpy(stu2.add, "delhi");
printf("enter the sno,name and add of third student\n");
scanf("%d%s%s", &stu3.sno, stu3.name, stu3.add);
printf("\ndetails of students are\n");
printf("\ndetails of 1st stu->%d\t%s\t%s", stu1.sno, stu1.name, stu1.add);
printf("\ndetails of 2nd stu->%d\t%s\t%s", stu2.sno, stu2.name, stu2.add);
printf("\ndetails of 3rd stu->%d\t%s\t%s", stu3.sno, stu3.name, stu3.add);
return 0;
}
You can check the solution:- Check here
Question 2: Write a program to store and print information of a student where information Comprises of student's name, son, and marks in 4 subjects.
Solution:
#include <stdio.h>
#include <conio.h>
int main()
{
typedef struct
{
int sno;
char name[20];
} student;
student s1;
printf("Enter the details of students\n");
printf("Enter sno and name\n");
scanf("%d%s", &s1.sno, s1.name);
printf("The details of students are\n");
printf("Sno-%d Name-%s\n", s1.sno, s1.name);
return 0;
}
You can check the solution:- Check here
Question 3: Write a c program to input Name, roll no. and percentage of n students. Calculate average percentages of class and print the details of all students having percentages greater than or equal to the average percentage.
Solution:
#include <stdio.h>
#include <string.h>
struct stu
{
char Name[15];
int Rn;
float per;
} s1[100];
int main()
{
int i, n;
float avgper, sumper;
printf("Enter no. of Students:");
scanf("%d", &n);
for (i = 0; i < n; i++)
{
printf("Name:");
fflush(stdin);
gets(s1[i].Name);
printf("Roll no. :");
scanf("%d", &s1[i].Rn);
printf("Enter percentage");
scanf("%f", &s1[i].per);
}
//calculating sum of percentage of class
for (i = 0; i < n; i++)
sumper = sumper + s1[i].per;
//Average percentage of whole class
avgper = (float)sumper / n;
printf("Student(s) with percentage greater than average\n");
for (i = 0; i < n; i++)
{
if (avgper <= s1[i].per)
{
printf("\nName:");
puts(s1[i].Name);
printf("\nRoll no. %d", s1[i].Rn);
}
}
return 0;
}
You can check the solution:- Check here
Question 4: Write a C program to enter name, roll no., marks in 4 sub of n students then calculate percentage for each student and print name and roll no. of a student with highest percentage.
Solution:
#include <stdio.h>
#include <string.h>
struct time_struct
{
int hours;
int minutes;
int seconds;
};
struct time_struct insert(struct time_struct);
void display(struct time_struct);
int main()
{
struct time_struct t1, t2;
t2 = insert(t1);
display(t2);
return 0;
}
struct time_struct insert(struct time_struct t)
{
printf("Enter hours:");
scanf("%d", &t.hours);
printf("Enter minutes:");
scanf("%d", &t.minutes);
printf("Enter seconds:");
scanf("%d", &t.seconds);
return t;
}
void display(struct time_struct t)
{
printf("Time: %d:%d:%d", t.hours, t.minutes, t.seconds);
}
You can check the solution:- Check here
Question 5: Write a C program to store the details of an employee where details consist of employye's sno, name, dob and doj (Structure within Structure)
Solution:
#include <stdio.h>
#include <conio.h>
typedef struct date
{
int day;
int mon;
int year;
} date;
typedef struct
{
int sno;
char name[20];
date dob, doj;
} employee;
int main()
{
int i, n;
employee e[10];
printf("enter the no employees\n");
scanf("%d", &n);
printf("enter the details of employee\n");
for (i = 0; i < n; i++)
{
printf("enter the sno and name of employee\n");
scanf("%d%s%", &e[i].sno, e[i].name);
printf("enter the dob of employee\n");
scanf("%d%d%d", &e[i].dob.day, &e[i].dob.mon, &e[i].dob.year);
printf("enter the doj of employee\n");
scanf("%d%d%d", &e[i].doj.day, &e[i].doj.mon, &e[i].doj.year);
}
printf("the details of employee are \n");
for (i = 0; i < n; i++)
{
printf("\n");
printf("sno-%d\nname-%s\n", e[i].sno, e[i].name);
printf("dob-%d%d%d\n", e[i].dob.day, e[i].dob.mon, e[i].dob.year);
printf("doj-%d%d%d\n", e[i].doj.day, e[i].doj.mon, e[i].doj.year);
}
return 0;
}
You can check the solution:- Check here
Question 6: Write a C program to accept records of employees.
The structure is:
Struct emp
{ char name[20];
int age;
int basic;
}
calculate total salary as-total salary=basic+hra+da=10% of basic hra=5% of basic salary Display age, the total salary of an employee in descending order on the basis of total salary. Create separate function for input & display
Solution:
struct emp
{
char name[20];
int age;
int basic;
};
#include <stdio.h>
void input(struct emp[]);
void display(struct emp[]);
int main()
{
struct emp s[5], temp;
int i, j;
input(s);
for (i = 0; i < 5; i++)
{
for (j = 0; j < 5 - 1; j++)
{
if (s[j].basic < s[j + 1].basic)
{
temp = s[j];
s[j] = s[j + 1];
s[j + 1] = temp;
}
}
}
display(s);
return 0;
}
void input(struct emp s[5])
{
int i;
for (i = 0; i < 5; i++)
{
printf("Enter Name : ");
fflush(stdin);
gets(s[i].name);
printf("Enter age : ");
scanf("%d", &s[i].age);
printf("Enter Basic Salary : ");
scanf("%d", &s[i].basic);
}
}
void display(struct emp s[5])
{
int i;
float total, hra, da;
for (i = 0; i < 5; i++)
{
printf("\nName : ");
puts(s[i].name);
printf("Age : %d\n", s[i].age);
da = 0.1 * s[i].basic;
hra = 0.05 * s[i].basic;
total = s[i].basic + hra + da;
printf("Total Salary : %f", total);
}
}
You can check the solution:- Check here
Question 7: Write a C program to read and print the values of a structure variable using structure pointer.
Solution:
#include <stdio.h>
#include <conio.h>
int main()
{
typedef struct student
{
int rollno;
char name[20];
} stud;
stud s1, s2, *p1, *p2;
p1 = &s1;
p2 = &s2;
printf("First Method \nenter the roll no and name\n");
scanf("%d%s", &(*p2).rollno, (*p2).name);
printf("rollno-%d name-%s", (*p2).rollno, (*p2).name);
printf("\n\n");
printf("Second Method \nenter the roll no and name\n");
scanf("%d%s", &(p1->rollno), p1->name);
printf("rollno-%d name-%s", p1->rollno, p1->name);
return 0;
}
You can check the solution:- Check here
Question 8: Write a program to read and print the following information using union :name, rollno, percentage, grade.
Solution:
#include <conio.h>
#include <stdio.h>
int main()
{
union student
{
char grade;
char name[20];
int roll;
float per;
} u1;
printf("enter the name\n");
gets(u1.name);
printf("name->%s\n", u1.name);
printf("enter the roll\n");
scanf("%d", &u1.roll);
printf("roll no->%d\n", u1.roll);
printf("enter the percentage\n");
scanf("%f", &u1.per);
printf("percentage->%f\n", u1.per);
printf("enter the grade\n");
fflush(stdin);
scanf("%c", &u1.grade);
printf("grade->%c", u1.grade);
//Now printing complete details
printf("\nname-%s\n", u1.name); //Garbage
printf("\nroll no-%d\n", u1.roll); //Garbage
printf("\npercentage-%f\n", u1.per); //Garbage
printf("\ngrade-%c", u1.grade);
return 0;
}
You can check the solution:- Check here
Question 9:Write a C program to compare the memory allocations between structure and union variable.
Solution:
#include <stdio.h>
#include <conio.h>
int main()
{
typedef union
{
int roll;
char grade;
float per;
} uni1;
typedef struct
{
int roll;
char grade;
float per;
} str1;
uni1 u1;
str1 s1;
printf("\nSTRUCTURE");
printf("\nsize of s1 is %d", sizeof(s1));
printf("\naddress of s1 is %u", &s1);
printf("\naddress of s1.roll is %u", &s1.roll);
printf("\naddress of s1.grade is %u", &s1.grade);
printf("\naddress of s1.per is %u", &s1.per);
printf("\nUNION");
printf("\nsize of u1 is %d", sizeof(u1));
printf("\naddress of u1 is %u", &u1);
printf("\naddress of u1.roll is %u", &u1.roll);
printf("\naddress of u1.grade is %u", &u1.grade);
printf("\naddress of u1.per is %u", &u1.per);
return 0;
}
You can check the solution:- Check here
Question 10:Develop a program to define, Assign, read and display two different structures:
1. Student Information such as:
Name
Student id
Section
Contact number etc.
2. Bank Account information:
Bank Account holder’ name
Bank Account number
IFSC code
Account type etc.
Solution:
#include <stdio.h>
#include <string.h>
struct bank
{
char name[20], type[20];
long int number;
int IFSC;
};
struct student
{
char name[20], section;
int student_id;
int contact1, contact2;
struct bank stu_bank;
} stu;
struct student insert();
void display();
int main()
{
stu = insert();
display(stu);
return 0;
}
struct student insert(struct student stuin)
{
int i;
printf("\n--------------X--------Enter Student Information------------X-----------------\n");
printf("\tName: ");
gets(stuin.name);
printf("\tStudent id: ");
scanf("%d", &stuin.student_id);
printf("\tSecton: ");
fflush(stdin);
scanf("%c", &stuin.section);
printf("\tContact number(make space after 5 digit): ");
scanf("%d%d", &stuin.contact1, &stuin.contact2);
printf("\n--------------X--------Enter Bank Information------------X-----------------\n");
printf("\tBank holder name: ");
fflush(stdin);
gets(stuin.stu_bank.name);
printf("\tAccount number: ");
scanf("%d", &stuin.stu_bank.number);
printf("\tIFSC code: ");
scanf("%d", &stuin.stu_bank.IFSC);
printf("\tAccount type: ");
fflush(stdin);
gets(stuin.stu_bank.type);
return stuin;
}
void display(struct student stuin)
{
printf("\n--------------X--------------------X-----------------\n");
printf("\nName: %s\n", stuin.name);
printf("Student id: %d\n", stuin.student_id);
printf("Section: %c\n", stuin.section);
printf("Contact number: %ld\n", stuin.contact1, &stuin.contact2);
printf("Bank holder name: %s\n", stuin.stu_bank.name);
printf("Account number: %ld\n", stuin.stu_bank.number);
printf("IFSC code: %d\n", stuin.stu_bank.IFSC);
printf("Account type: %s\n", stuin.stu_bank.type);
printf("\n--------------X--------------------X-----------------\n");
}
You can check the solution:- Check here
Question 11:Develop a program in C to read a structure in the main program of an Employee that contains Name, EmpCode, and Salary as the members. Write a function to the details of the employee
Solution:
#include <stdio.h>
struct empcode
{
int a;
char s;
};
struct date
{
int day, year;
char mon[20];
};
//structure creation
struct employe
{
char name[50]; // structure member1
struct empcode ecode; // structure member2
struct date dob; // structure member3
int netsal; // structure member3
} emp; // structure variable
void display();
int main()
{
int i;
printf(" PROGRAM TO PRINT DETAILS OF AN EMPLOYEE\n");
printf(" Enter the following details of employe\n");
printf("--------------X---------DETAIL HERE------X-----------------\n");
//Taking information from keyboard and store it by using structure variable std
printf("\tName:");
gets(emp.name);
printf("\tEmp code:");
scanf("%c%d", &emp.ecode.s, &emp.ecode.a);
printf("\tDate of birth:");
scanf("%d%s%d", &emp.dob.day, &emp.dob.mon, &emp.dob.year);
printf("\tsalary:");
scanf("%d", &emp.netsal);
display(emp);
}
void display(struct employe emp)
{
int i;
printf("\n--------------X------------X------------\n");
printf("\tName: %s\n", emp.name);
printf("\tEmp code: %c%d", emp.ecode.s, emp.ecode.a);
printf("\n\tDate of birth: %d %s %d\n", emp.dob.day, emp.dob.mon, emp.dob.year);
printf("\tsalary: Rs.%d\n", emp.netsal);
printf("\n--------------X------------X------------\n");
}
You can check the solution:- Check here
Question 12:A Mobile store needs to manage as its inventory it has different mobiles stored as brand name along with its corresponding quantities and price. Design a C program using appropriate data types to automate the process. The program should facilitate in storing, searching and displaying the total cost of the inventory of a specific brand of mobiles. Implement different functions for storing and searching the details of a mobile.
Solution:
#include <stdio.h>
#include <string.h>
#define max 100
struct mobile
{
char mobilebrand[100];
int qty;
int price;
};
int main()
{
int choice, n;
char brand[max];
struct mobile m1[max];
printf("Menu\n");
printf("1. Sorting\n2. Searching\n3.Exit\n");
while (1)
{
printf("Enter your choice: ");
scanf("%d", &choice);
switch (choice)
{
case 1:
{
printf("Enter the number of mobiles brands you want to sort: ");
scanf("%d",&n);
getchar();
for (int i = 0; i < n; i++)
{
printf("Mobile brand: ");
scanf("%s", &m1[i].mobilebrand);
printf("Quantity: ");
scanf("%d", &m1[i].qty);
printf("Price(Rs): ");
scanf("%d", &m1[i].price);
printf("\n");
}
break;
}
case 2:
{
printf("Enter mobile brand to search: ");
scanf("%s", &brand); //check here if erro
if(strcmp(brand,m1[0].mobilebrand)==0)
{
printf("Stock in hand:%d\n", m1[0].qty);
printf("Total Cost of Inventory (Rs): %d\n", m1[0].qty * m1[0].price);
}
else if(strcmp(brand,m1[1].mobilebrand)==0)
{
printf("Stock in hand:%d\n", m1[1].qty);
printf("Total Cost of Inventory (Rs): %d\n", m1[1].qty * m1[1].price);
}
break;
}
case 3:
goto end;
default:
break;
}
}
end:
return 0;
}
You can check the solution:- Check here
Question 13:A Computer Shoppe would like to automate its inventory operations. The owner would like to maintain the stock along with the price in his inventory. Design a program with appropriate data types available in C, so that he can track the number of Items in stock along with their total cost of inventory. Write a C program to store and search the inventory.
Solution:
#include <stdio.h>
#include <string.h>
#define max 100
struct mobile
{
char computerShop[100];
int qty;
int price;
};
int main()
{
int choice, n;
char brand[max];
struct mobile m1[max];
printf("\n");
printf("Menu\n");
printf("1. Stock Entry\n2. Search & Display \n3.Exit\n");
while (1)
{
printf("Enter your choice: ");
scanf("%d", &choice);
switch (choice)
{
case 1:
{
printf("Enter the number of items you want to store: ");
scanf("%d",&n);
getchar();
printf("\n");
for (int i = 0; i < n; i++)
{
printf("Iteams name : ");
scanf("%s", &m1[i].computerShop);
printf("Quantity: ");
scanf("%d", &m1[i].qty);
printf("Price(Rs): ");
scanf("%d", &m1[i].price);
printf("\n");
}
break;
}
case 2:
{
printf("Enter mobile brand to search: ");
scanf("%s", &brand); //check here if error
for (int i = 0; i < n; i++)
{
if(strcmp(brand,m1[i].computerShop)==0)
{
printf("Stock in hand:%d\n", m1[i].qty);
printf("Total Cost of Inventory (Rs): %d\n", m1[i].qty * m1[i].price);
}
}
break;
}
case 3:
goto end;
default:
printf("\nEnter with in the choice list\n\n");
break;
}
}
end:
return 0;
}
You can check the solution:- Check here
Question 14: A user is interested in maintaining a telephone directory by storing N names along with their numbers and cities they reside in. The directory needs to be sorted in alphabetical order so that searching becomes easier. Design a C program to store the names using appropriate data types and sort the same on Names using pointers.
Solution:
#include <stdio.h>
#include <string.h>
struct cricket
{
char pname[20];
char tname[20];
int number;
int number1;
} data[10], temp;
void main()
{
int i, j, n;
printf("\nEnter number of phone number you want to store : ");
scanf("%d", &n);
for (i = 0; i < n; i++)
{
printf("\nEnter Person Name : ");
scanf("%s", data[i].pname);
printf("Enter Town Name : ");
scanf("%s", data[i].tname);
printf("Enter mobile number(after 5 digit press space): ");
scanf("%d", &data[i].number);
scanf("%d", &data[i].number1);
printf("\n");
}
for (i = 1; i < n; i++)
for (j = 0; j < n - i; j++)
{
if (strcmp(data[j].pname, data[j + 1].pname) > 0)
{
temp = data[j];
data[j] = data[j + 1];
data[j + 1] = temp;
}
}
for (i = 0; i < n; i++)
{
printf("\n%s\t%s\t%d%d", data[i].pname, data[i].tname, data[i].number, data[i].number1);
}
}
You can check the solution:- Check here
Question 15: A bookseller wants to computerize his shop to keep track of the quantity of books in his shop. Assuming minimum details relevant to track the quantity of Books desired. Can you help the book seller to store the information using appropriate data types available in C. Write the corresponding C program to facilitate in storing and printing the book details along with the number of quantity of the desired book Name or Title to the output screen.
Solution:
#include <stdio.h>
#include <string.h>
#include <ctype.h>
int main()
{
char name[ ][50] = {"A TIME TO KILL", "ABSALOM", "C++", "HTML", "SQL", "THE HOUSE OF MIRTH","A MODERN APPROACH","NUTSHELL","DATA STRUCTURE"}, item[10];
//declaring the string array and the character array that will contain the string to be matched
int store[ ] = {198, 762, 543, 870, 350, 90,675,435,322};
int i, x, f = 0;
/entering the item to be found in the string array/
printf("\n\tEnter the string to be searched(only enter in capital letter):");
scanf("%s", &item);
/process for finding the item in the string array/
for (i = 0; i < 5; i++)
{
x = strcmp(&name[i][0], item);
//compares the string in the array with the item and if match is found returns 0 and stores it in variable x
if (x == 0)
f = i;
}
printf("\n--------------------X-----------X--------------X-------------------------\n");
/if match is not found/
if (f == 0)
printf("\tThe item does not match any name in the list\n");
/If the match is found/
else
printf("\t(%s)Item Found. Item quantity available is- %d\n",name[f], store[f]);
return 0;
}
You can check the solution:- Check here
Question 16: Explain the significance of a structure in C and illustrate the different ways a structure can be declared.
Solution:
C Structures
Structure is a user-defined datatype in C language which allows us to combine data of different types together. Structure helps to construct a complex data type which is more meaningful. It is somewhat similar to an Array, but an array holds data of similar type only. But structure on the other hand, can store data of any type, which is practical more useful.
For example: If I have to write a program to store Student information, which will have Student's name, age, branch, permanent address, father's name etc, which included string values, integer values etc, how can I use arrays for this problem, I will require something which can hold data of different types together.
In structure, data is stored in form of records.
Defining a structure:-
struct keyword is used to define a structure. struct defines a new data type which is a collection of primary and derived data types.
Syntax:
struct [structure_tag]
{
//member variable 1
//member variable 2
//member variable 3
...
}[structure_variables];
As you can see in the syntax above, we start with the struct keyword, then it's optional to provide your structure a name, we suggest you to give it a name, then inside the curly braces, we have to mention all the member variables, which are nothing but normal C language variables of different types like int, float, array etc.
After the closing curly brace, we can specify one or more structure variables, again this is optional.
Example of Structure:-
struct Student
{
char name[25];
int age;
char branch[10];
// F for female and M for male
char gender;
};
Here struct Student declares a structure to hold the details of a student which consists of 4 data fields, namely name, age, branch and gender. These fields are called structure elements or members.
Each member can have different datatype, like in this case, name is an array of char type and age is of int type etc. Student is the name of the structure and is called as the structure tag.
Declaring Structure Variables:-
It is possible to declare variables of a structure, either along with structure definition or after the structure is defined. Structure variable declaration is similar to the declaration of any normal variable of any other datatype. Structure variables can be declared in following two ways:
1) Declaring Structure variables separately
struct Student
{
char name[25];
int age;
char branch[10];
//F for female and M for male
char gender;
};
struct Student S1, S2; //declaring variables of struct Student
2) Declaring Structure variables with structure definition
struct Student
{
char name[25];
int age;
char branch[10];
//F for female and M for male
char gender;
}S1, S2;
Here S1 and S2 are variables of structure Student. However this approach is not much recommended.
Accessing Structure Members:-
Structure members can be accessed and assigned values in a number of ways. Structure members have no meaning individually without the structure. In order to assign a value to any structure member, the member name must be linked with the structure variable using a dot . operator also called period or member access operator.
For example:
#include<stdio.h>
#include<string.h>
struct Student
{
char name[25];
int age;
char branch[10];
//F for female and M for male
char gender;
};
int main()
{
struct Student s1;
/* s1 is a variable of Student type and age is a member of Student */
s1.age = 18;
/* using string function to add name */
strcpy(s1.name, "Viraaj");
/* displaying the stored values */
printf("Name of Student 1: %s\n", s1.name);
printf("Age of Student 1: %d\n", s1.age);
return 0;
}
Output:-
Name of Student 1: Viraaj
Age of Student 1: 18
We can also use scanf( ) to give values to structure members through terminal.
scanf(" %s ", s1.name);
scanf(" %d ", &s1.age);
Structure Initialization:-
Like a variable of any other datatype, structure variable can also be initialized at compile time.
struct Patient
{
float height;
int weight;
int age;
};
struct Patient p1 = { 180.75 , 73, 23 }; //initialization
or,
struct Patient p1;
p1.height = 180.75; //initialization of each member separately
p1.weight = 73;
p1.age = 23;
Array of Structure:-
We can also declare an array of structure variables. in which each element of the array will represent a structure variable. Example : struct employee emp[5];
The below program defines an array emp of size 5. Each element of the array emp is of type Employee.
#include<stdio.h>
struct Employee
{
char ename[10];
int sal;
};
struct Employee emp[5];
int i, j;
void ask()
{
for(i = 0; i < 3; i++)
{
printf("\nEnter %dst Employee record:\n", i+1);
printf("\nEmployee name:\t");
scanf("%s", emp[i].ename);
printf("\nEnter Salary:\t");
scanf("%d", &emp[i].sal);
}
printf("\nDisplaying Employee record:\n");
for(i = 0; i < 3; i++)
{
printf("\nEmployee name is %s", emp[i].ename);
printf("\nSlary is %d", emp[i].sal);
}
}
void main()
{
ask( );
}
Nested Structures:-
Nesting of structures, is also permitted in C language. Nested structures means, that one structure has another structure as member variable.
Example:
struct Student
{
char[30] name;
int age;
/* here Address is a structure */
struct Address
{
char[50] locality;
char[50] city;
int pincode;
}addr;
};
Summary:-
- A structure is usually used when we wish to store dissimilar data together.
- Structure elements can be accessed through a structure variable using a dot (.) operator.
- Structure elements can be accessed through a pointer to a structure using the arrow (->) operator.
- All elements of one structure variable can be assigned to another structure variable using the assignment (=) operator.
- It is possible to pass a structure variable to a function either by value or by address.
- It is possible to create an array of structures.
Question 17: Explain with an example the passing of a structure to a function by reference.
Solution:
Structure and Function in C
Using function we can pass structure as function argument and we can also return structure from function.
Passing structure as function argument:-
Structure can be passed to function through its object therefore passing structure to function or passing structure object to function is same thing because structure object represents the structure. Like normal variable, structure variable(structure object) can be pass by value or by references / addresses.
Passing Structure by Value:-
In this approach, the structure object is passed as function argument to the definition of function, here object is representing the members of structure with their values.
Example for passing structure object by value:-
#include<stdio.h>
struct Employee
{
int Id;
char Name[25];
int Age;
long Salary;
};
void Display(struct Employee);
void main()
{
struct Employee Emp = {1,"Kumar",29,45000};
Display(Emp);
}
void Display(struct Employee E)
{
printf("\n\nEmployee Id : %d",E.Id);
printf("\nEmployee Name : %s",E.Name);
printf("\nEmployee Age : %d",E.Age);
printf("\nEmployee Salary : %ld",E.Salary);
}
Output :-
Employee Id : 1
Employee Name : Kumar
Employee Age : 29
Employee Salary : 45000
Passing Structure by Reference:-
In this approach, the reference/address structure object is passed as function argument to the definition of function.
Example for passing structure object by reference:-
#include<stdio.h>
struct Employee
{
int Id;
char Name[25];
int Age;
long Salary;
};
void Display(struct Employee*);
void main()
{
struct Employee Emp = {1,"Kumar",29,45000};
Display(&Emp);
}
void Display(struct Employee *E)
{
printf("\n\nEmployee Id : %d",E->Id);
printf("\nEmployee Name : %s",E->Name);
printf("\nEmployee Age : %d",E->Age);
printf("\nEmployee Salary : %ld",E->Salary);
}
Output :
Employee Id : 1
Employee Name : Kumar
Employee Age : 29
Employee Salary : 45000
Function Returning Structure:-
Structure is user-defined data type, like built-in data types structure can be return from function.
Example for passing structure object by reference
#include<stdio.h>
struct Employee
{
int Id;
char Name[25];
int Age;
long Salary;
};
Employee Input); //Statement 1
void main()
{
struct Employee Emp;
Emp = Input();
printf("\n\nEmployee Id : %d",Emp.Id);
printf("\nEmployee Name : %s",Emp.Name);
printf("\nEmployee Age : %d",Emp.Age);
printf("\nEmployee Salary : %ld",Emp.Salary);
}
Employee Input()
{
struct Employee E;
printf("\nEnter Employee Id : ");
scanf("%d",&E.Id);
printf("\nEnter Employee Name : ");
scanf("%s",&E.Name);
printf("\nEnter Employee Age : ");
scanf("%d",&E.Age);
printf("\nEnter Employee Salary : ");
scanf("%ld",&E.Salary);
return E; //Statement 2
}
Output :
Enter Employee Id : 10
Enter Employee Name : Ajay
Enter Employee Age : 25
Enter Employee Salary : 15000
Employee Id : 10
Employee Name : Ajay
Employee Age : 25
Employee Salary : 15000
In the above example, statement 1 is declaring Input() with return type Employee. As we know structure is user-defined data type and structure name acts as our new user-defined data type, therefore we use structure name as function return type.
Input( ) have local variable E of Employee type. After getting values from user statement 2 returns E to the calling function and display the values.
Question 18: List the differences between structure and a union.
Solution:-
Here is the important difference between structure and union:
Structure:-
- You can use a struct keyword to define a structure.
- Every member within structure is assigned a unique memory location.
- Changing the value of one data member will not affect other data members in structure.
- It enables you to initialize several members at once.
- The total size of the structure is the sum of the size of every data member.
- It is mainly used for storing various data types.
- It occupies space for each and every member written in inner parameters.
- You can retrieve any member at a time.
- It supports flexible array.
Union:-
- You can use a union keyword to define a union.
- In union, a memory location is shared by all the data members.
- Changing the value of one data member will change the value of other data members in union.
- It enables you to initialize only the first member of union.
- The total size of the union is the size of the largest data member.
- It is mainly used for storing one of the many data types that are available.
- It occupies space for a member having the highest size written in inner parameters.
- You can access one member at a time in the union.
- It does not support a flexible array.
Advantages of structure
Here are pros/benefits for using structure:
- Structures gather more than one piece of data about the same subject together in the same place.
- It is helpful when you want to gather the data of similar data types and parameters like first name, last name, etc.
- It is very easy to maintain as we can represent the whole record by using a single name.
- In structure, we can pass complete set of records to any function using a single parameter.
- You can use an array of structure to store more records with similar types.
Advantages of union
Here, are pros/benefits for using union:
- It occupies less memory compared to structure.
- When you use union, only the last variable can be directly accessed.
- Union is used when you have to use the same memory location for two or more data members.
- It enables you to hold data of only one data member.
- Its allocated space is equal to maximum size of the data member.
Disadvantages of structure:-
Here are cons/drawbacks for using structure:
- If the complexity of IT project goes beyond the limit, it becomes hard to manage.
- Change of one data structure in a code necessitates changes at many other places. Therefore, the changes become hard to track.
- Structure is slower because it requires storage space for all the data.
- You can retrieve any member at a time in structure whereas you can access one member at a time in the union.
- Structure occupies space for each and every member written in inner parameters while union occupies space for a member having the highest size written in inner parameters.
- Structure supports flexible array. Union does not support a flexible array.
Disadvantages of union:-
Here, are cons/drawbacks for using union:
- You can use only one union member at a time.
- All the union variables cannot be initialized or used with varying values at a time.
- Union assigns one common storage space for all its members.
KEY DIFFERENCES:
- Every member within structure is assigned a unique memory location while in union a memory location is shared by all the data members.
- Changing the value of one data member will not affect other data members in structure whereas changing the value of one data member will change the value of other data members in union.
- Structure is mainly used for storing various data types while union is mainly used for storing one of the many data types.
- In structure, you can retrieve any member at a time on the other hand in union, you can access one member at a time.
- Structure supports flexible array while union does not support a flexible array.
0 Comments
If you are a good learner please leave a challenging question on comment box for us when you visited this website ( Coding with Fun).