Lab 1 C++ Review

14
Data Structures and Algorithms 3 Lab 1 C++ Review Objective: To Revise and Practice following C++ Programming Features: Functions Structures Classes Function and class Templates File I/O

Transcript of Lab 1 C++ Review

Page 1: Lab 1 C++ Review

Data Structures and Algorithms 3

Lab 1

C++ Review

Objective:

To Revise and Practice following C++ Programming Features:

Functions

Structures

Classes

Function and class Templates

File I/O

Page 2: Lab 1 C++ Review

Data Structures and Algorithms 4

Fundamental Data Types

Category Available data types

Boolean bool

Character char signed char unsigned char

Signed integer short int long

Unsigned integer unsigned short unsigned unsigned long

Floating point float double long double

Named Constants

The value of these constants cannot be changed during program execution.

C style constants:

#define zero 0

C++ style constants:

const int zero = 0; const float PI = 3.14159;

Type Aliases

Renaming existing datatypes:

typedef float real;

This means that “real” may now be used in place of “float”

Defining new datatypes based on existing datatypes:

typedef char* str;

This means “str” can be used in place of “char*”

Page 3: Lab 1 C++ Review

Data Structures and Algorithms 5

Arithmetic Expressions

Binary operators: , , *, /, %

Unary operators: +, , ++,

Usual precedence rules apply

Unary operators are right-associative: ++ X means ++ (X )

Binary operators are left-associative: A / B * C means (A / B) * C

Relational & Logical Expressions

Relational operators: <, >, <=, >=

Equality operators: = =, !=

Logical operators:

Unary: !

Binary: &&, | |

Examples:

(5 = = 4) && (a < b) // false, since 5 != 4 (5 = = 5) | | (a < b) // true, since 5 = = 5

Conditional Expressions

expression ? expression : expression

Executed like if else statement, but has a value

Example: larger = (A > B) ? A : B;

Page 4: Lab 1 C++ Review

Data Structures and Algorithms 6

Functions

A function is a group of statements that is executed when it is called from some point

of the program.

Example 1.1

int max1( int X, int Y ) { return (X > Y) ? X : Y; // result returned as function value } void max2( int X, int Y, int &Larger ) { Larger = (X > Y) ? X : Y; // result returned by reference } void max3( int X, int Y, int *Larger ) { *Larger = (X > Y) ? X : Y; // result returned by pointer }

Structures

A structure is a group of data elements grouped together under one name. These

data elements, known as members, can have different types. struct Student {

char name[30]; int section; float total_points;

}; Student class[30]; Student *ptr = class; class[0].name is the same as ptr-> name

Initialization:

Student Ali = {“Ali Ahmed”, 8, 592.5};

Structures may be copied with “=”

Structures may be passed to functions by value

Structures may be returned from functions

Structures may be nested

Arrays of structures may be defined

Page 5: Lab 1 C++ Review

Data Structures and Algorithms 7

Classes

Class is the capsule that is used to encapsulate an abstract data type.

A class defines a new data type. You can create many objects of this type.

A class is composed of one or more members (data and functions).

Class definition usually placed in an include (.h) file for ease of use.

Example 1.2: A Complex Number Class

#include <iostream> #include <math.h> using namespace std; class Complex

{ private: float re; float im; public: Complex(float r,float i) {re = r; im = i;} Complex(float r) {re = r; im = 0.0;} ~Complex() {};

double Magnitude() // calculate magnitude { return sqrt(re*re + Imag()*Imag()); }

float Real() {return re;} // return real part float Imag() {return im;} // return imaginary part Complex operator+(Complex b) {return Complex(re + b.re, im + b.im);} Complex operator=(Complex b) {re = b.re;im = b.im; return *this;}

}; int main() { Complex a(1.0,1.0); Complex *b = new Complex(5.0); Complex c(0,0); cout << "a real = " << a.Real() << “ a imaginary = “ << a.Imag() << endl; cout << "b real = " << b->Real() << “ b imaginary = “ << b->Imag() << endl; c = a + (*b); cout << "c real = " << c.Real() << “ c imaginary = “ << c.Imag() << endl; delete b; return 0; }

Exercise 1.1 Add a function to multiply two complex numbers using operator overloading.

Page 6: Lab 1 C++ Review

Data Structures and Algorithms 8

Function Templates

Function templates are special functions that can operate with generic types. This allows

us to create a function template whose functionality can be adapted to more than one type

without repeating the entire code for each type.

In C++ this can be achieved using template parameters. A template parameter is a special

kind of parameter that can be used to pass a type as argument: just like regular function

parameters can be used to pass values to a function, template parameters allow to pass also

types to a function. These function templates can use these parameters as if they were any

other regular type.

The format for declaring function templates with type parameters is:

template <class identifier> function_declaration;

Example 1.3

#include <iostream> using namespace std; template <class T> T GetMax (T a, T b) { T result; result = (a>b)? a : b; return (result); } int main () { int i=5, j=6, k; long l=10, m=5, n; k=GetMax<int>(i, j); n=GetMax<long>(l, m); cout << k << endl; cout << n << endl; return 0; }

Page 7: Lab 1 C++ Review

Data Structures and Algorithms 9

Class Templates

A class can have members that use template parameters as types.

template <class T> class mypair { T values [2]; public: mypair (T first, T second) { values[0]=first; values[1]=second; } };

This class serves to store two elements of any valid type. For example, if we wanted to

declare an object of this class to store two integer values of type int with the values 115

and 36 we would write:

mypair<int> myobject (115, 36);

this same class would also be used to create an object to store any other type:

mypair<double> myfloats (3.0, 2.18);

Page 8: Lab 1 C++ Review

Data Structures and Algorithms 10

Example 1.4

#include <iostream> using namespace std; template <class T> class mypair { T a, b; public: mypair (T first, T second) {a=first; b=second;} T getmax (); }; template <class T> T mypair<T>::getmax () { T retval; retval = a>b? a : b; return retval; } int main () { mypair <int> myobject (100, 75); cout << myobject.getmax(); return 0; }

Exercise 1.2 Add a function to compute minimum of two numbers in the above class.

Page 9: Lab 1 C++ Review

Data Structures and Algorithms 11

Example 1.5

#include <iostream> using namespace std; template <class T, int N> class mysequence { T memblock [N]; public: void setmember (int x, T value); T getmember (int x); }; template <class T, int N> void mysequence<T,N>::setmember (int x, T value) { memblock[x]=value; } template <class T, int N> T mysequence<T, N>::getmember (int x) { return memblock[x]; } int main () { mysequence <int,5> myints; mysequence <double,5> myfloats; myints.setmember (0,100); myfloats.setmember (3, 3.1416); cout << myints.getmember(0) << '\n'; cout << myfloats.getmember(3) << '\n'; return 0; }

Page 10: Lab 1 C++ Review

Data Structures and Algorithms 12

File Input/Output

Files are classified as containing either text (i.e. characters) or binary data

May read and write numbers from/to text files: C++ does the necessary translations

#include <fstream> // for C++ file I/O

Character Input with fstream

ifstream infile; // define infile infile.open( “MyData” ); // open “MyData” file if( !infile ) cout << “Can’t open ” << “MyData” << endl; infile >> chr; // read character from “MyData” file into chr infile.close( ); // close “MyData” file

Useful Functions for Character Input

infile.ignore( n ); // skip next n input characters chr = infile.get( ); // same as infile >> chr while( infile.get( ) != ‘\n’ ) ... // loop until end of line while( infile.get( ) != EOF ) ... // loop until end of file while( infile >> chr ) ... // loop until end of file

Character Output with fstream

ofstream outfile( “MyOut” ); // define & open outfile outfile << chr; // write chr to “MyOut” file outfile.put( chr ); // same as outfile << chr outfile.close( ); // close “MyOut” file

Numeric I/O with Text File and fstream

If numeric data is read to/written from a variable of numeric type, then >> translates the

data into the appropriate numeric representation

If “MyData” file contains

5280 2.718 3.141592653 then int ftPerMile;

float e;

double pi;

infile >> ftPerMile >> e >> pi;

stores input as int, float, and double.

Page 11: Lab 1 C++ Review

Data Structures and Algorithms 13

Example 1.6: To count number of characters in a Text file.

#include <iostream> #include <fstream> using namespace std; int main(void) { ofstream outFile; outFile.open("fout.txt"); ifstream inFile("fin.txt"); char ch; int count = 0; while(inFile.get(ch)) { outFile << ch; count++; } outFile << "\n\n Character count = " << count << endl; inFile.close(); outFile.close(); return 0; }

Exercise 1.3 Modify the above program to count number of words and number of sentences along with the characters.

Page 12: Lab 1 C++ Review

Data Structures and Algorithms 14

Exercise 1.4 Assume that a file contains the midterm1, midterm2 and final exam scores and names of

students of a class. Write a C++ program to read the input file and produce an output file

containing the original and average scores for each student. Suppose that the weights of

the exams are as follows:

midterm1 – 25%

midterm2 – 25%

final – 50%.

The average score of a student is calculated using the formula:

FINMTMT 5.0225.0125.0

Solution:

#include <iostream> #include <fstream> using namespace std; int main ( ) { char name[10]; float mt1, mt2, final, avg; ifstream fin ; //Create file input stream object ofstream fout ; //Create file output stream object fin.open ( "input.dat") ; //Open input file fout.open ( "output.dat"); //Open output file while (!fin.eof()) //Read data from input file { fin >> name >> mt1 >> mt2 >> final; avg = 0.25*mt1 + 0.25*mt2 + 0.5*final ; fout << name << '\t' << avg << endl ; //Write result to output file } fin.close ( ) ; //Close input file fout.close ( ) ; //Close output file }

Page 13: Lab 1 C++ Review

Data Structures and Algorithms 15

Exercise 1.5

a) Declare a class named House for a real estate locator service. The following information

should be included:

Owner: (a string of up to 20 characters)

Address: (a string of up to 20 characters)

Bedrooms: (an integer)

Price (floating point)

b) Declare available to be an array of 100 objects of class House.

c) Write a function to read values into the members of an object of House.

d) Write a driver program to test the data structures and the functions you have developed.

The driver program should read in house entries into the available array. After the code

for entering the data, you should write code to output the data that you have entered to

verify that it is correct.

Your program should look like this:

Enter Owner : M. Khan

Enter Address : G-9, Islamabad

Number of Bedrooms ? : 4

Price : 4500000

Enter another house? N

The output should look like:

Owner Address Bedrooms Price

M. Khan G-9, Islamabad 4 4500000

Page 14: Lab 1 C++ Review

Data Structures and Algorithms 16

Exercise 1.6

Write a student grades "database" program. It will read data of students from a file and will

let the user perform various operations on the data. You will have to store the student data

in an array of objects.

Input:

The input file will look like:

4 // number of students

3 // number of grades (per student)

Hassan Khan 99 87 90 // name grade grade ... grade

Sara Nazir 90 98 99

Ali Zaidi 55 43 0

Raza Ahmad 100 100 100

Data structure:

You will store all the information in an array of "student" objects. You may use the

following class definition:

class student { private: char name[30]; int grades[10]; float average; public: . . . };

Output:

Your program should work as follows:

Ask the user for the filename and open the file.

Read in the input from the file and store it in the student array.

Compute and store an average for every student.

Display the student data in tabular (formatted) form.

Compute the class average.

Compute the highest and lowest average grades.

List all the students whose average grade is less than the class average.