Homework #3

Due: Monday, February 5, at the beginning of class

Worth: 15 pts (5 pts per question), Late papers will be docked 5 points per 24 hour period.

Collaboration: Feel free to work together on this assignment, although each person should turn in his/her own copy.

Turn In: A printout of each C++ program, and a written answer to #2.

1. Input 3 floats from your user. Compute and display the average using indirect referencing (pointers). So, saying: num1 + num2 + num3 / 3 is NOT allowed! (However you can say *num1 + ....) Turn in a copy of your program.

 

  1. What is the output of the following program? Explain. (Perhaps draw a diagram showing what points where, and what is happening.) What do the "new" and "delete" do?

#include <iostream.h>

void main()

{ char *charptr1 = new char;

*charptr1 = 'A';

char *charptr2 = new char;

*charptr2 = 'B';

char *charptr3 = new char;

*charptr3 = 'A';

cout << *charptr1 << endl;

cout << *charptr2 << endl;

cout << *charptr3 << endl;

char *naughty_char_ptr = charptr1;

*naughty_char_ptr = 'D';

naughty_char_ptr = charptr2;

*naughty_char_ptr = 'F';

//Continued on next page…

naughty_char_ptr = charptr3;

*naughty_char_ptr = 'F';

cout << *charptr1 << endl;

cout << *charptr2 << endl;

cout << *charptr3 << endl;

delete charptr1;

delete charptr2;

delete charptr3;

}

3. The following program goes from "FAIL" to "PASS" in 5 steps. Modify this program to go from "DOG" to "CAT" in 4 steps.

#include <iostream.h>

void main()

{ char word[10] = "FAIL";

char *c;

cout << "FAIL to PASS in 5 steps..." << endl;

//Step 1 -- FAIL

cout << word << endl;

//Step 2 -- PAIL

c = &word[0];

*c = 'P';

cout << word << endl;

//Step 3 -- PALL

c = &word[2];

*c = 'L';

cout << word << endl;

//Step 4 -- PALS

c = &word[3];

*c = 'S';

cout << word << endl;

//Continued on next page…

 

//Step 5 -- PASS

c = &word[2];

*c = 'S';

cout << word << endl;

}