Question

Leave comments on code describing what does what Objectives: 1. To introduce pointer variables and their...

Leave comments on code describing what does what

Objectives:

1. To introduce pointer variables and their relationship with arrays

2. To introduce the dereferencing operator

3. To introduce the concept of dynamic memory allocation

A distinction must always be made between a memory location’s address and the data stored at that location. In this lab, we will look at addresses of variables and at special variables, called pointers, which hold these addresses.

The address of a variable is given by preceding the variable name with the C++ address operator (&). The & operator in front of the variable sum indicates that the address itself, and not the data stored in that location.

cout << &sum; // This outputs the address of the variable sum

To define a variable to be a pointer, we precede it with an asterisk (*). The asterisk in front of the variable indicates that ptr holds the address of a memory location.

int *ptr;

The int indicates that the memory location that ptr points to holds integer values. ptr is NOT an integer data type, but rather a pointer that holds the address of a location where an integer value is stored.

Explain the difference between the following two statements:

  

int sum; // ____________________________

int *sumPtr; // ___________________________

Using the symbols * and &:

  1. The & symbol is basically used on two occasions.

  • reference variable : The memory address of the parameter is sent to the function instead of the value at that address.

  • address of a variable

void swap (int &first, int &second) // The & indicates that the parameters

{ // first and second are being passed by reference.

int temp;

temp = first; // Since first is a reference variable,

// the compiler retrieves the value

// stored there and places it in temp.

first = second // New values are written directly into

second = temp; // the memory locations of first and second.

}

   

2) The * symbol is used on

  • define pointer variables:

  • the contents of the memory location

int *ptr;



Experiment 1

Step 1:

Complete this program by filling in the code (places in bold). Note: use only pointer variables when instructed to by the comments in bold. This program is to test your knowledge of pointer variables and the & and * symbols.

Step 2:

Run the program with the following data: 10 15. Record the output here .

// This program demonstrates the use of pointer variables

// It finds the area of a rectangle given length and width

// It prints the length and width in ascending order

#include <iostream>

using namespace std;

int main()

{

int length; // holds length

int width; // holds width

int area; // holds area

int *lengthPtr; // int pointer which will be set to point to length

int *widthPtr; // int pointer which will be set to point to width

  cout << "Please input the length of the rectangle" << endl;

cin >> length;

cout << "Please input the width of the rectangle" << endl;

cin >> width;

// Fill in code to make lengthPtr point to length (hold its address)

// Fill in code to make widthPtr point to width (hold its address)

area = // Fill in code to find the area by using only the pointer variables

cout << "The area is " << area << endl;

if (// Fill in the condition length > width by using only the pointer variables)

cout << "The length is greater than the width" << endl;

else if (// Fill in the condition of width > length by using only the pointer

// variables)

cout << "The width is greater than the length" << endl;

else

cout << "The width and length are the same" << endl;

return 0;

}




Experiment 2: Dynamic Memory

Step 1:

Complete the program by filling in the code. (Areas in bold) This problem requires that you study very carefully. The code has already written to prepare you to complete the program.

Step 2:

In inputting and outputting the name, you were asked NOT to use a bracketed subscript. Why is a bracketed subscript unnecessary? Would using name [pos] work for inputting the name? Why or why not? Would using name [pos] work for outputting the name? Why or why not?

Try them both and see.

// This program demonstrates the use of dynamic variables

#include <iostream>

using namespace std;

const int MAXNAME = 10;

int main()

{

int pos;

char * name;

int * one;

int * two;

int * three;

int result;

// Fill in code to allocate the integer variable one here

// Fill in code to allocate the integer variable two here

// Fill in code to allocate the integer variable three here

// Fill in code to allocate the character array pointed to by name

cout << "Enter your last name with exactly 10 characters." << endl;

cout << "If your name has < 10 characters, repeat last letter. " << endl

<< "Blanks at the end do not count." << endl;

for (pos = 0; pos < MAXNAME; pos++)

cin >> // Fill in code to read a character into the name array // WITHOUT USING a bracketed subscript

cout << "Hi ";

for (pos = 0; pos < MAXNAME; pos++)

cout << // Fill in code to a print a character from the name array // WITHOUT USING a bracketed subscript

cout << endl << "Enter three integer numbers separated by blanks" << endl;

// Fill in code to input three numbers and store them in the

// dynamic variables pointed to by pointers one, two, and three.

// You are working only with pointer variables

//echo print

cout << "The three numbers are " << endl;

// Fill in code to output those numbers

result = // Fill in code to calculate the sum of the three numbers

cout << "The sum of the three values is " << result << endl;

// Fill in code to deallocate one, two, three and name

return 0;

}

Sample Run:

Enter your last name with exactly 10 characters.

If your name < 10 characters, repeat last letter. Blanks do not count.

DeFinooooo

Hi DeFinooooo

Enter three integer numbers separated by blanks

5 6 7

The three numbers are 5 6 7

The sum of the three values is 18




Experiment 3: Dynamic Arrays

Question: Fill in the code as indicated by the comments in bold.

// This program demonstrates the use of dynamic arrays

#include <iostream>

#include <iomanip>

using namespace std;

int main()

{

float *monthSales; // a pointer used to point to an array

// holding monthly sales

float total = 0; // total of all sales

float average; // average of monthly sales

int numOfSales; // number of sales to be processed

int count; // loop counter

cout << fixed << showpoint << setprecision(2);

cout << "How many monthly sales will be processed? ";

cin >> numOfSales;

// Fill in the code to allocate memory for the array pointed to by

// monthSales.

if ( // Fill in the condition to determine if memory has been

// allocated (or eliminate this if construct if your instructor

// tells you it is not needed for your compiler)

)

{

cout << "Error allocating memory!\n";

return 1;

}

cout << "Enter the sales below\n";

for (count = 0; count < numOfSales; count++)

{

cout << "Sales for Month number "

<< // Fill in code to show the number of the month

<< ":";

// Fill in code to bring sales into an element of the array

}

for (count = 0; count < numOfSales; count++)

{

total = total + monthSales[count];

}

average = // Fill in code to find the average

cout << "Average Monthly sale is $" << average << endl;

// Fill in the code to deallocate memory assigned to the array.

return 0;

}

Sample Run:

How many monthly sales will be processed 3

Enter the sales below

Sales for Month number 1: 401.25

Sales for Month number 2: 352.89

Sales for Month number 3: 375.05

Average Monthly sale is $376.40

Homework Answers

Answer #1

Explain the difference between the following two statements:

int sum; // Declaration of a integer variable named 'sum'

int *sumPtr; // Declaration of a pointer to an integer which will hold the address of a integer

Experiment 1 :

// This program demonstrates the use of pointer variables

// It finds the area of a rectangle given length and width

// It prints the length and width in ascending order

#include <iostream>

using namespace std;

int main()

{

int length; // holds length

int width; // holds width

int area; // holds area

int *lengthPtr; // int pointer which will be set to point to length

int *widthPtr; // int pointer which will be set to point to width

cout << "Please input the length of the rectangle" << endl;

cin >> length;

cout << "Please input the width of the rectangle" << endl;

cin >> width;

lengthPtr = &length ; // Fill in code to make lengthPtr point to length (hold its address)

widthPtr = &width ; // Fill in code to make widthPtr point to width (hold its address)

area = (*lengthPtr) * (*widthPtr) ;// Fill in code to find the area by using only the pointer variables

cout << "The area is " << area << endl;

if ( *lengthPtr > *widthPtr ) /* Fill in the condition length > width by using only the pointer variables*/

cout << "The length is greater than the width" << endl;

else if ( *widthPtr > *lengthPtr )/* Fill in the condition of width > length by using only the pointer

variables*/

cout << "The width is greater than the length" << endl;

else

cout << "The width and length are the same" << endl;

return 0;

}


Output 1:

Please input the length of the rectangle
10
Please input the width of the rectangle
15
The area is 150
The width is greater than the length


Experiment 2: Dynamic Memory

// This program demonstrates the use of dynamic variables

#include <iostream>

using namespace std;

const int MAXNAME = 10;

int main()

{

int pos;

char * name;

int * one;

int * two;

int * three;

int result;

one = new int ; // Fill in code to allocate the integer variable one here

two = new int ; // Fill in code to allocate the integer variable two here

three = new int ; // Fill in code to allocate the integer variable three here

name = new char[MAXNAME] ; // Fill in code to allocate the character array pointed to by name

cout << "Enter your last name with exactly 10 characters." << endl;

cout << "If your name has < 10 characters, repeat last letter. Blanks do not count. " << endl;

for (pos = 0; pos < MAXNAME; pos++)
{
cin >>*(name+pos) ; // Fill in code to read a character into the name array // WITHOUT USING a bracketed subscript
//cin>>name[pos] ; // USING a bracketed subscript
}
cout << "Hi ";

for (pos = 0; pos < MAXNAME; pos++)
{
cout << *(name+pos) ; // Fill in code to a print a character from the name array // WITHOUT USING a bracketed subscript
//cout << name[pos] ; // USING a bracketed subscript
}
cout << endl << "Enter three integer numbers separated by blanks" << endl;

cin>>*one>>*two>>*three ; // Fill in code to input three numbers and store them in the
// dynamic variables pointed to by pointers one, two, and three.
// You are working only with pointer variables

//echo print

cout << "The three numbers are " << endl;

cout<<*one<<" "<<*two<<" "<<*three<<endl; // Fill in code to output those numbers

result = (*one) + (*two) + (*three) ;// Fill in code to calculate the sum of the three numbers

cout << "The sum of the three values is " << result << endl;

delete one;// Fill in code to deallocate one, two, three and name
delete two;
delete three;
delete []name;
return 0;

}

Output 2 : WITHOUT USING a bracketed subscript

Enter your last name with exactly 10 characters.
If your name has < 10 characters, repeat last letter. Blanks do not count.
Hi DeFinooooo
Enter three integer numbers separated by blanks
The three numbers are
5 6 7
The sum of the three values is 18

Output 2 : USING a bracketed subscript

Enter your last name with exactly 10 characters.
If your name has < 10 characters, repeat last letter. Blanks do not count.
Hi DeFinooooo
Enter three integer numbers separated by blanks
The three numbers are
5 6 7
The sum of the three values is 18


// Bracket or without bracket this program will work fine both ways. That's why brackets are unnecessary.

Experiment 3: Dynamic Arrays

//This program demonstrates the use of dynamic arrays

#include <iostream>

#include <iomanip>

using namespace std;

int main()

{

float *monthSales; // a pointer used to point to an array

// holding monthly sales

float total = 0; // total of all sales

float average; // average of monthly sales

int numOfSales; // number of sales to be processed

int count; // loop counter

cout << fixed << showpoint << setprecision(2);

cout << "How many monthly sales will be processed? ";

cin >> numOfSales;

monthSales = new float[numOfSales] ; // Fill in the code to allocate memory for the array pointed to by

// monthSales.


// Fill in the condition to determine if memory has been

// allocated (or eliminate this if construct if your instructor

// tells you it is not needed for your compiler)
if ( !monthSales)
{

cout << "Error allocating memory!\n";

return 1;

}

cout << "Enter the sales below\n";

for (count = 0; count < numOfSales; count++)

{

cout << "Sales for Month number "

<<count+1 // Fill in code to show the number of the month

<< ":";

cin>>*(monthSales+count) ;// Fill in code to bring sales into an element of the array

}

for (count = 0; count < numOfSales; count++)

{

total = total + monthSales[count];

}

average = total/numOfSales ; // Fill in code to find the average

cout << "Average Monthly sale is $" << average << endl;

delete []monthSales; // Fill in the code to deallocate memory assigned to the array.

return 0;

}

Output 3 :

How many monthly sales will be processed 3

Enter the sales below

Sales for Month number 1: 401.25

Sales for Month number 2: 352.89

Sales for Month number 3: 375.05

Average Monthly sale is $376.40

Know the answer?
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for?
Ask your own homework help question
Similar Questions
Lab 6    -   Program #2   -   Write one number to a text file. Use the write()...
Lab 6    -   Program #2   -   Write one number to a text file. Use the write() and read() functions with binary                                                        data, where the data is not char type.              (Typecasting is required) Fill in the blanks, then enter the code and run the program. Note:   The data is int type, so typecasting is            required in the write() and read() functions. #include <iostream> #include <fstream> using namespace std; int main() {    const int SIZE = 10;   ...
In the following C code, Which variable if NOT of primitive data type? A. a B....
In the following C code, Which variable if NOT of primitive data type? A. a B. b C. c D. d int a = 10; double b = 20.0; float c = false; char d[5] = "Hello"; // here we define a string In programming language C, the implementation of a string data type is limited dynamic length, which means the length of a string variable is fixed once it has been defined. A. True B. False In C# programming...
1. Create a new project. Type in the following program. Add a comment at the top...
1. Create a new project. Type in the following program. Add a comment at the top to include your name and the date. 2. Compile and Run with different values. What data values should you choose? Think about what we discussed in class. 3. Add code to compute the modulus. Hint: you will also have to declare a new variable. //this program demonstrates the use of various operators #include <iostream > using namespace std; int main() { int num1; int...
A program is already given to you.  There are five problems in this skeleton version of the...
A program is already given to you.  There are five problems in this skeleton version of the program, each is 10 points. All you got to do is complete the missing code in each function. What the function does is clearly stated in the name of the function.   // ASSIGNMENT ON FUNCTIONS #include <stdio.h> // Problem 1: Compile with gcc func_assignment.c -Wall // There are some warnings because there is a mismatch between // data type passed and defined. // Find...
Topics Arrays Accessing Arrays Description Write a C++ program that will display a number of statistics...
Topics Arrays Accessing Arrays Description Write a C++ program that will display a number of statistics relating to data supplied by the user. The program will ask the user to enter the number of items making up the data. It will then ask the user to enter data items one by one. It will store the data items in a double array. Then it will perform a number of statistical operations on the data. Finally, it will display a report...
#include<iostream> #include<iomanip> using namespace std; int main() { //variables int choice; float radius,base,height,area; const double PI=3.14159;...
#include<iostream> #include<iomanip> using namespace std; int main() { //variables int choice; float radius,base,height,area; const double PI=3.14159; //repeat until user wants to quits while(true) { //menu cout<<endl<<endl<<"Geometry Calculator"<<endl<<endl; cout<<"1. Calculate the area of a circle"<<endl; cout<<"2. Calculate the area of a triangle"<<endl; cout<<"3. Quit"<<endl<<endl; //prompt for choice cout<<"Enter your choice(1-3): "; cin>>choice; cout<<endl; //if choice is circle if(choice==1) { cout<<"What is the radius of the circle? "; cin>>radius; //calculating area area=PI*radius*radius; cout<<endl<<"The area of the circle is "<<fixed<<setprecision(3)<<area<<endl; } //if choice...
Code Example 8-1 1. int count = 1; 2. int item_total = 0; 3. int item...
Code Example 8-1 1. int count = 1; 2. int item_total = 0; 3. int item = 0; 4. while (count < 4) { 5.      cout << "Enter item cost: "; 6.      cin >> item; 7.      item_total += item; 8.      ++count; 9. } 10. int average_cost = round(item_total / count); 11. cout << "Total cost: " << item_total << "\nAverage cost: " << average_cost; (Refer to Code Example 8-1.) If the user enters 5, 10, and 15 at the prompts, the output is: Total...
Question 1 Which statement is false about what Data Types defines Question 1 options: What values...
Question 1 Which statement is false about what Data Types defines Question 1 options: What values a variable cannot hold? How much memory will be reserved for the variable? What value a variable will hold? How the program will use the data type? Question 2 Using the structure below, which of the following statements about creating an array (size 20) of structures are not true? struct Employee{     string emp_id;     string emp_name;     string emp_sex; }; Question 2 options:...
Complete this in C++ and explain what is being done. 1      Introduction The functions in the...
Complete this in C++ and explain what is being done. 1      Introduction The functions in the following subsections can all go in one big file called pointerpractice.cpp. 1.1     Basics Write a function, int square 1(int∗ p), that takes a pointer to an int and returns the square of the int that it points to. Write a function, void square 2(int∗ p), that takes a pointer to an int and replaces that int (the one pointed to by p) with its...
Strings The example program below, with a few notes following, shows how strings work in C++....
Strings The example program below, with a few notes following, shows how strings work in C++. Example 1: #include <iostream> using namespace std; int main() { string s="eggplant"; string t="okra"; cout<<s[2]<<endl; cout<< s.length()<<endl; ​//prints 8 cout<<s.substr(1,4)<<endl; ​//prints ggpl...kind of like a slice, but the second num is the length of the piece cout<<s+t<<endl; //concatenates: prints eggplantokra cout<<s+"a"<<endl; cout<<s.append("a")<<endl; ​//prints eggplanta: see Note 1 below //cout<<s.append(t[1])<<endl; ​//an error; see Note 1 cout<<s.append(t.substr(1,1))<<endl; ​//prints eggplantak; see Note 1 cout<<s.find("gg")<<endl; if (s.find("gg")!=-1) cout<<"found...
ADVERTISEMENT
Need Online Homework Help?

Get Answers For Free
Most questions answered within 1 hours.

Ask a Question
ADVERTISEMENT