Data Structure C++ Programming

24
1 Data Structure – C++ Programming Data Structure C++ Programming Dr Patrick Chan School of Computer Science and Engineering South China University of Technology 2 Data Structure – C++ Programming First Program in C++ Start Microsoft Visual Studio File > Win32 Application (Project) Input the project name File > C++ Source Input the file name Type the program Build > Run #include <iostream> using namespace std; int main() { cout<<"My name is XXX \n"; cout<< "My id is XXX \n"; return 0; } #include <iostream> using namespace std; int main() { cout<<"My name is XXX \n"; cout<< "My id is XXX \n"; return 0; } Use the library Main problem

Transcript of Data Structure C++ Programming

Page 1: Data Structure C++ Programming

1Data Structure – C++ Programming

Data Structure

C++ Programming

Dr Patrick Chan

School of Computer Science and Engineering

South China University of Technology

2Data Structure – C++ Programming

First Program in C++

� Start Microsoft Visual Studio

� File > Win32 Application (Project)

� Input the project name

� File > C++ Source

� Input the file name

� Type the program

� Build > Run

#include <iostream>

using namespace std;

int main()

{

cout<<"My name is XXX \n";

cout<< "My id is XXX \n";

return 0;

}

#include <iostream>

using namespace std;

int main()

{

cout<<"My name is XXX \n";

cout<< "My id is XXX \n";

return 0;

}

Use the library

Main problem

Page 2: Data Structure C++ Programming

3Data Structure – C++ Programming

Declare a variable

� Declare a variable

� Assign a value

� Declare and assign a value at the same time

int age;int age;

age = 18;age = 18;

float age = 18;float age = 18;

4Data Structure – C++ Programming

Correct Variable Name

� Determine if the following identifiers are valid or not.

� _option □ valid □ invalid

� salesAmount □ valid □ invalid

� amount □ valid □ invalid

� $salesAmount □ valid □ invalid

� sales_amount □ valid □ invalid

� A3 □ valid □ invalid

� tax-rate □ valid □ invalid

� float □ valid □ invalid

� Case Sensitive!!

Page 3: Data Structure C++ Programming

5Data Structure – C++ Programming

Input and Output

� Output

� Input

cin>>age;cin>>age;

cout<< "I am "<<"Peter.";cout<< "I am "<<"Peter.";

iostream

6Data Structure – C++ Programming

Operators

� int a = 2;

� int b = 5;

� cout << a + b;

� cout << a - b;

� cout << a * b;

� cout << a / b;

� cout << a % b;

� a += b;

� a -= b;

� a *= b;

� a /= b;

� a %= b;

Page 4: Data Structure C++ Programming

7Data Structure – C++ Programming

Operators

� a++, ++a, a--, --a

� a=10;

b = ++a*5;

� a=10;

c = a++*5;

8Data Structure – C++ Programming

Exercise

� Write a program which accepts the number of

seconds and converts it into corresponding minutes and seconds.

Input the number of seconds: 1232 minutes 3 seconds

Hint: Use the operators / and %.Hint: Use the operators / and %.

Page 5: Data Structure C++ Programming

9Data Structure – C++ Programming

Exercise - Answer

#include <iostream>

using namespce std;

int main()

{

return 0;

}

#include <iostream>

using namespce std;

int main()

{

return 0;

}

10Data Structure – C++ Programming

Condition

� int a = 1;

� int b = 2;

� a == 1

� a >= b

� b != a

� (a>b) || (a==1)

� (a<b) && (b==1)

� (a==1) || (a<b) && (b==1)

� (a==1) || ( (a<b) && (b==1) )

� !(a==1) || ( (a<b) && (b==1) )

True

False

True

True

False

False

True

False

Page 6: Data Structure C++ Programming

11Data Structure – C++ Programming

if statement

� if (condition)

one statement

� if (condition)

one statement

else

one statement

� if (condition)

{

statements

}

else

{

statements

}

12Data Structure – C++ Programming

Nested if statements

� if (condition1)if (condition2)

one statement

� if (condition1)&&(condition2)one statement

� if (condition1)one statement

elseif (condition2)

one statement

Page 7: Data Structure C++ Programming

13Data Structure – C++ Programming

Exercise

� If x=7 and y=9, what will be printed on the screen

after executing the following code?

if (x==1)

if (y==2)

cout<<x;

else

cout<<y;

cout<<(x+y);

if (x==1)

if (y==2)

cout<<x;

else

cout<<y;

cout<<(x+y);

if (x==1)

{

if (y==2)

cout<<x;

else

cout<<y;

}

cout<<(x+y);

if (x==1)

{

if (y==2)

cout<<x;

else

cout<<y;

}

cout<<(x+y);

14Data Structure – C++ Programming

Exercise

� If originally x=0, y=2, and z=1, what will be printed

on the screen by executing the following program fragment?

if (x <= 0 && y < z)

cout<<"x is not positive\n";

cout<<"y and z\n";

if (z == 1)

cout<<"z is 1\n";

if (x <= 0 && y < z)

cout<<"x is not positive\n";

cout<<"y and z\n";

if (z == 1)

cout<<"z is 1\n";

Page 8: Data Structure C++ Programming

15Data Structure – C++ Programming

switch – case statement

� switch (variable) {

case value:

statements

break;

case value:

statements

break;

default:

statements

}

� switch (examGrade) {

case "A":

cout << "good";

break;

case "B":

cout << "ok";

break;

default:

cout << "bad";

}

16Data Structure – C++ Programming

Exercise

� For each different value of n as shown

on the right, what will be printed by the program fragment below?

switch (n) {

case 1: cout << "abc";

break;

case 2: cout << "def";

case 3: cout << "jkl";

break;

case 4: cout << "mno";

default: cout << "hello";

}

switch (n) {

case 1: cout << "abc";

break;

case 2: cout << "def";

case 3: cout << "jkl";

break;

case 4: cout << "mno";

default: cout << "hello";

}

� n = 1

� n = 2

� n = 3

� n = 4

� n = 0

Page 9: Data Structure C++ Programming

17Data Structure – C++ Programming

Exercise

� Write a program that calculates the parking charge based on the following rates:

� car (type ‘c’) $12 per hour

� bus (type ‘b’) $25 per hour

� truck (type ‘t’) $45 per hour

Vehicle type? cNumber of hours? 3Charge = $36

Vehicle type? cNumber of hours? 3Charge = $36

Vehicle type? kInvalid type

Vehicle type? kInvalid type

18Data Structure – C++ Programming

#include <stdio.h>#include <iostream>using namespace std;

int main(){

return 0;}

#include <stdio.h>#include <iostream>using namespace std;

int main(){

return 0;}

Page 10: Data Structure C++ Programming

19Data Structure – C++ Programming

while Loop

� while (condition)

statement

age=0;

while (age < 10)

{

cout << age;

age++;

}

age=0;

while (age < 10)

{

cout << age;

age++;

}

c=0;

while (c <= 5) {

product *= c;

++c;

}

c=0;

while (c <= 5) {

product *= c;

++c;

}

20Data Structure – C++ Programming

do-while Loop

� do {

statements

} while (condition)

� Execute at least one time

c=0;

do {

product *= c;

++c;

} while (c <= 5)

c=0;

do {

product *= c;

++c;

} while (c <= 5)

age=0;

do {

cout << age;

age++;

} while (age < 10)

age=0;

do {

cout << age;

age++;

} while (age < 10)

Page 11: Data Structure C++ Programming

21Data Structure – C++ Programming

for Loop

� for (initial; condition; statement)

statement

for (c = 0; c <= 5; c++)

product *= c;

for (c = 0; c <= 5; c++)

product *= c;

22Data Structure – C++ Programming

Exercise

� Write a for statement that prints the following

sequence of values:

6 8 10 12 14 16

for ( ; ; )

cout<<i;

for ( ; ; )

cout<<i;

Page 12: Data Structure C++ Programming

23Data Structure – C++ Programming

Exercise

� Write a program to print the following sequence of

values

12111098

12111098

11111222223333344444

11111222223333344444

Num? 71 2 3 4 5 6 71 2 3 4 5 61 2 3 4 51 2 3 41 2 3 1 21

Num? 71 2 3 4 5 6 71 2 3 4 5 61 2 3 4 51 2 3 41 2 3 1 21

24Data Structure – C++ Programming

12111098

12111098

11111222223333344444

11111222223333344444

Num? 71 2 3 4 5 6 71 2 3 4 5 61 2 3 4 51 2 3 41 2 3 1 21

Num? 71 2 3 4 5 6 71 2 3 4 5 61 2 3 4 51 2 3 41 2 3 1 21

Page 13: Data Structure C++ Programming

25Data Structure – C++ Programming

Array

� 1 dimensional array

� 2 dimensional array

� n dimensional array

� Assign a value to an element of array

int a[10];int a[10];

a[6] = 97;a[6] = 97;

int b[5][10];int b[5][10];

int c[5][2]…[10];int c[5][2]…[10];

0 .. 9

b[2][3] = 97;b[2][3] = 97;

26Data Structure – C++ Programming

Array

� Initialize the array to store the data values:

5, 9, -1, 4, 0

� What is the value of list[1]?

int list[] = { 5, 9, -1, 4, 0 };int list[] = { 5, 9, -1, 4, 0 };

9

Page 14: Data Structure C++ Programming

27Data Structure – C++ Programming

Exercise

� What is the output of the following program?

#include <iostream>

using namespace std;

int main()

{

int list[10] = {2, 1, 2, 1, 1, 2, 3, 2, 1, 2};

cout<<list[2];

coun<<list[ list[2] ];

cout<<list[ list[2] + list[3] ];

return 0;

}

#include <iostream>

using namespace std;

int main()

{

int list[10] = {2, 1, 2, 1, 1, 2, 3, 2, 1, 2};

cout<<list[2];

coun<<list[ list[2] ];

cout<<list[ list[2] + list[3] ];

return 0;

}

28Data Structure – C++ Programming

Exercise

� You are given the following array declaration:

int list [] = {4, 5, 1, 9};

Write some program statements to add the values of the array and store the sum into the variable sum.

int sum=0;

for (i=0; i<4; i++)

sum += list[i];

int sum=0;

for (i=0; i<4; i++)

sum += list[i];

Page 15: Data Structure C++ Programming

29Data Structure – C++ Programming

Exercise

� Write a program:

Input 5 integers: 9 2 5 8 12Input an integer: 5The position is 3

Input 5 integers: 9 2 5 8 12Input an integer: 3Cannot Find

Input 5 integers: 9 2 5 8 12Input an integer: 5The position is 3

Input 5 integers: 9 2 5 8 12Input an integer: 3Cannot Find

int list[5], n, cnt;int list[5], n, cnt;

30Data Structure – C++ Programming

Array

� String = Array of Char

� char name[100];

cout<<"What is your name? ";

cin>>name;

cout<<"First character of your name is "

<<name[0];

Page 16: Data Structure C++ Programming

31Data Structure – C++ Programming

Pointer

� Declare an integer pointer variable

� Makes ptr pointing to the variable score.

int *ptr;int *ptr;

int a=10;

ptr = &a;

int a=10;

ptr = &a;

int a;

int* ptr;

a = 5;

ptr = &a;

cout << a << "\n";

cout << &a << "\n";

cout << ptr << "\n";

cout << *ptr << "\n";

int a;

int* ptr;

a = 5;

ptr = &a;

cout << a << "\n";

cout << &a << "\n";

cout << ptr << "\n";

cout << *ptr << "\n";

& returns the memory address

32Data Structure – C++ Programming

Exercise

� Write a program that performs the followings:

1. declares two integer variables data1 and data2;

2. asks the user to input values for data1 and data2;

3. declares two pointers pointing to data1 and data2;

4. by using the pointers, exchange the values of data1and data2.

Page 17: Data Structure C++ Programming

33Data Structure – C++ Programming

Exercise#include <iostream>Using namespace std;

int main(){

int temp, data1, data2, *ptr1, *ptr2;

cout<<"data 1 = "<<data1<<"\n";cout<<"data 2 = "<<data2<<"\n";return 0;

}

#include <iostream>Using namespace std;

int main(){

int temp, data1, data2, *ptr1, *ptr2;

cout<<"data 1 = "<<data1<<"\n";cout<<"data 2 = "<<data2<<"\n";return 0;

}

34Data Structure – C++ Programming

Function

#include <iostream>

using namespace std

int power(int x, int y)

{

return x*y;

}

int main()

{

cout<<power(10, 2);

return 0;

}

#include <iostream>

using namespace std

int power(int x, int y)

{

return x*y;

}

int main()

{

cout<<power(10, 2);

return 0;

}

Function

Main Program

Page 18: Data Structure C++ Programming

35Data Structure – C++ Programming

Exercise

� Write a function that accepts two integer values as

parameters. The function returns the average among these two values.

float average ( )

{

}

float average ( )

{

}

36Data Structure – C++ Programming

Function

#include <iostream>using namespace std;

void square(int *v){

*v = *v * *v;}

int main(){

int num;

cout<<"Num? ";cin>>num;square(&num);cout<<"Square is "

<<num<<"\n";return 0;

}

#include <iostream>using namespace std;

void square(int *v){

*v = *v * *v;}

int main(){

int num;

cout<<"Num? ";cin>>num;square(&num);cout<<"Square is "

<<num<<"\n";return 0;

}

#include <iostream>using namespace std;

void square(int v){

v = v * v;}

int main(){

int num;

cout<<"Num? ";cin>>num;square(num);cout<<"Square is "

<<num<<"\n";returrn 0;

}

#include <iostream>using namespace std;

void square(int v){

v = v * v;}

int main(){

int num;

cout<<"Num? ";cin>>num;square(num);cout<<"Square is "

<<num<<"\n";returrn 0;

}

Pass the valueWill not affect the value in main program

Pass the memory addressAffect the value in main program

Page 19: Data Structure C++ Programming

37Data Structure – C++ Programming

Exercise

� Write a program to ask the user to input three integers into x, y and z, which are defined in main(). Then write a function rotate() to rotate

the three values as follows.

x → y y → z z → x

� Print the rotated variables so as to verify the correctness of your function.

38Data Structure – C++ Programming

Exercise#include <iostream.h>using namespace std;

void rotate( ){

}

void main(){

int x, y, z;

cout<<("Input 3 integers: ");cin>>x>>y>>z;

rotate( );

cout<<x<<" "<<y<<" ";}

#include <iostream.h>using namespace std;

void rotate( ){

}

void main(){

int x, y, z;

cout<<("Input 3 integers: ");cin>>x>>y>>z;

rotate( );

cout<<x<<" "<<y<<" ";}

Page 20: Data Structure C++ Programming

39Data Structure – C++ Programming

Function

� Pass an array to a function

#include <iostream.h>

void printArray(int info[], int size){

for (int i=0 ; i < size; i++)cout << info[i];

}

void main(){

int intArray[] = {1, 3, 5, 7, 10, 15, 2};int size = 7;

printArray(intArray, size);}

#include <iostream.h>

void printArray(int info[], int size){

for (int i=0 ; i < size; i++)cout << info[i];

}

void main(){

int intArray[] = {1, 3, 5, 7, 10, 15, 2};int size = 7;

printArray(intArray, size);}

size = sizeof(intArray) / sizeof(int);

Array (Printer)

Size of Array

40Data Structure – C++ Programming

Class

� Define a class

� Define a variable

student peter;student peter;

� Access/Assign values

peter.height = 50;

peter.setAge(20);

cout << peter.getAge;

peter.height = 50;

peter.setAge(20);

cout << peter.getAge;

class student {

public:

int height;

int getStd_id() { return id; }

int getAge() { return age; }

void setStd_id(int id)

{ if (id > 0) std_id = id; }

void setAge(int a)

{ if (a > 0) age = a; }

private:

int std_id;

int age;

};

class student {

public:

int height;

int getStd_id() { return id; }

int getAge() { return age; }

void setStd_id(int id)

{ if (id > 0) std_id = id; }

void setAge(int a)

{ if (a > 0) age = a; }

private:

int std_id;

int age;

};

Page 21: Data Structure C++ Programming

41Data Structure – C++ Programming

Class

#include <iostream>

using namespace std;

class student {

public:

int height;

private:

int age;

};

int main()

{

student peter;

peter.height = 12;

return 0;

}

#include <iostream>

using namespace std;

class student {

public:

int height;

private:

int age;

};

int main()

{

student peter;

peter.height = 12;

return 0;

}

Declare a class

Declare a variable

Assign/Access value

42Data Structure – C++ Programming

Class

class student {

public:

int a;

int getA()

{return a};

private:

int b;

int getB()

{return b};

};

class student {

public:

int a;

int getA()

{return a};

private:

int b;

int getB()

{return b};

};

Private

Only be accessed by functions

that are part of that class

Public

Can be accessed by anyone

How can we access the variables or use the functions

in private region??

Page 22: Data Structure C++ Programming

43Data Structure – C++ Programming

Class

� Function Declarations:

� ReturnType FuncName(params) { code }� Code is provided

� ReturnType FuncName(params);� still need to define the function separately

class Robot {

public:

int getX() {return x};

int getY();

private:

int x, y;

};

int Robot::getY() { return y };

class Robot {

public:

int getX() {return x};

int getY();

private:

int x, y;

};

int Robot::getY() { return y };

44Data Structure – C++ Programming

Class

� Constructor

className

� A function will be executed when a class is created

� Destructor

~className

� A function will be executed when a class is deleted

class Robot {

public:

int size;

Robot()

{cout<<"Hello";}

void setSize(int s)

{ size = s; }

~Robot()

{cout<<"Bye~";}

}

}

class Robot {

public:

int size;

Robot()

{cout<<"Hello";}

void setSize(int s)

{ size = s; }

~Robot()

{cout<<"Bye~";}

}

}

Robot myR;Robot myR; delete myR;delete myR;

Page 23: Data Structure C++ Programming

45Data Structure – C++ Programming

Class

� Many Constructors

class Robot {

public:

int age;

Robot() {

cout<<"Hello~";

}

Robot(int n) {

cout<<"hi"<<n;

}

void printAge () {

cout << ago;

}

}

class Robot {

public:

int age;

Robot() {

cout<<"Hello~";

}

Robot(int n) {

cout<<"hi"<<n;

}

void printAge () {

cout << ago;

}

}

Robot myR;Robot myR; Robot myR(20);Robot myR(20);

� Default value

class Robot {

public:

int age;

Robot(int n=0) {

count<<n;

}

void printAge () {

cout << ago;

}

}

class Robot {

public:

int age;

Robot(int n=0) {

count<<n;

}

void printAge () {

cout << ago;

}

}

46Data Structure – C++ Programming

Class

� Variable

Robot myR1;

myR1.age = 1;

myR1.printWeight();

� Pointer

Robot* myR2;

myR2 = new Robot;

myR2->age = 1;

myR2->printWeight();

delete myR2;

class Robot {

public:

int age;

void printWeight()

{ cout << weight; }

private:

int weight = 10;

}

class Robot {

public:

int age;

void printWeight()

{ cout << weight; }

private:

int weight = 10;

}

Robot* myR2 = new Robot;

Page 24: Data Structure C++ Programming

47Data Structure – C++ Programming

Class

class basePrinter{public:

void print1() {cout << "BasePrinter1" << " \n"; }

};

int main(){basePrinter bPrinter;bPrinter.print1();

}

class basePrinter{public:

void print1() {cout << "BasePrinter1" << " \n"; }

};

int main(){basePrinter bPrinter;bPrinter.print1();

}class basePrinter{public:

void print1() {cout << "BasePrinter1" << " \n";}

};

class specialPrinter:public basePrinter{public:

void print2() {cout << "specialPrinter2" << "\n"; }

};

int main() {basePrinter bPrinter;specialPrinter sPrinterbprinter.print1();bprinter.print2();sprinter.print1();sprinter.print2();

}

class basePrinter{public:

void print1() {cout << "BasePrinter1" << " \n";}

};

class specialPrinter:public basePrinter{public:

void print2() {cout << "specialPrinter2" << "\n"; }

};

int main() {basePrinter bPrinter;specialPrinter sPrinterbprinter.print1();bprinter.print2();sprinter.print1();sprinter.print2();

}

48Data Structure – C++ Programming

Class

class basePrinter{public:

void print1() {cout << "BasePrinter1" << " \n"; }

};

int main(){basePrinter bPrinter;bPrinter.print1();

}

class basePrinter{public:

void print1() {cout << "BasePrinter1" << " \n"; }

};

int main(){basePrinter bPrinter;bPrinter.print1();

}class basePrinter{public:

void print1() {cout << "BasePrinter1" << " \n";}

};

class specialPrinter:public basePrinter{public:

void print1() {cout << "specialPrinter1" << "\n"; }

};

int main() {basePrinter bPrinter;specialPrinter sPrinterbprinter.print1();sprinter.print1();

}

class basePrinter{public:

void print1() {cout << "BasePrinter1" << " \n";}

};

class specialPrinter:public basePrinter{public:

void print1() {cout << "specialPrinter1" << "\n"; }

};

int main() {basePrinter bPrinter;specialPrinter sPrinterbprinter.print1();sprinter.print1();

}