Robotics C++ Physics II AP Physics B Electronics Java Astronomy Other Courses Summer Session  

Structures

 

Introduction

Alien Example

Monkey Example

Array of Structs 1

Time Example

Array of Structs 2

Exercise 1

Exercise 2

Exercise 3


Introduction

 

Structures were included in C and carried forward into C++.

Structures "encapsulate" data members and the member functions that operate on that data.

Structures are similar to classes

The major difference between a struct and a class is that data members and member functions in a struct are public by default. In a class, they are private by default.

The struct must be placed before the main function

Remember that an array can hold only one data type. You can, however, have an array of struct objects - a very powerful approach.

Note that the body of a structure is enclosed with braces. Structure definitions must end with a semicolon.

Members of a structure are accessed by

     Creating an object of the struct   

     Using the dot operator

Structures can be self-referential. This means they can have a member that points to the structure.

 

    struct listNode

     {

        int  data;

        listNode  *next;                //next is a pointer to a listNode - more on this second semester

      };

 

Alien Example

 

#include <iostream>
using namespace std;

struct Alien
{
    int age;
    double height;
    int nameAlien;
    void printStuff ()
    {
        cout << "I am alien "<<nameAlien<<endl;
        cout <<"my age is "<<age<<endl;
        cout <<"my height is "<<height<<endl;
    }
};



int main()
{
    Alien Red, Green;
    Red.age = 100;
    Red.height = 445.6;
    Red.nameAlien = 34;
    Green.nameAlien = 38;
    Green.age = 105;
    Green.height = 600.7;
    Red.printStuff();
    Green.printStuff();
    return 0;
}
 

 

Monkey Example

 

#include <iostream.h>

struct Monkey
{
    int age;
    int height;
    void Greeting ()
    {
        cout <<"Hi, I am a monkey"<<endl;
    }
    int askQuestion()
    {
        int theAge;
        cout<<"what is your age?"<<endl;
        cin >> theAge;
        return theAge;
    }
};

int main ( )
{
    Monkey Green;
    Green.age = 1000;
    int yourAge;
    yourAge = Green.askQuestion();
    cout <<"Your age is: "<<yourAge<<endl;

    return 0;
}

 

Time Example

 

// Create a structure, set its members, and print it.
#include <iostream.h>
 
struct Time
{                                                    // structure definition
   int hour;                                       // 0-23
   int minute;                                   // 0-59
   int second;                                   // 0-59
};                                                  // note the semicolon, end of struct definition
 
void printMilitary( const Time & );                 // prototype, note use of const
void printStandard( const Time & );    // pass object by reference but cannot change it
 
int main()
{
   Time dinnerTime;                         // dinnerTime is a variable of type Time
 
   // set members to valid values
   dinnerTime.hour = 18;                 //dot notation to access data members and member functions 
                                                                  
   dinnerTime.minute = 30;
   dinnerTime.second = 0;
 
   cout << "Dinner will be held at ";
   printMilitary( dinnerTime );
   cout << " military time,\nwhich is ";       //note  use of \n
   printStandard( dinnerTime );
   cout << " standard time.\n";
 
   // set members to invalid values
   dinnerTime.hour = 29;
   dinnerTime.minute = 73;
  
   cout << "\nTime with invalid values: ";
   printMilitary( dinnerTime );
   cout << endl;
   return 0;
}
 
// Print the time in military format
void printMilitary( const Time &t )
{
   cout << ( t.hour < 10 ? "0" : "" ) << t.hour << ":"
        << ( t.minute < 10 ? "0" : "" ) << t.minute;
}
 
// Print the time in standard format
void printStandard( const Time &t )
{
   cout << ( ( t.hour == 0 || t.hour == 12 ) ? 12 : t.hour % 12 )      //note the operator
        << ":" << ( t.minute < 10 ? "0" : "" ) << t.minute
        << ":" << ( t.second < 10 ? "0" : "" ) << t.second
        << ( t.hour < 12 ? " AM" : " PM" );
}
 

 

Array of Structs

 

#include <iostream.h>

struct fish                                                        //Established before the main
{
    int age;                                                       //Data members
    double weight;
    int printAge ()                                            //printAge and printWeight are member functions
    {
        return age;
    }
    double printWeight ()
    {
        return weight;
    }
};                                                                      //Note the semicolon - class also use this notation 


int main ()
{
    fish greenFish;                                           //Declaring an object of fish struct
    greenFish.age = 1;                                    //Accessing and initializing data members through the object 
    greenFish.weight = 2.67;
    fish pond [10][10];                                      //Declaring a 2-D array of type fish 
    for (int i = 0;i<10;i++)                                 //Initializing the pond array with greenFish objects
        for (int j = 0;j<10;j++)
            pond [i][j] = greenFish;               
    cout << "The age of the greenFish is: "<< greenFish.printAge ()<<endl;
    cout << "The weight of the greenFish is: "<<greenFish.printWeight ()<<endl;

    cout << "The weight of the greenFish in 1st row, 1st col of pond is: "<<pond[0][0].printWeight()<<endl;

    return 0;
}

 

 

Exercises

 

Exercise 1

 

Create a struct named Venusians that has

The following data members

    age - an integer

    weight - a double

    numberEyes - a double

A member function that prints the age, weight, and numberEyes entered.

Create a main function that will

     Create an object of the Venusian struct

    Use the object to set the age, weight, and numberEyes

    Use the object to call the member function and print the age, weight, and numberEyes

 

Exercise 2

 

Part a: Sludge

 

Create a two-dimensional lake named Sludge (or other appropriate name) that has fish swimming all at the same level (not three-dimensional)

Create a struct named Creatures (or other appropriate name). It has data members as follows:

    age - integer, public

    weight - double, public

    length - double, private

    It also has member functions as appropriate for the problem

Create 2 types of Creatures (objects): slowSlime, and ravenousSlime

Populate the lake such that the slowSlime and ravenousSlime are distributed randomly

Print the configuration of the lake

 

Part b: Sludge Battle

 

Create (and describe) some appropriate rules so that the ravenousSlime can eat the slowSlime.

Run the program for a number of sweeps through the array (simulated time steps)

Print the final configuration (with the dispatched slime gone)

 

Exercise 3

 

Modify the above code for the Time struct to accomplish the following.

 

Prompt the user to enter a time in standard format and then announce what he entered along with the time converted to military format.

Prompt the user to enter a time in military format and then announce what he entered along with the time converted to standard format.

For each case above, enter a valid and an invalid time.

If an incorrect format is entered, give the user one more try to get it right, then provide an appropriate response.

 

Your submission should include output for each of the 6 cases listed below, properly labeled.

 

1.  Correct standard format entered along with the conversion

2.  Incorrect standard format entered with appropriate response.

3.  Incorrect standard format entered 2nd time with appropriate response.

4.  Correct military format entered along with the conversion.

5.  Incorrect military format entered along with appropriate response.

6.  Incorrect military format entered 2nd time along with appropriate response.