1 / 27

Announcements

The first midterm exam will take place on Monday of next week at 19:40. Exam classes will be assigned based on last name. Make sure to check the announcement for your exam location. This week's recitations will cover sample midterm questions. Don't forget that Homework 3 is due on Friday.

dmoser
Download Presentation

Announcements

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Announcements • First Midterm • March 14thon Monday next week at 19:40 (100 minutes) • Exam classes: if (LastName <= "Çoruh")      cout << " FENS G077 " << endl; else if ("Demir" <= LastName <= "Kantoğlu")      cout << " FMAN 1099 " << endl; else if ("Kaplan" <= LastName <= "Örs")      cout << " FASS G062 " << endl; else if ("Öz" <= LastName <= "Soylu")      cout << " FENS L045 " << endl; else if ("Şahin" <= LastName <= "Tüysüz")      cout << " FENS G032 " << endl; else if ("Uçar" <= LastName)      cout << " FENS G035 " << endl; • This week recitations, we will solve sample midterm questions. • Detailed email about the midterm was sent with previous years’ exams. • Homework 3 is due on Friday, March 11th this week

  2. Developing Loops • 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

  3. Number Crunching • Number crunching is a CS term that means a computing operation that requires several (and sometimes complex) arithmetic operations • It was the job of early computers • Numeric Analysis • classical sub-discipline of computer science • Today • implicitly or explicitly, all operations are numeric • Now we will see some mathematical applications • factorial calculation • prime number testing

  4. Factorial • n! = 1x2x…xn is “n factorial”; used in math, statistics long factorial(long n) // pre: 0 <= n // post: returns n! (1 x 2 x … x n) • 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 productis n! when the loop terminates. Then we will return it at the end.

  5. 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; } • Issues • Why did we use long? What happens if we use int instead? • What happens if we initialize count to 1? • Let’s see fact.cpp

  6. Factorial (Cont’d) – Using BigInt class • What is the problem of the previous program? • integer overflow • even long is not sufficient (actually there is no difference between long and int for 32-bit computers like ours) • 12! is 479,001,600 so what happens with 13! ? • The type BigInt, 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 BigInt compared to int? • processing speed is lower • uses up more memory • Use BigInt if you really need it • Do not forget to add bigint.cpp to your project, • BigInt is a Tapestry class • Download wincode.zip file from http://cs.duke.edu/csed/tapestry

  7. Factorial using BigInt class • See bigfact.cpp

  8. Determining if a number is prime • Prime numberis 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 • 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 protocol • Sophisticated mathematics used for fast prime-testing, we’ll do basic prime testing • Since our algorithm is based on factorization, it will be really slow for large numbers

  9. Determining Primeness (continued) • 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 14x14 = 196, so 13 largest potential factor? • We will use modulus operator to check divisibility • 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

  10. Primeness Check – Details • 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

  11. for loop compared with while <initialization> while (<test>) { <statement1>; ... <statementN>; <update> } for (<initialization>; <test>; <update> ) { <statement1>; ...   <statementN>; }

  12. Example • Rewrite the while loop of main of primes.cpp using for k = low; while (k <= high) { if (IsPrime(k)) { cout << k << endl; numPrimes += 1; }k += 1; } for (k = low; k <= high; k += 1) { if (IsPrime(k)) { cout << k << endl; numPrimes += 1; } }

  13. Shorthand for increment/decrement • 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 • It is also possible to write ++num; • pre-increment • 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 post-decrement (and pre-decrement) num = num - 1; num -= 1; num--;

  14. The do-while loop • 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 <initialization> do { <statement1>;   ...  <statementN>; <update> } while (<condition>); • 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 ); Don’t forget

  15. Priming • 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; • Code duplication exists here: input (and perhaps prompt) code is repeated before the loop and in the loop

  16. Pseudo infinite solution using break • 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 prefer this kind of loops (I’d prefer code duplication) • Because the loop condition is not clear, hence prevents readability • Try not to usebreakin this course • Save it for later when you develop really complicated 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;

  17. Fence Post Problem • The problem that occurs when one or more operations of the loop body are executed one less then 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 • Think of other solutions! (see page 175 of Tapestry)

  18. Downward-counting loop • Calculate n to the power of m: nm=nxnx…xn • Example: 25=2x2x2x2x2=32 int power = 1; int n, m; cin >> n >> m; for (int i = m; i <= 1; i--) { power = power * n; }

  19. Nested loops • 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 • Although other loops can be nested as well, most of the time, for loops are used in nested manner

  20. Nested loops - Example • 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 1 line of stars { cout << "*"; } cout << endl; // end of line is put to the end of each line } • See drawfigures.cpp for the complete function and its use in main

  21. Nested loops - Example • 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 1 line of stars { cout << "*"; } cout << endl; // end of line is put to the end of each line } • See drawfigures.cpp for the complete function and its use in main

  22. Same loop: downward-counting for (i=1; i <= side; i++) { for (j=1; j<=i; j++) { cout << "*"; } cout << endl; } for (i=1; i <= side; i++) { for (j=i; j>=1; j--) { cout << "*"; } cout << endl; }

  23. Drawfigures – Other Considerations • What about having a function to display a line of stars (number of stars is a parameter) • useful for both rectangle and triangle void PrintLine (intnumstars) // pre: numstars > 0 // post: displays numstars stars in one line { inti; for (i=1; i<= numstars; i++) { cout << "*"; } cout << endl; // end of line is put to the end of the line } • in rectangle function, inner loop is replaced by a function call for (i=1; i<=height ; i++) { PrintLine(width); } • use of PrintLine in triangle function is similar

  24. Example – Multiplication Table • 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() { inti,k,numlines; const intWIDTH = 4; cin>> numlines; for (i=1; i <= numlines; i++) { for (k=1; k <= i; k++) { cout<< setw(WIDTH) << i*k; } cout << endl; } return 0; }

  25. Constants • Sometimes very useful • provides self documentation • re-use the same value across the program • avoid accidental value changes • 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= "CS201" const int WIDTH = 4; • later you can use their value cout << (PI * 4 * 4); • but cannot change their value PI = 3.14;causes a syntax error

  26. Formatting Output • 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) • defined in header file <iomanip>, so you have to have #include <iomanip> • Example cout << setw(9) << "cs201"; • output shown is four blanks and cs201

  27. Example using robot class (see rectangularscan.cpp) • 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

More Related