Programming II
Chapter Two
C++ Structure
2024-12-25 Kassahun @2024 1
Contents
• Structure declaration, definition…
• Structure syntax
• Initialization and referencing member of Structure
• Array of Structure
• Referencing Array of Structure
• Passing Array of Structure to function
2024-12-25 Kassahun @2024 2
Structure
• The term structure in C++ means both a user-defined type which is a
grouping of variables as well as meaning a variable based on a user-defined
structure type.
• For the purpose of distinction we will refer to
• the user-defined type side as structure definition and
• the variable side as structure variable.
2024-12-25 Kassahun @2024 3
• A structure definition is a user-defined variable type which is a
grouping of one or more variables known as elements or member
variables.
• The type itself has a name, just like ‘int’, ‘double’, or ‘char’ but it is
defined by the user and follows the normal rules of identifiers.
• Once the type has been defined through the C++ ‘struct’ keyword, you
can create variables from it just like you would any other type.
2024-12-25 Kassahun @2024 4
• Structure Variable
• Syntax
structureName varName;
• Example:
Product apple, orange;
• This can also be done at the moment the structure type is defined as:
struct Product {
int weight;
double price;
} apple, orange;
2024-12-25 Kassahun @2024 5
Cont.…
• A structure is a collection of one or more variable types grouped together
that can be referred using a single name (group name) and a member name.
• You can refer to a structure as a single variable, and you also can initialize,
read and change the parts of a structure (the individual variables that make it
up).
• Each element (called a member) in a structure can be of different data type.
2024-12-25 Kassahun @2024 6
• This structure block is similar to a statement block since it starts and ends with
curly braces.
• But don’t forget that it ultimately ends with a semi-colon.
• Within the structure block you declare all the member variables you want
associated with that type.
• Declare them as you would normal variables, but do not try to initialize them.
• This is simply a data blue print, it is not logic or instructions and the compiler
does not execute it.
2024-12-25 Kassahun @2024 7
Syntax of Structure
• The General Syntax of structures is: Example:
struct Student
Struct [structure tag] // structure tag
{
{
char ID[8];
Member definition;
char FName[15];
Member definition;
Member of the structure char LName[15];
…
char Sex;
Member definition;
int age;
}[one or more structure variables]; // all structure
float CGPA;
end with semicolon.
};
2024-12-25 Kassahun @2024 8
Declaration of Structure
• After the definition of the structure, one can declare a structure variable using the structure tag.
• If we need two variables to have the above structure property then the declaration would be:
struct Inventory inv1, inv2; //or
struct Student Stud1, Stud2, Stud3;
• Structure tag is not a variable name. Unlike array names, which reference the array as variables,
a structure tag is simply a label for the structure’s format.
• The structure tag Inventory informs C++ that the tag called Inventory looks like two character
arrays followed by one integer and one float variables.
• A structure tag is actually a newly defined data type that you, the programmer, defined.
2024-12-25 Kassahun @2024 9
Referencing members of a structure
▪ To refer to the members of a structure we need to use the dot operator (.)
▪ The General syntax to access members of a structure variable would be:
[Link]
▪ Where VarName is the variable name of the structure variable And Member is
variable name of the members of the structure.
Syntax: For the above student structure:
struct Student Stud; //declaring Stud to have the property of the Student structure
strcpy([Link],”Abebe”); //assigned Abebe as First Name
[Link]=3.21; //assignes 3.21 as CGPA value of Abebe
cout<<[Link]; //display the name
cout<<[Link]; // display the CGPA of Abebe
2024-12-25 Kassahun @2024 10
Initialization of Structure
• To initialize a structure variable’s members, you follow the original
declaration with the assignment operator (=).
• Next you define an initialization block which is a list of initializers
separated by commas and enclosed in curly braces.
• Lastly, you end it with a semi-colon.
• These values are assigned to member variables in the order that they
occur.
2024-12-25 Kassahun @2024 11
Initializing Structure Data
• You can initialize members when you declare a structure, or you can
initialize a structure in the body of the program. Here is a complete
program.
struct cd_collection cout<<"\nhere is the info about cd1"<<endl;
{ cout<<[Link]<<endl;
char title[25]; cout<<[Link]<<endl;
char artist[20];
cout<<cd1.num_songs<<endl;
int num_songs;
cout<<[Link]<<endl;
float price;
char date_purchased[9]; cout<<cd1.date_purchased<<endl;
} cd1 = {"Red Moon Men","Sams and the Sneeds",
12, 11.95,"08/13/93"};
2024-12-25 Kassahun @2024 12
Initializing cont.…
• A better approach to initialize structures is to use the dot operator(.). the dot
operator is one way to initialize individual members of a structure variable in the
body of your program.
The syntax of the dot operator is :
[Link]
#include<iostream> //initialize members here //print the data
#include<cstring>
strcpy([Link],"computer science"); cout<<"\nHere is the info"<<endl;
using namespace std;
int main() strcpy([Link],"Programmer"); cout<<"Title : "<<[Link]<<endl;
{
cd1.num_songs= 12; cout<<"Artist : "<<[Link]<<endl;
struct cd_collection{
char title[25]; [Link] = 11.95f; cout<<"Songs : "<<cd1.num_songs<<endl;
char artist[20];
strcpy(cd1.date_purchased,"22/12/02"); cout<<"Price : "<<[Link]<<endl;
int num_songs;
float price; cout<<"Date purchased “ <<
char date_purchased[9];
cd1.date_purchased<<endl;
} cd1;
2024-12-25 Kassahun @2024 } 13
Accessing members of a structure variable
• You can use a member variable in any place you’d use a normal variable, but
you must specify it by the structure variable’s name as well as the member
variable’s name using the member operator.
• To specify that you want a member of a specific structure variable, you use the
structure member operator which is the period (also known as a “dot”).
• Simply use the structure’s name, follow with the period, and end with the
member: [Link]
2024-12-25 Kassahun @2024 14
Example
• Example: to reading and displaying values to and from structure s1.
Struct student{
String id,name;
} s1;
cin>>[Link]; //storing to id item of s1
cin>>[Link]; //storing a name to s1
cout<<[Link]; //displaying the content of id of s1.
cout<<[Link]; //displaying name
2024-12-25 Kassahun @2024 15
Example
• Example:-a program that creates student struct and uses it to store student
information.
2024-12-25 Kassahun @2024 16
Arrays of Structures
• Arrays of structures are good for storing a complete employee file, inventory file, or any other
set of data that fits in the structure format.
• Consider the following structure declaration: struct Company
{
int employees;
int registers;
double sales;
} store[1000];
• In one quick declaration, this code creates 1,000 store structures with the definition of the
Company structure, each one containing three members.
• NB. Be sure that your computer does not run out of memory when you create a large number
of structures. Arrays of structures quickly consume valuable information.
2024-12-25 Kassahun @2024 17
Declaration of array of Structure
• You can also define the array of structures after the declaration of the
structure. struct Company
{
int employees;
int registers;
double sales;
}; // no structure variables defined yet
#include<iostream.h>
…
void main()
{
struct Company store[1000]; //the variable store is array of the structure Company
…
}
2024-12-25 Kassahun @2024 18
Declaration of array of Structure
#include <stdio.h>
// Example: Print values for the first store
int main() { cout<<("Store 1:\n");
struct Company { cout<<("Employees: ", store[0].employees);
int employees; cout("Registers:", store[0].registers);
int registers; cout("Sales:", store[0].sales);
double sales;
} store[1000]; return 0;
}
// Example: Assign values to the first
store
store[0].employees = 15;
store[0].registers = 3;
store[0].sales = 12345.67;
2024-12-25 Kassahun @2024 19
2024-12-25 Kassahun @2024 20
2024-12-25 Kassahun @2024 21
Referencing the array structure
• The dot operator (.) works the same way for structure array element as
it does for regular variables. If the number of employees for the fifth
store (store[4]) increased by three, you could update the structure
variable like this: store[4].employees += 3;
• Unlike in the case of arrays, where the whole content of an array could
not be copied to another one using a simple statement, in structures,
you can assign complete structures to one another by using array
notation.
• To assign all the members of the 20th store to the 45th store, you
would do this: store[44] = store[19];//copies all members from 20th
store to 45th.
2024-12-25 Kassahun @2024 22
Passing structure to function
• we can pass a structure variable to a function as argument like we pass any other
variable to a function.
• Structure variable is passed using call by value.
• To take a structure variable as argument, function must declare a structure
argument in it's declaration.
• Any change in the value of formal parameter inside function body, will not affect
the value of actual parameter.
2024-12-25 Kassahun @2024 23
• Example
struct employee {
char name[100];
int age;
float salary;
char department[50];
};
void printEmployeeDetails (employee emp);
2024-12-25 Kassahun @2024 24
• We can also pass address of a structure to a function.
• In this case, any change in the formal parameter inside
function's body will reflect in actual parameter also.
• To take a structure pointer as parameter a function declare a
structure pointer as it's formal parameter.
void printEmployeeDetails( employee *emp);
• Like any other inbuilt data type, we can also pass individual
member of a structure as function argument.
2024-12-25 Kassahun @2024 25
2024-12-25 Kassahun @2024 26
Passing array of structure to a function
• Like a normal array of elements we can pass array of structure to a function.
• For a normal array
• Function prototype:
• return type functionName (datatype[], int size);
• Fucntion call:
• functionName(variableName, size);
• Function definition
• return type functionName (datatype variableName [], int size);
2024-12-25 Kassahun @2024 27
2024-12-25 Kassahun @2024 28
2024-12-25 Kassahun @2024 29
• For array of structure
• Function prototype:
• return type functionName (structName [], int size);
• Fucntion call:
• functionName(structName, size);
• Function definition
• return type functionName (structName variableName [], int size);
2024-12-25 Kassahun @2024 30
2024-12-25 Kassahun @2024 31
2024-12-25 Kassahun @2024 32