New User Special Price Expires in

Let's log you in.

Sign in with Facebook


Don't have a StudySoup account? Create one here!


Create a StudySoup account

Be part of our community, it's free to join!

Sign up with Facebook


Create your account
By creating an account you agree to StudySoup's terms and conditions and privacy policy

Already have a StudySoup account? Login here

Programming in C++ Reviews

by: MJ F.

Programming in C++ Reviews EECS 138

Marketplace > Kansas > Engineering and Tech > EECS 138 > Programming in C Reviews

Preview These Notes for FREE

Get a free preview of these Notes, just enter your email below.

Unlock Preview
Unlock Preview

Preview these materials now for free

Why put in your email? Get access to more of this material and other relevant free materials for your school

View Preview

About this Document

Here are some reviews for upper-level topics in C++ along with a comprehensive review for the semester. I also have some practice projects and sample codes but don't know how much interest there wo...
Programming in C++
c++, programming, reviews
75 ?




Popular in Programming in C++

Popular in Engineering and Tech

This 26 page Bundle was uploaded by MJ F. on Monday September 5, 2016. The Bundle belongs to EECS 138 at Kansas taught by in Fall 2016. Since its upload, it has received 10 views. For similar materials see Programming in C++ in Engineering and Tech at Kansas.

Similar to EECS 138 at KU

Popular in Engineering and Tech


Reviews for Programming in C++ Reviews


Report this Material


What is Karma?


Karma is the currency of StudySoup.

You can buy or earn more Karma at anytime and redeem it for class notes, study guides, flashcards, and more!

Date Created: 09/05/16
Score:_______ / 100 EECS 138 C++ Exam 2 Spring 2016 - Review Name: _________________________ KUID: _________________________ Instructor: _________________________ Class Time: _________________________ Write clearly, using pencil. You have 120 minutes to complete the exam. Unless stated otherwise, please write only the C++ code needed to answer the question, not a complete program. No electronic devices (cell phones, calculators, etc.) may be used during the exam! Before you begin, ensure your exam is complete. There should be 5 parts and 14 pages, including this one. ● Part 1 (Multiple Choice) consists of 5 questions (10 Points). ● Part 2 (Short Answer) consists of 8 questions (40 Points). ● Part 3 (Tracing) consists of 2 questions (14 Points). ● Part 4 (Functions) consists of 3 questions (20 Points). ● Part 5 (Program Writing) consists of 1 question (16 Points). There is a total of 19 questions. Academic Integrity: It is expected that the work you do on this exam is your own. Any instance of dishonesty will result in an immediate grade of zero on this exam, and a report of the incident will be sent to the dean’s office. Page 1 of 14 Part 1 – Multiple Choice (2 points each; 10 points total) Circle the most appropriate answer for each of the following questions. Questions with more than one answer circled will receive no credit. 1) Which of the following data types requi#include directive before it can be used? a) int b) long c) double d) vector e) None of the above 2) Which of the following is a valid array declaration and initialization? a) char x[ 3.0 ] = { 'a', 'b', 'c' }; b) int arr2[ '2' ] = { "0" }; c) double y[ 0 ] = { 1.5 }; d) string arr[ 2 ] = { "a", "b" }; e) None of the above 3) What is stored in the variable c after the following code is executed? string a = "KU"; string b = "Final" + " Four"; string c = b + " & " + a + " !!”; a) KU and Final Four !! b) Final Four + & + KU + !! c) KU Final Four d) Final Four and KU !! e) None of the above 4) Given that in is a input file variable and text a string variable. Which of the following can be used as a condition in a loop when reading the contents of a file? a) in >> text b) ! c) !in.eof() d) All of the above e) None of the above 5) Which of the following operations will never fail? a) connecting an output file stream to a file that already exists b) connecting an output file stream to a file that was already opened c) connecting an input file stream to a file that already exists d) connecting an input file stream to a file that was already opened e) All of the above Page 2 of 14 Part 2 – Short Answer (40 points total) 6) Write C++ statements to answer the following questions about a vector named list : (4 points) a) Declare the vector so that it can holdstring values. (2 points) b) Add three names of your choice to the vector. (1 point) c) What is the size of the vector at this point? (1 point) 7) Write code to do the following: (6 points) a) Declare a double array of size 10. (1 point) b) Using a loop and your answer from part a, set each element of the array to the cube of (its index+1). After the loop, the array will contain the values 1, 8, 27, …, 729, 1000. (5 points) Page 3 of 14 8) Consider the following pictorial representation ofa two-dimensional arrayalphabet . (6 points) a b c d e f g h i j K l m n o p q r s t U v w x y z a) Give a declaration for the aralphabet . (Remember alphabet is a two-dimensional array) (1 point) b) Because this is an array there are two interpretations of the term size, what are they? (2 points) c) What problems could arise from leaving the last 4 places in the last row empty (i.e., what happens when we try to refer one of those places)? (2 points) d) Write codethat accesses the elements of talphabet array which are bold and prints them to the screen. (1 point) 9) How are cin and ifstream similar? Where can they be used interchangeably; i.e what is the difference between using one versus the other? (2 points) Page 4 of 14 10) In the following code there are at least 6 errors. Identify all errors by circling where the error occurs and suggest the correction to make program work correctly. (6 points) #include <iostream> using namespace std; int main() { string todo[100]; ifstream list;; if( { int i = 1; while (!todo.eof()) list >> todo[i]; i++; } ofstream newList;"newTodoList.txt"); for (int i = 0; i <= 100; i++) newList << todo[i]; list.close(); newList.close("newTodoList.txt"); return 0; } 11) Describe two advantages of using vector variables instead of generic arrays. (2 points) Page 5 of 14 12) Using the declarations and initializations given below, evaluate each of the following expressions. (2 points each; 8 points total) string s1 = "Kansas", s2 = "Jayhawks"; double myArr[2] = {9.0,1.0}; int count = 15; char chArr[20][5]; chArr[10][0] =; = '!'; char letter = chArr[10][0]; Value a) s2.substr(1,5).length() < (count – s1.size()) _______________ b) s1.find('K') + s2.find('U') _______________ c) (myArr[1] + count) / s1.length() _______________ d) letter + "U " +[1]+s2.substr(5,3) _______________ 13) State whether the following statements are true or false. (2 points each; 6 points total) a) (T/F) In the following code, the if statement comparison will return a true boolean value. string str1 = "K"; vector<char> str2; str2.push_back('U'); if( < str1[0]) b) (T/F) If v is a vector of 100 strings, using the at( ) function instead of [ ] automatically resizes the vector when inserting values at a position greater than the vector size. Hence, the following will automatically expand the vector to be able to store 200 values with “Kansas” being at the last position: = "Kansas"; c) (T/F) If the user enters the s“Kansas beat North Carolina in the Elite Eight” on the command line and hits enter the following code would store the“Kansas beat UNC in the Final Four before” in the variable s1. string s1; cin >> s1; getline(cin, s1); s1.insert(0, "Kansas"); s1.replace(s1.find("North Carolina"), 14, "UNC"); s1 = s1.substr(0, s1.find("Elite Eight")) + "Final Four before"; Page 6 of 14 Part 3 – Tracing (14 points) For the following code fragments, show all output to the monitor. There are no intentional errors. 13) Trace this program (8 points) #include <iostream> using namespace std; void print(int arr[][3], int size); int main() { int a[4][3]; print(a,4); return 0; } void print(int arr[][3], int size) { for(int i = 0; i < size; i++) { for(int j = 0; j < 3; j++) { arr[i][j] = i + j; cout << " " << arr[i][j]; } cout << endl; } } Output: Page 7 of 14 14) Trace this program. (part of the output to the screen is given, fill in remaining output) (6 points) #include <iostream> #include <string> using namespace std; int main() { string a,b,c; cout<<"Enter a line of input for ‘a’ and hit return. Then enter a line of input for ‘b’ and hit return:\n "<<endl; getline(cin,a); cin >> b ; cout<<"\nEnter a line of input for ‘c’ and hit return:\n"; getline(cin,c,'?'); cout<<endl; cout<<"\nvariable a value is: "<< a; cout<<"\nvariable b value is: "<< b; cout<<"\nvariable c value is: "<< c; return 0; } Output: Enter a line of input for ‘a’and hit return. Then enter a line of input for ‘b’and hit return: Welcome to EECS 138 Hope you enjoy the semester. Enter a line of input for ‘c’and hit return: How are you doing today? Feeling Good? Page 8 of 14 Part 4 – Functions (20 points) 16) Given the function declaration below, write the definition for this function (6 points) bool positive_test(int array[][4], int row_size); //The function takes an integer two dimensional array, row_size and returns //true if all elements of the array are positive, false otherwise 17) Given the function declaration below, write the definition for this function (6 points) int binary_search(int array[], int size, int target); //Does a binary search for target element on an array of integers. Returns the //index of the element if found else returns -1 Page 9 of 14 18) You are given a file named “input.txt” which has few characters in upper case. Write code that will open this file and change the characters read to lowercase and write it to “output.txt”. The code should open the streams, check for failures, and close the stream when finished. Assume that the library cctype is included and you may use functions from that library (8 points) Page 10 of 14 Part 5 – Complete the Program (16 points total) 19) Write a complete program that performs the following operations:  Prompt the user for 10 integers and read the 10 integers and store them in an array named numbers of maximum size 10.  Write a function named Multiples that has numbers as its array argument. This function should check whether the each number in the array is a multiple of 2 and place all multiples of 2 in an array named multiples_of_two, or whether a number is a multiple of 5 and put all multiples of 5 in an array named multiples_of_five.  Write a function named output. This function takes in an array and a number-used as it’s arguments. This function will output the contents of the array to a screen. Start by writing the functions in (a), then move on to the main program and menu in (b): a) Write two functions Multiples and output. (write both function prototypes/declarations and function definitions) (9 Points Total) – 6 points for function Multiples, 3 points for function output. Hint for multiples function: void Multiples(int numbers[], int n1, int multiples_of_two[], int& n2, int multiples_of_three[], int& n3); //function declaration for Multiples //Function takes original array “numbers” along with its size n1 as parameters //Function checks for multiples of 2 and 3 and places them in the arrays //multiples_of_two and multiples_of_three accordingly. For this reason, both these //arrays along with their respective sizes n2 and n3 are also taken as arguments //n2 and n3 are call-by-reference parameters as these values will be determined //inside this function . Page 11 of 14 Additional space for Question 19 a: Page 12 of 14 b) Write the main program function using the two functions written in part a) (7 Points): (Even if you haven’t completed the functions yet – for this part you may assume that the two functions described above are given, as if they were predefined functions. It is not necessary to have part a completed for full credit on part b) You do not need to repeat any of the code you wrote for part a)  In your main function, follow this outline: o (1) First, declare the arrays necessary to represent the numbers, multiples of two, and multiples of five. o (2) Prompt the user for 10 integers and store them in the numbers array. o (2) Finally, make the appropriate function calls for the two options, checking whether it’s a multiple of two or a multiple of five, and output the multiples of two and the multiple of five array’s to the screen.  For option 1, Call theMultiples() function with the corresponding inputs.  For option 2, Call theoutput() function for the multiples of two array and the multiples of five array separately.. Page 13 of 14 Additional space for Question 19 b: Page 14 of 14     Score: __________ / 100       EECS 138 (C++) – Spring 2016  Final Exam (Review)          Name:  ________________________________________       KUID:  ________________________________________        Instructor:  ________________________________________       Class Time:  ________________________________________     Instructions:  Write clearly, using pencil. You have up to ​ 50​minutes to complete the exam. For  questions requiring code, do not write an entire program. Write only the code necessary to solve  the problem.     Before you begin, please ensure that your exam is complete. There should be 4 parts and 12  pages, including this one (10 pages with questions, one cover page, and one blank page at the  end).     ●  ​art 1 (Multiple Choice) consists of 5 questions worth 10 points total.  ●  Part 2 (Short Answer & Functions) consists of 9 questions worth 49 points total.  ●  ​art 3 (Tracing) consists of 3 questions worth 17 points total.  ●  ​art 4 (A Complete C++ Program) consists of 2 questions worth 24 points total.                     A note on academic integrity:  It is expected that any work you do on this exam is your own.  Any instance of dishonesty will result in an immediate grade of zero on the exam, and a report  of the incident will be sent to the appropriate dean’s office.    Part 1 – Multiple Choice (2 points each; 10 points total)  Circle the most appropriate answer for each of the following questions.  Questions with more  than one answer circled will receive no credit.     1) Whi​o a correct way to in​j of a cert​xm? lass e Assume all constructors have been defined.  a.xa ob(6,7);  b.xa ob()  c.xa oj;  d.xa ob1,ob2(6);     2) Which of the following is the correct syntax to define a Constructor for a   Cla​hpes?  a oi Shpe::haps(  {  /staemnt  }    b haes:Costrctr(  {  /staemnt  }    c haes:Shpe()  {  /staemnt  }    d Shapes()  {  //statements  }       3) Declaring nt vr;basically means:  a​The va​a is a pointer to a Integer value.  b  Performing operati​a is res​ icted.ble v c.toring the addresses of Integer type values is possible.  d.​oth (a) and (c).  e.othing . It is the same ntva. laring a variable i      1 of 11  4)Assume all of the functions h​as: een defined. Given this C Cas A  {  pblc:     nta;     oi st(ntva);//et al arale i tisclsstova.  pivte     ntb;     oulefrctondobl nm) /reunsfrctonofnu.  }     it ai()  {   oj; //anobec o cas Aisdeind er  /smesatmets    }  Which of the following is illegal in C++ ?  a​;  b bja  4;  d bjb  4  e None of the above.       5) What is the correct way  that will be oule to store d data types?  a​obl vasveto;  b oule*v= e vctr(;  c​eto(dube)v;  d ecordobl>v;  e​oblVeto()          2 of 11  Part 2 – Short Answer & Functions (49 points)  6)  Using the declarations and initializations given below, find the values for each of the  following exp 2 points each; 1  points total)   srig 1  “nierit”,s2= Knss”    dube yAr[ ={45,9., .6 0.};    it out  1;    carchrr5]10;    cAr[0[0 =s2at0)      Value      a  (1 = 2)&& s1legt()<=cont  ______________     b  s +″ f  + 1    ______________      c  s.a(5    ______________     d  mAr[3/2  ______________     e  cAr[0[0 ­   ______________     7)f you make all of a class’s member variables private, what must be done in order to retrieve  and set the value of thos2 points) s?  Why?  (           8)  Given the function declaration  vod cmpueAvrageintvales[);  write an overloaded version of this function w 2 points) rent set of parameters. ​        9)  True or1 point each; 4 points total)   a T /​hen defining (not declaring) a member function for a class, we can define it  using the same syntax as a non­member function.     b  T ​ifferent classes can have member functions with the same name.     c T /​ll constructors for a class must be private.     d  T ​ou assign an individual member of a struct using the dot operator.  3 of 11  10)  Given the following class definition:  cas Nube  {  pivte:    it mnu;  pblc:    Nmbe(it );    Nmbe()    it GtNmbr()  }  Nmbr::umer)  {  }  Nmbr::umerintn)  {    mnum= ;  }  it umbr:GeNumer)  {    rtur mnu;  }  a) Add a setter (mutator) membe​_um. oin s)or the variable m                   b) Add a member function ​_um(​points)  lue of m                           4 of 11  11)  Given the following string objects:       trig a= ″Bwar″;    trig b= ″o th″;    trig c= ″pog″    trig cant;  Write some code that will, usin​​​ anc store “Beware of the phog” in  the str​ant.  Remember to includ 4 Points)                12)  We want to implement a function that finds the numb​ out ways we can arrange k ofn things (in which order matters).  The formula for that is       P(n, k) =  n! / (n – k)!     This formula uses several factorial calcu​ermut(n,k) before the p function can be written, we should write a function that computes the factorial. The  factorial fu​ is defined as:        n! = factorial(n) = n * (n – 1) * (n – 2) * … * 1     a  Write a factoria​​4 points)                      b  Write a funermuten,k)​or computing the number of wayk of ordering ​ different things fr​ thinusing the factorial function you  efined in part a). (4 points)                   5 of 11  13)  Given the following t​udnt aDte  initions for S cas Prso  {  pivte    srig nme    Dtebirhdy;  pblc:    it etNme);    Dtegetirhdy(;    vidsetam(it)    vidsetirhdy(at);  }  cas Dte  {  pivte    it ont;    it ay;    it ear  pblc:    Dteint it,in);    Dte);  }     Write three consteron​la​1 point each; 3 point total)  b  Write the member functetNme gtNme stBrthay  angeBithay​1.5 points each; 6 points total)                       14)  Why do we normally declare a class’s member variables as private?  When would we  use private member functions vs ​4 points) er functions?​                      6 of 11  Part 3 – Tracing (17 points)  15)  Consider the class declaration below. Show all outputs of the following program.  There are no in.5 Points) rrors​ #ncud <otram  uin nmepcest;    cas Nmbr{  pivte     ntm_u;  pblc:     umerit );     umer)     ntge(;     oi stin n;  }  Nmbr:Nubr({     _nm  ;  }  Nmbr:Nubr(ntn)     _nm  ;  }  it umer:etumer){     etrnmnu;  }  vidNube:seNube(it ){  m_um= ;  }  it ai()  Nube nm15) nm(3, um;*;  cot < < nd;  nm3gt()/);  cot < < nd;    reur 0  }         7 of 11  16)  Show all outputs ofThere are no in​6 Points) rrors.   #ncud <otram  uin nmepcest;    it eceae it , nta ;    it ai(){//excuio sarshee     ou < a  "<<derese ,  )<<enl;     etrn0  }  it eceae it , nta  {     ou < n  "<<n <  a=" < a < nd;     f  n= 2)       reun ;     ls            a =n;       reun eceae(n  1  )+ ;       }                                              8 of 11  17)  Given the following program, show wha6 poi ts). displayed as output?  #nlue istem>  #nlue vctr  uig amsac td  vcorstig>srt(ecorsrig s;    itman(  / xeuio satshre    veto<trn> tins;    stinspuhbak"tst)    stinspuhbak"Tst)    stinspuhbak"h")      stins= otVsrigs;    reur ;  }      vcorstig>srt(ecorsrig s  {    bol ote;    stin em;    do    {       sred=tre       fr(iti  ;  <ssie)­;i+)                cot<<sati)< "v "< sati1)         if(.a()  sa(i1)         {            ou < : ede o eswppd;            ore =fas;            em  sati;            .a()  sa(i1;            .a(+1 =tmp         }         cot<<edl           } hie(!ote)    reur ;  }               9 of 11  Part 4 – A Complete C++ Program (24 points, 12 each)  18​Write a complete​ehicle(declarations and definitions) . The class should be able to  store these items:     • Model  • Color  • Year    Regarding the functionality, at the minimum each class must contain  • A Default Constructor, a constructor with 2 parameters, a constructor with 3 parameters  • Accessor functions for at least two member variables.  • Mutator functions for at least two member variables.  Make sure that the accessor and the mutator functions are declared and defined in the class.  Declare and define a ​isplay()which prints out the model, color and year of the car.    In the main function declare at least 2 obehicle. At least one of the  objects  should be initialized at the time of its declaration. Call the accessor and mutator  functions for both of the objects and make necessary changes to the variable. Call the  display() function on the two different objects and show how the outputs will be different or  the same for the two objects.                                                                10 of 11     19​rite a full program (starting from #include) that reads a text file specified by the user and  reports how many times each word occurred in the file.  Consider words with different cases of  character to be the same word (eg “Programming” and “prOgraMMing” would count as the same  word). The output should be formatted in two columns, with the words in the first column aligned  along the left side and the numbers in the second column aligned on their right side in a column  of width 5. You may assume the input file contains no punctuation marks. An example output is  shown below for the file "in.txt".        ntx:   oesar rd   ioes reble   tuyngisfu ndObec rintd rgrmmngto   la la bahbahblh lh la ba bahblh     utu:   oss    1    re     2   ed     1   ioes   2   lu     1   tuyng  1   s      1   un     1   nd     1   bjc    1   rined  1   rormmng1   oo     1   la     10            11 of 11 


Buy Material

Are you sure you want to buy this material for

75 Karma

Buy Material

BOOM! Enjoy Your Free Notes!

We've added these Notes to your profile, click here to view them now.


You're already Subscribed!

Looks like you've already subscribed to StudySoup, you won't need to purchase another subscription to get this material. To access this material simply click 'View Full Document'

Why people love StudySoup

Steve Martinelli UC Los Angeles

"There's no way I would have passed my Organic Chemistry class this semester without the notes and study guides I got from StudySoup."

Amaris Trozzo George Washington University

"I made $350 in just two days after posting my first study guide."

Bentley McCaw University of Florida

"I was shooting for a perfect 4.0 GPA this semester. Having StudySoup as a study aid was critical to helping me achieve my goal...and I nailed it!"


"Their 'Elite Notetakers' are making over $1,200/month in sales by creating high quality content that helps their classmates in a time of need."

Become an Elite Notetaker and start selling your notes online!

Refund Policy


All subscriptions to StudySoup are paid in full at the time of subscribing. To change your credit card information or to cancel your subscription, go to "Edit Settings". All credit card information will be available there. If you should decide to cancel your subscription, it will continue to be valid until the next payment period, as all payments for the current period were made in advance. For special circumstances, please email


StudySoup has more than 1 million course-specific study resources to help students study smarter. If you’re having trouble finding what you’re looking for, our customer support team can help you find what you need! Feel free to contact them here:

Recurring Subscriptions: If you have canceled your recurring subscription on the day of renewal and have not downloaded any documents, you may request a refund by submitting an email to

Satisfaction Guarantee: If you’re not satisfied with your subscription, you can contact us for further help. Contact must be made within 3 business days of your subscription purchase and your refund request will be subject for review.

Please Note: Refunds can never be provided more than 30 days after the initial purchase date regardless of your activity on the site.