Spring 2025 CS 31

Project 6
Let's Get Right to the Point

Time due: 11:00 PM Tuesday, May 27

Part 1

Go through the following sections of the class zyBook, doing the Participation Activities and Challenge Activities. We will be looking at whether you have ever successfully completed them; it does not matter how many attempts you make before a successful completion (or how many attempts you make after a successful completion if you want to experiment).

Part 2

This project is designed to help you master pointers. To that end, you'll get the most out of it by working through the problems by hand. Only after that should you resort to running the programs (and stepping through them with the debugger) to check your understanding. Remember, on the final exam you'll have to be able to do problems like this by hand.

This "project" is more like a homework. There are five problems. In problems that ask you to change code, make the few changes necessary to fix the code without changing its overall approach. For example, don't fix the program in problem 1a by changing it to

	int main()
	{
	    cout << " 30 20 10" << endl;
	}
  1. The subparts to this problem involve errors in the use of pointers.

    1. This program is supposed to write  30 20 10, but it doesn't. Find all of the bugs and show a fixed version of the program:

          int main()
          {
              int arr[3] = { 5, 10, 15 };
              int* ptr = arr;
      
              *ptr = 10;          // set arr[0] to 10
              *ptr + 1 = 20;      // set arr[1] to 20
              ptr += 2;
              ptr[0] = 30;        // set arr[2] to 30
      
              while (ptr >= arr)
              {
                  ptr--;
                  cout << ' ' << *ptr;    // print values
              }
      	cout << endl;
          }
      
    2. The findDisorder function is supposed to find the first item in an array that is less than the element preceding it, and set the p parameter to point to that item so the caller can know the location of that item. Explain why this function won't do that, and show a way to fix it. Your fix must be to the function only; you must not change the the main routine below in any way, yet as a result of your fixing the function, the main routine below must work correctly.

          void findDisorder(int arr[], int n, int* p)
          {
              for (int k = 1; k < n; k++)
              {
                  if (arr[k] < arr[k-1])
                  {
                       p = arr + k;
                       return;
                  }
              }
      	p = nullptr;
          }       
      
          int main()
          {
              int nums[6] = { 10, 20, 20, 40, 30, 50 };
              int* ptr = &nums[0];
      
              findDisorder(nums, 6, ptr);
      	if (ptr == nullptr)
      	    cout << "The array is ordered" << endl;
      	else
      	{
                  cout << "The disorder is at address " << ptr << endl;
                  cout << "It's at position " << ptr - nums << endl;
                  cout << "The item's value is " << *ptr << endl;
      	}
          }
      
    3. The hypotenuse function is correct, but the main function has a problem. Explain why it may not work, and show a way to fix it. Your fix must be to the main function only; you must not change the hypotenuse function in any way.

          #include <iostream>
          #include <cmath>
          using namespace std;
      
          void hypotenuse(double leg1, double leg2, double* resultPtr)
          {
              *resultPtr = sqrt(leg1*leg1 + leg2*leg2);
          }
      
          int main()
          {
              double* p;
              hypotenuse(1.5, 2.0, p);
              cout << "The hypotenuse is " << *p << endl;
          }
      
    4. The match function is supposed to return true if and only if its two C string arguments have exactly same text. Explain what the problems with the implementation of the function are, and show a way to fix them.

            // return true if two C strings are equal
          bool match(const char str1[], const char str2[])
          {
              while (str1 != 0  &&  str2 != 0)  // zero bytes at ends
              {
                  if (str1 != str2)  // compare corresponding characters
                      return false;
                  str1++;            // advance to the next character
                  str2++;
              }
              return str1 == str2;   // both ended at same time?
          }
      
          int main()
          {
              char a[20] = "Hong";
              char b[20] = "Hung";
      
              if (match(a,b))
                  cout << "They're the same!\n";
          }
      
    5. This program is supposed to write 1 4 9 16 25 36 49 64 81 100 , but it probably does not. What is the program doing that is incorrect? (We're not asking you explain why the incorrect action leads to the particular outcome it does, and we're not asking you to propose a fix to the problem.)

          #include <iostream>
          using namespace std;
      
          int* computeSquares(int& n)
          {
              int arr[10];
              n = 10;
              for (int k = 0; k < n; k++)
                  arr[k] = (k+1) * (k+1);
              return arr;
          }
      
          void f(int b)
          {
              int junk[1000];
              for (int k = 0; k < 1000; k++)
                  junk[k] = b + k;
          }
      
          int main()
          {
              int m;
              int* ptr = computeSquares(m);
              f(123400000);
              for (int i = 0; i < m; i++)
                  cout << ptr[i] << ' ';
          }
      
  2. For each of the following parts, write a single C++ statement that performs the indicated task. For each part, assume that all previous statements have been executed (e.g., when doing part e, assume the statements you wrote for parts a through d have been executed). For each part, do not use any variable names or string literals not mentioned in that part (e.g., if the part doesn't mention fp or "tuna", do not use fp or "tuna" in your answer).

    1. Declare a pointer variable named fp that can point to a variable of type string.
    2. Declare fish to be a 5-element array of strings.
    3. Make the fp variable point to the last element of fish.
    4. Make the string pointed to by fp equal to "yellowtail", using the * operator.
    5. Without using the fp pointer, and without using square brackets, set the fourth element (i.e., the one at position 3) of the fish array to have the value "salmon".
    6. Move the fp pointer back by three strings.
    7. Using square brackets, but without using the name fish, set the third element (i.e., the one at position 2) of the fish array to have the value "wahoo". (You may use fp.)
    8. Without using the * operator or the name fish, but using square brackets, set the string pointed to by fp to have the value "tang".
    9. Using the == operator in the initialization expression, declare a bool variable named d and initialize it with an expression that evaluates to true if fp points to the string at the start of the fish array, and to false otherwise.
    10. Using the * operator in the initialization expression, but no square brackets, declare a bool variable named b and initialize it to true if the string pointed to by fp is equal to the string immediately following the string pointed to by fp, and false otherwise. Do not use the name fish

    1. Rewrite the following function so that it returns the same result, but does not increment the variable ptr. Your new program must not use any square brackets, but must use an integer variable to visit each double in the array. You may eliminate any unneeded variable.

          double computeAverage(const double* scores, int nScores)
          {
              const double* ptr = scores;
              double tot = 0;
              while (ptr != scores + nScores)
              {
                  tot += *ptr;
                  ptr++;
              }
              return tot/nScores;
          }
      
    2. Rewrite the following function so that it does not use any square brackets (not even in the parameter declarations) but does use the integer variable k. Do not use any of the <cstring> functions such as strlen, strcpy, etc.

          // This function searches through str for the character chr.
          // If the chr is found, it returns a pointer into str where
          // the character was first found, otherwise nullptr (not found).
      
          const char* findTheChar(const char str[], char chr)
          {
              for (int k = 0; str[k] != 0; k++)
                  if (str[k] == chr)
                      return &str[k];
      
              return nullptr;
          }
      
    3. Now rewrite the function shown in part b so that it uses neither square brackets nor any integer variables. Your new function must not use any local variables other than the parameters. Do not use any of the <cstring> functions such as strlen, strcpy, etc.

  3. What does the following program print and why? Be sure to explain why each line of output prints the way it does to get full credit.

        #include <iostream>
    
        using namespace std;
    
        int* minimart(int* a, int* b)
        {
            if (*a < *b)
                return a;
            else
                return b;
        }
    
        void swap1(int* a, int *b)
        {
            int* temp = a;
            a = b;
            b = temp;
        }
    
        void swap2(int* a, int *b)
        {
            int temp = *a;
            *a = *b;
            *b = temp;
        }
    
        int main()
        {
            int array[6] = { 5, 3, 4, 17, 22, 19 };
    
            int* ptr = minimart(array, &array[2]);
            ptr[1] = 9;
            ptr += 2;
            *ptr = -1;
            *(array+1) = 79;
    
            cout << "diff=" << &array[5] - ptr << endl;
    
            swap1(&array[0], &array[1]);
            swap2(array, &array[2]);
    
            for (int i = 0; i < 6; i++)
                cout << array[i] << endl;
        } 
    
  4. Write a function named deleteG that accepts one character pointer as a parameter and returns no value. The parameter is a C string. This function must remove all of the upper and lower case 'g' letters from the string. The resulting string must be a valid C string.

    Your function must declare no more than one local variable in addition to the parameter; that additional variable must be of a pointer type. Your function must not use any square brackets and must not use any of the <cstring> functions such as strlen, strcpy, etc.

        int main()
        {
            char msg[100] = "I recall the glass gate next to Gus in Lagos, near the gold bridge.";
            deleteG(msg);
            cout << msg;  // prints   I recall the lass ate next to us in Laos, near the old bride.
        }
    

You won't turn anything in through the CS 31 web site for Part 1; the zyBook system notes your successful completion of the PAs and CAs. For Part 2, prepare your solutions to these homework problems as a single Word document named hw.docx or a plain text file named hw.txt. Put that file in a zip file. By Monday, May 26, there will be a link on the class webpage that will enable you to turn in your zip file.