Structures and Unions in C Language, Exercises of Programming for Engineers

The concepts of structures and unions in c language, including their definition, initialization, access, arrays, and limitations. It also explains how to pass structures to functions and how structures are different from unions.

Typology: Exercises

2011/2012

Uploaded on 07/25/2012

hun_i
hun_i 🇮🇳

3.7

(3)

54 documents

1 / 14

Toggle sidebar

This page cannot be seen from the preview

Don't miss anything!

bg1
OBJECT ORIENTED PROGRAMMING
LAB 01
STRUCTURES
Summary
1) Structures
- Declaration of a Structure
- Initializing Structures
- Functions and structures
- Arrays of structures
- sizeof operator
2) Sample Program
3) Unions
Structures
Today, we will discuss the concepts of structures and unions which are very interesting
part of C language. These are also in C++. After dilating upon structures, we will move to
the concept of classes, quite similar to „structures‟.
What a structure is? We can understand „structure‟ with the example of students of a
class discussed in some of the earlier lectures. Suppose we have data about students of a
class i.e. name, addresses, date of birth, GPA and courses of study. This information is
related to only a single entity i.e. student. To understand the matter further, we can think
of a car with its specifications like model, manufacturer company, number of seats and so
on. But there is always a requirement in most of our data processing applications that the
relevant data should be grouped and handled as a group. This is what the concept of
structure is. In structure, we introduce a new data type. In the previous lectures, we had
been dealing with int, float, double and char in our programs. You are fully familiar with
the term ‟strings‟ but there is no data type called strings. We have used „array of char‟ as
strings. While dealing with numbers, there is no built-in mechanism to handle the
complex numbers. This means that there is no data type like complex. The FORTRAN
language (Formula Translation) written for scientific application, has a complex data
type. Therefore, in FORTRAN, we can say complex x; now x is a variable of type
complex and has a real part and an imaginary part. There is no complex data type in C
and C++. While trying to solve the quadratic equation on the similar grounds, we may
have a complex number as answer i.e. if we have to calculate the square root of -1, an
iota (ί) will be used. So the combination of real and imaginary parts is called complex
number. In C, C++ we deal with such situations with structures. So a structure is not
simply a grouping of real world data like students, car etc, it also has mathematical usage
like complex number. The definition of structure is as under:
“A structure is a collection of variables under a single name. These variables can be of
docsity.com
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe

Partial preview of the text

Download Structures and Unions in C Language and more Exercises Programming for Engineers in PDF only on Docsity!

OBJECT ORIENTED PROGRAMMING

LAB 01

STRUCTURES

Summary

1) Structures

  • Declaration of a Structure
  • Initializing Structures
  • Functions and structures
  • Arrays of structures
  • sizeof operator **2) Sample Program
  1. Unions**

Structures

Today, we will discuss the concepts of structures and unions which are very interesting part of C language. These are also in C++. After dilating upon structures, we will move to the concept of classes, quite similar to „structures‟.

What a structure is? We can understand „structure‟ with the example of students of a class discussed in some of the earlier lectures. Suppose we have data about students of a class i.e. name, addresses, date of birth, GPA and courses of study. This information is related to only a single entity i.e. student. To understand the matter further, we can think of a car with its specifications like model, manufacturer company, number of seats and so on. But there is always a requirement in most of our data processing applications that the relevant data should be grouped and handled as a group. This is what the concept of structure is. In structure, we introduce a new data type. In the previous lectures, we had been dealing with int, float, double and char in our programs. You are fully familiar with the term ‟strings‟ but there is no data type called strings. We have used „array of char‟ as strings. While dealing with numbers, there is no built-in mechanism to handle the complex numbers. This means that there is no data type like complex. The FORTRAN language (Formula Translation) written for scientific application, has a complex data type. Therefore, in FORTRAN, we can say complex x; now x is a variable of type complex and has a real part and an imaginary part. There is no complex data type in C and C++. While trying to solve the quadratic equation on the similar grounds, we may have a complex number as answer i.e. if we have to calculate the square root of -1, an iota (ί) will be used. So the combination of real and imaginary parts is called complex number. In C, C++ we deal with such situations with structures. So a structure is not simply a grouping of real world data like students, car etc, it also has mathematical usage like complex number. The definition of structure is as under:

“A structure is a collection of variables under a single name. These variables can be of

different types, and each has a name that is used to select it from the structure”

Declaration of a Structure:

Structures are syntactically defined with the word struct. So struct is another keyword that cannot be used as variable name. Followed by the name of the structure. The data, contained in the structure, is defined in the curly braces. All the variables that we have been using can be part of structure. For example:

struct student{ char name[60]; char address[100]; float GPA; };

Here we have a declared a structure, „student‟ containing different elements. The name of the student is declared as char array. For the address, we have declared an array of hundred characters. To store the GPA, we defined it as float variable type. The variables which are part of structure are called data members i.e. name, address and GPA are data members of student. Now this is a new data type which can be written as: student std1, std2; Here std1 and std2 are variables of type student like int x, y; x and y in this case are variables of int data type. This shows the power of C and C++ language and their extensibility. Moreover, it means that we can create new data types depending upon the requirements. Structures may also be defined at the time of declaration in the following manner:

struct student{ char name[60]; char address[100]; float GPA; }std1, std2;

We can give the variable names after the closing curly brace of structure declaration. These variables are in a comma-separated list.

Structures can also contain pointers which also fall under the category of data type. So we can have a pointer to something as a part of a structure. We can‟t have the same structure within itself but can have other structures. Let‟s say we have a structure of an address. It contains streetAddress like 34 muslim town, city like sukhar, rawalpindi, etc and country like Pakistan. It can be written in C language as:

Initializing Structures

We have so far learnt how to define a structure and declare its variables. Let‟s see how can we put the values in its data members. The following example can help us understand the phenomenon further.

struct student{ char name[64]; char course[128]; int age; int year; }; student s1, s2, s3;

Once the structure is defined, the variables of that structure type can be declared. Initialization may take place at the time of declaration i.e. student s1 = {“Ali”, “CS201”, 19, 2002 };

In the above statement, we have declared a variable s1 of data type student structure and initialize its data member. The values of data members of s1 are comma separated in curly braces. “Ali” will be assigned to name , “CS201” will be assigned to the course , 19 to age and 2002 to year. So far we have not touched these data members directly. To access the data members of structure, dot operator (.) is used. Therefore while manipulating name of s1 , we will say s1.name. This is a way of referring to a data member of a structure. This may be written as:

s1.age = 20; s1.year = 2002;

The above statement will assign the value 20 to the age data member of structure s1. Can we assign a string to the name of s1? Write programs to see how to do this? You may need string copy function to do this.

Similarly, to get the output of data members on the screen, we use dot operator. To display the name of s1 we can write it as:

cout << “The name of s1 = “ << s1.name;

Other data members can be displayed on the screen in the same fashion. Here is a simple example showing the initialization and displaying the structure.

/* Simple program showing the initialization of structure.*/ #include <iostream.h>

// Declaring student structure struct student{ char name[64]; char course[128]; int age; int year; };

main() {

// Initializing the structure student s1 = {"Ali", "CS201- Introduction to programming", 22, 2002}; cout << "Displaying the structure data members" << endl; cout << "The name is " << s1.name << endl; cout << "The course is " << s1.course << endl; cout << "The age is " << s1.age << endl; cout << "The year is " << s1.year << endl; }

The output of the above program is:

Displaying the structure data members The name is Ali The course is CS201- Introduction to programming The age is 22 The year is 2002

Here, s1 is a unit. The data members have been grouped together. If we have s1 and s2 as two variables of student type and want to copy the data of s1 to s2 , it can be written as: s2 = s1;

Functions and structures

We can pass structures to functions. Structures are passed into functions as per the C/C++ calling conventions by value. In other words, a copy of entire structure is put on the stack. The function is called which removes it from the stack and uses the structure. We can also pass the structures by reference to function. This can be performed in the same way we do with the normal variables i.e. pass the address of the structure to the function. This is call by reference.

When we pass an array to a function, the reference of the array is passed to the function.

Distance adddis(Distance dd1, Distance dd2) { Distance dd3; dd3.feet=dd1.feet+dd2.feet; dd3.inches=dd1.inches+dd2.inches; return dd3; }

Suppose we have a pointer to structure as student *sptr; here sptr is a pointer to student. Now s1 is a variable of type student and sptr = &s1 and sptr is pointing to s1. How can we access the data with sptr? We cannot say * sptr.name. The precedence of dot operator (.) is higher than * operator. So dot operator is evaluated first and then * operator. The compiler will give error on the above statement. To get the results, we have to evaluate * operator first i.e. (*sptr).name will give the desired result. There is another easy and short way to access the structure‟s data member i.e. using the arrow (->) in place of dot operator. We normally use the arrow (-> i.e. minus sign and then the greater than sign) to manipulate the structure‟s data with pointers. So to access the name with sptr we will write:

sptr->name;

Remember the difference between the access mechanism of structure while using the simple variable and pointer.

While accessing through a simple variable, use dot operator i.e. s1.name While accessing through the pointer to structure, use arrow operator i.e. sptr->name;

Following is the example, depicting the access mechanism of structure‟s data member using the pointer to structure.

The code of the sample example is:

/* This program shows the access of structure data members with pointer to structure */ #include <iostream.h>

// Declaration of student structure struct student{ char name[64]; char course[128]; int age; int year; };

main()

// Initializing the s student s1 = {"Ali", "CS201- Introduction to programming", 22, 2002}; student sptr; // Assigning a structure to pointer sptr = &s1; cout << "Displaying the structure data members using pointers" << endl; cout << "Using the * operator" << endl; cout << endl; cout << "The name is " << (sptr).name << endl; cout << "The course is " << (sptr).course << endl; cout << "The age is " << (sptr).age << endl; cout << "The year is " << (*sptr).year << endl; cout << endl; cout << "Using the -> operator" << endl; cout << endl; cout << "The name is " << sptr->name << endl; cout << "The course is " << sptr->course << endl; cout << "The age is " << sptr->age << endl; cout << "The year is " << sptr->year << endl; }

The output of the program is:

Displaying the structure data members using pointers Using the * operator The name is Ali The course is CS201- Introduction to programming The age is 22 The year is 2002 Using the -> operator The name is Ali The course is CS201- Introduction to programming The age is 22 The year is 2002

Arrays of structures

Let‟s discuss the arrays of structure. The declaration is similar as used to deal with the simple variables. The declaration of array of hundred students is as follows:

student s[100];

In the above statement, s is an array of type student structure. The size of the array is hundred and the index will be from 0 to 99. If we have to access the name of first student, the first element of the array will be as under:

Let‟s summarize what we can do with structures:

  • We can define the structure
  • We can declare variables of that type of structure
  • We can declare pointers to structure
  • We can declare arrays of structure
  • We can take the size of structure
  • We can do simple assignment of two variables of the same structure type

Sample Program

Problem:

Suppose we have ten students in a class. The attributes of student are name, course, age and GPA. Get the data input from the user to populate the array. Calculate the average age, average GPA of the class. Find out the grade of the class and student with max GPA.

Solution:

The problem is very simple. We will declare a structure of student with name, course, age and GPA as data members. In a loop, we will get the data from the user to populate the array. Then in a loop, we will calculate the totalAge and totalGPA of the class besides determining the max GPA in that loop. Finally calculate the average age and average GPA by dividing the totalAge and totalGPA by the number of students i.e. 10. The grade of the class can be determined by the average GPA.

The complete code of the program is:

/* This program calculates the average age and average GPA of a class. Also determine the grade of the class and the student with max GPA. We will use a student structure and manipulate it to get the desired result. */

#include <iostream.h>

// Declaration of student structure struct student { char name[30]; char course[15]; int age; float GPA; };

main() { const int noOfStudents = 10; // total no of students student students[noOfStudents]; // array of student structure

int totalAge, index, averageAge; float totalGPA, maxGPA, averageGPA; // initializing the structure, getting the input from user for ( int i = 0; i < noOfStudents; i++ ) { cout << endl; cout << "Enter data for Student # : " << i + 1 << endl; cout << "Enter the Student's Name : " ; cin >> students[i].name ; cout << "Enter the Student's Course : " ; cin >> students[i].course ; cout << "Enter the Student's Age : " ; cin >> students[i].age ; cout << "Enter the Student's GPA : " ; cin >> students[i].GPA ; } maxGPA = 0; // Calculating the total age, total GPA and max GPA for ( int j = 0; j < noOfStudents; j++ ) { totalAge = totalAge + students[j].age ; totalGPA = totalGPA + students[j].GPA ; // Determining the max GPA and storing its index if ( students[j].GPA > maxGPA ) { maxGPA = students[j].GPA; index = j; } } // Calculating the average age averageAge = totalAge / noOfStudents ; cout << "\n The average age is : " << averageAge << endl; // Calculating the average GPA averageGPA = totalGPA / noOfStudents ; cout << "\n The average GPA is : " << averageGPA << endl; cout << "\n Student with max GPA is : " << students[index].name << endl ; // Determining the Grade of the class if (averageGPA > 4) { cout << "\n Wrong grades have been enter" << endl ; } else if ( averageGPA == 4) { cout << "\n The average Grade of the class is : A" << endl; } else if ( averageGPA >= 3)

The syntax of union is:

union intOrChar{ int i, char c; };

The syntax is similar as that of structure. In structures, we have different data members and all of these have their own memory space. In union, the memory location is same while the first data member is one name for that memory location. However, the 2nd data member is another name for the same location and so on. Consider the above union (i.e. intOrChar) that contains an integer and a character as data members. What will be the size of this union? The answer is the very simple. The union will be allocated the memory equal to that of the largest size data member. If the int occupies four bytes on our system and char occupies one byte, the union intOrChar will occupy four bytes.

Consider another example:

union intOrDouble{ int ival; double dval; };

The above union has two data members i.e. ival of type int and dval of type double. We know that double occupies more memory space than integer. Therefore, the union will occupy the memory space equivalent to double. The data members of unions are accessed in a similar way as we use with structures i.e. using the dot operator. For example: intOrDouble uval; uval.ival = 10;

To get the output of the data members, cout can be used as:

cout << “ The value in ival = “ << uval.ival;

It will print “The value in ival = 10”. Now what will be output of the following statement?

cout << “ The value in dval = “ << uval.dval;

We don‟t know. The reason is that in the eight bytes of double, integer is written somewhere. When we use integer, it is printed fine. When we printed the double, the value of int will not be displayed. Rather something else will be printed. Similarly in the following statement i.e.

uval.dval = 100.0; cout << “ The value in dval = “ << uval.dval;

It will print the right value of dval. The value of this double is written in such a way that it will not be interpreted by the integer. If we try to print out ival , it will not display 100. Unions are little bit safer for integer and characters. But we have to think in terms that where to store the value in memory.

Unions are very rarely used. They become very important when we want to do some super efficient programming. Experiment with the unions and structures.

We have learnt how to use structures and unions. These are relatively less used parts of C/C++ language. But structures at least are very useful. They allow us a convenient way of grouping data about a single entity. We have used student entity in our example. You can think of a car or any other object and find out its properties before grouping them in a structure. We don‟t need to manipulate its properties individually as grouping them into a unit is a better option. Try to write different programs using structures.

Exercises

1 - Run the Sample Program and see how is it working.

2- Make an employee information database. Insert “Name”, “Date of Joining” and “Salary” for a few employees and display the result.

3- Using an array of structures, insert “Product Cost” and “Units Sold” for 3 products and calculate the total sale.