First Midterm Exam l l l l November
First Midterm Exam l l l l November 7, 2015, Saturday 14: 00 – 15: 40 ä max 100 minutes One A 4 size cheat-note allowed Closed book, closed notes, no calculators and no laptops Until the end of loops A detailed email will be sent later Next week, a Sample Question Set will be posted on the website of the course ä Solutions will be posted later CS 201 – Introduction to Computing – Sabancı University 1
Homework 3 l Homework 3 is due October 21, 2015, 19: 00 ä Robot application. ä Be careful where and how you create the robots • Robot must be created only once within the main • Examine example robot programs covered in recitations ä Scope rules say that each identifier can be used only in the compound block in which it is declared • If you receive an “undeclared identifier” error for a robot even you declare it, check where you declare and use it! l Use of functions ä You have to split the task into several functions ä Do not forget to use & for robot parameters CS 201 – Introduction to Computing – Sabancı University 2
From Selection to Repetition l The if statement and if/else statement allow a block of statements to be executed selectively: based on a condition cout << "Please enter a non-negative number" << endl; cin >> inputnumber; if (inputnumber < 0) { cout << inputnumber << " is negative. Wrong Input" << endl; } This piece of code does not ask another input number if the number is negative. ---------------------------------------------------l The while statement repeatedly executes a block of statements while the condition is true cout << " Please enter a non-negative number" << endl; l cin >> inputnumber; while (inputnumber < 0) { cout << inputnumber << " is negative! Try again" << endl; cin >> inputnumber; } CS 201 – Introduction to Computing – Sabancı University 3
Semantics of while loop if (test) { statement list; } test false true Statement list Next statement CS 201 – Introduction to Computing – Sabancı University while (test) { statement list; } test false true Statement list Next statement 4
Another simple example l Calculate the sum of the integer numbers between 1 and 10 int sum = 0; int num = 1; while (num <= 10) { sum = sum + num; num += 1; } CS 201 – Introduction to Computing – Sabancı University // // this program piece calculates the sum of integers between and including 1 and 10 Let us see how it works step by step 5
Easy Example (not in book) l l Input 10 integer numbers and find their sum What about having cin >> num; sum = sum + num; 10 times? • not a good solution l l Good solution is to use loops. ä code is developed on board. see sum 10 nums. cpp This type of loops are called counting loops ä number of iterations is known CS 201 – Introduction to Computing – Sabancı University 6
Another easy example (not in book) l Read a sequence of integer numbers from keyboard and find their sum. ä input should finish when user enters – 1 • -1 is the sentinel value in this example • not to be added to the sum l l Code is developed on board (see sumnums. cpp) This type of loop is called conditional loop ä number of iterations is not known ä depends on input CS 201 – Introduction to Computing – Sabancı University 7
Anatomy of a loop sum = 0; initialization count = 1; while (count <= 10) { cin >> num; sum += num; Loop body count += 1; } Loop test expression Update statement CS 201 – Introduction to Computing – Sabancı University 8
Anatomy of a loop l l l Initialize variables used in loop body and loop test (before the loop) ä No general rule. The way of initialization and the initial values are to be determined according to the application The loop test is evaluated before each loop iteration ä NOT evaluated after each statement in the loop body ä Current value of variables are used for the loop test before each iteration The loop body must update some variables used in the loop test so that the loop eventually terminates ä If loop test is always true, loop is infinite • Infinite loops must be avoided l Basic rule of designing a loop: ä Initialization, loop test and update parts should be designed carefully in order to iterate the loop as many times as needed • ä neither one less nor one more. Unfortunately there is no straightforward rule of designing a bug -free loop • you should be able to develop those parts by understanding and analyzing the underlying problem that needs a loop CS 201 – Introduction to Computing – Sabancı University 9
The for loop l l l Initialization, test and update parts are combined for (initialization; loop test expression; update) { statement list; //loop body } initialization statement ä executed once before the loop test expression ä boolean expression ä checked each time before entering the loop body • if true execute loop body, if false terminate loop l update statement ä executed after the last statement of the loop body in every iteration CS 201 – Introduction to Computing – Sabancı University 10
for loop example (similarities with while) sum = 0; count = 1; while (count <= 10) { sum = sum + count; count = count + 1; } sum = 0; for (count = 1; count <= 10; count = count+1) { sum = sum + count; } CS 201 – Introduction to Computing – Sabancı University 11
Example: Print a string backwards (revstring. cpp) l Determine the index of the last character of the string, and then access each character backwards ä How many times should the loop iterate ? string s; int k; cout << "enter string: "; cin >> s; cout << s << " reversed is "; k = s. length() - 1; // index of last character in s while (k >= 0) { cout << s. substr(k, 1); k -= 1; } cout << endl; l What could we use instead of s. substr(k, 1) ? s. at(k) CS 201 – Introduction to Computing – Sabancı University 12
Reverse String as a function l First step, what is the function heading? string revstring(string s) // pre: s = c 0 c 1 c 2…cn-1 // post: returns cn-1…c 2 c 1 c 0 l Second step, how do we build a new string? ä Start with an empty string, "" ä Add one character at each iteration using concatenation, + rev = rev + s. substr(k, 1); l Use revstring to determine if a string is a palindrome CS 201 – Introduction to Computing – Sabancı University 13
See palindrome. cpp for full program string revstring(string s) { // post: returns reverse of s, that is "stab" for "bats" int k = s. length() - 1; string rev = ""; // start with empty string while (k >= 0) { rev = rev + s. substr(k, 1); k -= 1; } return rev; } bool Is. Palindrome(string word) { // post: returns true if and only word is a palindrome return word == revstring(word); } CS 201 – Introduction to Computing – Sabancı University 14
Infinite loops l Infinite loop is a loop that never stops ä something that must be avoided ä happens when the loop condition is always true ä same loop body iterates indefinitely • sometimes you see an output, sometimes you don’t • press Ctrl-C to stop maybe the effect of a wrong or missing update statement ä maybe due to a wrong condition; may be due to another reason Example: consider the following modified code from sum 10 nums ä What’s the problem in the loop below? What is missing? ä l • count never reaches 10, because count is not updated in the loop sum = 0; count = 1; while (count <= 10) { cin >> num; sum += num; } CS 201 – Introduction to Computing – Sabancı University 15
Infinite loops l What is the problem with the code below? ä cannot say infinite loop, depends on input number • For example, if num is an odd number, then the loop is infinite cin >> num; int start = 0; while (start != num) { start += 2; cout << start << endl; } CS 201 – Introduction to Computing – Sabancı University 16
Developing Loops l l Some loops are easy to develop, others are not Sometimes the proper loop test and body are hard to design Practice helps, but remember: ä Good design comes from experience, experience comes from bad design Common loop bugs ä Easy to iterate one more or one less than needed ä Test the following cases all the time • Zero iteration case (or whatever the minimum number of iterations) • One iteration case (or one more than the minimum number of iterations) • Maximum number of iterations • One less than the maximum number of iterations CS 201 – Introduction to Computing – Sabancı University 17
Number Crunching l l l Number crunching is a CS term that means a computing operation that requires several (and sometimes complex) arithmetic operations was the job of early computers Numeric Analysis ä classical subdiscipline of computer science today ä implicitly or explicitly, all operations are numeric Now we will see some mathematical applications ä factorial calculation ä prime number testing CS 201 – Introduction to Computing – Sabancı University 18
Factorial l n! = 1 x 2 x…xn is “n factorial”; used in math, statistics long factorial(int n) // pre: 0 <= n // post: returns n! (1 x 2 x … x n) l Similar to sum, but this time we will calculate a product within the loop. At the end we will return the final product. ä The loop will iterate n times, multiplying by 1, 2, …, n ä Suppose we use a variable called product to hold the result, then product is n! when the loop terminates. So we will return it at the end. CS 201 – Introduction to Computing – Sabancı University 19
Factorial long Factorial(int num) // precondition: num >= 0 // postcondition returns num! (1 x 2 x … x num) { long product = 1; int count = 0; while (count < num) { count += 1; product *= count; } return product; } l Issues ä Why did we use long? What happens if we use int instead? ä what happens if we initialize count to 1? l Let’s see fact. cpp CS 201 – Introduction to Computing – Sabancı University 20
Factorial (Cont’d) – Using Big. Int class l l What is the problem of the previous program? ä integer overflow ä even long is not sufficient (actually there is not difference between long and int for 32 -bit computers like ours) • 12! is 479, 001, 600 so what happens with 13! ? The type Big. Int, accessible via #include "bigint. h" ä ä can be used like an int, but gets as big as you want it to be Really arbitrarily large? • No, limited to computer memory, but computers most likely run out of time before running out of memory ä Disadvantages of using Big. Int compared to int? • processing speed is lower • uses up more memory ä ä Use Big. Int if you really need it Do not forget to add bigint. cpp to your project, • Big. Int is a Tapestry class, but we modified it a bit. Thus, please use the bigint. h and bigint. cpp files provided in the lecture notes rather than the one given in book's website. CS 201 – Introduction to Computing – Sabancı University 21
Factorial using Big. Int class l See bigfact. cpp CS 201 – Introduction to Computing – Sabancı University 22
Determining if a number is prime l l Prime number is a natural number which has only two divisors: 1 and itself Some Cryptographic algorithms depend on prime numbers ä Determining if a number is prime must be “easy” ä Actually factoring a number must be “hard” • “hard” in the sense that it must be computationally infeasible to factorize in a reasonable amount of time l RSA Cryptosystem ä Rivest, Shamir, Adleman ä based on the factorization problem of large numbers ä has been utilized by several security products and services • PGP (Pretty Good Privacy) – e-mail security • WWW security using SSL/TLS protocol and bany banking applications l Sophisticated mathematics used for fast prime-testing, we’ll do basic prime testing that’s reasonably fast for small numbers, but not good enough for RSA (why not? ) ä because our algorithm is based on factorization, so it is really slow for large numbers CS 201 – Introduction to Computing – Sabancı University 23
Determining Primeness (continued) l 1 is NOT prime, 2 is prime, 3 is prime, 5 is prime, 17 is prime, … 137, 193? ä We do not need to check even numbers other than 2 (2 is a special case) ä To check 193, divide it by 3, 5, 7, 9, 11, 13 • Note that 14 x 14 = 196, so 13 largest potential factor? • we use modulus operator to check divisibility l We’ll check odd numbers as potential divisors ä Watch out for 2, it is a special case ä How far should we go to check potential divisors? • up to and including sqrt(number) + 1 • If there was a bigger factor, a smaller factor would exist. And this smaller one must have been checked before. So we do not need to go beyond this limit. • +1 is there to make sure that there will be no problems with precision ä See primes. cpp for code CS 201 – Introduction to Computing – Sabancı University 24
Primeness Check – Details l Special even number check is added before the loop to eliminate even numbers to be checked in the loop ä In order to make the code more efficient int limit = int(sqrt(n) + 1); ä To assign a double value to an int, a typecast is used, to tell the compiler that the loss of precision is intentional • Make typecasts explicit to tell the compiler you know what you are doing • Compiler warnings are avoided ä We will see typecast in more detail later CS 201 – Introduction to Computing – Sabancı University 25
What is next with loops l Loops are useful instruments in program development Loops are statements, can be combined with other loops, with if statements, in functions, etc. Other kinds of looping statements can make programming simpler l for loops l good for counting loops do – while loops l l ä ä l good if the loop body must be executed at least once nested loops ä loops inside other loops CS 201 – Introduction to Computing – Sabancı University 26
Four Sections of a while loop CS 201 – Introduction to Computing – Sabancı University 27
for loop compared with while initialization while (test) { statement 1; . . . statement. N; update; } for (initialization; test; update) { statement 1; . . . statement. N; } CS 201 – Introduction to Computing – Sabancı University 28
The for loop l l l Initialization, test and update parts are combined for (initialization; test expression; update) { statement list; //loop body } initialization statement ä executed once before the loop test expression ä boolean expression ä checked each time before entering the loop body • if true execute loop body, if false terminate loop l l l update statement ä executed after the last statement of the loop body in every iteration several statements in initialization and update are separated by comma initialization and/or test and/or update parts could be missing ä but semicolons are there CS 201 – Introduction to Computing – Sabancı University 29
Example l Rewrite the while loop of main of primes. cpp using for k = low; while (k <= high) { if (Is. Prime(k)) { cout << k << endl; num. Primes += 1; } k += 1; } for (k = low; k <= high; k += 1) { if (Is. Prime(k)) { cout << k << endl; num. Primes += 1; } } CS 201 – Introduction to Computing – Sabancı University 30
The for loop l For loops are good for counting loops (although they can be used for conditional loops) ä Number of iterations known before loop begins • Example: sum of 10 input numbers • Example: print a string vertically void Vertical(string s) // post: chars of s printed vertically int len; int k; len = s. length(); k = 0; while (k < len) { cout << s. substr(k, 1) << endl; k += 1; } // for loop alternative 3 int len; int k; len = s. length(); k = 0; for(; k < len; k+= 1) { cout << s. substr(k, 1) << endl; } // for loop alternative 1 // for loop alternative 2 int len; int k; len = s. length(); int len; int k; for(k=0; k < len; k+= 1) for(len = s. length(), k=0; k < len; k+= 1) { { cout << s. substr(k, 1) << endl; } } CS 201 – Introduction to Computing – Sabancı University 31
Shorthand for increment/decrement l Lots of code requires incrementing a variable by one ä Three methods, using = and +, using +=, and using ++ • effectively they are same num = num + 1; num += 1; num++; // post increment l It is also possible to write ++num ä ä preincrement These differ on when the increment is performed, but this difference doesn’t matter when used as an abbreviation for the statement n += 1; in a single statement Similarly there are postdecrement (and predecrement) num = num - 1; num -= 1; num--; l CS 201 – Introduction to Computing – Sabancı University 32
The do-while loop l l Similar to while loop, but the test is after the execution of the loop body The while loop may never execute; do-while loop executes at least once do { loop body; } while (test ); Don’t forget //executes loop while the test is true l If needed, add some initialization statements to the beginning (before do) l Example; Prompt for a number between 0 and 100, loop until such a number is entered • user should enter at least one number do { cout << "enter number in range [0. . 100] "; cin >> num; } while (num < 0 || num > 100 ); CS 201 – Introduction to Computing – Sabancı University 33
Priming l l Priming: reading an initial value before the loop ä do not get confused with prime numbers; this is something else Problem: enter numbers, add them up, stop when -1 entered int sum = 0; int num; cin >> num; // prime the loop while (num != -1) { sum += num; cin >> num; } cout << "total = " << sum << end; l Code duplication exists here: input (and perhaps prompt) code is repeated before the loop and in the loop CS 201 – Introduction to Computing – Sabancı University 34
Pseudo infinite solution using break l l To avoid repeating code, include it in the body of the loop only, use a test to break out of the loop ä break statement exits (inner-most) loop I don’t like this kind of loops (I’d prefer code duplication). ä l Because the loop condition is not clear, hence prevents readability DO NOT use break to break the loops int sum = 0; int num; while (true) //seemingly infinite loop { cin >> num; if (num == -1) { break; // get out of loop } sum += num; } cout << "total = " << sum << end; CS 201 – Introduction to Computing – Sabancı University 35
Fence Post Problem l l The problem that occurs when one or more operations of the loop body are executed one less than the others. Example: Display integers between 1 and 10 separated by comma 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ä no comma after 10; no comma before 1. for (n=1; n <= 10; n++) { cout << n << ", "; } Problem: comma after 10 for (n=1; n < 10; n++) { cout << n << ", "; } cout << n; No problem, but code duplicates l Think of other solutions! (see page 175 of Tapestry) CS 201 – Introduction to Computing – Sabancı University 36
Nested loops l Sometimes one loop occurs in another ä Generating 2 -dimensional tabular data • multiplication table ä ä Sorting vectors (which will be studied much later) display some geometric figures using character * (or any other character) • display rectangles, triangles l Although other loops can be nested as well, most of the time, for loops are used in nested manner CS 201 – Introduction to Computing – Sabancı University 37
Nested loops - Example l Write a function to display a rectangle of stars (height and width are parameters) ä e. g. if height is 4 and width is 7, the output should look like ******* for (i=1; i<= height; i++) { for (j=1; j<=width; j++) // inner loop prints one line of stars { cout << "*"; } cout << endl; // end of line marker is put to the end of each line } l See drawfigures. cpp for the complete function and its use in main CS 201 – Introduction to Computing – Sabancı University 38
Nested loops - Example l Write a function to display a perpendicular isosceles triangle of stars (perpendicular side length is parameter) ä e. g. if side length is 6 , the output should look like * ** ****** for (i=1; i<= side; i++) { for (j=1; j<=i; j++) // inner loop prints one line of stars { cout << "*"; } cout << endl; // end of line marker is put to the end of each line } l See drawfigures. cpp for the complete function and its use in main CS 201 – Introduction to Computing – Sabancı University 39
Drawfigures – Other Considerations l What about having a function to display a line of stars (number of stars is a parameter) ä useful for both rectangle and triangle void Print. Line (int numstars) // pre: numstars > 0 // post: displays numstars in one line { int i; for (i=1; i<= numstars; i++) { cout << "*"; } cout << endl; // end of line marker is put to the end of the line } l in rectangle function, inner loop is replaced by a function call for (i=1; i<=height; i++) { Print. Line(width); } l use of Print. Line in triangle function is similar CS 201 – Introduction to Computing – Sabancı University 40
Example – Multiplication Table l On ith line print, i*1, i*2, i*3, . . . , i*i ä total number of lines is an input. Display lines starting with 1. ä See multiply. cpp #include <iostream> #include <iomanip> // for setw using namespace std; int main() { int i, k, numlines; const int WIDTH = 4; cin >> numlines; for (i=1; i <= numlines; i++) { for (k=1; k <= i; k++) { cout << setw(WIDTH) << i*k; } cout << endl; } return 0; } CS 201 – Introduction to Computing – Sabancı University 41
Constants l l Sometimes very useful ä provide self documentation and avoid accidental value changes ä re-use the same value in the entire program like variables, but their value is assigned at declaration and can never change afterwards ä declared by using const before the type name (any type is OK) const double PI = 3. 14159; const string thisclass = "CS 201" const int WIDTH = 4; ä later you can use their value cout << (PI*4*4) << endl; ä but cannot change their value PI = 3. 14; CS 201 – Introduction to Computing – Sabancı University causes a syntax error 42
Formatting Output l We use stream manipulator setw to specify the total number of spaces that the next output will use ä setw(field length) • written in cout and affects only the next output value not the whole cout line • output is displayed using field length spaces in right justified manner (any empty space is on the left) ä l defined in header file <iomanip>, so you have to have #include <iomanip> Example cout << setw(9) << "cs 201"; • output shown is four blanks and cs 201 CS 201 – Introduction to Computing – Sabancı University 43
Example using robot class (see rectangularscan. cpp) l Write a program in which the robot starts at 0, 0 and searches a rectangular space that covers n*n cells ä n is input (in the example below, n is 8) ä during this journey, the robot should pick or put things on the cells so that all visited cells occupy one thing CS 201 – Introduction to Computing – Sabancı University 44
- Slides: 44