SlideShare a Scribd company logo
1 of 12
The C++ language allows you to create and use data types other than the
fundamental data types. These types are called user-defined data types. There are
two ways by which a user-defined data type can be created. The first is by using the
keyword struct, and the second is by using the keyword class. Data types defined
using the keyword struct are called structures.

Structures

In C++, a structure is a collection of variables that are referenced by a single name.
The variable can be of different data types. They provide a convenient means of
keeping related information together. Structure definition forms a template which is
then used to create structure variables. The variables that make up the structure are
called structure elements.

All the elements found in the structure are related to each other. For example, the
invoice number and the invoice amount found in an invoice would normally be
represented in a structure. The following code segment shows how a structue
template that defines an invoice number and invoice amount can be created. The
keyword struct tells the compiler that a structure template is being declared.

struct invoice
{
intiInvoice_no;
float fInvoice_amt;
};

Notice that the structure declaration is terminated by a semi-colon. This is because a
structure declaration is a statement. Also, the structure tag invoice identifies this
particular data structure. At this point in the code, no variable has been declared;
only the form of the data has been defined.

To declare a variable, you need to use the following statement:

invoice Inv1;
This defines a structure variable of type 'invoice', called Inv1. When you declare a
structure, you are, in essence, defining a data type. Memory is not allocated for a
structure until a variable of that type is created.

The compiler automatically allocates sufficient memory to accommodate all the
elements that make up the structure.

You may also declare two or more variables at the time of declaring a structure. For
example:

struct invoice
{
intiInvoice_no;
float fInvoice_amt;
}Inv1,Inv2;

will declare a structure type called invoice and declare the variable Inv1 and Inv2.

If only one structure has to be declared in a program, then following definition would
suffice:

struct
{
intiInvoice_no;
float fInvoice_amt;
}Inv1;

The general form of a structure declaration is:

struct<tag>
{
<type><variable1>;
<type><variable2>;
...
...
<type><variableN>;
}<structvars>;

where <tag> is the name of the structure declaration, effectively the name of the
new data type. The structure tag is then used to declare structure variables.
<structvars> are the names of structure variables. Either the <tag> or the
<structvars> can be omitted, but noth both.



Data Structures
We have already learned how groups of sequential data can be used in C++. But this is somewhat
restrictive, since in many occasions what we want to store are not mere sequences of elements all of
the same data type, but sets of different elements with different data types.




Data structures
A data structure is a group of data elements grouped together under one name. These data elements,
known asmembers, can have different types and different lengths. Data structures are declared in
C++ using the following syntax:

structstructure_name {
member_type1 member_name1;
member_type2 member_name2;
member_type3 member_name3;
.
.
} object_names;

where structure_name is a name for the structure type, object_name can be a set of valid identifiers
for objects that have the type of this structure. Within braces { } there is a list with the data
members, each one is specified with a type and a valid identifier as its name.

The first thing we have to know is that a data structure creates a new type: Once a data structure is
declared, a new type with the identifier specified as structure_name is created and can be used in the
rest of the program as if it was any other type. For example:



1   struct product {
2   int weight;
3   float price;
4   } ;
5
6 product apple;
7 product banana, melon;



We have first declared a structure type called product with two members: weight and price, each of
a different fundamental type. We have then used this name of the structure type (product) to declare
three objects of that type: apple, banana and melon as we would have done with any fundamental
data type.

Once declared, product has become a new valid type name like the fundamental
ones int, char or short and from that point on we are able to declare objects (variables) of this
compound new type, like we have done with apple,banana and melon.

Right at the end of the struct declaration, and before the ending semicolon, we can use the optional
fieldobject_name to directly declare objects of the structure type. For example, we can also declare
the structure objects apple, banana and melon at the moment we define the data structure type this
way:



1   struct product {
2   int weight;
3   float price;
4   } apple, banana, melon;



It is important to clearly differentiate between what is the structure type name, and what is an object
(variable) that has this structure type. We can instantiate many objects (i.e. variables,
like apple, banana and melon) from a single structure type (product).

Once we have declared our three objects of a determined structure type (apple, banana and melon)
we can operate directly with their members. To do that we use a dot (.) inserted between the object
name and the member name. For example, we could operate with any of these elements as if they
were standard variables of their respective types:



1   apple.weight
2   apple.price
3   banana.weight
4   banana.price
5   melon.weight
6   melon.price



Each one of these has the data type corresponding to the member they refer
to: apple.weight, banana.weight andmelon.weight are of type int,
while apple.price, banana.price and melon.price are of type float.

Let's see a real example where you can see how a structure type can be used in the same way as
fundamental types:
1   // example about structures                              Enter title: Alien
  2   #include <iostream>                                      Enter year: 1979
  3   #include <string>
  4   #include <sstream>                                       My favorite movie is:
  5   usingnamespacestd;                                        2001 A Space Odyssey (1968)
  6                                                            And yours is:
  7   structmovies_t {                                          Alien (1979)
  8     string title;
  9   int year;
 10   } mine, yours;
 11
 12   voidprintmovie (movies_t movie);
 13
 14   int main ()
 15   {
 16     string mystr;
 17
 18   mine.title = "2001 A Space Odyssey";
 19   mine.year = 1968;
 20
 21   cout<<"Enter title: ";
 22   getline (cin,yours.title);
 23   cout<<"Enter year: ";
 24   getline (cin,mystr);
 25   stringstream(mystr) >>yours.year;
 26
 27   cout<<"My favorite movie is:n ";
 28   printmovie (mine);
 29   cout<<"And yours is:n ";
 30   printmovie (yours);
 31   return 0;
 32   }
 33
 34   voidprintmovie (movies_t movie)
 35   {
 36   cout<<movie.title;
 37   cout<<" ("<<movie.year<<")n";
 38   }



The example shows how we can use the members of an object as regular variables. For example, the
memberyours.year is a valid variable of type int, and mine.title is a valid variable of type string.

The objects mine and yours can also be treated as valid variables of type movies_t, for example we
have passed them to the function printmovie as we would have done with regular variables.
Therefore, one of the most important advantages of data structures is that we can either refer to their
members individually or to the entire structure as a block with only one identifier.

Data structures are a feature that can be used to represent databases, especially if we consider the
possibility of building arrays of them:



   1 // array of structures                                     Enter title: Blade Runner
   2 #include <iostream>                                        Enter year: 1982
3   #include <string>                                      Enter   title: Matrix
     4   #include <sstream>                                     Enter   year: 1999
     5   usingnamespacestd;                                     Enter   title: Taxi Driver
     6                                                          Enter   year: 1976
     7   #define N_MOVIES 3
     8                                                          You have entered these movies:
     9   structmovies_t {                                       Blade Runner (1982)
    10     string title;                                        Matrix (1999)
    11   int year;                                              Taxi Driver (1976)
    12   } films [N_MOVIES];
    13
    14   voidprintmovie (movies_t movie);
    15
    16   int main ()
    17   {
    18     string mystr;
    19   int n;
    20
    21   for (n=0; n<N_MOVIES; n++)
    22     {
    23   cout<<"Enter title: ";
    24   getline (cin,films[n].title);
    25   cout<<"Enter year: ";
    26   getline (cin,mystr);
    27   stringstream(mystr) >> films[n].year;
    28     }
    29
    30   cout<<"nYou have entered these movies:n";
    31   for (n=0; n<N_MOVIES; n++)
    32   printmovie (films[n]);
    33   return 0;
    34   }
    35
    36   voidprintmovie (movies_t movie)
    37   {
    38   cout<<movie.title;
    39   cout<<" ("<<movie.year<<")n";
    40   }




Pointers to structures
Like any other type, structures can be pointed by its own type of pointers:



1   structmovies_t {
2      string title;
3   int year;
4   };
5
6   movies_tamovie;
7   movies_t * pmovie;
Here amovie is an object of structure type movies_t, and pmovie is a pointer to point to objects of
structure typemovies_t. So, the following code would also be valid:



  pmovie = &amovie;



The value of the pointer pmovie would be assigned to a reference to the object amovie (its memory
address).

We will now go with another example that includes pointers, which will serve to introduce a new
operator: the arrow operator (->):



  1   // pointers to structures                               Enter title: Invasion of the body
  2   #include <iostream>                                     snatchers
  3   #include <string>                                       Enter year: 1978
  4   #include <sstream>
  5   usingnamespacestd;                                      You have entered:
  6                                                           Invasion of the body snatchers (1978)
  7   structmovies_t {
  8      string title;
  9   int year;
 10   };
 11
 12   int main ()
 13   {
 14     string mystr;
 15
 16   movies_tamovie;
 17   movies_t * pmovie;
 18   pmovie = &amovie;
 19
 20   cout<<"Enter title: ";
 21   getline (cin, pmovie->title);
 22   cout<<"Enter year: ";
 23   getline (cin, mystr);
 24     (stringstream) mystr>>pmovie->year;
 25
 26   cout<<"nYou have entered:n";
 27   cout<<pmovie->title;
 28   cout<<" ("<<pmovie->year <<")n";
 29
 30   return 0;
 31   }



The previous code includes an important introduction: the arrow operator (->). This is a dereference
operator that is used exclusively with pointers to objects with members. This operator serves to
access a member of an object to which we have a reference. In the example we used:
pmovie->title



Which is for all purposes equivalent to:



  (*pmovie).title



Both expressions pmovie->title and (*pmovie).title are valid and both mean that we are
evaluating the membertitle of the data structure pointed by a pointer called pmovie. It must be
clearly differentiated from:



  *pmovie.title



which is equivalent to:



  *(pmovie.title)



And that would access the value pointed by a hypothetical pointer member called title of the
structure objectpmovie (which in this case would not be a pointer). The following panel summarizes
possible combinations of pointers and structure members:



Expression            What is evaluated             Equivalent

a.b          Member b of object a

a->b         Member b of object pointed by a        (*a).b

*a.b         Value pointed by member b of object a *(a.b)




Nesting structures

Structures can also be nested so that a valid element of a structure can also be in its turn another
structure.



 1 structmovies_t {
 2   string title;
 3 int year;
4   };
 5
 6   structfriends_t {
 7     string name;
 8     string email;
 9   movies_tfavorite_movie;
10     } charlie, maria;
11
12   friends_t * pfriends = &charlie;



After the previous declaration we could use any of the following expressions:



1   charlie.name
2   maria.favorite_movie.title
3   charlie.favorite_movie.year
4   pfriends->favorite_movie.year

(where, by the way, the last two expressions refer to the same member).




Defined data types (typedef)
C++ allows the definition of our own types based on other existing data types. We can do this using
the keywordtypedef, whose format is:

typedefexisting_typenew_type_name ;

where existing_type is a C++ fundamental or compound type and new_type_name is the name for
the new type we are defining. For example:


1   typedefchar C;
2   typedefunsignedint WORD;
3   typedefchar * pChar;
4   typedefchar field [50];


In this case we have defined four data types: C, WORD, pChar and field as char, unsigned
int, char* and char[50]respectively, that we could perfectly use in declarations later as any other
valid type:


1   C mychar, anotherchar, *ptc1;
2   WORD myword;
3   pChar ptc2;
4   field name;


typedef does not create different types. It only creates synonyms of existing types. That means that
the type ofmyword can be considered to be either WORD or unsigned int, since both are in fact the
same type.
typedef can be useful to define an alias for a type that is frequently used within a program. It is also
useful to define types when it is possible that we will need to change the type in later versions of our
program, or if a type you want to use has a name that is too long or confusing.




Unions
Unions allow one same portion of memory to be accessed as different data types, since all of them are
in fact the same location in memory. Its declaration and use is similar to the one of structures but its
functionality is totally different:


unionunion_name {
  member_type1 member_name1;
  member_type2 member_name2;
  member_type3 member_name3;
  .
  .
} object_names;

All the elements of the union declaration occupy the same physical space in memory. Its size is the
one of the greatest element of the declaration. For example:


1   unionmytypes_t {
2   char c;
3   int i;
4   float f;
5     } mytypes;


defines three elements:


1 mytypes.c
2 mytypes.i
3 mytypes.f


each one with a different data type. Since all of them are referring to the same location in memory,
the modification of one of the elements will affect the value of all of them. We cannot store different
values in them independent of each other.

One of the uses a union may have is to unite an elementary type with an array or structures of
smaller elements. For example:


1   unionmix_t {
2   long l;
3   struct {
4   short hi;
5   short lo;
6       } s;
7   char c[4];
8   } mix;
defines three names that allow us to access the same group of 4 bytes: mix.l, mix.s and mix.c and
which we can use according to how we want to access these bytes, as if they were a single long-type
data, as if they were twoshort elements or as an array of char elements, respectively. I have mixed
types, arrays and structures in the union so that you can see the different ways that we can access
the data. For a little-endian system (most PC platforms), this union could be represented as:




The exact alignment and order of the members of a union in memory is platform dependant. Therefore
be aware of possible portability issues with this type of use.




Anonymous unions
In C++ we have the option to declare anonymous unions. If we declare a union without any name, the
union will be anonymous and we will be able to access its members directly by their member names.
For example, look at the difference between these two structure declarations:

structure with regular union structure with anonymous union
struct {                        struct {
  char title[50];                 char title[50];
  char author[50];                char author[50];
  union {                         union {
    float dollars;                   float dollars;
int yen;                        int yen;
  } price;                        };
} book;                         } book;

The only difference between the two pieces of code is that in the first one we have given a name to
the union (price) and in the second one we have not. The difference is seen when we access the
members dollars and yenof an object of this type. For an object of the first type, it would be:


1 book.price.dollars
2 book.price.yen


whereas for an object of the second type, it would be:


1 book.dollars
2 book.yen


Once again I remind you that because it is a union and not a struct, the
members dollars and yen occupy the same physical space in the memory so they cannot be used to
store two different values simultaneously. You can set a value for price in dollars or in yen, but not in
both.
Enumerations (enum)
Enumerations create new data types to contain something different that is not limited to the values
fundamental data types may take. Its form is the following:


enumenumeration_name {
  value1,
  value2,
  value3,
  .
  .
} object_names;

For example, we could create a new type of variable called colors_t to store colors with the following
declaration:


  enumcolors_t {black, blue, green, cyan, red, purple, yellow, white};


Notice that we do not include any fundamental data type in the declaration. To say it somehow, we
have created a whole new data type from scratch without basing it on any other existing type. The
possible values that variables of this new type color_t may take are the new constant values included
within braces. For example, once thecolors_t enumeration is declared the following expressions will
be valid:


1 colors_tmycolor;
2
3 mycolor = blue;
4 if (mycolor == green) mycolor = red;


Enumerations are type compatible with numeric variables, so their constants are always assigned an
integer numerical value internally. If it is not specified, the integer value equivalent to the first
possible value is equivalent to 0 and the following ones follow a +1 progression. Thus, in our data
type colors_t that we have defined above,black would be equivalent to 0, blue would be equivalent
to 1, green to 2, and so on.

We can explicitly specify an integer value for any of the constant values that our enumerated type can
take. If the constant value that follows it is not given an integer value, it is automatically assumed the
same value as the previous one plus one. For example:


1 enummonths_t { january=1, february, march, april,
2                 may, june, july, august,
3 september, october, november, december} y2k;



In this case, variable y2k of enumerated type months_t can contain any of the 12 possible values that
go fromjanuary to december and that are equivalent to values between 1 and 12 (not
between 0 and 11, since we have made january equal to 1).

More Related Content

Similar to C++ assignment

Similar to C++ assignment (20)

03 structures
03 structures03 structures
03 structures
 
Module 5-Structure and Union
Module 5-Structure and UnionModule 5-Structure and Union
Module 5-Structure and Union
 
Unit-V.pptx
Unit-V.pptxUnit-V.pptx
Unit-V.pptx
 
structenumtypedefunion.pptx
structenumtypedefunion.pptxstructenumtypedefunion.pptx
structenumtypedefunion.pptx
 
C UNIT-4 PREPARED BY M V BRAHMANANDA RE
C UNIT-4 PREPARED BY M V BRAHMANANDA REC UNIT-4 PREPARED BY M V BRAHMANANDA RE
C UNIT-4 PREPARED BY M V BRAHMANANDA RE
 
IAT334-Lab02-ArraysPImage.pptx
IAT334-Lab02-ArraysPImage.pptxIAT334-Lab02-ArraysPImage.pptx
IAT334-Lab02-ArraysPImage.pptx
 
C programming(part 3)
C programming(part 3)C programming(part 3)
C programming(part 3)
 
structures_v1.ppt
structures_v1.pptstructures_v1.ppt
structures_v1.ppt
 
structures_v1.ppt
structures_v1.pptstructures_v1.ppt
structures_v1.ppt
 
Chapter 8 Structure Part 2 (1).pptx
Chapter 8 Structure Part 2 (1).pptxChapter 8 Structure Part 2 (1).pptx
Chapter 8 Structure Part 2 (1).pptx
 
Structure
StructureStructure
Structure
 
Csc1100 lecture13 ch16_pt1
Csc1100 lecture13 ch16_pt1Csc1100 lecture13 ch16_pt1
Csc1100 lecture13 ch16_pt1
 
structure1.pdf
structure1.pdfstructure1.pdf
structure1.pdf
 
[ITP - Lecture 16] Structures in C/C++
[ITP - Lecture 16] Structures in C/C++[ITP - Lecture 16] Structures in C/C++
[ITP - Lecture 16] Structures in C/C++
 
Structures in c++
Structures in c++Structures in c++
Structures in c++
 
Structures in c++
Structures in c++Structures in c++
Structures in c++
 
Unit 5 (1)
Unit 5 (1)Unit 5 (1)
Unit 5 (1)
 
C Programming - Refresher - Part III
C Programming - Refresher - Part IIIC Programming - Refresher - Part III
C Programming - Refresher - Part III
 
Oop lec 3(structures)
Oop lec 3(structures)Oop lec 3(structures)
Oop lec 3(structures)
 
TMDb movie dataset by kaggle
TMDb movie dataset by kaggleTMDb movie dataset by kaggle
TMDb movie dataset by kaggle
 

Recently uploaded

1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdfQucHHunhnh
 
APM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAPM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAssociation for Project Management
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformChameera Dedduwage
 
9548086042 for call girls in Indira Nagar with room service
9548086042  for call girls in Indira Nagar  with room service9548086042  for call girls in Indira Nagar  with room service
9548086042 for call girls in Indira Nagar with room servicediscovermytutordmt
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Celine George
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13Steve Thomason
 
Disha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdfDisha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdfchloefrazer622
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdfSoniaTolstoy
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)eniolaolutunde
 
IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...
IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...
IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...PsychoTech Services
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphThiyagu K
 
General AI for Medical Educators April 2024
General AI for Medical Educators April 2024General AI for Medical Educators April 2024
General AI for Medical Educators April 2024Janet Corral
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsTechSoup
 
Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3JemimahLaneBuaron
 
Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Disha Kariya
 
social pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajansocial pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajanpragatimahajan3
 
Student login on Anyboli platform.helpin
Student login on Anyboli platform.helpinStudent login on Anyboli platform.helpin
Student login on Anyboli platform.helpinRaunakKeshri1
 
Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxVishalSingh1417
 

Recently uploaded (20)

1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
 
APM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAPM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across Sectors
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy Reform
 
9548086042 for call girls in Indira Nagar with room service
9548086042  for call girls in Indira Nagar  with room service9548086042  for call girls in Indira Nagar  with room service
9548086042 for call girls in Indira Nagar with room service
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13
 
Disha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdfDisha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdf
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)
 
IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...
IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...
IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot Graph
 
General AI for Medical Educators April 2024
General AI for Medical Educators April 2024General AI for Medical Educators April 2024
General AI for Medical Educators April 2024
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The Basics
 
Advance Mobile Application Development class 07
Advance Mobile Application Development class 07Advance Mobile Application Development class 07
Advance Mobile Application Development class 07
 
Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3
 
Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..
 
Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1
 
social pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajansocial pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajan
 
Student login on Anyboli platform.helpin
Student login on Anyboli platform.helpinStudent login on Anyboli platform.helpin
Student login on Anyboli platform.helpin
 
Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptx
 

C++ assignment

  • 1. The C++ language allows you to create and use data types other than the fundamental data types. These types are called user-defined data types. There are two ways by which a user-defined data type can be created. The first is by using the keyword struct, and the second is by using the keyword class. Data types defined using the keyword struct are called structures. Structures In C++, a structure is a collection of variables that are referenced by a single name. The variable can be of different data types. They provide a convenient means of keeping related information together. Structure definition forms a template which is then used to create structure variables. The variables that make up the structure are called structure elements. All the elements found in the structure are related to each other. For example, the invoice number and the invoice amount found in an invoice would normally be represented in a structure. The following code segment shows how a structue template that defines an invoice number and invoice amount can be created. The keyword struct tells the compiler that a structure template is being declared. struct invoice { intiInvoice_no; float fInvoice_amt; }; Notice that the structure declaration is terminated by a semi-colon. This is because a structure declaration is a statement. Also, the structure tag invoice identifies this particular data structure. At this point in the code, no variable has been declared; only the form of the data has been defined. To declare a variable, you need to use the following statement: invoice Inv1;
  • 2. This defines a structure variable of type 'invoice', called Inv1. When you declare a structure, you are, in essence, defining a data type. Memory is not allocated for a structure until a variable of that type is created. The compiler automatically allocates sufficient memory to accommodate all the elements that make up the structure. You may also declare two or more variables at the time of declaring a structure. For example: struct invoice { intiInvoice_no; float fInvoice_amt; }Inv1,Inv2; will declare a structure type called invoice and declare the variable Inv1 and Inv2. If only one structure has to be declared in a program, then following definition would suffice: struct { intiInvoice_no; float fInvoice_amt; }Inv1; The general form of a structure declaration is: struct<tag> { <type><variable1>; <type><variable2>; ...
  • 3. ... <type><variableN>; }<structvars>; where <tag> is the name of the structure declaration, effectively the name of the new data type. The structure tag is then used to declare structure variables. <structvars> are the names of structure variables. Either the <tag> or the <structvars> can be omitted, but noth both. Data Structures We have already learned how groups of sequential data can be used in C++. But this is somewhat restrictive, since in many occasions what we want to store are not mere sequences of elements all of the same data type, but sets of different elements with different data types. Data structures A data structure is a group of data elements grouped together under one name. These data elements, known asmembers, can have different types and different lengths. Data structures are declared in C++ using the following syntax: structstructure_name { member_type1 member_name1; member_type2 member_name2; member_type3 member_name3; . . } object_names; where structure_name is a name for the structure type, object_name can be a set of valid identifiers for objects that have the type of this structure. Within braces { } there is a list with the data members, each one is specified with a type and a valid identifier as its name. The first thing we have to know is that a data structure creates a new type: Once a data structure is declared, a new type with the identifier specified as structure_name is created and can be used in the rest of the program as if it was any other type. For example: 1 struct product { 2 int weight; 3 float price; 4 } ; 5
  • 4. 6 product apple; 7 product banana, melon; We have first declared a structure type called product with two members: weight and price, each of a different fundamental type. We have then used this name of the structure type (product) to declare three objects of that type: apple, banana and melon as we would have done with any fundamental data type. Once declared, product has become a new valid type name like the fundamental ones int, char or short and from that point on we are able to declare objects (variables) of this compound new type, like we have done with apple,banana and melon. Right at the end of the struct declaration, and before the ending semicolon, we can use the optional fieldobject_name to directly declare objects of the structure type. For example, we can also declare the structure objects apple, banana and melon at the moment we define the data structure type this way: 1 struct product { 2 int weight; 3 float price; 4 } apple, banana, melon; It is important to clearly differentiate between what is the structure type name, and what is an object (variable) that has this structure type. We can instantiate many objects (i.e. variables, like apple, banana and melon) from a single structure type (product). Once we have declared our three objects of a determined structure type (apple, banana and melon) we can operate directly with their members. To do that we use a dot (.) inserted between the object name and the member name. For example, we could operate with any of these elements as if they were standard variables of their respective types: 1 apple.weight 2 apple.price 3 banana.weight 4 banana.price 5 melon.weight 6 melon.price Each one of these has the data type corresponding to the member they refer to: apple.weight, banana.weight andmelon.weight are of type int, while apple.price, banana.price and melon.price are of type float. Let's see a real example where you can see how a structure type can be used in the same way as fundamental types:
  • 5. 1 // example about structures Enter title: Alien 2 #include <iostream> Enter year: 1979 3 #include <string> 4 #include <sstream> My favorite movie is: 5 usingnamespacestd; 2001 A Space Odyssey (1968) 6 And yours is: 7 structmovies_t { Alien (1979) 8 string title; 9 int year; 10 } mine, yours; 11 12 voidprintmovie (movies_t movie); 13 14 int main () 15 { 16 string mystr; 17 18 mine.title = "2001 A Space Odyssey"; 19 mine.year = 1968; 20 21 cout<<"Enter title: "; 22 getline (cin,yours.title); 23 cout<<"Enter year: "; 24 getline (cin,mystr); 25 stringstream(mystr) >>yours.year; 26 27 cout<<"My favorite movie is:n "; 28 printmovie (mine); 29 cout<<"And yours is:n "; 30 printmovie (yours); 31 return 0; 32 } 33 34 voidprintmovie (movies_t movie) 35 { 36 cout<<movie.title; 37 cout<<" ("<<movie.year<<")n"; 38 } The example shows how we can use the members of an object as regular variables. For example, the memberyours.year is a valid variable of type int, and mine.title is a valid variable of type string. The objects mine and yours can also be treated as valid variables of type movies_t, for example we have passed them to the function printmovie as we would have done with regular variables. Therefore, one of the most important advantages of data structures is that we can either refer to their members individually or to the entire structure as a block with only one identifier. Data structures are a feature that can be used to represent databases, especially if we consider the possibility of building arrays of them: 1 // array of structures Enter title: Blade Runner 2 #include <iostream> Enter year: 1982
  • 6. 3 #include <string> Enter title: Matrix 4 #include <sstream> Enter year: 1999 5 usingnamespacestd; Enter title: Taxi Driver 6 Enter year: 1976 7 #define N_MOVIES 3 8 You have entered these movies: 9 structmovies_t { Blade Runner (1982) 10 string title; Matrix (1999) 11 int year; Taxi Driver (1976) 12 } films [N_MOVIES]; 13 14 voidprintmovie (movies_t movie); 15 16 int main () 17 { 18 string mystr; 19 int n; 20 21 for (n=0; n<N_MOVIES; n++) 22 { 23 cout<<"Enter title: "; 24 getline (cin,films[n].title); 25 cout<<"Enter year: "; 26 getline (cin,mystr); 27 stringstream(mystr) >> films[n].year; 28 } 29 30 cout<<"nYou have entered these movies:n"; 31 for (n=0; n<N_MOVIES; n++) 32 printmovie (films[n]); 33 return 0; 34 } 35 36 voidprintmovie (movies_t movie) 37 { 38 cout<<movie.title; 39 cout<<" ("<<movie.year<<")n"; 40 } Pointers to structures Like any other type, structures can be pointed by its own type of pointers: 1 structmovies_t { 2 string title; 3 int year; 4 }; 5 6 movies_tamovie; 7 movies_t * pmovie;
  • 7. Here amovie is an object of structure type movies_t, and pmovie is a pointer to point to objects of structure typemovies_t. So, the following code would also be valid: pmovie = &amovie; The value of the pointer pmovie would be assigned to a reference to the object amovie (its memory address). We will now go with another example that includes pointers, which will serve to introduce a new operator: the arrow operator (->): 1 // pointers to structures Enter title: Invasion of the body 2 #include <iostream> snatchers 3 #include <string> Enter year: 1978 4 #include <sstream> 5 usingnamespacestd; You have entered: 6 Invasion of the body snatchers (1978) 7 structmovies_t { 8 string title; 9 int year; 10 }; 11 12 int main () 13 { 14 string mystr; 15 16 movies_tamovie; 17 movies_t * pmovie; 18 pmovie = &amovie; 19 20 cout<<"Enter title: "; 21 getline (cin, pmovie->title); 22 cout<<"Enter year: "; 23 getline (cin, mystr); 24 (stringstream) mystr>>pmovie->year; 25 26 cout<<"nYou have entered:n"; 27 cout<<pmovie->title; 28 cout<<" ("<<pmovie->year <<")n"; 29 30 return 0; 31 } The previous code includes an important introduction: the arrow operator (->). This is a dereference operator that is used exclusively with pointers to objects with members. This operator serves to access a member of an object to which we have a reference. In the example we used:
  • 8. pmovie->title Which is for all purposes equivalent to: (*pmovie).title Both expressions pmovie->title and (*pmovie).title are valid and both mean that we are evaluating the membertitle of the data structure pointed by a pointer called pmovie. It must be clearly differentiated from: *pmovie.title which is equivalent to: *(pmovie.title) And that would access the value pointed by a hypothetical pointer member called title of the structure objectpmovie (which in this case would not be a pointer). The following panel summarizes possible combinations of pointers and structure members: Expression What is evaluated Equivalent a.b Member b of object a a->b Member b of object pointed by a (*a).b *a.b Value pointed by member b of object a *(a.b) Nesting structures Structures can also be nested so that a valid element of a structure can also be in its turn another structure. 1 structmovies_t { 2 string title; 3 int year;
  • 9. 4 }; 5 6 structfriends_t { 7 string name; 8 string email; 9 movies_tfavorite_movie; 10 } charlie, maria; 11 12 friends_t * pfriends = &charlie; After the previous declaration we could use any of the following expressions: 1 charlie.name 2 maria.favorite_movie.title 3 charlie.favorite_movie.year 4 pfriends->favorite_movie.year (where, by the way, the last two expressions refer to the same member). Defined data types (typedef) C++ allows the definition of our own types based on other existing data types. We can do this using the keywordtypedef, whose format is: typedefexisting_typenew_type_name ; where existing_type is a C++ fundamental or compound type and new_type_name is the name for the new type we are defining. For example: 1 typedefchar C; 2 typedefunsignedint WORD; 3 typedefchar * pChar; 4 typedefchar field [50]; In this case we have defined four data types: C, WORD, pChar and field as char, unsigned int, char* and char[50]respectively, that we could perfectly use in declarations later as any other valid type: 1 C mychar, anotherchar, *ptc1; 2 WORD myword; 3 pChar ptc2; 4 field name; typedef does not create different types. It only creates synonyms of existing types. That means that the type ofmyword can be considered to be either WORD or unsigned int, since both are in fact the same type.
  • 10. typedef can be useful to define an alias for a type that is frequently used within a program. It is also useful to define types when it is possible that we will need to change the type in later versions of our program, or if a type you want to use has a name that is too long or confusing. Unions Unions allow one same portion of memory to be accessed as different data types, since all of them are in fact the same location in memory. Its declaration and use is similar to the one of structures but its functionality is totally different: unionunion_name { member_type1 member_name1; member_type2 member_name2; member_type3 member_name3; . . } object_names; All the elements of the union declaration occupy the same physical space in memory. Its size is the one of the greatest element of the declaration. For example: 1 unionmytypes_t { 2 char c; 3 int i; 4 float f; 5 } mytypes; defines three elements: 1 mytypes.c 2 mytypes.i 3 mytypes.f each one with a different data type. Since all of them are referring to the same location in memory, the modification of one of the elements will affect the value of all of them. We cannot store different values in them independent of each other. One of the uses a union may have is to unite an elementary type with an array or structures of smaller elements. For example: 1 unionmix_t { 2 long l; 3 struct { 4 short hi; 5 short lo; 6 } s; 7 char c[4]; 8 } mix;
  • 11. defines three names that allow us to access the same group of 4 bytes: mix.l, mix.s and mix.c and which we can use according to how we want to access these bytes, as if they were a single long-type data, as if they were twoshort elements or as an array of char elements, respectively. I have mixed types, arrays and structures in the union so that you can see the different ways that we can access the data. For a little-endian system (most PC platforms), this union could be represented as: The exact alignment and order of the members of a union in memory is platform dependant. Therefore be aware of possible portability issues with this type of use. Anonymous unions In C++ we have the option to declare anonymous unions. If we declare a union without any name, the union will be anonymous and we will be able to access its members directly by their member names. For example, look at the difference between these two structure declarations: structure with regular union structure with anonymous union struct { struct { char title[50]; char title[50]; char author[50]; char author[50]; union { union { float dollars; float dollars; int yen; int yen; } price; }; } book; } book; The only difference between the two pieces of code is that in the first one we have given a name to the union (price) and in the second one we have not. The difference is seen when we access the members dollars and yenof an object of this type. For an object of the first type, it would be: 1 book.price.dollars 2 book.price.yen whereas for an object of the second type, it would be: 1 book.dollars 2 book.yen Once again I remind you that because it is a union and not a struct, the members dollars and yen occupy the same physical space in the memory so they cannot be used to store two different values simultaneously. You can set a value for price in dollars or in yen, but not in both.
  • 12. Enumerations (enum) Enumerations create new data types to contain something different that is not limited to the values fundamental data types may take. Its form is the following: enumenumeration_name { value1, value2, value3, . . } object_names; For example, we could create a new type of variable called colors_t to store colors with the following declaration: enumcolors_t {black, blue, green, cyan, red, purple, yellow, white}; Notice that we do not include any fundamental data type in the declaration. To say it somehow, we have created a whole new data type from scratch without basing it on any other existing type. The possible values that variables of this new type color_t may take are the new constant values included within braces. For example, once thecolors_t enumeration is declared the following expressions will be valid: 1 colors_tmycolor; 2 3 mycolor = blue; 4 if (mycolor == green) mycolor = red; Enumerations are type compatible with numeric variables, so their constants are always assigned an integer numerical value internally. If it is not specified, the integer value equivalent to the first possible value is equivalent to 0 and the following ones follow a +1 progression. Thus, in our data type colors_t that we have defined above,black would be equivalent to 0, blue would be equivalent to 1, green to 2, and so on. We can explicitly specify an integer value for any of the constant values that our enumerated type can take. If the constant value that follows it is not given an integer value, it is automatically assumed the same value as the previous one plus one. For example: 1 enummonths_t { january=1, february, march, april, 2 may, june, july, august, 3 september, october, november, december} y2k; In this case, variable y2k of enumerated type months_t can contain any of the 12 possible values that go fromjanuary to december and that are equivalent to values between 1 and 12 (not between 0 and 11, since we have made january equal to 1).