Question

In: Computer Science

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

Solutions

Expert Solution

Experiment 1: Experiment 1 is for how to use the pointer operator appropriately. As per the Question, the program to be filled with appropriate code using the pointer concept.

Pointer: pointer is a variable that holds the address of another variable. Pointers are used to access the variables dynamically. * and & operators are used to declaring a pointer variable.

if declare a variable preceding * then it will be called as a pointer variable. & is used to assign the variable address to the pointer variable.

Example

int a, *b; // a is regular integer variable whereas b is a pointer variable

a=10; //a is assigned with value 10

b=&a; //b is assigned with address of a

cout<<a; // it prints a i.e.,10

cout<<b; //it prints address of a for ex, 0011

cout<<*b //here *b is represented as "value at b". it results 10.

Explanation:

int sum; //it is normal integer variable

int *sumptr; //it is a pointer variable

Program step1:

#include <iostream>
using namespace std;

//main methods starts
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;
// code to make lengthPtr point to length (hold its address)
lengthPtr=&length;        
// code to make widthPtr point to width (hold its address)
widthPtr=&width;         
// code to find the area by using only the pointer variables
area =((*lengthPtr)*(*widthPtr));      //area = length*width
cout << "The area is " << area << endl;
// the condition length > width by using only the pointer variables
if (*lengthPtr > *widthPtr)cout << "The length is greater than the width" << endl;
// Fill in the condition of width > length by using only the pointer
else if (*widthPtr >*lengthPtr)
cout << "The width is greater than the length" << endl;
else
cout << "The width and length are the same" << endl;
return 0;
}

Step2: run the code using 10 and 15

Please input the length of the rectangle

10

Please input the width of the rectangle

10

The area is 150

the width is greater than length.

------------------------------------------------------

Experiment 2:

Explanation: Dynamic memory allocation is the process of allocating memory in runtime. this helps the programmer to allocate the memory at runtime without wasting the memory.

new and delete are the two keywords used to allocate the memory and deallocate it. By deallocating the allocated memory the program can use the deallocated memory again without creating unnecessary garbage in memory.

syntax:

int *n= new int[10]; // array declaration using dynamic memory

char *nm=new char[20]; //string declaration

here we need not use brackets to access the array values.that can be done in an easy way like.

n[0] represents n+i where i=1 automatically add 2 ytes to the pointer n.so it represents the next location

n[1] represents n+i here i will be 2

same applies to strings as well.

deallocating also very simple.

delete[] n; //deletes entire array once

delete[] nm; //deletes string array.

Step1:Program with filled code

#include <iostream>
using namespace std;
const int MAXNAME = 10;
int main ()
{
int pos;
char *name;
int *one;
int *two;
int *three;
int result;
// code to allocate the integer variable one here
one = new int;
// Fill in code to allocate the integer variable two here
two = new int;
// code to allocate the integer variable three here
three = new int;
// code to allocate the character array pointed to by name
name = new char[MAXNAME];

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++)
// code to read a character into the name array // WITHOUT USING a bracketed subscript
cin >> *(name + pos);

cout << "Hi ";

for (pos = 0; pos < MAXNAME; pos++)
// Fill in code to a print a character from the name array // WITHOUT USING a bracketed subscript
cout << *(name + pos);

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

// Fill in code to input three numbers and store them in the
std::cin >> *one >> *two >> *three;
// 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;

// code to output those numbers
std::cout << *one << *two << *three;
result = *one + *two + *three;   // code to calculate the sum of the three numbers

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

return 0;
//code to deallocate one, two, three and name

delete (one);
delete (two);
delete (three);

}

step2:

Enter your last name with exactly 10 characters.                                                                              

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

Blanks at the end do not count.                                                                                               

sasanknknk                                                                                                                    

Hi sasanknknk                                                                                                                 

Enter three integer numbers separated by blanks                                                                               

6 7 8                                                                                                                         

The three numbers are                                                                                                         

678

The sum of the three values is 21  

Experiment 3:

step1:

#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;

// code to allocate memory for the array pointed to by monthSales.
monthSales= new float(numOfSales);

if (!monthSales)
//the condition to determine if memory has been allocated

{

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)// code to show the number of the month

<< ":";

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

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

{

total = total + monthSales[count];

}

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

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

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

delete[] monthSales;
return 0;

}

step2:

How many monthly sales will be processed? 5                                                                                   

Enter the sales below                                                                                                         

Sales for Month number 1:56                                                                                                   

Sales for Month number 2:64                                                                                                   

Sales for Month number 3:45                                                                                                   

Sales for Month number 4:34                                                                                                   

Sales for Month number 5:65                                                                                                   

Average Monthly sale is $52.8


Related Solutions

1. Write code in mips that will play battleships. Include comments in code on what each...
1. Write code in mips that will play battleships. Include comments in code on what each part is doing.
Replace the todo comments with the right code. //Create variables to use later const int TRIG_PIN...
Replace the todo comments with the right code. //Create variables to use later const int TRIG_PIN = 9; const int ECHO_PIN = 10; const int RED_PIN = 3; const int GREEN_PIN = 5; const int BLUE_PIN = 6; float duration, distance_in_cm, distance_in_feet; void setup() { //Setup pins for correct I/O pinMode(TRIG_PIN, OUTPUT); pinMode(ECHO_PIN, INPUT); pinMode(RED_PIN, OUTPUT); pinMode(GREEN_PIN, OUTPUT); pinMode(BLUE_PIN, OUTPUT); } void loop() { //Generate the ultrasonic waves digitalWrite(TRIG_PIN, LOW); delayMicroseconds(2); digitalWrite(TRIG_PIN, HIGH); delayMicroseconds(10); digitalWrite(TRIG_PIN, LOW); //Read in the echoed...
1. One of the objectives of corporate governance reform is to, A. introduce expensive and burdensome...
1. One of the objectives of corporate governance reform is to, A. introduce expensive and burdensome accounting reforms. B. strengthen the protection of outside investors from expropriation by managers and controlling insiders. C. none of the options D. provide taxpayer financing for corporate raiders to strengthen the discipline of the marketplace. 2. Free cash flow refers to A. a firm's cash reserve in excess of tax obligation. B. a firm's income tax refund that is due to interest payments on...
Matlab assignment. The objectives of this project are (1) to introduce the students to scripting applied...
Matlab assignment. The objectives of this project are (1) to introduce the students to scripting applied to solution of mechanical engineering problems and (2) to create a Matlab script that allows the computation of principal stresses and strains starting from a generic state of stress and that automates the drawing of 3D Mohr circles Assignment 1) Read from input a stress tensor (3D); 2) For any state of 3D stress compute the principal stress values (σ1, σ2, σ3) with σ1...
Can you add more comments explaining what this code does? i commented what I know so...
Can you add more comments explaining what this code does? i commented what I know so far #include<stdio.h> #include<pthread.h> #include<semaphore.h> #include<unistd.h> sem_t mutex,writeblock; int data = 0,rcount = 0; int sleepLength = 2; // used to represent work void *reader(void *arg) { int f; f = ((int)arg); sem_wait(&mutex); // decrement by 1 if rcount = rcount + 1; if(rcount==1) sem_wait(&writeblock); sem_post(&mutex); printf("Data read by the reader%d is %d\n",f,data); //shows current reader and data sleep(sleepLength); // 1 second of "work" is...
Introduce variables to represent items of interest in the problem. For example, (1) Let n be...
Introduce variables to represent items of interest in the problem. For example, (1) Let n be the number to be found, or (2) Let a be Alice’s current age, or (3) Let r be the rate of the first car. (2) Write down an equation using the information given in the problem. This is the really important part for this particular assignment! (3) Solve the equation and find the value requested in the problem. The distance between A and B...
1. in the code below, 2 variables (largest and smallest) are declared. use these variables to...
1. in the code below, 2 variables (largest and smallest) are declared. use these variables to store the largest and smallest of three integer values. you must decide what other variables you will need and initialize them if appropriate. 2. write the rest of the program using assignment statements, if statements, or if else statements as appropriate. There are comments in the code that tell you where you should write your statements 3. compile and execute. Output should be: The...
a. Discuss the objectives of monetary policy. b. What are the target variables and tools of...
a. Discuss the objectives of monetary policy. b. What are the target variables and tools of monetary policy.
What does it mean for a catalog to be self-describing? What does the following query mean?
DBMS:What does it mean for a catalog to be self-describing? What does the following query mean?((TABLES JOIN COLUMNS) WHERE COLCOUNT < 3) [TABNAME, COLNAME]
Explain your code with comments. Solve in C++. 1. Write a str2int() function that convers a...
Explain your code with comments. Solve in C++. 1. Write a str2int() function that convers a string to integer. The function will take the number as a string then will return it as integer. E.g. str2int(“123”) will return 123 str2int(“005”) will return 5 str2int(“102”) will return 102
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT