Você está na página 1de 12

TMF1434/TMC1434 Data Structure and Algorithms 1

LAB 3

TMF1434/TMC1434 Data Structure and Algorithms


2015/2016 - Semester 2

LAB 3
ARRAYS & POINTERS

A. Arrays

1. Simple Array

#include <iostream>
using namespace std;

int main()
{
int sample[10]; // this reserves 10 integer elements
int idx;

// load the array


for(idx =0; idx <10; ++idx)
sample[idx]= idx;

// display the array


for(idx =0; idx <10; ++idx)
cout << sample[idx] << ' ';

return 0;
}

Exercise :

a) Modify the program above by utilizing a constant variable SIZE to define the size
of the array to value 10 and making use of this constant value throughout your
program.

b) Create a new array of type integer named as myZeroArray with number of element
as many as your constant SIZE defined earlier and initial with zero 0 value to all
elements in this array in a single statement. Display this array.

c) Create another new array named as myOtherArray and initial with 3 different
integer values in this array. Think of a way to display the content of this array
without specify value 3 as the number of element in this array. (Hint: this array is
containing int data type in each element)
TMF1434/TMC1434 Data Structure and Algorithms 2
LAB 3

Sample Answer:

#include <iostream>
using namespace std;
const int SIZE = 10;

int main()
{
int sample[SIZE]; // this reserves 10 integer elements
int idx;
int myZeroArray[SIZE] = {0};
int myOtherArray[] = {10 , 20 , 30};

// load the array


for(idx =0; idx <SIZE; ++idx)
sample[idx]= idx;

// display the array


for(idx =0; idx < SIZE; ++idx)
cout << sample[idx] << ' ';

// display the myZeroArray


for(idx =0; idx < SIZE; ++idx)
cout <<"\n\nmyZeroArray = "<<myZeroArray[idx] << ' ';

for(idx =0; idx < sizeof(myOtherArray)/sizeof(int); ++idx)


// you may use sizeof(myOtherArray)/sizeof(*myOtherArray)
cout << "\n\nmyOtherArray = "<<myOtherArray[idx] << ' ';

return 0;
}
TMF1434/TMC1434 Data Structure and Algorithms 3
LAB 3

2. Multidimensional Array

Declaring and Accessing Elements in a Multidimensional Array

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

int main()
{
int TwoDArray [3][3] = {{-501, 206, 2011},
{989, 101, 206},
{303, 456, 596}};

cout << "Row 0: " << TwoDArray [0][0] << " "
<< TwoDArray [0][1] << " "
<< TwoDArray [0][2] << endl;

cout << "Row 1: " << TwoDArray [1][0] << " "
<< TwoDArray [1][1] << " "
<< TwoDArray [1][2] << endl;

cout << "Row 2: " << TwoDArray [2][0] << " "
<< TwoDArray [2][1] << " "
<< TwoDArray [2][2] << endl;
getch();
return 0;
}

B. POINTERS

1. Single pointer (Single indirection)


#include <iostream>
using namespace std;

int main()
{
int balance;
int *balptr;
int value;

balance = 3200;
balptr = &balance;
value = *balptr;

cout << "balance is: " << value << '\n';


return 0;
}

Exercise :

Modify the program, create a new pointer of type int named it as newBalance and
copy the content of balptr to this pointer. Print out the contents of both balptr and
newBalance as well the value of their references.
TMF1434/TMC1434 Data Structure and Algorithms 4
LAB 3

Sample Answer:

#include <iostream>
using namespace std;

int main()
{
int balance;
int *balptr;
int value;

int *newBalance;

balance = 3200;
balptr = &balance;
value = *balptr;
newBalance = balptr;

cout << "balance is: " << value << '\n';


cout << "Address of value is: " << &value << '\n';

cout << "Content of balptr is: (address of value)" << balptr << '\n';
cout << "Address of balptr is: " << &balptr << '\n';
cout << "Value of balptr's dereference is: " << *balptr << '\n\n';

cout << "Content of newBalance is:(address of value)"<< newBalance<<'\n';


cout << "Address of newBalance is: " << &newBalance << '\n';
cout << "Value of newBalance's dereference is: " << *newBalance << '\n';
return 0;
}

2. Multiple pointers (Multiple indirection / pointer to pointer)

#include <iostream>
using namespace std;
int main()
{
int x, *p, **q;
x = 10;
p = &x;
q = &p;

cout << "\nAddress of x " << &x; // prints the address of x


cout << "\nAddress of p " << &p; // prints the adrrss p
cout << "\nAddress of q " << &p; // prints the adrrss p

cout << "\n\nContent of x " << x; // prints the value of x


cout <<"\nContent of p(address of x) " <<p;//content p holding address of x
cout << "\nContent of *p(value of x) " <<*p;//derefence p holding value of x

cout << "\n\nContent of q(address of p) " <<q;//content q holding address of p


cout << "\nContent of *q(address of x) " <<*q;//derefence q holding address of x
cout << "\nContent of **q "<<**q; // prints the value of x
return 0;
}
TMF1434/TMC1434 Data Structure and Algorithms 5
LAB 3

3. A Demonstration of Bad Programming Using Invalid Pointers


(CAUTION: Save all your works before try out this program)

#include <iostream>
using namespace std;
int main()
{
// uninitialized pointer (bad)
int* pTemperature;
cout << "Is it sunny (y/n)?" << endl;
char UserInput = 'y';
cin >> UserInput;

if (UserInput == 'y')
{
pTemperature = new int;
*pTemperature = 30;
}

// pTemperature contains invalid value if user entered n


cout << "Temperature is: " << *pTemperature;
//delete also being invoked for those cases new wasnt done
delete pTemperature;
return 0;
}
TMF1434/TMC1434 Data Structure and Algorithms 6
LAB 3

4. Passing pointer to function

4a. Pass a pointer to a function.

#include <iostream>
using namespace std;
void f(int *j);
int main()
{
int i;
int *p;
p = &i; // p now points to i
f(p);
cout << i; // i is now 100
return 0;
}

void f(int *j)


{
*j = 100; // var pointed to by j is assigned 100
}

4b. Pass a pointer to a function -- revised version.

//pass a pointer to a function -- revised version.


#include <iostream>
using namespace std;
void f(int *j);

int main()
{
int i;
f(&i);
cout << i;
return 0;
}

void f(int *j)


{
*j = 100; // var pointed to by j is assigned 100
}
TMF1434/TMC1434 Data Structure and Algorithms 7
LAB 3

5a. Calling function with array

#include <iostream>
using namespace std;
void display(int num[10]);
int main()
{
int t[10],i;
for(i=0; i<10; ++i)
t[i]=i;

display(t); // pass array t to a function


return 0;
}

// Print some numbers.


void display(int num[10])
{
int i;
for(i=0; i<10; i++)
cout << num[i] << ' ';
}

5b. Calling function with pointers

In the following program, examine the function cube( ), which converts the value of
each element in an array into its cube. To call cube( ), pass the address of the array as
the first argument, and the size of the array as the second.

#include <iostream>
using namespace std;
void cube(int *n, int num);

int main()
{
int i, nums[10];
for(i=0; i<10; i++) nums[i] = i+1;
cout << "Original contents: ";

for(i=0; i<10; i++) cout << nums[i] << ' ';


cout << '\n';
cube(nums, 10); // compute cubes
cout << "Altered contents: ";

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


cout << nums[i] << ' ';
return 0;
}

void cube(int *n, int num)


{
while(num) {
*n = *n * *n * *n;
num--;
n++;
}
}
TMF1434/TMC1434 Data Structure and Algorithms 8
LAB 3

Here is the output produced by this program:

Original contents: 1 2 3 4 5 6 7 8 9 10

Altered contents: 1 8 27 64 125 216 343 512 729 1000


TMF1434/TMC1434 Data Structure and Algorithms 9
LAB 3

Self-Practice Exercises

A-1: Sample program to access to the content of an array using pointer.

#include <iostream>
using namespace std;

int main(){
int number[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
int *pNumbers = number;
cout << "Values - Using the Array";
cout << "\n number[0]: " << number[0];
cout << "\n number[1]: " << number[1];
cout << "\n number[2]: " << number[2];
cout << "\n number[3]: " << number[3];
cout << "\n number[4]: " << number[4];

cout << "\n\nValues - Using the Pointer - No Parentheses";


cout << "\n*pNumbers: " << *pNumbers;
cout << "\n*pNumbers+1: " << *pNumbers+1;
cout << "\n*pNumbers+2: " << *pNumbers+2;
cout << "\n*pNumbers+3: " << *pNumbers+3;
cout << "\n*pNumbers+4: " << *pNumbers+4;

cout << "\n\nValues - Using the Pointer - With Parentheses";


cout << "\n*pNumbers: " << *pNumbers;
cout << "\n*(pNumbers+1): " << *(pNumbers+1);
cout << "\n*(pNumbers+2): " << *(pNumbers+2);
cout << "\n*(pNumbers+3): " << *(pNumbers+3);
cout << "\n*(pNumbers+4): " << *(pNumbers+4);
return 0;
}
TMF1434/TMC1434 Data Structure and Algorithms 1
LAB 3 0

B-1: One Dimensional Array-Indexing

In the following program, extracts words, separated by spaces, from a string. For
example, given "Hello Tom," the program would extract "Hello" and "Tom." For example,
if you enter This is a test. the program displays the following:
This
is
a
test.

Here is the Array version of the tokenizing program:

#include <iostream>
#include <cstdio>
using namespace std;

int main(){
char str[80];
char token[80];
int i, j;

cout << "Enter a sentence: ";


gets(str); // Read a token at a time from the string.

/* Read characters until either a space or the null terminator is


encountered. */
for(i=0; ; i++) {
for(j=0; str[i]!=' ' && str[i]; j++, i++)
token[j] = str[i];

token[j] = '\0'; // null terminate the token


cout << token << '\n';

if(!str[i]) break;
}
return 0;
}
TMF1434/TMC1434 Data Structure and Algorithms 1
LAB 3 1

B-2 Exercise:

This program acts similar way as program B-1 in previous section, here is the pointer
version of the tokenizing program: (You may only use a single array or two arrays as in
program A-3)
Answer:

#include <iostream>
using namespace std;

int main(){
char str[20] = "This is a test";
cout << "\n\n*Content of str array: \n";

for (int idx = 0; idx <20; idx++){


if(*(str + idx) =='\0')
break;
else {
if (*(str + idx) ==' ' )
cout << "\n";
else
cout << *(str + idx);
}
}
return 0;
}

B-3: This program acts similar way as program B-1 in previous section, here is the
#include <iostream>
pointer version
#include of the tokenizing program:
<cstdio>
using namespace std;
int main()
{
char str[80];
char token[80];
char *p, *q;

cout << "Enter a sentence: ";


gets(str);

p = str;

// Read a token at a time from the string.


while(*p) {
q = token; // set q pointing to start of token
/* Read characters until either a space or the
null terminator is encountered. */
while(*p!=' ' && *p) {
*q = *p;
q++; p++;
}
if(*p) p++; // advance past the space
*q = '\0'; // null terminate the token
cout << token << '\n';
}
return 0;
}
TMF1434/TMC1434 Data Structure and Algorithms 1
LAB 3 2

Você também pode gostar