CS 115 Midterm 2 Solutions

Similar documents
CS 115 Midterm 2A Solutions

CS 115 Exam 2 Review Quiz

CS 115 Exam 2, Fall 2009

Functions, Arrays & Structs

CS 115 Midterm 2 Exam Review Quiz

CS 141, Introduction to Computer Science Fall Midterm Exam

Week 3. Function Definitions. Example: Function. Function Call, Return Statement. Functions & Arrays. Gaddis: Chapters 6 and 7.

Functions, Arrays & Structs

Week 3. Function Definitions. Example: Function. Function Call, Return Statement. Functions & Arrays. Gaddis: Chapters 6 and 7. CS 5301 Spring 2018

! Pass by value: when an argument is passed to a. ! It is implemented using variable initialization. ! Changes to the parameter in the function body

1) What of the following sets of values for A, B, C, and D would cause the string "one" to be printed?

Computer Department. Question (1): State whether each of the following is true or false. Question (2): Select the correct answer from the following:

Agenda. The main body and cout. Fundamental data types. Declarations and definitions. Control structures

The American University in Cairo Department of Computer Science & Engineering CSCI &09 Dr. KHALIL Exam-I Fall 2011

1- Write a single C++ statement that: A. Calculates the sum of the two integrates 11 and 12 and outputs the sum to the consol.

True or False (12 Points)

CSc Introduc/on to Compu/ng. Lecture 8 Edgardo Molina Fall 2011 City College of New York

True or False (15 Points)

5.1. Chapter 5: The Increment and Decrement Operators. The Increment and Decrement Operators. The Increment and Decrement Operators

CS 115 Midterm 2 Review Quiz

Introduction to Programming I COS1511 School of Computing Revision Notes

CSCI 1370 APRIL 26, 2017

Jordan University of Science & Technology Department of Computer Science CS 211 Exam #1 (23/10/2010) -- Form A

Tutorial 13 Salary Survey Application: Introducing One- Dimensional Arrays

CSCE Practice Midterm. Data Types

C++ Basics. Data Processing Course, I. Hrivnacova, IPN Orsay

Introduction to C++ 2. A Simple C++ Program. A C++ program consists of: a set of data & function definitions, and the main function (or driver)

Increment and the While. Class 15

Kingdom of Saudi Arabia Princes Nora bint Abdul Rahman University College of Computer Since and Information System CS242 ARRAYS

In this chapter you will learn:

Name SECTION: 12:45 2:20. True or False (12 Points)

Starting Out with C++: Early Objects, 9 th ed. (Gaddis, Walters & Muganda) Chapter 2 Introduction to C++ Chapter 2 Test 1 Key

Functions and Recursion

Lab Instructor : Jean Lai

C++ Programming: From Problem Analysis to Program Design, Third Edition

Do not turn to the next page until the start of the exam.

Unit 7. 'while' Loops

CPE 112 Spring 2015 Exam III (100 pts) April 8, True or False (12 Points)

BTE2313. Chapter 2: Introduction to C++ Programming

Programming Language. Functions. Eng. Anis Nazer First Semester

CMSC 202 Midterm Exam 1 Fall 2015

Linked List using a Sentinel

CSC 126 FINAL EXAMINATION Spring Total Possible TOTAL 100

C++ basics Getting started with, and Data Types.

Data Types (C/C++) Structures

Here, type declares the base type of the array, which is the type of each element in the array size defines how many elements the array will hold

Chapter 2: Basic Elements of C++

Objectives. Chapter 2: Basic Elements of C++ Introduction. Objectives (cont d.) A C++ Program (cont d.) A C++ Program

Chapter 2: Basic Elements of C++ Objectives. Objectives (cont d.) A C++ Program. Introduction

Creating a C++ Program

Topics. Functions. Functions

Introduction to Programming EC-105. Lecture 2

True or False (14 Points)

BITG 1233: Array (Part 1) LECTURE 8 (Sem 2, 17/18)

Object-oriented Programming for Automation & Robotics Carsten Gutwenger LS 11 Algorithm Engineering

Why Is Repetition Needed?

do { statements } while (condition);

Pointers, Dynamic Data, and Reference Types

Name MULTIPLE CHOICE. Choose the one alternative that best completes the statement or answers the question.

CS2255 HOMEWORK #1 Fall 2012

Problem Solving: Storyboards for User Interaction

A First Program - Greeting.cpp

CSCE Practice Midterm. Data Types

Programming. C++ Basics

2 nd Week Lecture Notes

CS 376b Computer Vision

CSCE121: Introduction to Program Design and Concepts Practice Questions for Midterm 3

Module 7 b. -Namespaces -Exceptions handling

CS Introduction to Programming Midterm Exam #2 - Prof. Reed Fall 2015

Lecture 23: Pointer Arithmetic

Array Elements as Function Parameters

BITG 1233: Introduction to C++

Review Problems for Final Exam. 1. What is the output of the following program? #include <iostream> #include <string> using namespace std;

Review of Important Topics in CS1600. Functions Arrays C-strings

CHAPTER 1.2 INTRODUCTION TO C++ PROGRAMMING. Dr. Shady Yehia Elmashad

Complex data types Structures Defined types Structures and functions Structures and pointers (Very) brief introduction to the STL

CS 115 Final Review Quiz

1. In C++, reserved words are the same as predefined identifiers. a. True

Lecture 4. 1 Statements: 2 Getting Started with C++: LESSON FOUR

Name Section: M/W or T/TH. True or False (14 Points)

Basic program The following is a basic program in C++; Basic C++ Source Code Compiler Object Code Linker (with libraries) Executable

Review Questions for Final Exam

Summary of basic C++-commands

Exceptions, Case Study-Exception handling in C++.

1. a) What #include statement do you put at the top of a program that does uses cin, cout or endl?

The sequence of steps to be performed in order to solve a problem by the computer is known as an algorithm.

READ THIS NOW! Do not start the test until instructed to do so!

! The address operator (&) returns the address of a. ! Pointer: a variable that stores the address of another

Fundamentals of Programming CS-110. Lecture 2

Computer Programming : C++

BITG 1113: Array (Part 1) LECTURE 8

Ch 6. Functions. Example: function calls function

Your first C++ program

By the end of this section you should: Understand what the variables are and why they are used. Use C++ built in data types to create program

Lab # 02. Basic Elements of C++ _ Part1

Tutorial Letter 103/1/2017 Introduction to Programming I

Understanding main() function Input/Output Streams

EECS402 Lecture 02. Functions. Function Prototype

ENGI 1020 Introduction to Computer Programming J U L Y 5, R E Z A S H A H I D I

Exam 2. CSI 201: Computer Science 1 Fall 2016 Professors: Shaun Ramsey and Kyle Wilson. Question Points Score Total: 80

Transcription:

CS115Midterm2Solutions April9,2009 Rules Youmustbrieflyexplainyouranswerstoreceivepartialcredit. Whenasnippetofcodeisgiventoyou,youcanassumethatthecodeis enclosedwithinsomefunction,evenifnofunctiondefinitionisshown.you canalsoassumethatthemainfunctionisproperlydefinedandthatthe iostream,fstream,iomanip,string,andcmathlibrarieshavebeen includedatthebeginningoftheprogram. Whenyouareaskedtowriteasnippetofcode,youmayalsoassumethatitis enclosedwithinsomefunctionthatanynecessarylibrarieshavebeen included. Whenyouareaskedtowriteacompleteprogram,youmustwritethe #includestatements,theint main(),etc.inyoursolutiontoreceivefull credit. Alineconsistingsolelyof representsoneormoreunspecifiedc++ statements,someofwhichmaychangethevaluesofprogramvariables. Youareencouragedtousethebacksofthesepagesforscratchpaper.Ifyou wantanswerswrittentheretobegraded,theymustbeveryclearlylabeled andalsonotedonthemaintest,e.g. Seethebackofpage1for3a. Page1of9

Problem1:15points. Whatistheoutputofeachofthefollowingsnippetsofcode? (a) Ifthefollowingfunctionisdefinedsomewhereintheprogramandprototyped abovemain. int my_function (int x, float array[]) { array[1] = 2.5; return x*2; whatdoesthefollowingcodeprint? Answer: 5 10 2.5 0.6 int x = 5; float a[3] = {0.2, 0.4, 0.6; int y = my_function(x, a); cout << x << endl; cout << y << endl; cout << a[1] << endl; cout << a[2] << endl; (b) for (int i=0; i < 2; i++) { for (int j=1; j < 3; j++) { cout << "i=" << i; cout << ", j=" << j << endl; Answer: i=0, j=1 i=0, j=2 i=1, j=1 i=1, j=2 Page2of9

Problem2:25points. Thesnippetsofcodeinthisproblemdonotsuccessfullyaccomplishthetask describedintheiraccompanyingcomments.correctthecodesothatitperforms thetaskdescribedinthecomment.eachsnippetmayhavemorethanoneerror. Makeyourcorrectionsclearandunambiguous. (a) /* Function that squares every element in an array of floats. Inputs are the array and its size. No return value.*/ float Square(float[] array) { for (i=0; i!= size; i++) { array[i] = i^2; Corrections: Return type should be void Brackets in function header should be moved: float array[] int size should be included as a function input The loop counter i should be declared as an int The loop test i!= size should be i < size We want to square each element of the array, and not the subscript i,, plus the ^ is not how we raise a number to a power. Should be array[i] = array[i] * array[i]; Corrected code: void Square(float array[]) { for (int i=0; i < size; i++) { array[i] = array[i] * array[i]; Page3of9

(b) /* Defines a struct named Student to hold a student s name, address, student ID number, and email */ struct { string Student.name, string Student.address, int Student.id, string Student.email Corrections: The struct needs a name Each field should have a semicolon at the end, rather than a comma Shouldn t use the. notation when we re defining the struct Definition needs a semicolon at end Corrected code: struct Student { string name; string address; int id; string email; ; Page4of9

(c) Assumethatthe2Darray int x[100][5] hasalreadybeendeclaredanddefined. /* Prints out all the elements of the 2D array X */ for (int i=0; i<=5; i++) { cout X[i][j]; Corrections: Loop test should be i < 5, not i <=5 Need an outer loop that starts at 0 and stops at 99 Need to print X[j][i] Need arrows in cout Corrected code: for (int j=0; j< 100; j++) { for (int i=0; i<=5; i++) { cout << X[j][i]; Problem3:30points. Writeshortsnippetsofcodetoaccomplishthefollowingtasks: (a) Foranarraythathasbeendeclaredas float floatarr[5][8]; writeasnippetofcodethatcomputesandprintsthetotalofallofthe elementsinthefirstcolumnofthearray. float sum = 0; for (int i=0; i<8; i++) { sum += floatarr[0][i]; cout << sum << endl; Page5of9

(b) WriteafunctioncalledAllEqualwhoseinputisanintegerarrayofsize10. Thefunctionshouldreturnaboolwhosevalueistrueifalloftheelements ofthearrayareequalandfalseotherwise. bool AllEqual(int array[]) { int element = array[0]; for (int i=1; i< 10; i++) { if (array[i]!= element) { return false; return true; (c) Writeasnippetofcodethat o Declaresanintegerarrayofsize10andinitializeseveryelementto thevalue0 o CallsAllEqual(yourfunctionfrompart(b))withthisarrayasinput o Printsthevaluereturnedbythefunctioncall. int array[10]; for (int i=0; i<10; i++) { array[i] = 0; cout << AllEqual(array); (d) WriteasnippetofcodethatdefinesastructcalledPersonwithfieldsfor aperson snameandage.thesefieldscanbeanyreasonabledatatype. struct Person { string name; int age; ; Page6of9

(e) WriteasnippetofcodethatdeclaresavariableoftypePerson(basedon yourcodefrompart(d))andinitializesthenametoyournameandtheageto whatever(plausible)ageyoulike. Person p; p.name = Suzanne Rivoire ; p.age = 21; // I wish (f) WriteasnippetofcodethatdefinesastructcalledFootballTeamwith fieldsfor: o Thenameoftheteam o Thenumberofplayerscurrentlyontheteam o Upto70players,eachoftypePerson (seeparts(e)and(f)) struct FootballTeam { string name; int num_players; Person players[70]; ; Page7of9

Problem4:30points. Forthisproblem,youmustwriteacompleteprogramthatcontainsthefollowing: AdefinitionfortheconstNUM_SKATERS,anintegerequalto80 ThedefinitionofastructcalledSkaterthathastwofields.Youshould decidetheappropriatedatatypesforthesefields: o name,thenameofafigureskater o score,theskater slatestscore,whichcouldbefractional PrototypeforafunctionnamedGetSkaterInfo,which o Requiresnoinput o ReturnsaSkater ThedefinitionofGetSkaterInfo.GetSkaterInfoshouldpromptthe usertotypein: o Thenameofa Skater o Ascoreforthat Skater ThefunctionshouldreturnaSkaterwiththenameandscoresuppliedby theuser. Amainfunctionthatdoesthefollowing: o DeclaresanarrayofNUM_SKATERS Skatervariables o Inaloop,callsGetSkaterInfotofillineachoftheelementsofthe array o Printsthenameandscoreofthefirstskaterinthearray [see next page] Page8of9

#include <iostream> using namespace std; const int NUM_SKATERS = 80; struct Skater { string name; float score; ; Skater GetSkaterInfo(); int main() { Skater s[num_skaters]; for (int i=0; i<num_skaters; i++) { s[i] = GetSkaterInfo(); cout << s[0].name << endl; cout << s[0].score << endl; return 0; Skater GetSkaterInfo() { Skater sk; cout << Name? << endl; cin >> sk.name; cout << Score? << endl; cin >> sk.score; return sk; Page9of9