Abstract Data Types
Contents
Data Types in C++
- primitive data types (e.g., int, bool, float)
- user-defined data types (e.g., string)
- data type
- domain of values
- operations
Structuring Data in C++
- collection of data variables under a common name
- unlike an array, a
can hold variables of different typesAخAstruct
- introduces a new type into the program
- definition syntaxx
struct identifier {
variable declaration;
//variable declaration 1;
//variable declaration 2;
//...
};
- variables in a
are called membersstruct
- access members through dot operator (.)
identifier.member;
- initialization
struct_name var_name = {value0, value1, value2, ... };
- Example
struct Student {
string name;
int test_grades[3];
};
Student John;
John.name = "John";
John.test_grades[0] = 95;
John.test_grades[1] = 84;
John.test_grades[2] = 92;
Student Mary = {"Mary", {88, 93, 99} }
Fraction example
-
using namespace std;
/**
* gcd(a, 0) = a
* gcd(a, b) = gcd(b, a mod b)
*/
int gcd(int a, int b)
{
if (b==0)
return a;
return gcd(b, a%b);
}
/**
* lcm = (a*b)/gcd(a,b)
*/
int lcm(int a, int b)
{
auto local_gcd = gcd(a,b);
if (local_gcd == 0)
return 0;
return a / gcd(a,b) * b;
}
void add(int num_1, int den_1, int num_2, int den_2, int& result_num, int& result_den)
{
result_den = lcm(den_1, den_2);
result_num = num_1*(result_den/den_1) + num_2*(result_den/den_2);
}
int main()
{
int num_1 = 1;
int den_1 = 2;
int num_2 = 1;
int den_2 = 3;
int result_num;
int result_den;
add(num_1, den_1, num_2, den_2, result_num, result_den);
cout << result_num << "/" << result_den << endl;
return 0;
}
In-Class Modifications to fraction Example
-
using namespace std;
/**
* gcd(a, 0) = a
* gcd(a, b) = gcd(b, a mod b)
*/
int gcd(int a, int b)
{
if (b==0)
return a;
return gcd(b, a%b);
}
/**
* lcm = (a*b)/gcd(a,b)
*/
int lcm(int a, int b)
{
auto local_gcd = gcd(a,b);
if (local_gcd == 0)
return 0;
return a / gcd(a,b) * b;
}
struct Fraction
{
int numerator;
int denominator;
};
Fraction operator+(Fraction lhs, Fraction rhs)
{
auto common_den = lcm(lhs.denominator, rhs.denominator);
Fraction rtn;
lhs.numerator = lhs.numerator * common_den/lhs.denominator;
rhs.numerator = rhs.numerator * common_den/rhs.denominator;
rtn.numerator = rhs.numerator + lhs.numerator;
rtn.denominator = common_den;
return rtn;
}
ostream& operator<<(ostream& ostm, const Fraction& frac)
{
ostm << frac.numerator << "/" << frac.denominator;
return ostm;
}
int main()
{
Fraction f1 = {1,2};
Fraction f2 = {1,3};
Fraction result = f1 + f2;
cout << f1 << " + " << f2 << " = " << result << endl;
return 0;
}