Self--Check Exercises

(not graded...just for practice!)

 

CS 161: Introduction to Computer Science 1

 

 

                                                            Solutions!

 

 

Self-Check Exercises

1.  Short answer:

 

a) How do you close a file that you have just written to?

 

            ofstream out;                       //assume this variable definition

 

            out.close();

 

 

b) When reading data from a file, how can you tell when you have read a line of data?

 

            The end of each line is terminated by a ‘\n’

 

 

c) Why can't you use cout <<  to write data to a file?

 

            This would write to standard out rather than to a text file. You need to

            use an ofstream variable.

 

d) List 3 advantages to using files instead of standard in/out.

 

            The data is preserved beyond the execution of your program. Data written by one program and be read from another. Programs can accept inputs from multiple external sources -- not just a single source. Data from a text file can be used in conjunction with input from the user.

 

 

2. Before you can write data to a text file, what three things need to be done? Explain what each is ... and show the corresponding C++ code

 

            • Include the fstream library                    #include <fstream.h>

            • Define a file varialble                             ofstream out;

            • Open the file for output                         out.open(“file.dat”);

 

 

 

3. Write the code to initialize array c so that each element has a value of zero:

 

            main()

            {

                        float c[101];

 

                        for (int k = 0; k < 101; ++k)

                                    c[k] = 0.0;

 

 

            }

 

 

4.Write a function to read in exactly 6 letters from the keyboard and store them in an array. Then, output the array in the reverse order.

 

            char array[7];             //provide 1 element for the ‘\0’

 

            cout <<“Please enter exactly 6 letters, followed by a newline”;

            cin.get(array,7,’\n’);

 

            for (int k=strlen(array)-1; k > 0; --k)

                        cout <<array[k]

 

5. Explain the difference between call by reference versus call by value. When would you use one over the other.

 

            Call by value makes a copy of the argument; therefore, within a function the argument passed by value is a local variable with an initial value of the function call’s argument.

 

            Call by references makes an alias between the argument and the function call’s argument. No local copy is made. Everytime the argument is used or stored in, it is the calling routine’s memory that is accessed.

 

            Use call by reference whenever modifying the contents of an argument and when you want to save memory from being duplicated unnecessarily.

 

 

 

 

 

 

 

 

 

 

 

 

6. What is the output for the following program?

 

            #include <iostream.h>

            main() {

                        void numbers(int  x, int & y);

                        int a,b,c;

 

                        a = 22;

                        b = 90;

                        c = 14;

 

                        numbers(a,a);

                        numbers(a,b);

                        numbers(b,a);

                        cout <<a <<"  " <<b  <<"  " <<c <<endl;

            }

                       

            void numbers (int x, int & y) {

                        int b;

                        x +=6;

                        y += 11;

                        b = 55;

                        cout <<b <<"  "  <<x <<"  " <<y <<endl;

                        }

 

Output:

     55 28 33

     55 39 101

     55 107 44

     44 101 14

 

 

7. Write a program that allows the user to type in up to 10 positive numbers and then echoes back the numbers typed in but in reverse order. Have the user terminate the list with a control D.

 

            int numbers[10];

            cout <<“Enter 10 numbers”

           

            for (int k=0; k<10; ++k)

                        cin >>numbers[k];

           

            for (int k=9; k>=0; --k)

                        cout <<numbers[k];

 

 

 

 

 

8. Show how you would read in an array of characters from the keyboard. Make sure that you don’t read more characters than there is room for in the array:

 

            char name[20];

 

 

            cin.get(name, 20, ‘\n’);

 

 

 

9. What is the difference between the following two statements:

 

            given:

                        char ch;         

 

            cin.get(ch);                Reads in the next character, even if it is whitespace

                                                and saves it in variable ch

versus

            cin >>ch;                   Skips leading whitespace and then reads in the first

                                                non-whitespace character, saving it into variable ch

 

 

 

10. Show how you would copy one array of characters into another, given:

 

            char original_name[20];

            char copied_name[20];

 

            simple way:

 

                                    strcpy(copied_name, original_name);

 

            longer way:

 

                                    int k = 0;

                                    while (original_name[k] != ‘\0’) {

                                                copied_name[k] = original_name[k];

                                                ++k;

                                    }

 

 

 

 

 

 

 

 

 

 

11. Write a function to concatenate one string of characters onto the end of another string of characters. Use the following function prototype:

 

            void concatenate(char combined_string[], char to_append[]);

 

            simple way:

                                    strcat(combined_string, to_append);

 

 

            longer way (this is what I would expect):

 

                        int k = 0;

                        //get to the end of th combined_string array

                        while (combined_string[k] != ‘\0’) {

                                                ++k;

                        }

 

                        //now add the “to_append” string to it:

                        int j = 0;

                        while (to_append[j] != ‘\0’) {

                                    combined_string[k] = to_append[j];

                                    ++k;

                                    ++j;

                        }

 

 

 

12. Write a function that sums together all the values supplied in an array of integers. Use the following function prototype:

 

            int sum_all(int values[], int count);

 

                        int total = 0;

                        for (int k = 0; k < count; ++k) {

                                    total += values[k];

                        }

           

                        return total;

13. Write a function that will compare the contents of two arrays and return a true if each of the elements matches (i.e., the first element in both arrays matches, the second element in both arrays matches with one another, etc.). If one of the elements doesn’t match in both arrays, return a false. Use the following function prototype:

 

            int match_array_elements(int array_1[], int array_2[], int size_1, int             size_2);

 

                        int same=1;               //initialize to true

 

                        //loop until we reach the end of the arrays or until the

                        //the arrays do not contain the same values

 

                        for (int k=0; k<size_1 && k <size_2 && same != 0; ++k) {

                                    if (array_1[k] == array_2[k])

                                                same = 1;                   //true

                                    else

                                                same = 0;                   //false

                        }

 

                        return same;

            }

 

14. Write the prototype for a function named pass that has two integer arguments. The first argument should be a value argument and the second a reference argument.

 

            void pass(int, int &);

 

15. Write a program to simulate a state police radar gun. The program should read an automobile speed and print the message “speeding” if the speed exceeds 55 mph.

 

            int speed=0;

 

            cout <<“Please enter the speed”;

            cin >> speed;

 

            if (speed > 55)

                        cout <<“Speeding” <<endl;

 

 

 

 

 

 

 

 

16. Write a loop that reads up to 10 integer values from a data file and displays them on the screen. If there are not 10 integers in the file, the message “That’s all folks” should be displayed after the last number.

 

            ifstream in;

            char filename[21];

            int count=10;

            int data;

 

            cout <<“Please enter a file name:”;

            cin >>filename;

 

            in.open(filename);

 

            in >> data;

            while (count > 0 && !in.eof()){

 

                        cout << data <<endl;         // echo integer values from data file

                        in >>data;                              //read in the next one

                        --count;                                  //decrement the counter

            }

           

            if (count != 0) //hit end of file prior to reading in 10 values

                        cout <<“That’s all folks” <<endl;

 

            in.close();