Вы находитесь на странице: 1из 30

char short int (short) int

Character or small integer. Short Integer. Integer.

1byte 2bytes 4bytes

long int (long) bool float double long double wchar_t

Long integer. Boolean value. It can take one of two values: true or false. Floating point number. Double precision floating point number. Long double precision floating point number. Wide character.

4bytes 1byte 4bytes 8bytes 8bytes 2 or 4 bytes

signed: -128 to 127 unsigned: 0 to 255 signed: -32768 to 32767 unsigned: 0 to 65535 signed: -2147483648 to 2147483647 unsigned: 0 to 4294967295 signed: -2147483648 to 2147483647 unsigned: 0 to 4294967295
true

or false

+/- 3.4e +/- 38 (~7 digits) +/- 1.7e +/- 308 (~15 digits) +/- 1.7e +/- 308 (~15 digits) 1 wide character

Tutorial 1
#include "stdafx.h" #include <stdio.h> #include <iostream> using namespace std;

int main() { int x = 2; switch(x)

{ case 2: printf("Two\n"); // break ; case 3: printf("Three\n"); // break; }

-----------------------int x = 4; if ( x = 6 ) // if( x == 6) printf("x equals 6\n"); ---------------------------for (int i=100; i!=0;i-=3){ // the loop is infinite (100, 97, 94 ... , 1, -2, ..... infinte) printf("i equals %d\n", i); } ----------------------------double halfval=1/2; // halfval will equal 0.0 because of integer division, correction => double halfval = (double) 1/2 ; -----------------------char st1[] = "abc"; char st2[] = "abc"; if ( st1 == st2 ) // if(str.comp(st1, st2)) printf("Yes"); else printf("No"); --------------------int x = 0; while( 1 ) x++; -----------------int a, intArray[5]; for (a=0 ; a <= 10 ; a++) // for (a=0;a<5;a++) incorrect access to unavailable array position intArray[a] = a * 2; -----------------int x; char st[31]; printf("Enter an integer: "); scanf(%d, &d); // cin.ignore() must clean buffer for /n printf("Enter a line of text: "); fgets(st, 31, stdin); --------------------------------

int myFunction(){ int x; if (x) { // return x; int function require a return type } } -------------------------int inP = 5; switch (inP) { int test = inP * 2; case 10: * ...... */ break; default: * ...... */ } // redundant quesion ----------------------------int intVal1 = 8; int intVal2 = 010; if (intVal1 == intVal2) printf (Both variables are equal!?); // 010 is 8 in octal system --------------------------------------

/************************* //ID: 1081107325 //Name: Ehsan Elbadery //Tutorial 01 section B *************************/ #include "stdafx.h" #include <iostream> using namespace std;

void void void void

findMin(int findMax(int findAvg(int findSum(int

array[], array[], array[], array[],

int &minVal); int &maxVal); double &avg); double &sum);

int _tmain(int argc, _TCHAR* argv[]) { int i, ltZero=0, gtZero=0, minVal=0, maxVal=0; int arrayNum[10]; double avg =0, sum=0; cout <<"Please enter 10 numbers : " ; for (i = 0 ; i<10; i++) { cin >> arrayNum[i]; if(arrayNum[i] < 0) ltZero++; else if(arrayNum[i])

gtZero++; } findMin(arrayNum,minVal); findMax(arrayNum,maxVal); findAvg(arrayNum,avg); findSum(arrayNum,sum); cout cout cout cout cout cout << << << << << << "Minimum value = " << minVal <<endl; "Maximum value = " << maxVal <<endl; "average of the ten numbers is = " << avg <<endl; "Total sum of the ten numbers = " << sum <<endl; "Total numbers less than zero is = " << ltZero <<endl; "Total numbers greater than zero is = " << gtZero <<endl;

return 0; } void findMin(int array[], int &minVal) { int min = array[0]; int i; for (i=1; i<10; i++) { if(array[i]<min) {min = array[i];} } minVal = min; } void findMax(int array[], int &maxVal) { int max = array[0]; int i; for (i=1; i<10; i++) { if(array[i]>max) {max = array[i];} } maxVal = max; } void findAvg(int array[], double &avg) { int i; double total =0; for(i=0; i<10 ; i++) {total += array[i];} avg = (double)total/10; } void findSum(int array[], double &sum) { int i; double total =0; for(i=0; i<10 ; i++) {total += array[i];} sum = total; }

Tutorial 2
/********************************** // ID: 1081107325 // Name: Ehsan Elbadery // Tutorial 02 section b **********************************/ #include "stdafx.h" #include <iostream> using namespace std; int _tmain(int argc, _TCHAR* argv[]) { char grade; int aCount=0, bCount=0, cCount=0; cout << "please enter a grade <f> to exit "; cin >> grade; while(grade != 'f') { switch (grade) { case 'A': case 'a': ++aCount; break; case 'B': case 'b': ++bCount; break; case 'C': case 'c': ++cCount; break; default: cout<<"Incorrect grade entered"<<endl; } /*if (grade == 'a' || grade == 'A') aCount++; else if(grade == 'b' || grade == 'B') bCount++; else if(grade == 'c' || grade == 'C') cCount++; else cout << "Incorrect grade entered"<<endl;*/ cout << "please enter a grade <f> to exit "; cin >> grade; } cout << "aCoutn " << aCount << "\nbCount " << bCount << "\ncCount " << cCount << endl; return 0; }

/*-----------------------------------//question int sum = 0; for (int i=0 ; i <= 1000 ; i++) sum = sum + 1; // solution int i = 0, sum=0; while(i<= 1000) {sum = sum + 1; i++;} int i = 0, sum=0; do {sum = sum + 1 ; i++; } while(i <= 1000); -------------------------------------------*/ /*-----------------------------------------//question int counter = 1000; while (1) { if (counter<9) break; counter -= 9; } cout << "Counter is " << counter << endl; //solution int counter = 1000; while (1) { counter -= 9; if(counter < 9) {counter += 9; break;} } cout << "Counter is " << counter << endl; //question int counter = 1000; while(true){ if (counter<9) continue; counter-=9; } cout << "Counter is " << counter << endl; //solution --------------------------------------------*/ /*-------------------------------------------question testVal = (x < y) ? x : y; solution int testVal; if(x<y) testVal = x;

else testVal = y; question aVal = ( var3 < (var1<var2?var1:var2) ? var3:(var1<var2?var1:var2) ); solition int aVal; if (Var1 < Var2) { if(Var3 < Var1) aVal = Var3; else aVal = Var1; } else { if(Var3 < Var2) aVal = Val3; else aVal = Val2; } -------------------------------------*/

/************************** Tutorial 2 part c *****************************/

#include "stdafx.h" #include <iostream> using namespace std; #include "MinMax.h" int _tmain(int argc, _TCHAR* argv[]) { float Array[10], MinVal=0, MaxVal=0; int size = 10; cout<< "pleaseenter 10 floating numbers " ; for(int i=0; i< 10; i++) cin>>Array[i]; FindMinMax(Array, size,&MinVal ,&MaxVal); cout <<"the minimum value is " << MinVal <<"\nthe maximum value is " << MaxVal << endl;

return 0; }

#include "stdafx.h" #include <iostream> #include <iomanip> using namespace std; int _tmain(int argc, _TCHAR* argv[]) { int input; cout<<"please enter the value between 0 and 50 : "; cin >> input; while (input < 50 && input >0) { for(int i = 1; i <=input; i++) { for(int y=1; y<= input; y++) {cout<< "*";} cout << "\n"; } for(int i = 1; i <=input; i++) { for(int y=1; y<= input; y++) { if(i == 1 || i == input) cout<<"*"; else if(y == 1 || y == input) cout<< "*"; else cout<<" "; } cout << "\n"; } int update=1;// to prevent reinitialisation of counter y in the inner y loop for(int i=1; i<=input ; i++) { for(int y=update; y <= (input * i); y++) {cout << left << setw(3) << y; update = y+1;} cout << "\n"; } cout<<"please enter the value between 0 and 50 : "; cin >> input; } cout <<"U have EXITED" <<endl; return 0; }

Tutorial 3
#include "stdafx.h" #include<iostream> #include <string> using namespace std; int _tmain(int argc, _TCHAR* argv[]) { /*float pr, num, total; int x, cent; cout<< "please enter the price of the item:"; cin>> pr; cout<<"please enter the number of items bought:"; cin>> num; x=pr; cent = (int)((pr - x)*100); total= pr*num; cout<< "price of the item is \t" << x << " rigget(s) and " << cent << " \n" << endl; cout<<"Number of items boaught is "<< num << "\n"<<endl; cout<<"Total amount to be paid is "<< total<<"\n"<<endl;*/ string name; float pr, total=0; int num, totnum=0, ring, cent;

cent

do { cout<<"Enter name of the item (-1 to terminate): "; getline(cin,name); if(name=="-1") continue; cout<<"Enter price of the item:"; cin >> pr; cout<<"Enter number of items bought:"; cin>> num; total = total + (pr*num); totnum = totnum + num; cin.ignore(); }while(name!="-1"); ring=total; cent=(total-ring)*100; cout <<"------------------------------------------" <<endl; cout <<"Total number of Items bought is " << totnum <<endl; cout <<"Total cost of items bought is " << ring<< " Ringgit(s) and " << cent<<" cent(s)" << endl; return 0; }

Tutorial 4
/***************************** //ID:1081107325 //Name: Ehsan Elbadery //Tutorial 04 section B modified *****************************/

#include "stdafx.h" #include <string> #include <iostream> using namespace std; class Purchase { int qty, totqty; string itemName; float price,total, grandtotal; public: Purchase(){grandtotal=0; totqty=0;} void set_data(int x, float y, string i); void calculate(); void print(); void printgrandtotal(); }; void Purchase::set_data(int x, float y, string i) { qty=x; itemName=i; price=y; } void Purchase::calculate() { total=price*qty; grandtotal += total; totqty += qty; } void Purchase::print() { cout<< "===============================\nSubtotal :"<<total<< "\n==============================="<<endl; } void Purchase::printgrandtotal( ) { cout << "===============================\n\t Grand Toatal\n=============================== " << endl; cout << "Total number of items : " << totqty<<endl; cout <<"Total amount to be paid : "<<grandtotal<<endl;

cout <<"===============================\n\t End\n==============================="<<endl; }

int _tmain(int argc, _TCHAR* argv[]) { Purchase a; string itemNamemain; int qtymain; float pricemain; cout << "===============================\n\tWelcome\n==============================="<<endl; do { cout << "Enter item <'Q' to quit>: "; getline(cin, itemNamemain); if(itemNamemain == "Q") continue; cout << "Enter Quantitiy : "; cin >> qtymain; cout <<"Enter price : "; cin>> pricemain; a.set_data(qtymain,pricemain,itemNamemain); a.calculate(); a.print(); cin.ignore(); } while(itemNamemain != "Q"); a.printgrandtotal(); return 0; }

Tutorial 5
#include "stdafx.h" #include <iostream> using namespace std; class Temp { private: double tempCel, tempFeh; public: Temp() { tempCel = 0; tempFeh= 32; } Temp(char type, double in_temp) { switch (type) {case 'C': tempCel = in_temp; tempFeh =( (double)9/5 * in_temp )+ 32; break; case 'F' : tempFeh = in_temp; tempCel = ((double)5/9 * (in_temp - 32)); //convert break; } } double getCel() {return tempCel;} double getFeh() {return tempFeh;} }; int main() { Temp t1('C',100),t2('F',100); cout<<"t1 = "<<t1.getCel()<<" C\n"; cout<<"t1 = "<<t1.getFeh()<<" F\n"; cout<<"t2 = "<<t2.getCel()<<" C\n"; cout<<"t2 = "<<t2.getFeh()<<" F\n"; t1 = t2; cout<<"After assigning t2 to t1"<<endl; cout<<"t1 = "<<t1.getCel()<<" C\n"; cout<<"t1 = "<<t1.getFeh()<<" F\n"; return 0;

Tutorial 6
#include "stdafx.h" #include <iostream> using namespace std; class Time { private: int minutes, hours; public: Time() { minutes = 0; hours = 0; } Time (int in_hours, int in_minutes) { hours = (in_hours <= 23 || in_hours >=0)? in_hours: 0; minutes = (in_minutes <=59 || in_minutes>=0)? in_minutes : 0; } void setTime (int in_hours, int in_minutes) { hours = (in_hours <= 23 || in_hours >=0)? in_hours: hours; minutes = (in_minutes <=59 || in_minutes>=0)? in_minutes : minutes; } void showTime() { (hours < 10)? cout << "0" << hours <<":" : cout<<hours <<":"; (minutes < 10) ? cout << "0" << minutes <<endl : cout << minutes << endl; } void copyTime (Time &input) { hours = input.hours; minutes = input.minutes; } void addTime(int in_hours, int in_minutes) { int temp_hr, temp_min, addHr1, addHr2; temp_hr = in_hours + hours; temp_min = in_minutes + minutes; if (temp_hr > 23) {addHr1 = temp_hr / 24; hours = temp_hr - (addHr1 * 24); }

if (temp_min > 59) {addHr2 = temp_min / 60 ; hours += addHr2; minutes = (temp_min) - (addHr2 * 60); } }

}; int main() { Time time1, time2(18,30) ; time1.showTime(); time2.showTime(); time1.setTime(8,47); time1.showTime(); Time time3; time3.copyTime(time1); time3.addTime(18,15); time3.showTime(); time2.addTime(36,11); time2.showTime(); return 0; }

#include "stdafx.h" #include <iostream> using namespace std; class Imperial { int iYard, iFoot, iInch; public: Imperial (int aYard = 0, int aFoot=0, int anInch =0) { iYard = aYard; iFoot = aFoot; iInch = anInch; } int getYard (){return iYard;} int getFoot (){return iFoot;} int getInch (){return iInch;} void add(Imperial &input) { int tempFoot, tempInch, addYard, addFoot;

iYard += input.iYard; tempFoot = iFoot + input.iFoot; tempInch = iInch + input.iInch; if(tempInch>=12){ addFoot = tempInch / 12 ; tempFoot += addFoot; iInch = tempInch - (addFoot * 12); } if(tempFoot >= 3){ addYard = tempFoot / 3; iYard += addYard; iFoot = tempFoot - (addYard*3);} } void mul(int factor) { int tempFoot, tempInch, addYard, addFoot; iYard = iYard * factor; tempFoot = iFoot * factor; tempInch = iInch *factor; if(tempInch>=12){ addFoot = tempInch / 12 ; tempFoot += addFoot; iInch = tempInch - (addFoot * 12); } if(tempFoot >= 3){ addYard = tempFoot / 3; iYard += addYard; iFoot = tempFoot - (addYard*3);} } }; int main() { Imperial opj1(15, 2, 6); Imperial opj2(10,1,11); opj1.add(opj2); opj2.mul(4); cout << "the imperial object 1 member variable after addition is \n " << opj1.getYard()<<"Yard and\n" << opj1.getFoot() << "feet and\n "<<opj1.getInch() << "inches" <<endl; cout << "the imperial object 2 member variable after multiplication by factor of 4 is \n " << opj2.getYard()<<"Yard and\n" << opj2.getFoot() << "feet and\n "<<opj2.getInch() << "inches" <<endl; return 0; }

Tutorial 7
#include <iostream> using namespace std; class Distance{ int m_Kilometre; int m_Metre; int m_Centimetre; public: Distance(double input) { m_Kilometre = input; m_Metre = ((input-m_Kilometre)*1000); m_Centimetre = ((((input - m_Kilometre)*1000) - m_Metre) * 100); } Distance operator+(const Distance &in) { int temp_kilo, temp_metre, temp_centi; double distance; temp_kilo= m_Kilometre + in.m_Kilometre; temp_metre = m_Metre + in.m_Metre; temp_centi = m_Centimetre + in.m_Centimetre; if(temp_centi > 99) // handle the carry of one only {temp_metre ++; temp_centi = (temp_centi - 100);} if(temp_metre > 999) {temp_kilo++; temp_metre = (temp_metre - 1000);} distance = temp_kilo + ((double)temp_metre/1000) + ((double)temp_centi/100000); return Distance(distance); } friend ostream &operator<<(ostream &out, Distance &input); }; ostream &operator<<(ostream &out, Distance &input) { out << input.m_Kilometre << "km "<< input.m_Metre<<"m and "<< input.m_Centimetre<<"cm"<<endl; return out; } int main() { Distance val1(2.5359); Distance val2(3.7769); cout<< "Value 1 is: " << val1 << endl; cout<< "Value 2 is: " << val2 << endl << endl; cout<< val1 << " + " << val2 << " = " << val1 + val2 << endl; cout << endl << endl; return 0;

include "stdafx.h" #include <iostream> #include <math.h> using namespace std; class RM { int ringgit, sen; public: RM() { ringgit = 0; sen = 0; } RM operator+(RM &input) { int temp_rm=0, temp_sen=0; float temp_amount; temp_rm = ringgit + input.ringgit; temp_sen = sen + input.sen; if (temp_sen > 99) {temp_rm ++; temp_sen = temp_sen - 100;} temp_amount = temp_rm + ((float)temp_sen / 100); return RM() = temp_amount; } RM operator-(RM &input) { int temp_rm=0, temp_sen=0; float temp_amount; temp_rm = ringgit - input.ringgit; if(temp_rm>0 && (sen - input.sen) < 0) {ringgit --; sen += 100; temp_sen = sen - input.sen;} else temp_sen = sen - input.sen; temp_amount = temp_rm + ((float)temp_sen / 100); return RM() = temp_amount; } RM &operator=(const float amount) { this->ringgit = amount; this->sen =((float)(amount - ringgit) * 100); return *this; } friend ostream &operator<<(ostream &out, RM &input); };

ostream &operator<<(ostream &out, RM &input) { (input.ringgit < 0)? out << "RM"<<abs(input.ringgit)<<"."<<abs(input.sen)<<endl : "RM"<<abs(input.ringgit)<<"."<<abs(input.sen)<<endl; return out; } int main () { RM acc1, acc2; acc1 = 50.99; acc2 = 25.50; cout << "Amount in account 1 = " << acc1; cout <<"Amount in account 2 = " << acc2; cout <<"acc1 + acc2 = " << acc1 + acc2; cout <<"acc1 - acc2 = " << acc1 - acc2; cout << "acc2 - acc1 = "<< acc2-acc1; return 0; }

out <<

Tutorial 8
#include <iostream> #include <string> using namespace std; class Employee { char employeeName[256]; char companyName[256]; char departmentName[256]; int unsigned ID; double annualSalary; public: Employee(char *in_employeeName, int unsigned in_ID, double in_annualSalary) { strcpy(employeeName, in_employeeName); ID = in_ID; annualSalary = in_annualSalary; } void setCompanyName(char *in_companyName) { strcpy(companyName, in_companyName); } void setDeprtmentName(char *in_departmentName) { strcpy(departmentName, in_departmentName); } void getEmployeeName(char *out_employeeName, unsigned int bufferSize) { out_employeeName = (bufferSize > sizeof employeeName ) ? strcpy(out_employeeName,employeeName) : strcpy(out_employeeName,"0"); } unsigned int getEmployeeID() { return ID; } void getAnnualSalary(double &out_annualSalary) { out_annualSalary = annualSalary; } }; class Manager : public Employee { unsigned int executives; double bounus; public: Manager(char *in_employeeName , int unsigned in_ID, double in_annualSalary); void setNoExecutives (unsigned int in_executives)

{ executives = in_executives; } double calcBonus () { double temp_salary; getAnnualSalary(temp_salary); bounus = temp_salary*(executives*0.1); return bounus; } }; Manager::Manager(char *in_employeeName, int unsigned in_ID, double in_annualSalary) :Employee( in_employeeName,in_ID,in_annualSalary) { executives = 0; bounus = 0; } class Engineer : public Employee { int unsigned tech; double bounus; public: Engineer(char *in_employeeName, int unsigned in_ID, double in_annualSalary); void setNoTechnicians(unsigned int in_tech) { tech = in_tech; } double clacBounus() { double temp_salary; getAnnualSalary(temp_salary); bounus = temp_salary * (tech*0.1); return bounus; } }; Engineer::Engineer(char *in_employeeName, int unsigned in_ID, double in_annualSalary) :Employee(in_employeeName,in_ID,in_annualSalary) { tech =0; bounus =0; } int main() { char name[265]; int ID; double salary, getsalary; char getname[256];

cout << "pease enter the name of the Manager: "; cin >> name; cout << "enter ID and salary :"; cin >> ID >> salary; Manager man1(name, ID, salary); man1.getEmployeeName(getname,266); man1.getAnnualSalary(getsalary); cout << "the manager name is " << getname << endl; cout << "the manager ID is " << man1.getEmployeeID() << endl; cout << "the manager salary is " << getsalary << endl; return 0;

Tutorial 9
// Tutorial 9 question 1.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include <iostream> #include <math.h> using namespace std; class IGeometricCalc { public: virtual void SetGeometricAttributes (float side1, float side2, float radius) =0; virtual float CalculateSurfaceArea() =0; virtual float CalculateVolume() =0; }; class CubeGeometricCalc : public IGeometricCalc { float m_side1, m_side2, m_radius; public: CubeGeometricCalc(){}; ~CubeGeometricCalc(){}; virtual void SetGeometricAttributes(float side1, float side2, float radius) { m_side1 = side1; m_side2 = side2; m_radius = radius; } virtual float CalculateSurfaceArea() { return (6*(m_side1 * m_side1)); } virtual float CalculateVolume() { return (m_side1*m_side1*m_side1); } }; class SphereGeometricCalc : public IGeometricCalc { float m_side1, m_side2, m_radius; public: SphereGeometricCalc(){}; ~SphereGeometricCalc(){}; virtual void SetGeometricAttributes(float side1, float side2, float radius) { m_side1 = side1; m_side2 = side2; m_radius = radius; }

virtual float CalculateSurfaceArea() { return (4*3.14*m_radius * m_radius); } virtual float CalculateVolume() { return ((4.00/3.00)* 3.14 *pow(m_radius,3)); } }; class CylinderGeometricCalc : public IGeometricCalc { float m_side1, m_side2, m_radius; public: CylinderGeometricCalc(){}; ~CylinderGeometricCalc(){}; virtual void SetGeometricAttributes(float side1, float side2, float radius) { m_side1 = side1; m_side2 = side2; m_radius = radius; } virtual float CalculateSurfaceArea() { return ((2* 3.14 *m_radius*m_side1) + (2*3.14*pow(m_radius,2))); } virtual float CalculateVolume() { return (3.14 * pow(m_radius,2)*m_side1); } }; int main() { IGeometricCalc *pPointer = new CubeGeometricCalc(); pPointer->SetGeometricAttributes(10,0,0); cout << "the surface area of cube is " << pPointer->CalculateSurfaceArea() << "\nthe volume of cube is "<< pPointer->CalculateVolume() <<"\n----------------"<< endl; delete pPointer; pPointer = new SphereGeometricCalc(); pPointer->SetGeometricAttributes(0,0,25); cout << "the surface area of Sphere is " << pPointer->CalculateSurfaceArea() << "\nthe volume of Sphere is "<< pPointer->CalculateVolume() <<"\n----------------"<< endl; delete pPointer; pPointer = new CylinderGeometricCalc(); pPointer->SetGeometricAttributes(10,0,25); cout << "the surface area of Cylender is " << pPointer->CalculateSurfaceArea() << "\nthe volume of Cylender is "<< pPointer->CalculateVolume() <<"\n----------------"<< endl; delete pPointer;

return 0; }

#include "stdafx.h" #include <iostream> #include <string> using namespace std; class IStudent { public: virtual void SetName(string &studentName)=0; virtual void SetId(unsigned long studentId)=0; virtual void SetMajor(string &studentMajor)=0; virtual void PrintDetails()=0; }; class Undergraduate : public IStudent { string m_name, m_major; unsigned long m_ID; public: Undergraduate(){}; ~Undergraduate(){}; virtual void SetName(string &studentName) { m_name = studentName; } virtual void SetId(unsigned long studentId) { m_ID = studentId; } virtual void SetMajor(string &studentMajor) { m_major = studentMajor; } virtual void PrintDetails() { cout << "Udergraduate Details: \n-------------------\nName: " << m_name << "\nMajor: "<< m_major <<"\nID: " << m_ID <<endl; } }; int _tmain(int argc, _TCHAR* argv[]) { string nm = "Ehsan"; string mj = "Telecomunication"; unsigned long id = 1081107325; IStudent *pStudent = new Undergraduate (); pStudent->SetName(nm); pStudent->SetId(id); pStudent->SetMajor(mj); pStudent->PrintDetails(); delete pStudent;

return 0;

#ifndef EMPLOYEE_H #define EMPLOYEE_H // Symbolic constant to represnt size of // employee's name, company's name & dept. #define NAME_LEN 256 // Symbolic constant for income tax calculation #define INCOME_TAX_PERCENT 15 class Employee { // Attributes private: // Dynamic buffer to store employee's name char *m_pEmpName; // Employee's Id unsigned int m_EmpId; // Employee's annual salary double m_AnnualSalary; // Employee's rank (values between 1 & 3) int m_Rank; // Dynamic buffer to store company's name char *m_pCompanyName; // Dynamic buffer to store department's name char *m_pDeptName; // Operations public: // Default constructor & destructor // Hint: You can initialize your buffers in the constructor Employee(); ~Employee(); // Concrete functions void SetCompanyName(char companyName[]); void SetDepartmentName(char departmentName[]); void SetEmployeeDetails(char empName[], unsigned int empId, double annualSalary, int rank); void GetCompanyName(char *pBuffer, unsigned int bufferSize); void GetDepartmentName(char *pBuffer, unsigned int bufferSize); void GetEmployeeName(char *pBuffer, unsigned int bufferSize); void GetEmployeeId(int *pId) const; 4 void GetRankAndAnnualSalary(int *pRank, double *pSalary); // Virtual function // Prints out the name of the employee and position virtual void DisplayNameAndPosition(); // Pure virtual functions virtual void CalculateBonus(int *pBonusMonths, double *pBonusSum) = 0; virtual void CalculateSalaryIncrement(double *pPercentageIncrement, double *pIncrementSum) = 0; };

#endif

Tutorial 10
include "stdafx.h" #include <iostream> using namespace std; class ICalculate { public : virtual int Calculate(int num1, int num2) =0; }; class Adder : public ICalculate { public: Adder(){}; ~Adder(){}; virtual int Calculate(int num1, int num2) { return (num1 + num2); } }; class Mult : public ICalculate { public: Mult(){}; ~Mult(){}; virtual int Calculate(int num1, int num2) { return (num1*num2); } }; class Problem { int m_x, m_y; ICalculate *m_pICalculate; public: void SetCalculate(ICalculate * in_pointer) { m_pICalculate = in_pointer; } void SetX(int in_x) { m_x = in_x; } void setY(int in_y) { m_y = in_y; } int Calculate() {

int temp; temp = m_pICalculate->Calculate(m_x,m_y); return temp; } };

int main() { int xValue, yValue; Problem prob_obj; ICalculate *pICalculate; cout << "please enter x and y value: "; cin >> xValue >> yValue; prob_obj.SetX(xValue); prob_obj.setY(yValue); pICalculate = new Adder(); prob_obj.SetCalculate(pICalculate); cout << "Addition Result : " << prob_obj.Calculate() << endl; delete pICalculate; pICalculate = new Mult(); prob_obj.SetCalculate(pICalculate); cout << "Multiplication Result is : " << prob_obj.Calculate() << endl; delete pICalculate; return 0; }

Tutorial 11
#include "stdafx.h" #include <iostream> using namespace std; template<class T> class ArrayCalc { public: ArrayCalc(){} ~ArrayCalc(){} void FindMin(T inArrayData[],int inArraySize,T &outMinVal) { outMinVal = inArrayData[0]; for (int i=1; i< inArraySize ; i++) outMinVal = (inArrayData[i]<minVal)? inArrayData[i]:outMinVal; } void FindMax(T inArrayData[],int inArraySize,T &outMaxVal) { outMaxVal = inArrayData[0]; for (int i=1; i< inArraySize ; i++) outMaxVal = (inArrayData[i]>outMaxVal)? inArrayData[i]:outMaxVal; } void CalcSum(T inArrayData[],int inArraySize,T &outSumVal) { outSumVal = 0; for (int i=0; i< inArraySize ; i++) outSumVal += inArrayData[i]; } void CalcAvg(T inArrayData[],int inArraySize,T &outAvgVal) { outAvgVal = 0; for (int i=0; i< inArraySize ; i++) {outAvgVal += inArrayData[i];} outAvgVal /=2; } }; int main() { float rand[3] = {1.256,25.698,125.69}; const int MAX = 3; float res; ArrayCalc <float> object; object.FindMax(rand, MAX, res); cout << "the maximum value is " << res <<endl; return 0; }

#include "stdafx.h" #include <iostream> using namespace std; template<class T, class U> class MathCalc { public: MathCalc (){} T Sum(T in_X, U in_Y) { return(in_X + in_Y); } T Subtract(T in_X, U in_Y) { return (in_X - in_Y); } T Multiply (T in_X, U in_Y) { return (in_X * in_Y); } T Divide (T in_X, U in_Y) { return (in_X / in_Y); } }; int _tmain(int argc, _TCHAR* argv[]) { float inputX; int inputY; MathCalc <float, int> objMathCalc; cout << "Enter tow numbers : " ; cin >> inputX >> inputY ; cout cout cout cout << << << << "Sum :" <<objMathCalc.Sum(inputX, inputY) << endl; "Subtract :" << objMathCalc.Subtract(inputX, inputY) << endl; "Multiply :" <<objMathCalc.Multiply(inputX, inputY)<< endl; "Divide :" <<objMathCalc.Divide(inputX, inputY)<< endl;

return 0; }

#include "stdafx.h" #include <stdexcept> #include <iostream> #include<string> using namespace std; class NonDigitOption : public runtime_error { public: NonDigitOption(): runtime_error("Attempted to return a non digit character"){} }; int DigiOption (char gimmedigit) { int digit_choice = -1; if (gimmedigit == '0'){ gimmedigit = 0;} else { digit_choice= atoi(& gimmedigit); if (digit_choice ==0) { throw NonDigitOption(); } } return digit_choice; } int_tmain(int argc, _TCHAR* argv[]) { char input; int option; cout<< "Enter one printable keyboard button (end-of-file key to end) :" ; cin>> input; while (input != '^Z') { option = DigiOption(input); cout<< "The selected digit option is : " << option << endl; cout<< "Enter one printable keyboard button cin>> input; } cout << "Program Exited." ; return 0; } :" ;

#include "stdafx.h" #include <math.h> #include <iostream> using namespace std; template<class T, class U, class M> class EqOfMotion { private: T velocity; U desplacement; M velocitySquared; public: EqOfMotion() { velocity = 0; desplacement = 0; velocitySquared = 0; } T CalculateVelocity(T initialVelocity, T accelaration, T timeInterval) { velocity = initialVelocity + (accelaration*timeInterval); return (velocity); } U CalculateDisplacement(U initialDisplacement, U initialVelocity, U accelaration, U timeInterval) { desplacement = initialDisplacement + (initialVelocity*timeInterval) + ((0.5) * accelaration* timeInterval*timeInterval); return (desplacement); } M CalculateVelocitySquared(M initialDisplacement, M initialVelocity, M accelaration, M timeInterval) { velocitySquared = ((initialVelocity*initialVelocity) + (2*accelaration*(desplacement-initialDisplacement))); return (velocitySquared); } }; int main() { float velocity; int desplacement; double velocitySquared; EqOfMotion <float, int, double> object; velocity = object.CalculateVelocity(110.2, 20.25, 6.25); desplacement = object.CalculateDisplacement(20, 110.2, 25.25, 6.25); velocitySquared = object.CalculateVelocitySquared(20, 110.2, 25.25, 6.25); cout<< "The Velocity is: "<<velocity <<endl; cout<< "The desplacement is :"<<desplacement<<endl; cout<< "The velocity squared is :"<<velocitySquared<<endl; return 0; }

Вам также может понравиться