Notes on the 2015 Exam
|
|
- Edward Greene
- 5 years ago
- Views:
Transcription
1 Notes on the 2015 Exam The stuff inside borders is all that you needed to write. The rest is commentary. Please also read notes on previous years exams especially the 2005 set of notes. Note that up to 2008 each question was worth 20 marks (for a total exam mark out of 80). So the relative marks per piece of solution will be very different. Question 1 (a) statistics 6 marks This required a sentinel controlled loop. Marks as follows 2 for while loop and its set up; 2 for all aspects of min; 2 for average. int main() { double tot = 0;//NB initialisation int count = 0;//NB initialisation int n, min; cin >> n; min = n;//nb while (n!= -9999) { tot = tot + n; count++; if (n < min) min = n; cin >> n; cout << endl; cout << min << " " << tot / count << endl; return 0; (b) polygon perimeter 15 marks This requires a counter controlled loop and a bit of attention to detail. First note that a polygon is a shape made from a series of connected straight lines of possibly varying lengths. The question implied that the sides of the polygon were not equal since it asked you to read in (x,y) coordinates of the n vertices. There were very few marks (5 of the 15) for reading two points, computing the length of that side, then multiplying by n! (In the 1E3 exam, every part of question 1 will require a loop!! Anything less than a loop is just too easy!) You needed to treat the first vertex differently, to use the loop to read all but the first one, and to keep the first one in mind till the end to close off the polygon. In the code below I
2 have not shown the code for the distance function, and you did not need to use a distance function you could just do the sum in the main program. Marks 3 for the counter controlled loop; 3 for computing distances correctly; 3 for computing the running total; 3 for moving the vertices along (xa = xb;); 3 for remembering the last edge. I penalized people who read in n pairs of vertices i.e. got the user to reenter every vertex twice, rather than remembering the second vertex of the previous edge. int main() { int n; double x1, y1, xa, ya, xb, yb, perimeter, length; cout << "This program computes the total distance between n successive (x, y) vertices."; cout << "Please first enter n: "; cin >> n; perimeter = 0; cout << "Now enter vertex 1:"; cin >> x1 >> y1; xa = x1; ya = y1; for (int i=2; i<=n; i++) { cout << "Now enter vertex " << i << ":"; cin >> xb >> yb; length = distance(xa, ya, xb, yb); cout << length << endl; perimeter = perimeter + length; //move on xa = xb; ya = yb; //Now add the final edge length = distance(xa, ya, x1, y1); cout << length << endl; perimeter = perimeter + length; cout << "The perimeter of that polygon is " << perimeter << endl; return 0; Note that this problem could be solved well using arrays. You would read into two arrays, and x array and a y array, and then work through the arrays computing edge
3 lengths. But its important to remember that you can t declare an array to be of a size not known at compile time, so you can not say cin >> n; double xs[n]; double ys[n]; Instead you have to assume there will never be more than say 100 vertices, and declare the arrays to be double xs[100] and then only use n of the slots. (c) Perfect numbers up to marks Nested for loop. The outer one handles each integer 1 to 500. The inner one works through integers looking for divisors of the current n. Note that you were asked to print out perfect numbers. Imperfect numbers should have been ignored so either you cout << n; or you don t. Nothing else. int main() { int n,i,sum; for (n=1; n<500; n++) { //test if n is perfect sum=0; // sum of divisors so far for (i=1;i<n;i++) { if (n%i==0) //if i is a divisor of n sum = sum + i; // add it on //end of looking for divisors of n if (n == sum) cout << n << " "; //end of testing numbers cout << endl; return 0; The most common error was setting sum to 0 at the start, but it has to be reset for each of the n s that we are testing for perfectness, so inside the outer for loop. This question can be done much more elegantly using functions but you were not penalized for not Q1 does not require you to write functions. The functions would be isafactor, isperfect, sumoffactors. See Q1cFNS2015.cpp linked from webpage. Question 2 (a)(i) 7 marks 1 mark for the declaration; 2 for the if statement; 4 for some loop that achieved the required effect. See notes from int gcd (int n1, int n2) { int i; //make i be the smaller of the two numbers if (n1 < n2) i = n1; else i = n2;
4 while (!((n1%i == 0) && (n2%i == 0))) //while i does not divide evenly into both n1 and n2 i--; //now i divides into both n1 and n2 return i; This solution is a direct translation of the suggested brute force algorithm and is an improvement of the gcd_better function provided in the solution to Practical 10. It depends on the fact that 1 will divide into any two integers, so that the while loop will stop when i is 1 without us having to explicitly tell it to do so. The WHILE loop says as long as it is not the case that i divides evenly into both n1 and n2, decrement i. The not is coded as!. The && means AND. Decrement means take 1 away from as in i--. An alternative formulation of this would be while ((n1%i!= 0) (n2%i!= 0)) i--; or as long as i does not divide n1 OR i does not divide n2, decrement i.. That the above WHILE loop is equivalent to the program above is an example of De Morgan s Law, which you may have heard of DeMorgan says NOT (A AND B) is equivalent to (NOT A) OR (NOT B). Many of you understandably used a FOR loop. The problem then is that you need to jump out of the FOR loop when you find a common divisor, or at least remember the highest one that you found. Remember that there can be many common divisors of two integers (e.g. 2, 3, 4, 6, 8, 12, and 24 are divisors of both 48 and 120) and we only want the highest one. Let s look at some alternatives using FOR loops. Assuming that n1 is the smaller of the numbers, and using /* i divides both */ as pseudocode for (!((n1%i == 0) && (n2%i == 0)))): here are some alternative solutions for (i = n1, i <= 1, i--) if (/* i divides both */) return i; The return jumps right out of the loop and out of the gcd function. for (i = n1, i <= 1, i--) if (/* i divides both */) {gcd = i; i = 0;
5 This one gets out of the loop by immediately setting i to 0, so that the (i<=1) terminating condition is made true. This fiddling with FOR loop control variables is not considered clean living and should be used sparingly. for (i = 1, i > n1, i++) if (/* i divides both */) gcd = i; This one works the other way, from 1 up towards n1. Each time it finds a common divisor it sets gcd to be that number. When the loop terminates the last common divisor encountered, which will be the biggest of them, will be in the gcd variable and can be returned. But if you return gcd as soon as you find it, inside the loop, you will be returning the least common divisor (which will be 1 always!). This was a common mistake. (a)(ii) 6 marks 2 marks for the declaration, especially the &s; 2 for calling gcd properly; 2 for updating n and d but not trying to return them. void simplify_fraction (int& n, int& d) { int g = gcd (n,d); n = n / g; d = d / g; return; (a)(iii) 5 marks int main() { int numer, denom; cout << "Enter your fraction's top and bottom:"; cin >> numer >> denom; simplify_fraction (numer, denom); cout << "\nthe simplest form of your fraction is "; cout << numer << "/" << denom << "\n"; return 0; This is all about knowing that you call simplify_fraction like that, then use the updated values of numer and denom after. To understand this you need to understand the &s in the definition of simplify_fraction. (b) (i) isprime 3 marks bool isprime(int n);
6 (ii) printnstars 5 marks 2 marks for the declaration; 2 for the for loop; 1 for the endl AFTER the loop. void printnstars (int n) { for (int i=1; i<=n; i++) cout << "*"; cout << endl; (iii) main 7 marks 1 mark for the header; 2 for the for loop; 1 for the call to printnstars; 3 for the whole IF stmt. int main() { for (int i=1; i<=5; i++) cout << " "; cout << endl; //test each int to 50 ; print if prime... for (int i=1; i<=50; i++) { if (isprime (i)){ printnstars(i); //else do nothing return 0; Question 3 (Question 2 in 2011) This question is testing your ability to use functions. Therefore there were marks for designing, declaring, defining, and calling functions properly. (a) close_enough 5 marks A very small bit of code (you were given the fn declaration) for 5 marks, but you had to test the right thing the absolute difference between x and y has to be smaller than precision. The caller of the function provides the very small number (precision) against which to test, so you should not mention or anything like it. bool close_enough (double x, y, precision) { return (fabs(x-y) < precision);
7 Because it was so easy, 1 mark was lost for nasty solutions that said if (fabs(x-y) < precision) return true; else return false; (b) newtonsqrt 15 marks You already knew how Newton s method for square roots works. This question challenged you to vary it a little. The close_enough function of part (a) was designed to help. You had to keep track of the previous and the new approximation, called old_approx and approx below, and keep going till these were close to each other (i.e. till there is little room for improvement of the approximation). Getting old_approx and approx started off, and then keeping them in sync was the key bit. If you didn t correctly maintain 2 versions of the approximation, you lost up to 7 marks. You were expected to use a function for improving approximations (better_approx). 2 marks off if you didn t. A loop is essential, so 4 marks went for the while line. No need for a main program. If you do provide one, make sure you call newton_sqrt properly! See Q3b2015.cpp for a full program that uses this function. double newtonsqrt(double n, double init, double precision) { double old_approx = init; double approx = better_approx(old_approx, n); while (!(close_enough (old_approx, approx, precision))) { old_approx = approx; approx = better_approx (old_approx,n); return approx; double better_approx (double x, double n) { return (n/x + x)/2; What s wrong with this version of the loop? while (!(close_enough (old_approx, approx, precision))) { approx = better_approx (old_approx,n); old_approx = approx; I got quite a few like this. It will never loop more than once. Simplifying a bit (this is wrong!!!) while (!(x == y)) { y = f(x); x = y;
8 If the last line inside a loop says give x the same value as y and then the loop test says while x is not equal to y the loop is definitely going to terminate immediately. For the same reason, you can t start old_approx and approx off as init they need to be different from one another. (c) Newton for f 13 marks The intention was that you would use the close_enough provided by 2(a), and the same loop structure as 2(b). But this was rarely done. You were expected to use functions for f, Df, and better_approx. In this case there is no n, so the Newton function, and better_approx don t have a parameter n. Otherwise, it s exactly like 2(b). Some people decided not to use any loop because I didn t specify how precise the approximation had to be. They lost marks, but these are not the people who failed! double newtonf(double init, double precision) { double old_approx = init; double approx = better_approx(old_approx); while (!(close_enough (old_approx, approx, precision))) { old_approx = approx; approx = better_approx (old_approx); return approx; double better_approx (double x) { return x - (f(x) / Df(x)); //close_enough as in 2(a). //The specific function and its derivative function double f (double x) {return x*x*x + 5*x - 3; double Df (double x) {return 3*x*x + 5; Question 4 This question required you to complete a program to index text that has been read into an array. We talked about this program in class.
9 (a) 3 marks The keyword const in this context says that the function will not / cannot alter the value of the array passed in as a or nums. It keeps the array values safe and tells the user of the function that an array passed in will not be affected. A function can normally alter the values of an array parameter a normal array parameter behaves like a call-by-reference parameter. To avoid that, you need to explicitly protect it using the const keyword. Your answer to this had to make clear that you understood that the const applied to an array, and to what the function could do. This const is not the same as the one used to declare constant values such as const double PI = (b) 7 marks int count (string s, const string a[], int size) { int n = 0; for (int i = 0; i < size; i++) if (a[i] == s) n++; return n; This didn t cause much difficulty. For each element of the array, using the parameter size to tell you how many elements there are, if the array entry is equal to the thing we are counting (the string s), add one to the counter. And start at 0! And return the counter. (c) 8 marks int maxpos (const int nums[], int size) { int i; int maxi=0;//slot of max so far is 0 for (i=1; i<size; i++) //start at 1 if (nums[i] > nums[maxi]) maxi = i; return maxi; This was a little trickier. You needed to distinguish between the biggest value seen so far, nums[maxi], and the slot containing the biggest value,
10 maxi. You need to return maxi, but you need to be comparing nums[maxi] against the current array entry, nums[i]. You might find it easier to store the biggest value seen so far at the same time as you update maxi: int maxi=0;//slot of max so far is 0 int maxvalue = nums[0]; for (i=1; i<size; i++) //start at 1 if (nums[i] > maxvalue) { maxi = i; maxvalue = nums[i]; return maxi; It s a queston of not comaring apples with oranges, not putting apples into containers for oranges! i and maxi are indexes into the array, and the function has to return one of these things. maxvalue and nums[i] are values in the array, and the function has to find (but not return) the biggest of these. (d) 15 marks int counts [NUMTERMS];//holds a count for each terms in terms int i; //no need to initialize the counts, as the next for loop assigns some //value to every slot of the array. But no harm to initialize either. //count index terms for (i=0; i< NUMTERMS; i++) counts[i] = count (terms[i], text, numwords); //output counts for (i=0; i< NUMTERMS; i++) if (counts[i] > 2) { cout << setw(15) << left << terms[i]; cout << setw(4) << right << counts[i] << endl; //determine most common term int max = maxpos (counts, NUMTERMS); string topterm = terms[max];
11 This wasn t much code for 15 marks. But you needed to pay attention. The array needed here is for storing counters for each term we want to count, i.e. each term in the terms array it is declared as string terms [NUMTERMS]. So we need NUMTERMS counters. (2 marks for the array declaration). Then we need to arrange to use the count function to get the appropriate counter and store it in the counts array the count of terms[i] term goes in the counts[i] slot. (3 marks for that for loop). To call count, pay attention to what each parameter is the first one is a string in this case a term from the terms array. The second parameter is where we want to look for the string, our text. And the final parameter is the number of words in that text, that is the value assigned to numwords by the call to readtosentinel at the top fo the program note the & beside the third parameter of readtosentinel s declaration. Then we need to print out the terms and their counters easy enough (4 mark). Finally, and many of you missed this, we need to USE THE maxpos FUNCTION to find the position of the largest counter, and then get the corresponding term stored in topterm, ready for the last line of the program (not shown above). (4 marks, you missed 2 if you didn t use the maxpos function!) Other Miscellaneous Comments that I noted while grading in They are all very useful to you if you are repeating 1E3: Sentinel Controlled Loops Template is cin >> x; while (x!= ) { *** cin > x; Where the *** are you put all processing of the current valid x. The processing of x must all be inside the loop. I had many examples of cin >> x;
12 while (x!= ) { cin > x; tot = tot+x; //wrong more stuff on x.//wrong But those last two lines must be inside the loop, before the cin > x statement. Obviously instead of x, you might have studentno or code or n or whatever it is that you are reading that will eventually be the sentinel instead of a valid value. Many people used the above template (with ***s in it or in it!!!!) every time they thought a while loop was needed. The template is ONLY for SENTINEL CONTROLLED input. Functions Many of these comments or similar appear in Notes for 2005 exam. Local variables and accessing a function s value: If a function looks like this int f(int x) { int ans; ans = x; return ans; you can t do this z = 4; f(z); cout << ans; // wrong ans here is not related to f s ans and expect it to print the value of f(z) ans only has meaning inside f. Even if you declared ans in the calling program, that would be a separate variable from the one f uses, which is a local variable whose scope in the function f. The calling program has no access to f s ans. The correct way to call f and use the value it returns is: or cout << f(z); int x = f(z); //now use or print x
13 Accessing parameters: With the following declaration of f int f(int x, int y) the body of f has access to variables called x and y, and the values in there are the ones provided by the calling function. Therefore, f should not redeclare these variables read values for these variable initialize these variables So more than likely these are all wrong: int f(int x, int y) { int x, y; //creates new local variables x and y which //effectively hides the ones passed in as parameters int f(int x, int y) { cin >> x >> y; //if it succeeds in reading data it will replace // the values the calling function provided. int f(int x, int y) { y=0; //if the calling function provides f with a value for y //f should use it!! Not replace it. And, unrelated to parameters, but the f declared above should not print any values, but must return its answer. So NOT int f(int x, int y) { cout << (x*y)/2; return 0; but probably something like int f(int x, int y) { return (x*y)/2; Good luck!
Notes on the 2008 Exam
Notes on the 2008 Exam A hastily compiled review of this year s exam. Apologies if there are errors. Please also read notes on previous years exams especially the first set of notes. Question 1 Question
More informationUniversity of Dublin
University of Dublin TRINITY COLLEGE Faculty of Enginering & Systems Sciences School of Engineering Junior Freshman Engineering Trinity Term 2015 Computer Engineering I (1E3) Date Location Time Dr L. Hederman
More informationNotes on the 2009 Exam
Notes on the 2009 Exam A hastily compiled review of this year s exam. Apologies if there are errors. The stuff inside borders is all that you needed to write. The rest is commentary. Please also read notes
More informationNotes on the 2016 Exam
Notes on the 2016 Exam The stuff inside borders is all that you needed to write. The rest is commentary. Please also read notes on previous years exams especially the 2005 set of notes. Note that up to
More informationComputer Programming. Basic Control Flow - Loops. Adapted from C++ for Everyone and Big C++ by Cay Horstmann, John Wiley & Sons
Computer Programming Basic Control Flow - Loops Adapted from C++ for Everyone and Big C++ by Cay Horstmann, John Wiley & Sons Objectives To learn about the three types of loops: while for do To avoid infinite
More informationArrays in Functions!
Arrays in Functions! 1E3! Topic 12! 12 Arrays in Functions 1 Objectives! n This topic should allow students to! n Pass array elements to functions! n Pass whole arrays to functions! n Write functions that
More informationChapter 4. Procedural Abstraction and Functions That Return a Value. Copyright 2014 Pearson Addison-Wesley. All rights reserved.
Chapter 4 Procedural Abstraction and Functions That Return a Value 1 Overview 4.1 Top-Down Design 4.2 Predefined Functions 4.3 Programmer-Defined Functions 4.4 Procedural Abstraction 4.5 Local Variables
More informationBasic memory model Using functions Writing functions. Basics Prototypes Parameters Return types Functions and memory Names and namespaces
Basic memory model Using functions Writing functions Basics Prototypes Parameters Return types Functions and memory Names and namespaces When a program runs it requires main memory (RAM) space for Program
More informationChapter 5. Repetition. Contents. Introduction. Three Types of Program Control. Two Types of Repetition. Three Syntax Structures for Looping in C++
Repetition Contents 1 Repetition 1.1 Introduction 1.2 Three Types of Program Control Chapter 5 Introduction 1.3 Two Types of Repetition 1.4 Three Structures for Looping in C++ 1.5 The while Control Structure
More informationChapter Four: Loops. Slides by Evan Gallagher. C++ for Everyone by Cay Horstmann Copyright 2012 by John Wiley & Sons. All rights reserved
Chapter Four: Loops Slides by Evan Gallagher The Three Loops in C++ C++ has these three looping statements: while for do The while Loop while (condition) { statements } The condition is some kind of test
More informationREPETITION CONTROL STRUCTURE LOGO
CSC 128: FUNDAMENTALS OF COMPUTER PROBLEM SOLVING REPETITION CONTROL STRUCTURE 1 Contents 1 Introduction 2 for loop 3 while loop 4 do while loop 2 Introduction It is used when a statement or a block of
More information5. Control Statements
5. Control Statements This section of the course will introduce you to the major control statements in C++. These control statements are used to specify the branching in an algorithm/recipe. Control statements
More information(Refer Slide Time: 00:26)
Programming, Data Structures and Algorithms Prof. Shankar Balachandran Department of Computer Science and Engineering Indian Institute Technology, Madras Module 07 Lecture 07 Contents Repetitive statements
More informationChapter Four: Loops II
Chapter Four: Loops II Slides by Evan Gallagher & Nikolay Kirov Chapter Goals To understand nested loops To implement programs that read and process data sets To use a computer for simulations Processing
More informationIslamic University of Gaza Computer Engineering Dept. C++ Programming. For Industrial And Electrical Engineering By Instructor: Ruba A.
Islamic University of Gaza Computer Engineering Dept. C++ Programming For Industrial And Electrical Engineering By Instructor: Ruba A. Salamh Chapter Four: Loops 2 Chapter Goals To implement while, for
More informationWeek 2. Relational Operators. Block or compound statement. if/else. Branching & Looping. Gaddis: Chapters 4 & 5. CS 5301 Spring 2018.
Week 2 Branching & Looping Gaddis: Chapters 4 & 5 CS 5301 Spring 2018 Jill Seaman 1 Relational Operators l relational operators (result is bool): == Equal to (do not use =)!= Not equal to > Greater than
More informationLecture 7: General Loops (Chapter 7)
CS 101: Computer Programming and Utilization Jul-Nov 2017 Umesh Bellur (cs101@cse.iitb.ac.in) Lecture 7: General Loops (Chapter 7) The Need for a More General Loop Read marks of students from the keyboard
More informationLOOPS. Repetition using the while statement
1 LOOPS Loops are an extremely useful feature in any programming language. They allow you to direct the computer to execute certain statements more than once. In Python, there are two kinds of loops: while
More information5.1. Chapter 5: The Increment and Decrement Operators. The Increment and Decrement Operators. Looping. ++ is the increment operator.
Chapter 5: Looping 5.1 The Increment and Decrement Operators Copyright 2009 Pearson Education, Inc. Copyright Publishing as Pearson 2009 Addison-Wesley Pearson Education, Inc. Publishing as Pearson Addison-Wesley
More informationThe American University in Cairo Computer Science & Engineering Department CSCE Dr. KHALIL Exam II Spring 2010
The American University in Cairo Computer Science & Engineering Department CSCE 106-08 Dr. KHALIL Exam II Spring 2010 Last Name :... ID:... First Name:... Form - I EXAMINATION INSTRUCTIONS * Do not turn
More informationChapter 3. More Flow of Control. Copyright 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Chapter 3 More Flow of Control Overview 3.1 Using Boolean Expressions 3.2 Multiway Branches 3.3 More about C++ Loop Statements 3.4 Designing Loops Slide 3-3 Flow Of Control Flow of control refers to the
More informationIntroduction. C provides two styles of flow control:
Introduction C provides two styles of flow control: Branching Looping Branching is deciding what actions to take and looping is deciding how many times to take a certain action. Branching constructs: if
More informationCSE 142 Su 04 Computer Programming 1 - Java. Objects
Objects Objects have state and behavior. State is maintained in instance variables which live as long as the object does. Behavior is implemented in methods, which can be called by other objects to request
More informationLoops / Repetition Statements
Loops / Repetition Statements Repetition statements allow us to execute a statement multiple times Often they are referred to as loops C has three kinds of repetition statements: the while loop the for
More information5.1. Chapter 5: The Increment and Decrement Operators. The Increment and Decrement Operators. The Increment and Decrement Operators
Chapter 5: 5.1 Looping The Increment and Decrement Operators The Increment and Decrement Operators The Increment and Decrement Operators ++ is the increment operator. It adds one to a variable. val++;
More informationC++ for Everyone, 2e, Cay Horstmann, Copyright 2012 John Wiley and Sons, Inc. All rights reserved. Using a Debugger WE5.
Using a Debugger WE5 W o r k E D E x a m p l e 5.2 Using a Debugger As you have undoubtedly realized by now, computer programs rarely run perfectly the first time. At times, it can be quite frustrating
More informationLooping. Arizona State University 1
Looping CSE100 Principles of Programming with C++, Fall 2018 (based off Chapter 5 slides by Pearson) Ryan Dougherty Arizona State University http://www.public.asu.edu/~redoughe/ Arizona State University
More informationMultiple Choice (Questions 1 13) 26 Points Select all correct answers (multiple correct answers are possible)
Name Closed notes, book and neighbor. If you have any questions ask them. Notes: Segment of code necessary C++ statements to perform the action described not a complete program Program a complete C++ program
More informationQuiz Determine the output of the following program:
Quiz Determine the output of the following program: 1 Structured Programming Using C++ Lecture 4 : Loops & Iterations Dr. Amal Khalifa Dr. Amal Khalifa - Spring 2012 1 Lecture Contents: Loops While do-while
More informationModule 10A Lecture - 20 What is a function? Why use functions Example: power (base, n)
Programming, Data Structures and Algorithms Prof. Shankar Balachandran Department of Computer Science and Engineering Indian Institute of Technology, Madras Module 10A Lecture - 20 What is a function?
More informationGetting started with C++ (Part 2)
Getting started with C++ (Part 2) CS427: Elements of Software Engineering Lecture 2.2 11am, 16 Jan 2012 CS427 Getting started with C++ (Part 2) 1/22 Outline 1 Recall from last week... 2 Recall: Output
More informationCS1100 Introduction to Programming
Decisions with Variables CS1100 Introduction to Programming Selection Statements Madhu Mutyam Department of Computer Science and Engineering Indian Institute of Technology Madras Course Material SD, SB,
More informationLab Instructor : Jean Lai
Lab Instructor : Jean Lai Group related statements to perform a specific task. Structure the program (No duplicate codes!) Must be declared before used. Can be invoked (called) as any number of times.
More informationChapter 3 - Functions
Chapter 3 - Functions 1 Outline 3.1 Introduction 3.2 Program Components in C++ 3.3 Math Library Functions 3.4 Functions 3.5 Function Definitions 3.6 Function Prototypes 3.7 Header Files 3.8 Random Number
More information*Starting Out with C++: From Control Structures through Objects, 7/E* by *Tony Gaddis* COMPUTER PROGRAMMING LECTURE 05 LOOPS IMRAN IHSAN
PowerPoint Slides adapted from *Starting Out with C++: From Control Structures through Objects, 7/E* by *Tony Gaddis* Copyright 2012 Pearson Education Inc. COMPUTER PROGRAMMING LECTURE 05 LOOPS IMRAN IHSAN
More informationc++ keywords: ( all lowercase ) Note: cin and cout are NOT keywords.
Chapter 1 File Extensions: Source code (cpp), Object code (obj), and Executable code (exe). Preprocessor processes directives and produces modified source Compiler takes modified source and produces object
More informationTotal 100. The American University in Cairo Computer Science & Engineering Department CSCE 106. Instructor: Final Exam Fall Section No.
The American University in Cairo Computer Science & Engineering Department CSCE 106 Instructor: Final Exam Fall 2010 Last Name :... ID:... First Name:... Section No.: EXAMINATION INSTRUCTIONS * Do not
More informationFOR loops! Objectives! 1E3! Topic 7! n To be able to write a FOR statement! n To be able to predict what a given FOR statement will do.!
FOR loops! 1E3! Topic 7! 7 FOR Loops 1 Objectives! n To be able to write a FOR statement! n To be able to predict what a given FOR statement will do.! n To recognise when a FOR loop is appropriate! n To
More informationPost Experiment Interview Questions
Post Experiment Interview Questions Questions about the Maximum Problem 1. What is this problem statement asking? 2. What is meant by positive integers? 3. What does it mean by the user entering valid
More informationComputer Department. Question (1): State whether each of the following is true or false. Question (2): Select the correct answer from the following:
Computer Department Program: Computer Midterm Exam Date : 19/11/2016 Major: Information & communication technology 1 st Semester Time : 1 hr (10:00 11:00) Course: Introduction to Programming 2016/2017
More informationCSCE Practice Midterm. Data Types
CSCE 2004 - Practice Midterm This midterm exam was given in class several years ago. Work each of the following questions on your own. Once you are done, check your answers. For any questions whose answers
More information8. Control statements
8. Control statements A simple C++ statement is each of the individual instructions of a program, like the variable declarations and expressions seen in previous sections. They always end with a semicolon
More informationC++ Programming: From Problem Analysis to Program Design, Fourth Edition. Chapter 5: Control Structures II (Repetition)
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 5: Control Structures II (Repetition) Objectives In this chapter, you will: Learn about repetition (looping) control structures
More informationECE15: Introduction to Computer Programming Using the C Language. Lecture Unit 4: Flow of Control
ECE15: Introduction to Computer Programming Using the C Language Lecture Unit 4: Flow of Control Outline of this Lecture Examples of Statements in C Conditional Statements The if-else Conditional Statement
More informationRepe$$on CSC 121 Fall 2015 Howard Rosenthal
Repe$$on CSC 121 Fall 2015 Howard Rosenthal Lesson Goals Learn the following three repetition methods, their similarities and differences, and how to avoid common errors when using them: while do-while
More informationFunctions that Return a Value. Approximate completion time Pre-lab Reading Assignment 20 min. 92
L E S S O N S E T 6.2 Functions that Return a Value PURPOSE PROCEDURE 1. To introduce the concept of scope 2. To understand the difference between static, local and global variables 3. To introduce the
More informationMultiple Choice (Questions 1 13) 26 Points Select all correct answers (multiple correct answers are possible)
Name Closed notes, book and neighbor. If you have any questions ask them. Notes: Segment of code necessary C++ statements to perform the action described not a complete program Program a complete C++ program
More informationCS 142 Style Guide Grading and Details
CS 142 Style Guide Grading and Details In the English language, there are many different ways to convey a message or idea: some ways are acceptable, whereas others are not. Similarly, there are acceptable
More informationLoops! Loops! Loops! Lecture 5 COP 3014 Fall September 25, 2017
Loops! Loops! Loops! Lecture 5 COP 3014 Fall 2017 September 25, 2017 Repetition Statements Repetition statements are called loops, and are used to repeat the same code mulitple times in succession. The
More informationIron County Schools. Yes! Less than 90 No! 90 No! More than 90. angle: an angle is made where two straight lines cross or meet each other at a point.
Iron County Schools 1 acute angle: any angle that is less than 90. Yes! Less than 90 No! 90 No! More than 90 acute triangle: a triangle where all the angles are less than 90 angle: an angle is made where
More informationRepe$$on CSC 121 Spring 2017 Howard Rosenthal
Repe$$on CSC 121 Spring 2017 Howard Rosenthal Lesson Goals Learn the following three repetition structures in Java, their syntax, their similarities and differences, and how to avoid common errors when
More informationVariables and Constants
HOUR 3 Variables and Constants Programs need a way to store the data they use. Variables and constants offer various ways to work with numbers and other values. In this hour you learn: How to declare and
More informationLECTURE 5 Control Structures Part 2
LECTURE 5 Control Structures Part 2 REPETITION STATEMENTS Repetition statements are called loops, and are used to repeat the same code multiple times in succession. The number of repetitions is based on
More informationCS 007A Midterm 1 Practice Chapters 1 5
CS 007A Midterm 1 Practice Chapters 1 5 1. Consider the 4 bytes stored in contiguous memory, as shown to the right. a. Determine the decimal representation of these 4 one-byte integers: b. Determine the
More informationC++ Programming Lecture 1 Software Engineering Group
C++ Programming Lecture 1 Software Engineering Group Philipp D. Schubert Contents 1. More on data types 2. Expressions 3. Const & Constexpr 4. Statements 5. Control flow 6. Recap More on datatypes: build-in
More informationdo { statements } while (condition);
Topic 4 1. The while loop 2. Problem solving: hand-tracing 3. The for loop 4. The do loop 5. Processing input 6. Problem solving: storyboards 7. Common loop algorithms 8. Nested loops 9. Problem solving:
More informationTotal 100. The American University in Cairo Computer Science & Engineering Department CSCE 106. Dr. Khalil Exam II Fall 2011
The American University in Cairo Computer Science & Engineering Department CSCE 106 Dr. Khalil Exam II Fall 2011 Last Name :... ID:... First Name:... Form I Section No.: ( ) EXAMINATION INSTRUCTIONS *
More informationConverting Between Mixed Numbers & Improper Fractions
01 Converting Between Mixed Numbers & Improper Fractions A mixed number is a whole number and a fraction: 4 1 2 An improper fraction is a fraction with a larger numerator than denominator: 9 2 You can
More informationCPE 112 Spring 2015 Exam II (100 pts) March 4, Definition Matching (8 Points)
Name Definition Matching (8 Points) 1. (8 pts) Match the words with their definitions. Choose the best definition for each word. Relational Expression Iteration Counter Count-controlled loop Loop Flow
More informationChapter 5: Loops and Files
Chapter 5: Loops and Files 5.1 The Increment and Decrement Operators The Increment and Decrement Operators ++ is the increment operator. It adds one to a variable. val++; is the same as val = val + 1;
More informationThe American University in Cairo Department of Computer Science & Engineering CSCI &09 Dr. KHALIL Exam-I Fall 2011
The American University in Cairo Department of Computer Science & Engineering CSCI 106-07&09 Dr. KHALIL Exam-I Fall 2011 Last Name :... ID:... First Name:... Form I Section No.: EXAMINATION INSTRUCTIONS
More informationDiscussion 1H Notes (Week 3, April 14) TA: Brian Choi Section Webpage:
Discussion 1H Notes (Week 3, April 14) TA: Brian Choi (schoi@cs.ucla.edu) Section Webpage: http://www.cs.ucla.edu/~schoi/cs31 More on Arithmetic Expressions The following two are equivalent:! x = x + 5;
More informationUNIT- 3 Introduction to C++
UNIT- 3 Introduction to C++ C++ Character Sets: Letters A-Z, a-z Digits 0-9 Special Symbols Space + - * / ^ \ ( ) [ ] =!= . $, ; : %! &? _ # = @ White Spaces Blank spaces, horizontal tab, carriage
More informationCIS 130 Exam #2 Review Suggestions
CIS 130 - Exam #2 Review Suggestions p. 1 * last modified: 11-11-05, 12:32 am CIS 130 Exam #2 Review Suggestions * remember: YOU ARE RESPONSIBLE for course reading, lectures/labs, and especially anything
More informationChapter 5: Prefix vs. Postfix 8/19/2018. The Increment and Decrement Operators. Increment and Decrement Operators in Program 5-1
Chapter 5: Loops and Files The Increment and Decrement Operators ++ is the increment operator. It adds one to a variable. val++; is the same as val = val + 1; ++ can be used before (prefix) or after (postfix)
More informationChapter Overview. More Flow of Control. Flow Of Control. Using Boolean Expressions. Using Boolean Expressions. Evaluating Boolean Expressions
Chapter 3 More Flow of Control Overview 3.1 Using Boolean Expressions 3.2 Multiway Branches 3.3 More about C++ Loop Statements 3.4 Designing Loops Copyright 2011 Pearson Addison-Wesley. All rights reserved.
More information3 The L oop Control Structure
3 The L oop Control Structure Loops The while Loop Tips and Traps More Operators The for Loop Nesting of Loops Multiple Initialisations in the for Loop The Odd Loop The break Statement The continue Statement
More informationUnit 7. 'while' Loops
1 Unit 7 'while' Loops 2 Control Structures We need ways of making decisions in our program To repeat code until we want it to stop To only execute certain code if a condition is true To execute one segment
More informationThe American University in Cairo Computer Science & Engineering Department CSCE 106 Fundamentals of Computer Science
The American University in Cairo Computer Science & Engineering Department CSCE 106 Fundamentals of Computer Science Instructor: Dr. Khalil Final Exam Fall 2013 Last Name :... ID:... First Name:... Form
More informationCHAPTER 4 FUNCTIONS. 4.1 Introduction
CHAPTER 4 FUNCTIONS 4.1 Introduction Functions are the building blocks of C++ programs. Functions are also the executable segments in a program. The starting point for the execution of a program is main
More informationCS112 Lecture: Repetition Statements
CS112 Lecture: Repetition Statements Objectives: Last revised 2/18/05 1. To explain the general form of the java while loop 2. To introduce and motivate the java do.. while loop 3. To explain the general
More informationProgramming in C++ Prof. Partha Pratim Das Department of Computer Science and Engineering Indian Institute of Technology, Kharagpur
Programming in C++ Prof. Partha Pratim Das Department of Computer Science and Engineering Indian Institute of Technology, Kharagpur Lecture - 08 Constants and Inline Functions Welcome to module 6 of Programming
More informationCSCE 206: Structured Programming in C++
CSCE 206: Structured Programming in C++ 2017 Spring Exam 2 Monday, March 20, 2017 Total - 100 Points B Instructions: Total of 13 pages, including this cover and the last page. Before starting the exam,
More informationFunctions and Recursion
Functions and Recursion 1 Storage Classes Scope Rules Functions with Empty Parameter Lists Inline Functions References and Reference Parameters Default Arguments Unary Scope Resolution Operator Function
More informationScore score < score < score < 65 Score < 50
What if we need to write a code segment to assign letter grades based on exam scores according to the following rules. Write this using if-only. How to use if-else correctly in this example? score Score
More informationFunctions. Lecture 6 COP 3014 Spring February 11, 2018
Functions Lecture 6 COP 3014 Spring 2018 February 11, 2018 Functions A function is a reusable portion of a program, sometimes called a procedure or subroutine. Like a mini-program (or subprogram) in its
More informationCOMP-202 Unit 4: Programming with Iterations
COMP-202 Unit 4: Programming with Iterations Doing the same thing again and again and again and again and again and again and again and again and again... CONTENTS: While loops Class (static) variables
More informationCS/IT 114 Introduction to Java, Part 1 FALL 2016 CLASS 10: OCT. 6TH INSTRUCTOR: JIAYIN WANG
CS/IT 114 Introduction to Java, Part 1 FALL 2016 CLASS 10: OCT. 6TH INSTRUCTOR: JIAYIN WANG 1 Notice Assignments Reading Assignment: Chapter 3: Introduction to Parameters and Objects The Class 10 Exercise
More informationCSE 374 Programming Concepts & Tools. Hal Perkins Spring 2010
CSE 374 Programming Concepts & Tools Hal Perkins Spring 2010 Lecture 19 Introduction ti to C++ C++ C++ is an enormous language: g All of C Classes and objects (kind of like Java, some crucial differences)
More informationChapter Procedural Abstraction and Functions That Return a Value. Overview. Top-Down Design. Benefits of Top Down Design.
Chapter 4 Procedural Abstraction and Functions That Return a Value Overview 4.1 Top-Down Design 4.2 Predefined Functions 4.3 Programmer-Defined Functions 4.4 Procedural Abstraction 4.5 Local Variables
More informationChapter 4. Procedural Abstraction and Functions That Return a Value
Chapter 4 Procedural Abstraction and Functions That Return a Value Overview 4.1 Top-Down Design 4.2 Predefined Functions 4.3 Programmer-Defined Functions 4.4 Procedural Abstraction 4.5 Local Variables
More informationC++ Arrays and Vectors
C++ Arrays and Vectors Contents 1 Overview of Arrays and Vectors 2 2 Arrays 3 2.1 Declaring Arrays................................................. 3 2.2 Initializing Arrays................................................
More informationStatements execute in sequence, one after the other, such as the following solution for a quadratic equation:
Control Structures Sequence Statements execute in sequence, one after the other, such as the following solution for a quadratic equation: double desc, x1, x2; desc = b * b 4 * a * c; desc = sqrt(desc);
More informationwhile for do while ! set a counter variable to 0 ! increment it inside the loop (each iteration)
Week 7: Advanced Loops while Loops in C++ (review) while (expression) may be a compound (a block: {s) Gaddis: 5.7-12 CS 1428 Fall 2015 Jill Seaman 1 for if expression is true, is executed, repeat equivalent
More informationJAVA PROGRAMMING LAB. ABSTRACT In this Lab you will learn to define and invoke void and return java methods
Islamic University of Gaza Faculty of Engineering Computer Engineering Dept. Computer Programming Lab (ECOM 2114) ABSTRACT In this Lab you will learn to define and invoke void and return java methods JAVA
More informationADARSH VIDYA KENDRA NAGERCOIL COMPUTER SCIENCE. Grade: IX C++ PROGRAMMING. Department of Computer Science 1
NAGERCOIL COMPUTER SCIENCE Grade: IX C++ PROGRAMMING 1 C++ 1. Object Oriented Programming OOP is Object Oriented Programming. It was developed to overcome the flaws of the procedural approach to programming.
More informationThe American University in Cairo Computer Science & Engineering Department CSCE 106 Fundamentals of Computer Science. Instructor: Final Exam Fall 2011
The American University in Cairo Computer Science & Engineering Department CSCE 106 Fundamentals of Computer Science Instructor: Final Exam Fall 2011 Last Name :... ID:... First Name:... Section No.: EXAMINATION
More informationSection A Arithmetic ( 5) Exercise A
Section A Arithmetic In the non-calculator section of the examination there might be times when you need to work with quite awkward numbers quickly and accurately. In particular you must be very familiar
More informationCONTENTS: While loops Class (static) variables and constants Top Down Programming For loops Nested Loops
COMP-202 Unit 4: Programming with Iterations Doing the same thing again and again and again and again and again and again and again and again and again... CONTENTS: While loops Class (static) variables
More informationWhy Is Repetition Needed?
Why Is Repetition Needed? Repetition allows efficient use of variables. It lets you process many values using a small number of variables. For example, to add five numbers: Inefficient way: Declare a variable
More informationArrays. Arizona State University 1
Arrays CSE100 Principles of Programming with C++, Fall 2018 (based off Chapter 8 slides by Pearson) Ryan Dougherty Arizona State University http://www.public.asu.edu/~redoughe/ Arizona State University
More informationSTUDENT LESSON A12 Iterations
STUDENT LESSON A12 Iterations Java Curriculum for AP Computer Science, Student Lesson A12 1 STUDENT LESSON A12 Iterations INTRODUCTION: Solving problems on a computer very often requires a repetition of
More informationCOSC 2P95. Procedural Abstraction. Week 3. Brock University. Brock University (Week 3) Procedural Abstraction 1 / 26
COSC 2P95 Procedural Abstraction Week 3 Brock University Brock University (Week 3) Procedural Abstraction 1 / 26 Procedural Abstraction We ve already discussed how to arrange complex sets of actions (e.g.
More informationThe name of our class will be Yo. Type that in where it says Class Name. Don t hit the OK button yet.
Mr G s Java Jive #2: Yo! Our First Program With this handout you ll write your first program, which we ll call Yo. Programs, Classes, and Objects, Oh My! People regularly refer to Java as a language that
More informationPointers. A pointer is simply a reference to a variable/object. Compilers automatically generate code to store/retrieve variables from memory
Pointers A pointer is simply a reference to a variable/object Compilers automatically generate code to store/retrieve variables from memory It is automatically generating internal pointers We don t have
More informationReview. Modules. CS 151 Review #6. Sample Program 6.1a:
Review Modules A key element of structured (well organized and documented) programs is their modularity: the breaking of code into small units. These units, or modules, that do not return a value are called
More informationHow to approach a computational problem
How to approach a computational problem A lot of people find computer programming difficult, especially when they first get started with it. Sometimes the problems are problems specifically related to
More informationProblem Solving: Storyboards for User Interaction
Topic 6 1. The while loop 2. Problem solving: hand-tracing 3. The for loop 4. The do loop 5. Processing input 6. Problem solving: storyboards 7. Common loop algorithms 8. Nested loops 9. Problem solving:
More informationVariable Definitions and Scope
Variable Definitions and Scope The scope of a variable is the part of the program where the variable may be used. For a variable defined inside a function, its scope is the function, from the point of
More informationLecture 5: Methods CS2301
Lecture 5: Methods NADA ALZAHRANI CS2301 1 Opening Problem Find the sum of integers from 1 to 10, from 20 to 30, and from 35 to 45, respectively. 2 Solution public static int sum(int i1, int i2) { int
More information