Two-week ISTE workshop on Effective teaching/learning of computer programming Dr Deepak B Phatak Subrao Nilekani Chair Professor Department of CSE, Kanwal.

Slides:



Advertisements
Similar presentations
Introduction to C Programming
Advertisements

Dr. Yang, Qingxiong (with slides borrowed from Dr. Yuen, Joe) LT4: Control Flow - Loop CS2311 Computer Programming.
CSE 1301 Lecture 6B More Repetition Figures from Lewis, “C# Software Solutions”, Addison Wesley Briana B. Morrison.
While Loops Programming. COMP102 Prog Fundamentals I: while Loops/Slide 2 Shortcut Assignments l C++ has a set of shortcut operators for applying an operation.
Computer Science 1620 Loops.
1 Lecture 11:Control Structures II (Repetition) (cont.) Introduction to Computer Science Spring 2006.
A loop is a repetition control structure. it causes a single statement or block to be executed repeatedly What is a loop?
Chapter 6 - Repetition. Introduction u Many applications require certain operations to be carried out more than once. Such situations require repetition.
1 Lecture 14 Chapter 6 Looping Dale/Weems/Headington.
Computer Science 1620 Programming & Problem Solving.
Loops Programming. COMP104 Lecture 9 / Slide 2 Shortcut Assignment l C++ has a set of operators for applying an operation to a variable and then storing.
Two-week ISTE workshop on Effective teaching/learning of computer programming Dr Deepak B Phatak Subrao Nilekani Chair Professor Department of CSE, Kanwal.
11 Chapter 4 LOOPS AND FILES. 22 THE INCREMENT AND DECREMENT OPERATORS To increment a variable means to increase its value by one. To decrement a variable.
REPETITION STRUCTURES. Topics Introduction to Repetition Structures The while Loop: a Condition- Controlled Loop The for Loop: a Count-Controlled Loop.
Chapter 5: Control Structures II (Repetition)
CHAPTER 5: CONTROL STRUCTURES II INSTRUCTOR: MOHAMMAD MOJADDAM.
EGR 2261 Unit 5 Control Structures II: Repetition  Read Malik, Chapter 5.  Homework #5 and Lab #5 due next week.  Quiz next week.
CS 101: Numerical Computing Abhiram Ranade. Representing Integers “int x;” : reserves one cell in memory for x. One cell: “One word” has 32 capacitors.
Numerical Methods Applications of Loops: The power of MATLAB Mathematics + Coding 1.
Java Programming: From the Ground Up
Two-week ISTE workshop on Effective teaching/learning of computer programming Dr Deepak B Phatak Subrao Nilekani Chair Professor Department of CSE, Kanwal.
Two-week ISTE workshop on Effective teaching/learning of computer programming Dr Deepak B Phatak Subrao Nilekani Chair Professor Department of CSE, Kanwal.
Lecture 4 C Program Control Acknowledgment The notes are adapted from those provided by Deitel & Associates, Inc. and Pearson Education Inc.
CS 101: “If” and Recursion Abhiram Ranade. This week’ lab assignment: Write a program that takes as input an integer n and a sequence of numbers w1,w2,...,wn.
Loops: Handling Infinite Processes CS 21a: Introduction to Computing I First Semester,
Computer Science 111 Fundamentals of Programming I The while Loop and Indefinite Loops.
Algorithms and Algorithm Analysis The “fun” stuff.
Loop Application: Numerical Methods, Part 1 The power of Matlab Mathematics + Coding.
Two-week ISTE workshop on Effective teaching/learning of computer programming Dr Deepak B Phatak Subrao Nilekani Chair Professor Department of CSE, Kanwal.
Looping II (for statement). CSCE 1062 Outline  for statement  Nested loops  Compound assignment operators  Increment and decrement operators.
 Wednesday, 9/18/02, Slide #1 CS106 Introduction to CS1 Wednesday, 9/18/02  QUESTIONS?? HW #1 due today at 5!!  Today: Loops, and two new data types.
Chapter 5: Control Structures II (Repetition). Objectives In this chapter, you will: – Learn about repetition (looping) control structures – Learn how.
Computer Science Department LOOPS. Computer Science Department Loops Loops Cause a section of your program to be repeated a certain number of times. The.
Chapter 8 Repetition Statements. Introduction Iteration - process of looping or the repetition of one or more statements Loop body - the statement, or.
While Loops Programming. COMP102 Prog Fundamentals I: while Loops/Slide 2 Shortcut Assignments l C++ has a set of shortcut operators for applying an operation.
Chapter 8 Iteration Dept of Computer Engineering Khon Kaen University.
COMPUTER PROGRAMMING. Iteration structures (loops) There may be a situation when you need to execute a block of code several number of times. In general,
Program Flow Control - Looping Addis Ababa Institute of Technology Yared Semu April 2012.
CSE1222: Lecture 7The Ohio State University1. logExample.cpp // example of log(k) for k = 1,2,..,8... int main() { cout
GAME102 - INTRO WHILE LOOPS G. MacKay. Fundamental Control Structures  STRAIGHT LINE  CONDITIONAL  LOOPS.
+ Starting Out with C++ Early Objects Seventh Edition by Tony Gaddis, Judy Walters, and Godfrey Muganda Chapter 5: Looping.
ITERATIVE STATEMENTS. Definition Iterative statements (loops) allow a set of instruction to be executed or performed several until condition are met.
Control Structures RepetitionorIterationorLooping Part I.
Quiz 3 is due Friday September 18 th Lab 6 is going to be lab practical hursSept_10/exampleLabFinal/
Overview Go over parts of quiz? Another iteration structure for loop.
Two-week ISTE workshop on Effective teaching/learning of computer programming Dr Deepak B Phatak Subrao Nilekani Chair Professor Department of CSE, Kanwal.
REPETITION STATEMENTS - Part2 Structuring Input Loops Counter-Controlled Repetition Structure Sentinel-Controlled Repetition Structure eof()-Controlled.
CS101: Numerical Computing 2 Abhiram Ranade. Topics More examples of for statement  Evaluating e x.  Hemachandra Numbers  Newton Rhapson method for.
REPETITION STATEMENTS - Part1  Also called LOOP STATEMENTS OR LOOP STRUCTURES 1 C++ Statements that repeat one or more actions while some condition is.
Repetition Statements (Loops). 2 Introduction to Loops We all know that much of the work a computer does is repeated many times. When a program repeats.
Chapter 05 (Part II) Control Statements: Part II.
Two-week ISTE workshop on Effective teaching/learning of computer programming Dr Deepak B Phatak Subrao Nilekani Chair Professor Department of CSE, Kanwal.
Two-week ISTE workshop on Effective teaching/learning of computer programming Dr Deepak B Phatak Subrao Nilekani Chair Professor Department of CSE, Kanwal.
C++ Programming: From Problem Analysis to Program Design, Fifth Edition Chapter 5: Control Structures II (Repetition)
1 COMS 261 Computer Science I Title: C++ Fundamentals Date: September 23, 2005 Lecture Number: 11.
Looping I (while statement). CSCE 1062 Outline  Looping/repetition construct  while statement (section 5.1)
UCT Department of Computer Science Computer Science 1015F Iteration
Repetitive Structures
REPETITION CONTROL STRUCTURE
Introduction To Repetition The for loop
Computing Fundamentals
Lecture 7: Repeating a Known Number of Times
Programming Fundamentals
Lecture 07 More Repetition Richard Gesick.
Functions.
Lecture 4B More Repetition Richard Gesick
Arrays, For loop While loop Do while loop
Computing Fundamentals
Lecture 8:The For Loop AP Computer Science Principles.
LOOPS The loop is the control structure we use to specify that a statement or group of statements is to be repeatedly executed. Java provides three kinds.
Presentation transcript:

Two-week ISTE workshop on Effective teaching/learning of computer programming Dr Deepak B Phatak Subrao Nilekani Chair Professor Department of CSE, Kanwal Rekhi Building IIT Bombay Lecture 3, Fundamental programming concepts (Iterative algorithms) Tuesday 29 June 2010

OVERVIEW  Need for repetitive execution of instructions Problem of finding maximum of given numbers  Instructions for specifying iteration with ‘for’ With ‘While’  Problem of estimating value of log x  General problem of finding roots of a polynomial

Revisiting problem to find Maximum  We saw that if we have to find maximum of 5 numbers we could write: int a, b, c, d, e, max; cin >>a >>b >>c >>d >e ; max = a; if (b > max) {max = b}; if (c > max) {max = c}; if (d > max) {max = d}; if (e > max) {max = e}; cout<<“Max is”<< max << "\n";  What do we do if the number of numbers is very large

A possible strategy  We notice a repetitive pattern in our program, which is if (number > max) { max = number}  If we could execute this instruction repeatedly, every time with a different value of number, we will get the desired result. To ensure that this comparison is made with a new value every time, we consider repeating a modifying pattern cin >> number; if (number > max) { max = number}

Further analysis of the repetitive strategy  If we repeat this block five times, we will find the maximum of five numbers. But we need an initial value for max.  If we assume all the given numbers are positive, then we could assign an arbitrary negative initial value to max  Expanding our strategy in words, we wish to say something like: max = -999; // repeat the following block 5 times {cin >> number; if (number > max) { max = number} }

Repetitive execution  We need some kind of a ‘counting mechanism’ which will add 1 to the count every time we execute the block, and will stop repeated execution of the block once the count reaches 5  The ‘ for’ instruction provides such mechanism max = -999; for (count =1, count <=5; count ++) {cin >> number; if (number > max) { max = number} }

Repetitive execution  The artificial initial value for max in not a good idea (What if we are given negative numbers also).  A better thing would be to read the first given number separately, assign it to max, and then repeat the block only 4 times cin >> number; max = number; for (count =1, count <=4; count ++) {cin >> number; if (number > max) { max = number} }

Finding maximum of N given numbers // Program 4 (prog4.cpp) #include using namespace std; // To find maximum of N given numbers int main() { int count, number, N, max; cin >> N; cin >> number; max = number; for (count =1, count <=N-1; count ++){ cin >> number; if (number > max) { max = number} }

General format and semantics of the ‘for’ statement for( xxx; yyy; zzz ) { www; } 0. Execute “xxx;”. Must be an assignment statement. “loop initialization” 1. Evaluate condition yyy. “loop test”. If true, continue with step 2; if false, execution of ‘for’ statement ends. 2. Execute www. “loop body” 3. Execute zzz. “loop increment” 4. Go back and repeat from 1.

Sum of N natural numbers ---- int main(){ int i, N, Sum = 0; cin >> N for(i=1; i < N; i=i+1){ sum = sum + i; } cout << “Sum of” << N < “numbers is”; cout << sum << “\n”; return 0; }

Computing Natural Logarithm  Natural Logarithm of a number a is defined as  A computer cannot integrate Must use arithmetic operations.  Estimate area under the curve f(x) = 1/x from 1 to a.  Area approximated by small rectangles. 1/ x dx 1 a

Riemann Integral 1 a calculate Sum of areas of all rectangles between 1 and a.

Riemann Integral using n rectangles Width w of i th Rectangle (same for all rectangles)‏ 1 a w = (a-1)/n)‏

Riemann Integral using n rectangles 1 a x coordinate of i th Rectangle x = 1 + (i-1)w

Riemann Integral using n rectangles 1 a Height h of i th Rectangle h = 1 / x = 1/(1 + (i-1)w)‏

How many rectangles?  More the merrier! Say  Total width of rectangles = a - 1.  Width w of each rectangle= (a - 1)/1000  x coordinate of left side of i th rectangle x = 1 + (i-1)w.  Height of i th rectangle 1/x = 1/(1+(i-1)w)‏

Program to compute logarithm of a given value int main(){ int i; float x, area=0, w; cin >> x; w = (x-1)/1000.0; for(i=1; i <= 1000; i=i+1){ area = area + w*(1/(1+(i-1)*w)); } cout << “Log of ” << x << “is ” << area; return 0; }

Factorial of a number int nfactorial, n, i; cin >> n; nfactorial = 1; for (i =1; i <= n, i++){ nfactorial = nfactorial * i; }; cout << nfactorial;

Hemachandra’s Problem (12 th Century AD)  Suppose I have to build a wall of length 8 feet. I have bricks 2 feet long and also 1 foot long. In how many ways I can lay the bricks so that I fill the 8 feet?  Possibilities: 2,2,2,2; 1,1,1,1,1,1,1,1; 2,2,2,1,1....

Hemachandra’s Actual Problem  Suppose I am designing a poetic meter with 8 beats. The meter is made of short syllables and long syllables.  Short syllable (s) = 1 beat,  Long syllable (l) = 2 beats.  How many ways are there of filling 8 beats?  Example of a poetic meter ya kun den du tu sha r ha r dha va la l l l s s l s l s s s l ya shubh r vas tra vru ta l l s l l s s

Hemachandra’s Solution  “By the method of Pingala, it is enough to observe that the last beat is long or short”  Pingala: mathematician/poet from 500 A.D.  Hemachandra is giving credit to someone who lived hundreds of years before him!!  Copy if necessary and if permitted,  but always give credit

Hemachandra’s solution contd.  S : Class of 8 beat patterns with short last beat.  L : Class of 8 beat patterns with long last beat.  Each 8 beat pattern is in class L or class S  S = all 7 beat patterns + short beat appended.  L = all 6 beat patterns + long beat appended | class S | = Number of patterns with 7 beats | class L | = Number of patterns with 6 beats |8 beat patterns| = |class S| + |class L| = |7 beat patterns| + |6 beat patterns|

Algebraically..  H n = number of patterns with n beats H 8 = H 7 + H 6 In general H n = H n-1 + H n-2  Does this help us to compute H 8 ? We need to know H 7, H 6, for which we need H 5,...

Algorithm Idea  H 1 = number of patterns with 1 beat = 1 {S}  H 2 = Number with 2 beats = 2 {SS, L}  H 3 = H 2 + H 1 = = 3 {SSS, SL, LS}  H 4 = H 3 + H 2 = = 5  H 5 = H 4 + H 3 = = 8  H 6 = H 5 + H 4 = = 13  H 7 = H 6 + H 5 = = 21  H 8 = H 7 + H 6 = = 34...

Program to compute H n int n; cin >> n; // which number to compute int hprev = 1, hcurrent = 2, hnext; For (int i=3; i <= n; i++){ hnext = hprev + hcurrent; // prepare for next iteration hprev = hcurrent; hcurrent = hnext; } cout << hnext;

On Hemachandra Numbers  Mathematics from poetry!  Series is very interesting. - Number of petals in many flowers. - Ratio of consecutive terms tends to a limit.  What are these numbers more commonly known as? Fibonacci numbers!!  Hemachandra lived before Fibonacci.

Newton Raphson method  Method to find the root of f(x), i.e. x such that f(x)=0.  Method works if: f(x) and f '(x) can be easily calculated. and a good initial guess is available.  Example: To find square root of k. use f(x) = x 2 - k. f’ (x) = 2x. f(x), f’ (x) can be calculated easily. only 2 or 3 arithmetic operations needed Initial guess x 0 = 1 always works! can be proved.

How to get better x i+1 given x i Point A =(x i,0) known. f’ (x i ) = AB/AC = f(x i )/(x i - x i+1 )  x i+1 = (x i - f(x i )/f’ (x i )) Point B=(x i,f(x i )) is known Calculate f(x i ). Approximate f by tangent C= intercept on x axis C=(x i+1,0) f(x) xixi x i+1 A B C

Square root of k  x i+1 = (x i - f(x i )/f’ (x i ))  f(x) = x 2 - k, f’ (x) = 2x  x i+1 = x i - (x i 2 - k)/(2x i ) = (x i + k/x i )/2  Starting with x 0 =1, we compute x 1, then x 2, then...  We can get as close to sqrt(k) as required.

Program segment float k; cin >> k; float xi=1; // Initial guess. Known to work. for (int i=0; i < 10; i++){ // 10 iterations xi = (xi + k/xi)/2; } cout << xi;

Another way float xi, k; cin >> k; for( xi = 1 ; // Initial guess. Known to work. xi*xi – k > || k - xi*xi > ; //until error in the square is at most xi = (xi + k/xi)/2); cout << xi;

Yet Another way float k; cin >> k; float xi=1; while(xi*xi – k > || k - xi*xi > 0.001){ xi = (xi + k/xi)/2 ; } cout << xi;

While statement while (condition) { loop body};  check condition, if true then execute loop body. Repeat.  If loop body is a single statement, then need not use { }. Always putting braces is recommended; if you insert a statement, you may forget to put them, so do it at the beginning.  True for other statements also: for/repeat/if.

for and while  If there is a “control” variable with initial value, update rule, and whose value distinctly defines each loop iteration, use for.  If loop executes fixed number of times, use for.

THANK YOU