Structs C++ - Reading Assignments

  1. Structs allow us to group different types of information together that we can refer to as a whole.
  2. Members are the individual pieces of information in a struct.
  3. Members can be accessed through the dot operator and then the name of the member.
  4. A nested struct contains other structs.
1 Like

You have to send the struct pointer to the function and set the values inside. Returning the fraction like this would return a pointer but since its declared in the function it wouldn’t exist anymore. I fixed your code to make it work. :slight_smile:

 struct Fraction
 {
     int numerator{};
     int denominator{};
 };
 
void getFractions(Fraction *fractions)
 {
     cout << "Enter first fraction numerator: ";
     cin >> fractions[0].numerator;
     cout << "Enter first fraction denominator: ";
     cin >> fractions[0].denominator;
     cout << "Enter second fraction numerator: ";
     cin >> fractions[1].numerator;
     cout << "Enter second fraction denominator: ";
     cin >> fractions[1].denominator;
 }
 
 int main()
 {
     Fraction fractions[2]{};
     getFractions(fractions);
 
     cout << "The product of these fractions is " << fractions[0].numerator * fractions[0].numerator / fractions[0].denominator * fractions[0].denominator;
 }
1 Like

Thanks. Based on my prior experience, it looks like you’re passing an argument by it’s reference and the reference is modified as the function does it’s work. I feel like the tutorials we’ve seen so far aren’t getting me to the level of understanding where I can see where I went wrong though. I basically did the same as the solution that was provided, but with an array and I don’t know why all of a sudden conversion would be a problem, although the compile error directly addressed the array issue, so it does seem to come down to that. Maybe if I understood your fix better…

When you say “since it’s declared in the function, it wouldn’t exist anymore” do you mean the first line of the function where I have Fraction fractions[] {}; ?

Where it includes Fraction *fractions in the argument section, what is the significance of the *?

Do you see the tutorials as adequate for this level of understanding, like maybe I just need to review some of it again, did you look elsewhere, or are you basing some of this on previous experience?

Thanks again!

The variable exists in the scope of the function and will not be there after the function is complete. Therefore you must provide a pointer from the calling function to the object and edit the said object instead. This also prevents copying the object from one function to the other which is more efficient than returning it.

Agree its a basic course which will help you get started with C++ but a lot of stuff you will have to learn by yourself. Its what a teacher at my school used to say at the end of semester: “Now you know the language, all you’re missing is a million details.” :stuck_out_tongue:

1 Like
  1. So we can group variables of mixed data into a single unit.
  2. The variables that are defined inside a struct.
  3. Dot notation
  4. A struct that contains another struct.
1 Like
  1. Why do we need structs?+
    We need structs so that we can group variables of mixed data types together into a single unit.

  2. What are members in a struct?
    The variables that are part of the struct.

  3. How do you access a member inside a struct?
    By using the member selection operator (which is a period).

  4. What is a nested struct?
    Structs that contain other structs.

1 Like

This was very helpful. Thanks!

Why do we need structs?

In order to represent an object. If you want to store information about an object, let’s say person’s name, age, height etc., you’d have to declare variables for each additional person in repeat. So Structs are being used in C++ by declaring as like an object. A structure name and properties that belongs.

What are members in a struct?

As talking generally, members are the properties of a structure object which is just a decleration and not a memory allocated for them until they are assigned. As an example, a struct has a name of an employee object as Employee, and the members (being called as fields in cpp as well) of this objects are salary, startDate, retired etc…

How do you access a member inside a struct?

We need to know that the members belong to the all struct variables. Let’s say the employee Yang has the same member variables as another employee Sara like salary, age, workTitle etc. Period is the member selection operator, as an example Employee alex.salary = 60000.0;

What is a nested struct?

Structs can contain other structs. In a programming lanugage education this sentence must be gifted with an example:

struct Servant
{
	int id;
	string area;
	double wage;
};

struct Country
{
	Servant MinisterOfEconomy;
	string regime;
}

Country theirCountry;

// selecting a member of a servant's wage within country struct by using the binding operator twice
theirCountry.President.wage;

// access to id, area and wage members of struct within country struct
Country theirCountry{{ 1, "Politics", 123600 }, "republic" };

Question #1
You are running a website, and you are trying to keep track of how much money you make per day from advertising. Declare an advertising struct that keeps track of how many ads you’ve shown to readers, what percentage of ads were clicked on by users, and how much you earned on average from each ad that was clicked. Read in values for each of these fields from the user. Pass the advertising struct to a function that prints each of the values, and then calculates how much you made for that day (multiply all 3 fields together).

#include <iostream>

using namespace std;

struct Website
{
		int shownAds;
		int percentageClicked;
		int averageGain;
};

void printValues(Website ads)
{
		cout << "Shown Ads:   " << ads.shownAds << '\n';
		cout << "Click Percentage:  " << ads.percentageClicked << '\n';
		cout << "Average Gain: " << ads.averageGain << '\n';
}

int main()
{
		Website migrationvlog;

		cout << "Ads: ";
		cin >> migrationvlog.shownAds;
		cout << "Percentage: ";
		cin >> migrationvlog.percentageClicked;
		cout << "Average: ";
		cin >> migrationvlog.averageGain;

		int result =
				migrationvlog.averageGain *
				migrationvlog.percentageClicked *
				migrationvlog.shownAds;

		printValues(migrationvlog);

		cout << "You've made " << result;

		return 0;
}			

Here’s my answer to the Quiz #1, My code prompts values, assigns the values to the struct members. Then my function prints the results as required in the quiz. But the main difference was that the solution has an extra function that creates a temporary struct called temp which is inside of getAdvertising() function struct. I call it function struct, because it has returning method, runs as like a function and also defined as a struct during creation: Advertising getAdvertising(). It is presented subtly nice for an Object Oriented Programming example. So my wrong was that deploying target requirement hardly on the main function instead of designing the program in the modular way. Every time I need to create another website struct I would need to restore the main function instead of getting a name of a website via prompting.

_

Question #2
Create a struct to hold a fraction. The struct should have an integer numerator and an integer denominator member. Declare 2 fraction variables and read them in from the user. Write a function called multiply that takes both fractions, multiplies them together, and returns the result as a decimal number. You do not need to reduce the fraction to its lowest terms. Print the result of the multiplication of the 2 fraction variables.

#include <iostream>

using namespace std;

struct Fraction
{
		int numerator;
		int denominator;
};

Fraction getFraction()
{
		Fraction temp{};
		cout << "Numerator: ";
		cin >> temp.numerator;
		cout << "Denominator: ";
		cin >> temp.denominator;
		return temp;
}

int multiply(Fraction n1, Fraction n2)
{
		double result =
				(n1.numerator * n2.numerator) /
				(n1.denominator * n2.denominator);
		return result;
}

int main()
{
		Fraction fracA{getFraction()};
		Fraction fracB{getFraction()};

		cout << multiply(fracA, fracB);
		return 0;
}

My solution won’t work or I maybe I couldn’t analyse the returns. Probably because I didn’t know about static_cast which converts the value gets operated. I gave up here. First I must admit that I learned why I need to define a getter function seperately and then I used it in the second quiz. Also I learned something more about C++, structs can be subtly integrated with the functions. They seems very modular (or maybe I must say the PL is the modular, basically) and useful with large data models.

1 Like

What doesn’t work? I tried your solution and it worked fine for me.

1 Like

Thank you for the feedback @Alko89, lately I’ve been through about capacities of staying successful in this… that funny stuck… so the feedbacks value a lot.

It was around 3 o’clock in the morning while I was posting that answer, I have just missed something at the console while testing. It was all about getting int only instead of double at the end. Every time I saw 0 if I give proper fractions, so I thought there could be a mistake. declaring variable types in modularity requires proper attention.

It’s fine now, I assume I practiced enough with structs. all good.

  1. to store values in a struct
    2)members are the values listed in a sturct
  2. assign the structs name. value
    4)a struct with in a struct
1 Like
  1. To easier group multiple individual variables and perform operations on them.
  2. Variables inside of the struct.
  3. We use the member selection operator.
  4. A struct that contains other struct.
1 Like
  1. Why do we need structs?
    Because we can use more than one variable to represent an object.
  2. What are members in a struct?
    The variables in the struct
  3. How do you access a member inside a struct?
    By using the member selection operator which is basically a period.
    referenced_strunct.variable_of_referenced_strunct
  4. What is a nested struct?
    A struct within a struct .
1 Like
  1. Why do we need structs?

You may require more than one variable in order to represent an object.

  1. What are members in a struct?

Variables within a struct

  1. How do you access a member inside a struct?

To access the individual members, we use the member selection operator, which is a period.

  1. What is a nested struct?

Structs within structs.

1 Like
  1. Why do we need structs?
    -When you need more than 1 variable to represent an object

2.What are members in a struct?
-Variables that identify the struct

3.How do you access a member inside a struct?

  • use the “.”

4.What is a nested struct?
-Struct inside a struct

1 Like
  1. Why do we need structs? To have more than one variable to represent an object and groups multiple individual variables together/groups variables of mixed data type together i a single unit.
  2. What are members in a struct? Members or fields are the variables inside the struct Which has a capital letter at the start of the name.
  3. How do you access a member inside a struct? member selection operator simple declare a variable of type name.
  4. What is a nested struct? Is a struct inside a struct. this will give you more detail about the original struct.
1 Like
  • Why do we need structs? We need structs to have user defined groups of mixed data types, i.e. int, string, double, etc.
  • What are members in a struct? The members of the struct are the variable types with indentifiers and initialization.
  • How do you access a member inside a struct? You access a member by calling its name with a dot.
  • What is a nested struct? A nested struct is a struck inside another struct.
    [/quote]
1 Like

1. a struct is a user defined aggregate data type, that groups multiple individual variables together into a single unit. we need structs because we want to have groups of data, not millions of variables.
2. members are variables that are part of a struct
3. struct members act just like normal variables, so it is possible to do normal operations on them
4. a nested struct is a " struct that cointains other structs".

1 Like

Because Structs allows us to group mixed data types into one single unit.

Members or also fields are variables that are part of the struct.

nameOfStruct.variable(member)

a struct inside another struct

1 Like
  • We need structs because they allows us to group variables of mixed data types together into a single unit saving a lot of time and redundancy in the code.
  • Members are the variables that lie within the struct
  • you call on a member by first identifying the struct followed by a period and the member “Struct.member”
  • a nested struct is just a struct within a struct
1 Like