A Simple Program using Dynamic Arrays

 

 

1. Write a program that uses a dynamic array to compute the information about temperatures over a set of days.  The first line of your file has a number that specifies how many temperatures follow.  The next number of lines contain the temperatures.  For example, your data file might look as follows:

8

66

62

70

71

71

70

59

59

Your program should do the following:

 

 

1)    Declare an int pointer Temperature which will be used for the dynamic array

2)    Declare an int variable numDays

3)    Read in the number of days for which temperatures will be computed

4)    Dynamically allocate an array large enough to hold that many days

5)    Read the temperatures for each day into the array (use pointer notation)

6)    Calculate the average temperature (use pointer notation)

7)    Print out the result

 

 

2. What’s wrong with the following code?  It should call a function to code a message into a secret string. Get it to run properly!

#include <iostream>

#include <cstring>

#include <cctype>

 

using namespace std;

 

char  codeIt(char * s)

{

     int i;

     int len = strlen(s);

     char * result;

    

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

           result[i] = s[i] + 2;

     result[i] = '\0';

     return result;

}

int main()

{

    char *str;

     char *codedStr;

 

    int strLen;

    int len;

    char ch;

 

    int i;

 

    cout << "Enter the size of the string: ";

     cin >> strLen;

    cout << endl;

 

    cin.get(ch);

 

    str = new char[strLen + 1];

 

    cout << "Enter a string of length at most "

         << strLen << ": ";

    cin.get(str, strLen + 1);

    cout << endl;

   

    codedStr = codeIt(str);

 

    cout << codedStr;

 

    return 0;

}