Download presentation
Presentation is loading. Please wait.
Published byLeony Gunardi Modified over 6 years ago
1
DATA STRUCTURE : DAT 20104 JENIS DATA DAN JENIS DATA ABSTRAK (4JAM) Jenis Data.(DATA TYPE) Tatasusunan.(ARRAY) Penuding.?(POINTER) Jenis Data Abstrak.(DATA ABSTRACTION) Objek.(OBJECT) Kelas.(CLASS) Bahasa Pengaturcaraan Sokongan untuk Jenis Data Abstrak.(PROGRAMMING LANGUAGE IN DATA ABSTRACTION)
2
Constants DATA STRUCTURE : DAT 20104
A constant is the quantity that does not change. This quantity can be stored at a locations in the memory of the computer. A variable can be consider as a name given to the location in memory where this constant is stored. Three Basic Types of Constant Integer Constants Real Constants String Constants
3
Integer Constant DATA STRUCTURE : DAT 20104
Rules for Constructing Integer Constant An integer constant must have at least one digit. It must not have a decimal point. It could be either negative or positive. If no sign precedes an integer constant it is assumed to be positive. No commas or blanks are allowed in integer constant. Example 426 -777 +20000
4
Floating Point Constant / Real Constants
DATA STRUCTURE : DAT 20104 Floating Point Constant / Real Constants Rules for Constructing Real Constant A real constant must have at least one digit. It must have a decimal point. It could be either positive or negative Default sign is always positive. No commas or blanks are allowed in real constant. Example
5
Character Constant DATA STRUCTURE : DAT 20104
Rules for Constructing Character Constants A character constant is either a single alphabet, a single digit or a single special symbol enclosed within Single inverted commas. The maximum length of a character constant can be 1 character. Example ’a’ ’5’ ’=’ ’G’
6
Data Types DATA STRUCTURE : DAT 20104 Built-in Data Type
A computer Program operates on data and produce an output. In C++, each data must be of specific data type. The data type determines how the data is represented in the computer and kind of processing the computer can perform on it. There are two kind of data types. Built-in data type User define data type Built-in Data Type The are already defined by C++. int ( For working with integer numbers) float (For working with real numbers having decimal points) char ( for working with character data)
7
Variables DATA STRUCTURE : DAT 20104
Variable is a location in memory, referenced by an identifier, that contain a data value that can be changed. Identifier: name given to a variable is known as identifier. Rules for writing Identifier The first character must be letter or underscore ( _ ). You can use upper and lowercase letters and digits from 1 to 9. Identifier can be as long as you like but only the first 250 character are recognizable in C++ Compiler.
8
Integer Variables DATA STRUCTURE : DAT 20104
Integer variables represent integer numbers like 1, 30,000 and -45. Integer variables do not store real numbers. Defining integer variables The amount of memory occupied by integer types is system dependent. On 32-bit system like windows 98/XP an integer occupies 4 bytes of memory. This allows an integer variable to hold numbers in the range from -2,147,483,648 to 2,147,483,647.
9
Integer Variables Example
DATA STRUCTURE : DAT 20104 Integer Variables Example #include<iostream.h> void main ( ) { int var1; //define var1 int var2, var3; //define var2, var3 var1 = 20; //assign value to var1 var2 = var1 + 10; //assign value to var2 cout<<“Result =”; cout<<var2<< endl; //displaying the sum of var }
10
Character Variables DATA STRUCTURE : DAT 20104
Type char stores integer that range in value from -128 to 127. Variables of this type occupy only 1 byte of memory. Character variables are sometime use to store number but they are much more commonly used to store ASCII characters. Character Constants Character constants use single quotation marks around a character, like ‘a’ and ‘b’. When the C++ compiler encounters such a character constant, it translates it into the corresponding ASCII code. 10
11
Character Variable Example
DATA STRUCTURE : DAT 20104 Character Variable Example #include<iostream.h> void main ( ) { char charvar1 = ‘A’; //define char variable char charvar2 = ‘\t’; cout << charvar1; // display character cout << charvar2; charvar1 = ‘B’; //reassigning charvar1 to B cout << charvar1; }
12
DATA STRUCTURE : DAT 20104 Floating point Types Floating point variables represent number with a decimal place e.g or 10.2 There are three kind of floating point variables in C++ float double long double
13
float Type float stores numbers in the range of about to .
DATA STRUCTURE : DAT 20104 float Type float stores numbers in the range of about to It occupy 4 bytes of memory. Double and Long Double: Double and long double, are similar to float except that they require more memory space and provide a wider range of values and more precision.
14
float DATA STRUCTURE : DAT 20104
#include<iostream.h> void main ( ) { float rad, area; float PI =3.14; cout << “Enter radius of circle”; cin >> rad; area = PI * rad * rad; cout <<“Area is” << area << endl; }
15
Variable Type Summary DATA STRUCTURE : DAT 20104 Bytes of Memory
Digits of precision High range Low Range Keyword 1 n/a 127 -128 Char 2 32,767 -32,768 short 4 2,147,483,647 -2,147,483,648 int long 7 float 8 15 double
16
DATA STRUCTURE : DAT 20104 Arrays
17
DATA STRUCTURE : DAT 20104 What is Array An Array is a structured collection of components, all of same type, that is given a single name. Each component (array element) is accessed by an index that indicates the component’s position within the collection.
18
DATA STRUCTURE : DAT 20104 Defining Array Like other variables in C++, an array must be defined before it can be used to store information. Like other definitions, an array definition specifies a variable type and a name. But it includes another feature i.e. size. DataType ArrayName [Const Int Expression ];
19
Array Elements The items in an array are called array elements.
DATA STRUCTURE : DAT 20104 Array Elements The items in an array are called array elements. All elements in an array are of the same type; only the values vary. Example int array1[4] = { 10, 5, 678, -400 } ;
20
Accessing Array Elements
DATA STRUCTURE : DAT 20104 Accessing Array Elements To Access an individual array component, we write the array name, followed by an expression enclosed in square brackets. The expression specifies which component to access. Syntax ArrayName [ IndexExpression] Example array1[2] array1[i] where i = 3
21
Initializing array in Declarations
To initialize an array, you have to specify a list of initial values for the array elements, separate them with commas and enclose the list within braces. int array1[5] = {23, 10, 16, 37, 12}; We don’t need to use the array size when we initialize all the array elements, since the compiler can figure it out by counting the initializing variables. int array1[ ] = { 23, 10, 16, 37}; What happens if you do use an explicit array size, but it doesn’t agree with the number of components ? If there are too few components/ items , the missing element will be set to zero. If there are two many, an error is signaled.
22
Lack of Aggregate Array Operations
C++ does not allow aggregate operations on arrays. int x[50], y[50] ; There is no aggregate assignment of y to x x = y; //not valid To copy array y into array x, you must do it yourself, element by element. for ( i=0; i<50; i++) x[i] = y[i]; //valid operation Similarly, there is no aggregate comparison of arrays. if (x == y ) //Not valid
23
Lack of Aggregate Array Operations
Also, you cannot perform aggregate input / output operations on arrays. cin>>x; //not valid, where x is an array cout<<x //not valid You cannot perform aggregate arithmetic operations on arrays x = x + y // not valid, where x and y are arrays Finally, it is not possible to return an entire array as the value of a value-returning function return x; //not valid, where x is an array.
24
Example of One Dimensional Array
void main() { double sales [6], average, total=0; cout<< “Enter sales of 6 days”; for( int j=0; j<6; j++) cin >> sales[ i ]; for (int j=0; j<6; j++) total += sales[ j ] ; average = total / 6; cout<< “Average =”<< average; }
25
Multidimensional Arrays
A two dimensional array is used to represent items in a table with rows and columns, provided each item in the table is of same data type. Each component is accessed by a pair of indexes that represent the component’s position in each dimension.
26
Defining Multidimensional Array
Two Dimensional Array The array is defined with two size specifiers, each enclosed in brackets DataType ArrayName[ConstIntExp][ConstIntExp] Example double array2[3][4]; Three Dimensional Array float array3[x][y][z]
27
Accessing Multidimensional Array Elements
Array elements in two dimensional arrays required two indexes array2[1][2] Notice that each index has its own set of brackets. Don’t write commas. array2[1,2] // not valid syntax
28
Example Two Dimensional Array
void main() { float array2[3][3]= {{ 12.2, 11.0, 9.6 }, { 23.9, -50.6, 2.3 }, { 2.2, 3.3, 4.4 } }; for (int row=0; row<3; row++) for (int col=0; col<3; col++) cout<< array2[row][col]; }
29
DATA STRUCTURE : DAT 20104 BYE BYE ARRAY
30
C++ Pointers and Strings
DATA STRUCTURE : DAT 20104 C++ Pointers and Strings
31
Pointers A pointer is a variable that holds the address of something else. ... MEMORY 1 2 3 4 5 81345 81346 81347 Address ME 123 int ME; int *x; ME = 123; x = &ME; x 3
32
int *x; x is a pointer to an integer.
You can use the integer x points to in a C++ expression like this: y = *x + 17; *x = *x +1; “the int x points to”
33
&ME In C++ you can get the address of a variable with the “&” operator. ... MEMORY 1 2 3 4 5 Address int ME; ME = 123; x = &ME; ME 123 &ME means “the address of ME”
34
Assigning a value to a dereferenced pointer
A pointer must have a value before you can dereference it (follow the pointer). int *x; *x=3; int ME; int *x; x = &ME; *x=3; x doesn’t point to anything!!! ERROR!!! this is fine x points to foo
35
Pointers to anything int *x; int **y; double *z; x some int y
some double
36
Pointers and Arrays An array name is basically a const pointer.
You can use the [] operator with a pointer: int *x; int a[10]; x = &a[2]; for (int i=0;i<3;i++) x[i]++; x is “the address of a[2] ” x[i] is the same as a[i+2]
37
Pointer arithmetic Integer math operations can be used with pointers.
If you increment a pointer, it will be increased by the size of whatever it points to. int *ptr = a; *(ptr+2) *(ptr+4) *ptr a[0] a[1] a[2] a[3] a[4] int a[5];
38
printing an array void print_array(int a[], int len) {
for (int i=0;i<len;i++) cout << "[" << i << "] = " << a[i] << endl; } array version void print_array(int *a, int len) { for (int i=0;i<len;i++) cout << "[" << i << "] = " << *a++ << endl; } pointer version
39
Passing pointers as parameters
void swap( int *x, int *y) { int tmp; tmp = *x; *x = *y; *y = tmp; }
40
Pointer Parameters Pointers are passed by value (the value of a pointer is the address it holds). If we change what the pointer points to the caller will see the change. If we change the pointer itself, the caller won't see the change (we get a copy of the pointer)
41
C++ strings A string is a null terminated array of characters.
null terminated means there is a character at the end of the the array that has the value 0 (null). Pointers are often used with strings: char *msg = “RPI”; zero (null) msg 'R' 'P' 'I'
42
String Manipulation Functions
C++ includes a library of string handling functions: char * strcpy(char *dst, const char *src) char * strcat(char *dst, const char *src) lots more!
43
String Example - Count the chars
int count_string( char *s) { int n=0; while (*s) { n++; s++; } return(n); while the thing pointed to by s is not null increment count set s to point to the next char
44
Another way int count_string( char *s) { char *ptr = s; while (*ptr) {
} return(ptr - s); pointer arithmetic!
45
Abstract Data Type DATA STRUCTURE : DAT 20104 Consider
Rational a(1,2); // a = 1/2 Rational b(2,3); // b = 2/3 cout << a << " + " << b << " = " << a + b; Rational s; // s = 0/1 Rational t; // t = 0/1 cin >> s >> t; cout << s << " * " << t << " = " << s * t; Observation Natural look that is analogous to fundamental-type arithmetic objects
46
Classes A class is similar to a struct
A class contains data members, but it also contains function members Objects are made from classes, similarly to the way that objects are made from structs The main program communicates with the objects data is passed from main program to object and from object back to the main program
47
Main Program Using Objects
Object A Main Program Object C Object B
48
Main Program Using Objects
Object A Main Program Object C Object B
49
Main Program Using Objects
Object A Main Program Object C Object B
50
Main Program Using Objects
Object A Main Program Object C Object B
51
Main Program Using Objects
Object A Main Program Object C Object B
52
Main Program Using Objects
Object A Main Program Object C Object B
53
Main Program Using Objects
Object A Main Program Object C Object B
54
Main Program Using Objects
Object A Main Program Object C Object B
55
Main Program Using Objects
Object A Main Program Object C Object B
56
How the Main Program Uses A Class Object
The main program does not access the data within a class object The main program only accesses the functions of a class object communication occurs by passing data as parameters into the object’s function the object passes data to the main program through its return type
57
Main Program and Object
public: functions private: data Main Program
58
Main Program Calls a Function in the Object
public: functions private: data Main Program
59
The Function Accesses Data
Object public: functions private: data Main Program
60
Function Returns a Value Back to the Main Program
Object public: functions private: data Main Program
61
Main Program Calls a Different Function
Object public: functions private: data Main Program
62
Function Calls Another Function
Object public: functions private: data Main Program
63
Second Function Accesses Data
Object public: functions private: data Main Program
64
Second Function Returns Back to First Function
Object public: functions private: data Main Program
65
First Function Accesses Data
Object public: functions private: data Main Program
66
Function Returns Back to Main Program
Object public: functions private: data Main Program
67
Example of a Class 1 class Checkbook 2 { 3 public:
2 { 3 public: void setBalance( float amount ); bool writeCheck( float amount ); void deposit( float amount ); float getBalance( ); float getLastCheck( ); float getLastDeposit( ); 10 private: float balance; 12 float lastCheck; float lastDeposit; 14 }; This class definition is placed into its own file, called the class specification file, named checkbook.h (by convention)
68
Example of a Class (cont.)
1 class Checkbook 2 { 3 public: void setBalance( float amount ); bool writeCheck( float amount ); void deposit( float amount ); float getBalance( ); float getLastCheck( ); float getLastDeposit( ); 10 private: float balance; 12 float lastCheck; float lastDeposit; 14 }; The writeCheck function returns false if the amount of the check is greater than the balance; returns true otherwise.
69
Example of a Class (cont.)
1 class Checkbook 2 { 3 public: void setBalance( float amount ); bool writeCheck( float amount ); void deposit( float amount ); float getBalance( ); float getLastCheck( ); float getLastDeposit( ); 10 private: float balance; 12 float lastCheck; float lastDeposit; 14 }; Don’t forget the semicolon.
70
Example of a Class (cont.)
15 #include “checkbook.h” 16 17 void Checkbook::setBalance( float amount ) 18 { 19 balance = amount; 20 } The function definitions are placed into a separate file called the class implementation file. This file would be called checkbook.cpp (by convention).
71
Example of a Class (cont.)
15 #include “checkbook.h” 16 17 void Checkbook::setBalance( float amount ) 18 { 19 balance = amount; 20 } The balance variable is declared in the private section of the class definition.
72
Example of a Class (cont.)
15 #include “checkbook.h” 16 17 void Checkbook::setBalance( float amount ) 18 { 19 balance = amount; 20 } Special notation for class function definitions
73
Example of a Class (cont.)
21 bool Checkbook::writeCheck( float amount ) 22 { 23 if ( amount > balance ) 24 return false; 25 balance -= amount; 26 lastCheck = amount; 27 return true; 28 }
74
Example of a Class (cont.)
29 void Checkbook::deposit( float amount ) 30 { 31 balance += amount; 32 lastDeposit = amount; 33 }
75
Example of a Class (cont.)
34 float Checkbook::getBalance( ) 35 { 36 return balance; 37 } 38 39 float Checkbook::getLastCheck( ) 40 { 41 return lastCheck; 42 } end of checkbook.cpp
76
A Program that Uses the Checkbook Class
1 #include <iostream> 2 #include <iomanip> 3 #include "checkbook.h" 4 5 using namespace std; 6 7 int menu( ); 8 9 const int CHECK = 1, DEPOSIT = 2, BALANCE = 3, QUIT = 4; 10 11 int main( ) 12 { 13 Checkbook cb; 14 float balance, amount; 15 int choice; A main program that uses the Checkbook class is placed into a separate .cpp file
77
A Program that Uses the Checkbook Class (cont.)
16 cout << "Enter the initial balance: $"; 17 cin >> balance; 18 cb.setBalance( balance ); 19 20 cout << fixed << showpoint << setprecision( 2 );
78
A Program that Uses the Checkbook Class (cont.)
21 choice = menu( ); 22 while ( choice != QUIT ) { 23 if ( choice == CHECK ) { cout << "Enter check amount: $"; cin >> amount; if ( cb.writeCheck( amount ) ) 27 cout << "Check accepted." << endl; else { 29 cout << "Your balance is not high "; 30 cout << "enough for that check." << endl; 31 } } body of the while loop continues
79
A Program that Uses the Checkbook Class (cont.)
33 else if ( choice == DEPOSIT ) { 34 cout << "Enter deposit amount: $"; 35 cin >> amount; 36 cb.deposit( amount ); 37 cout << "Deposit accepted." << endl; 38 } body of the while loop continues
80
A Program that Uses the Checkbook Class (cont.)
else { // must be a balance request amount = cb.getBalance( ); cout << "Your balance is: $" << amount << endl; } 43 choice = menu( ); 45 } 46 47 return 0; 48 } 49 end of while loop
81
A Program that Uses the Checkbook Class (cont.)
50 int menu( ) 51 { 52 int choice; 53 54 cout << endl; 55 cout << "1 Write a check" << endl; 56 cout << "2 Make a deposit" << endl; 57 cout << "3 Get the balance" << endl; 58 cout << "4 Quit" << endl << endl; 59 cout << "Enter a number between 1 and 4: "; 60 cin >> choice; 61 return choice; 62 }
82
Keep In Mind The data members of a class cannot be accessed by a main program. The object always retains the current values of its data members, even when object code is no longer executing. Each function of a class can use the data members of the class as though they have been declared within the function.
83
DATA STRUCTURE : DAT 20104 SAYONARA CLASS....
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.