Final Exam CS
Write program fragment to read filename from the user and open the file for writing. Show only relevant code, including includes.
#include <iostream> #include <fstream> #include <string> using namespace std; ofstream outFile; string fileName; cout << "Please input file name: "; cin >> fileName; outFile.open(fileName.c_str());
Write a program fragment to print a number of stars on a line, as instructed by the user. The fragment will ask user for the number of stars and then print them on a single line. Example: Give number of stars to start: 4 ****
#include <iostream> using namespace std; int main () { int numOfStars cout << "Enter number of stars (pick a number 1 -100): " << endl; cin >> numOfStars; if ( numOfStars < 1 || numOfStars > 100) cout <<"Out of given range, try again." return 0; }
Write a program fragment, using loop(s), to print all numbers that are divisible by 2 and 3, between 1 and 50 inclusive. Do not worry about spaces.
#include <iostream> using namespace std; int main() { for(int i = 1;i<=50;i++){ if(i%2==0 && i%3==0) { cout<<i<<endl; } return 0; }
[8] Write a complete program in C++ that lets the user enter 10 integer values into an array. The program should then display the data from the first to the last, and from the last to the first, on two different lines, separated by spaces.
#include using namespace std; int main() { const int SIZE = 10; int arr[SIZE]; for (int i = 0; i < SIZE; i++) { cin >> arr[i]; } for (int i = 0; i < SIZE; i++) { cout << arr[i] << ' '; } cout << endl; for (int i = SIZE-1; i >= 0; i--) { cout << arr[i] << ' '; } cout << endl; return 0; }
Write a complete program, using proper standards, to open a file called numbers.txt containing integer numbers separated by some white spaces. The program will display to the screen total of the numbers, and their average with 1 decimal digit, on two different lines. Make sure to read all numbers, and validate that the file was successfully opened and if not then display an error message and terminate the program.
#include<iostream> #include<iomanip> #include<fstream> using namespace std; int main() { ifstream fin("numbers.txt"); if (!ifstream) { cout << "Could not open file";return 1; } int data, sum=0, num=0;while (fin >> data) { sum+=data;num++; } cout << fixed << setprecision(1);cout << sum << endl << static_cast<double>(sum)/num;cout << endl; // could check if num != 0 fin.close(); return 0; }
Write a complete program that will ask the user how many sales amounts the user has. The program will then open the file txt, and will read all keyboard-entered sales and write them to the file, followed by sales total, separated by spaces. No validation of any sort needed. Sales are with dollars and cents. // Example run 1: Give the number of sales: 3 Give the 3 sales: 120.55 20.55 70.99 At the end, the above 3 sales followed by total 212.09 are written in the file sales.txt // Example run 2: Give the number of sales: 2 Give the 2 sales: 65.57 45.38 At the end, the above 2 sales followed by total 110.95 are written in the file sales.txt
#include<iostream>#include<fstream> using namespace std; int main() { //open the out put file ofstream outputFile; outputFile.open("sales.txt"); //prompt the user to enter the number of salescout<< "Give the number of sales:\t"; int num; cin>>num; //intialize sum to 0 double sum = 0; double temp = 0; //prompt the user to enter all the sales cout<< "Give the " << num << " sales :\t"; for(int i = 0;i < num;i++) { //store the number cin>>temp; //add the number to sum sum += temp; //write the number into output file outputFile << temp << " "; } //write the sum into output file outputFile << sum; //close the file outputFile.close();}
21. What is the last number printed out when the following fragment executes? int i = 4; while (i>0) { cout << i << endl; i--; }
1
What will the following program segment display? int funny = 7, serious = 15; funny = serious%2; if(funny!=1) { funny = 0; serious = 0; } else if (funny == 2) { funny = 10; serious = 10; } else { funny = 1; serious = 1; } cout << funny << serious << endl;
1 1
Answer the questions below concerning the following fragment of code. int x; cout << "Enter an integer: "; cin >> x; if (x > 10) cout << "Hello" << endl; else if (x < 10) cout << "Bonjour" << endl; else cout << "I am not sure" << endl; 1. What will be the output of the fragment above if the user enters the integer value 10? 2. What will be the output of the fragment above if the user enters the integer value 19? 3. What will be the output of the fragment above if the user enters the integer value -1?
1. "I am not sure" 2."Hello" 3."Bonjour"
What will get printed and how would you explain what is being printed? int x = 1; for (int i = 0; i < 5; i++) { x *= 3;cout << x <<endl; }
3, 9 , 27, 81, 243
What will get printed given the function definition and calls as shown. Add spaces for clarity. int c =1; // globalvoid wow() { int a=2; static int b =5; a++; b++;c++; cout << a << b << c; } and these calls: wow(); wow(); wow();
362, 373, 384 At first at compilation the variable c is created becasue it is a global variable. Then when you call wow() for the first time , locacl variable a will be created and assigned value 2. Then the static variable b will be created and assigned the value 5. Then a,b,c are incremented respectively so When you print a,b,c you will get a=3, b=6,c=2 When the function call over the local variable a will be vanished, the remaining variables stays. When you call it for the second time the local variable a gets created and assigned the value 2. When you increment a,b,c the values will be a=3, b=7,c=3 and these values will be printed. Then for the third time call, same local variable created then all three are incremented. The values printed will be a=3, b=8,c=4
19. What will the following code display? int number = 6; int x = 0; x = number--; cout << x << endl;5
5
What will the following code display?int number = 6int x = 0;x = --number;cout << x << endl;
5
18. What will the following code display? int number = 6; cout << number++ << endl;
6
17. What will the following code display? int number = 6; ++number; cout << number << endl;
7
What will the following segment of code output if 11 is entered at the keyboard? int number; cin>>number; if(number>0) cout<<"C++"; else cout<<"Soccer"; cout<<" is "; cout<<"fun"<<endl;
C++ is fun
11. Function prototypes are required in the language. (True / False)
FALSE
10. Which header file should be included to allow file access in a program?
FSTREAM
You must furnish an argument with a function call.
False
A for statement contains three expressions. What are those expressions?
Initialization, test, and update.
[2] Explain briefly why binary search is more efficient than linear search? What additional condition must be satisfied to replace linear search with binary search?
The linear search compares the target value with each element in the array. In the worst case, the search needs to go through the entire array to find the target element. The binary search cuts the unsearched area by half each time it compares the target value with an array element. The search time can be greatly reduced.
. [2] Is there a problem with the following code segment? If not, in detail, what are the consequences? int nums[10]; nums[10] = 100;
The second statement tries to assign value to a memory location outside of the boundary of the array. It could cause hard-to-detect corruption of data and possibly wrong program behavior.
14. What will happen if a program attempts to open a file, for writing, that does not exist.
The system will create an empty file of the specified name for writing, no error.
At the heart of a computer is its central processing unit. The CPU's job is:
To fetch instructions To carry out the operations commanded by the instructions To produce some outcome or resultant information
You may use the exit( ) function to terminate a program, regardless of which control mechanism is executing.
True
[1] True/False: Assume array1 and array2 are the names of arrays. To assign the contents of array2 to array1, you would use the following statement. array1 = array2; a) assuming this is array of integers b) assuming this is NTS string that is array of char with the end of the string marker
a) False b) False
Write a function definition for function named equals which takes 3 integers and returns true if sum of the first two arguments is greater than the third argument, and returns false otherwise. For example, equals(2,4,5) should return true because 2+4>5.
bool equals(int x, int y, int z) { return x+y>z; // short version }
Without this statement appearing in a switch construct, the program "falls through" all of the statements below the one with the matching case expression.
break
Write a statement so the variable payment is displayed in field 7 spaces wide, left justified, to at least 3 decimal places, with the decimal point always displayed
cout << left<< fixed << showpoint <<setprecision(3)<< setw(7) << payment<< endl;
To use the rand( ) function, you must #include this header file in your program.
cstdlib
13. The exit() function requires which library and how many parameters does it take
cstdlib , 1
Following programming standards, order the groups below the way they should be ordered in a file looking from the top to the bottom. a) Global variables/constants b) main function c) Function prototypes d) Include directives e) Additional functions
d, a, c, b, e
16. Write a program fragment, using loop(s), to print all numbers that are divisible by 6 between 1 and 1000, inclusive. Do not worry about spaces.
for (int x=1; x <= 1000; x++) if (x % 6 == 0) cout << x << endl;
________ reads a line of input, including leading and embedded spaces, and stores it in a string object.
getline
Assume that i, j and k are integer variables. Show the output produced by the following code fragment i = 4; j = 2; k = 1; i/ =j*= k+ = 3; cout<<"i="<< i<<" j="<<j<<" k="<<k<<endl;
i = 0, j = 8, k = 4
[2] Without specifying the total number of elements, declare and initialize an integer array numbers to store the sequence of numbers {1, 2, 3, 1, 5}
int numbers[] = {1, 2, 3, 1, 5};
[6] Write sum() function prototype and definition that returns the sum of a 2D array scores with 3 rows and 4 columns. The function receives the 2D array and also the number of rows in the array. Separately, show how to use the function to print the total from the array (assuming some initialization with numbers 0-100) to the screen.
int sum (int [][COLS], int rows); int sum(int arr[][COLS], int rows) { int total = 0; for (int r = 0; r < rows; r++) { for (int c = 0; c < COLS; c++) { total += arr[r][c]; } } return total; } cout << sum(scores,ROWS);
Repeat the above using overloaded function(s) instead of default arguments. Show separately prototype(s) and definition(s).
int sum(int a) ; int sum(int a, int b); int sum(int a, int b, int c); int sum(int a) { return a; } int sum(int a, int b) { return a+b; } int sum(int a, int b, int c) { return a+b+c; }
Write separately prototype and definition for function sum that can be used as shown (it adds its arguments and returns the summation, and it can be called with 1 arguments as well just returning the argument itself). Do it with default parameters. cout << sum(2) << sum(2,4) << sum(2,3,5); // will print 2 6 10 without spaces
int sum(int, int=0, int=0); int sum(int a, int b, int c) { return a+b+c; }
Which statement is equivalent to the following? number += 1;
number = number + 1;
What is the value stored at x in the following statements: int x; x = 3 / static_cast<int>(5.4 + 4.5);
o
To write data to a file, you define an object of this data type.
ofstream
When a variable is assigned a number that is too large for its data type, it:
overflows
A statement that starts with a # is called a:
preprocessor directive
Write a prototype and a definition of the function total that takes one integer parameter (number of items sold); two double parameters (price of item and sales tax rate) and returns total price of the purchase with tax. (NOTE: it is your responsibility to choose the return data type. (Just to give you an idea: if I call the function total for 10 items sold, 12 dollar price of the item and .03 tax, I would write the following code: total(10, 12, 0.03); )(Please use the back side of this page to answer)
prototype: double total (int, double, double); definition: double total(int n, double pricePerItem, double salesTax) { return (n*pricePerItem)*salesTax; }
This statement causes a function to end.
return
[5] Write a function that will take an array of names (each name is a string) and will return the smallest of the names (lexicographic order).
string findLowest(string arr[],int SIZE) { if (SIZE == 1) // this is not needed but looks nice return arr[0]; string lowest = arr[0]; for (int i = 1; i < SIZE; i++) { if (lowest > arr[i]) lowest = arr[i]; } return lowest; }
For the above, show the function call to swap two integers x and y.
swap(x,y);
Programmer-defined names of memory locations that may hold data are:
variables
[6] Now, using the same array as above, and assuming that the array has data on 3 students (the rows) taking 4 tests (the columns), write studentsAvg() function definition that will just print tests average for each of the 3 students. The function will receive the same data as above. For extra 2 points, print instead averages on the 4 tests rather than averages of the students.
void studentsAvg(int arr[][COLS], int rows) { int total; for (int r = 0; r < rows; r++) { total = 0; for (int c = 0; c < COLS; c++) { total += arr[r][c]; } cout << "Student " << r+1 << "avg= " << static_cast(total)/COLS << endl; } // for the extra, reverse the two loops and // divide by ROWS instead }
Write separately prototype and definition for a swap function to swap the values of its two integer parameters. The function does not need to return anything but the parameters need to swap values.
void swap(int &x, int &y); void swap(int &x,int &y) { int temp;temp = x;x = y;y = temp; }
Write a function test using if-else-if statements that tests the condition of a number range. If the integer number is between 1 and 3, including those numbers, it should display the message "Low". If the number is between 4 and 5, including those numbers, it should display the message, "High".
void test(int number) { if (number >= 1 && number <= 3) cout << "Low\n";else if (number >= 4 && number <= 5) cout << "High\n"; else cout << "Error\n";}
void test(int number) { if (number >= 1 && number <= 3) cout << "Low\n";else if (number >= 4 && number <= 5) cout << "High\n"; else cout << "Error\n";} SWITCH
void test(int number) { switch(number) { case 1: case 2: case 3: cout << "Low\n"; break; case 4: case 5: cout << "High\n"; break; default: cout << "Error\n"; } }