Point me in the right direction? For an assignment I'm suppose to put an Array in my program that I have already made. The program is very simple, you put in a numerator and a denominator and it prints it as numerator/denominator.
Now I'm suppose to make it so it has an Array and will take in multiple integers and print them out as fractions.
Later I will have to change it so it adds these fractions, and leaves them in fraction form.
fraction fraction; All right... doesn't that give you at least a warning?
So far so good. Now you need to use an array?
1 2 3 4 5 6 7 8 9
int main()
{
fraction arrayOfFractions[10]; // ten fractions
// counting starts from 0, so the first fraction is
arrayOfFractions[0].print();
// and the last is
arrayOfFractions[9].print(); // that's right, nine not ten
}
I thought people who needed something from strangers and relied on nothing but the goodwill of those strangers to get it were smart enough to ask politely and clearly, and not act like a child when the universe doesn't revolve around them.
#include <iostream>
int main()
{
fraction *pointerToFractions;
// we use a pointer, which is a variable holding a memory address
int howMany; // how many fractions
std::cout << "How many? : ";
std::cin >> howMany;
pointerToFractions = new fraction[howMany];
// now use pointerToFractions as if it's an array, as in previous example
delete[] pointerToFractions;
// give back the memory we took after we're done with it.
// otherwise we'll have a "memory leak"
// languages that can de-allocate memory themselves are said to be
// "garbage collected"
}
I would say this is the old school approach.
The new school way to do this is by using Containers, provided by the C++ library. But they'll take some getting used to, if you're new to templates and classes.
#include <iostream>
#include <vector> // std::vector container
int main()
{
int howMany;
std::cout << "How many? : ";
std::cin >> howMany;
std::vector<fraction> vectorOfFractions(howMany);
// now you can use vectorOfFractions as an array
vectorOfFractions[0].print();
}
By the way, adding a usingnamespace std; makes it unnecessary to write std:: over and over, but in the end it's a style thing.