Structure

Estimated reading: 8 minutes 141 Views

Structures in C++ provide a powerful way to organize and store related data under a single name. They are a fundamental concept in Object-Oriented Programming (OOP) that allows you to create custom data types to suit your program’s needs. In this guide, we’ll delve into the basics of structures in C++.

What is a Structure?

A structure is a user-defined data type in C++ that enables you to group together different data types under a single name. This makes it easier to manage and organize related information. Unlike primitive data types, structures can hold a collection of variables with various data types.

Defining a Structure:

To create a structure, you use the struct keyword, followed by the structure’s name and a block of variables inside curly braces. Here’s a simple example:

// Define a structure named 'Person'
struct Person {
    char name[50];
    int age;
    float height;
};

In this example, we’ve created a structure named Person with three members: a character array for the name, an integer for age, and a float for height.

Accessing Structure Members:

You can access the members of a structure using the dot (.) operator.

Example 1:

#include <iostream>
using namespace std;

struct car 
{
    string name;
    string color;
    int maxspeed;
    int model;
};

int main()
{
    car g;
    g.name = "Kia";
    g.color = "red";
    cout << g.name << endl; //Kia
    cout << g.color << endl;  //red

    return 0;
}

This code defines a simple program that utilizes a structure named car. The structure car has four members: name (string), color (string), maxspeed (integer), and model (integer). The program then declares a variable g of type car and assigns values to its name and color members. Finally, it prints the values of name and color to the console.

Initializing Structure Variables:

You can initialize structure variables at the time of declaration, similar to how you initialize primitive variables:

// Initialize structure variables
Person person3 = {"Alice", 30, 5.5};

Example 2:

#include <iostream>
using namespace std;

struct car 
{
    string name;
    string color;
    int maxspeed;
    int model;
}g, k;

int main()
{
    k = {"aa", "black", 300, 97};
    g = {"kia", "red", 250, 96};
    cout << g.maxspeed << endl;

    return 0;
}

This code defines a structure named car with four members (name, color, maxspeed, and model). Additionally, it declares two structure variables, g and k, of type car. In the main function, it assigns values to these structure variables using an initialization syntax and then prints the value of the maxspeed member of the g structure variable. Here’s a detailed explanation:

– Structure Definition and Variable Declaration:

struct car {
    string name;
    string color;
    int maxspeed;
    int model;
} g, k;  // Declaration of structure variables g and k of type car

Defines a structure named car and declares two structure variables g and k of type car.

– Main Function:

int main() {
    // Initialization of structure variable k
    k = {"aa", "black", 300, 97};

    // Initialization of structure variable g
    g = {"kia", "red", 250, 96};

    // Print the value of the maxspeed member of the g structure variable
    cout << g.maxspeed << endl;

    return 0;
}

Execution Flow:

  1. Initialization of Variables:
    k = {“aa”, “black”, 300, 97}; initializes the members of structure variable k with the provided values.
    g = {“kia”, “red”, 250, 96}; initializes the members of structure variable g with the provided values.
  2. Print to Console:
    cout << g.maxspeed << endl; prints the value of the maxspeed member of the g structure variable to the console, followed by a newline.
  3. Return Statement:
    return 0; indicates that the program has executed successfully.

The output of this program would be:

250

Functions and Structures:

Structures can be passed as arguments to functions, allowing you to create more modular and organized code.

Example 3:

#include <iostream>
#include <string>
using namespace std;

struct Distance
{
    int feet;
    float inches;
};
Distance add_distance(Distance d1, Distance d2)
{
    Distance result;
    result.feet = d1.feet + d2.feet;
    result.inches = d1.inches + d2.inches;
    return result;
}

int main()
{
    Distance x, y, z;
    cout << "Enter feet value \n";
    cin >> x.feet >> y.feet;
    cout << "Enter inches value \n";
    cin >> x.inches >> y.inches;
    z = add_distance(x, y);
    cout << "z.feet = " << z.feet << " z.inches = " << z.inches << endl;

    return 0;
}

This code demonstrates the use of structures to represent distances in feet and inches. It defines a structure Distance with two members: feet (integer) and inches (float). The program then includes a function add_distance to add two distance structures, and the main function takes user input for two distances, adds them using the add_distance function, and prints the result. Here’s a step-by-step explanation:

– Structure Definition:

struct Distance {
    int feet;
    float inches;
};

Defines a structure named Distance with two members: feet (integer) and inches (float).

– Function to Add Distances:

Distance add_distance(Distance d1, Distance d2) {
    Distance result;
    result.feet = d1.feet + d2.feet;
    result.inches = d1.inches + d2.inches;
    return result;
}

Defines a function add_distance that takes two Distance structures as parameters, adds their corresponding feet and inches members, and returns a new Distance structure representing the sum.

– Main Function:

int main() {
    Distance x, y, z;

    // User input for the first distance (x)
    cout << "Enter feet value \n";
    cin >> x.feet;
    cout << "Enter inches value \n";
    cin >> x.inches;

    // User input for the second distance (y)
    cout << "Enter feet value \n";
    cin >> y.feet;
    cout << "Enter inches value \n";
    cin >> y.inches;

    // Add the two distances using the add_distance function
    z = add_distance(x, y);

    // Print the result
    cout << "z.feet = " << z.feet << " z.inches = " << z.inches << endl;

    return 0;
}

Execution Flow:

  1. User Input:
    The user is prompted to enter the feet and inches values for two distances (x and y).
  2. Function Call:
    The add_distance function is called with the x and y structures as arguments, and the result is stored in the z structure.
  3. Print to Console:
    The program prints the result, displaying the summed feet and inches of the distances.
  4. Return Statement:
    return 0; indicates that the program has executed successfully.

– Sample Execution:
If the user enters:

Enter feet value
3
Enter inches value
6.5
Enter feet value
2
Enter inches value
3.2

The program would output:

z.feet = 5 z.inches = 9.7

Example 4:

#include <iostream>
#include <string>
#include <cstring>
#include <cstdlib>
using namespace std;

struct exam
{
    float first;
    float second;
    float final;
};
class subject
{
        char name[10];
        exam Exam;
    public:
        subject()
        {
            strcpy(name, "no name");
            Exam = {0, 0, 0};
        }
        subject(char n[], float fa, float s, float fi)
        {
            strcpy(name, n);
            Exam = {fa, s, fi};
        }
        float total()
        {
            return Exam.first + Exam.second + Exam.final;
        }
        void print()
        {
            cout << "The subject = " << name << endl
                 << "First Exam = " << Exam.first << endl
                 << "Second Exam = " << Exam.second << endl
                 << "Final Exam = " << Exam.final << endl
                 << "The Total is = " << total() << endl;
        }
};

int main()
{
    subject e("OOP", 25, 24, 49);
    e.print();
    return 0;
}

This code defines a program that uses a combination of structures and classes to model a subject with exam scores. Let’s break down the code step by step:

– Structure Definition:

struct exam {
    float first;
    float second;
    float final;
};

Defines a structure named exam with three members representing exam scores: first, second, and final.

– Class Definition:

class subject {
    char name[10];
    exam Exam;
public:
    // Default constructor
    subject() {
        strcpy(name, "no name");
        Exam = {0, 0, 0};
    }

    // Parameterized constructor
    subject(char n[], float fa, float s, float fi) {
        strcpy(name, n);
        Exam = {fa, s, fi};
    }

    // Member function to calculate the total exam score
    float total() {
        return Exam.first + Exam.second + Exam.final;
    }

    // Member function to print subject details
    void print() {
        cout << "The subject = " << name << endl
             << "First Exam = " << Exam.first << endl
             << "Second Exam = " << Exam.second << endl
             << "Final Exam = " << Exam.final << endl
             << "The Total is = " << total() << endl;
    }
};

Defines a class named subject with private members:

  • name: An array of characters representing the subject’s name.
  • Exam: An instance of the exam structure representing exam scores.

The class includes:

  • A default constructor (subject()) initializing name to “no name” and Exam to all zeros.
  • A parameterized constructor (subject(char n[], float fa, float s, float fi)) initializing name and Exam with provided values.
  • A total() member function calculating the total exam score.
  • A print() member function printing subject details.

– Main Function:

int main() {
    // Create an instance of the subject class
    subject e("OOP", 25, 24, 49);

    // Call the print() member function to display subject details
    e.print();

    return 0;
}

In the main function:

  • An instance e of the subject class is created using the parameterized constructor.
  • The print() member function is called on the e object, displaying the details of the subject and its exam scores.

– Sample Output:

The subject = OOP
First Exam = 25
Second Exam = 24
Final Exam = 49
The Total is = 98

This output represents the details of the “OOP” subject, including scores on the first, second, and final exams, as well as the total score.

 

Share this

Structure

Or copy link

CONTENTS
English