Statistical Programming with R
|
|
- Alexina Kelly
- 6 years ago
- Views:
Transcription
1 Statistical Programming with R Lecture 6: Programming Examples Bisher M. Iqelan biqelan@iugaza.edu.ps Department of Mathematics, Faculty of Science, The Islamic University of Gaza , Semester 1
2 Hilbert Matrix We have explained the structure of Hilbert matrices of dierent orders in Lecture 4. Here we are going to write an R code to produce the Hilbert matrix of any order. H=function(n){ H=matrix(0,n,n) for(i in 1:n){ for(j in 1:n){ H[i,j]=1/i+j-1 H You can try it now: > H(7) Bisher M. Iqelan (IUG) Lecture 6: Programming Examples 1 st Semester / 38
3 The Low of Big Number Think with the following R code about the probability of obtaining one of the six faces when tossing a fair die. It explain the fact that they should be equal for large and large number of tosses. w=list() freq=list() n=c(20,100,500,1000,5000,20000) for(i in 1:6){ w[[i]]=sample(1:6,n[i],replace=true) freq[[i]]=table(w[[i]])/length(w[[i]]) freq Bisher M. Iqelan (IUG) Lecture 6: Programming Examples 1 st Semester / 38
4 The Low of Big Number Continue We can easily see the bar plot of the frequencies of these trials by applying the following R code (it depends on the previous code) par(mfrow=c(3,2)) for(i in 1:6){ barplot(freq[[i]]) title(main=substitute(paste('no. of trials=',a),list(a=n[i]))) Bisher M. Iqelan (IUG) Lecture 6: Programming Examples 1 st Semester / 38
5 Root Finding Finding the solutions of equations of the form h(x) = c is a very important problem in applied mathematics (and statistics). By writing f (x) = h(x) c, it is clear that solving the above equation is equivalent to solving f (x) = 0, and we can restrict our attention to nding the solutions of this type of equation. The solutions are called roots or zeros of the function f (x). A function may have zero, one, or many roots. Bisher M. Iqelan (IUG) Lecture 6: Programming Examples 1 st Semester / 38
6 The Roots of a General Polynomial R has a built-in function, called polyroot(), for nding all the roots of a polynomial. The coecients of the polygon a n x n + + a 1 x + a 0 are passed in a vector (a 0, a 1,..., a n ) to polyroot. The computed roots are returned in a vector. Since, in general, the roots of polynomials are complex-valued, this vector has mode "complex". Bisher M. Iqelan (IUG) Lecture 6: Programming Examples 1 st Semester / 38
7 Examples Let us nd the roots or zeros of the polynomial > polyroot(c(1,-2,1)) [1] 1+0i 1-0i and for the polynomial p(x) = 1 2x + x 2 p(x) = 3 4x + 5x 2 7x 3 + x 4 > polyroot(c(3,-4,5,-7,1)) [1] i [2] i [3] i [4] i Bisher M. Iqelan (IUG) Lecture 6: Programming Examples 1 st Semester / 38
8 where f denotes the derivative of f. Bisher M. Iqelan (IUG) Lecture 6: Programming Examples 1 st Semester / 38 Finding square roots Suppose we want to create a function mysqrt for nding the square root of its argument x. Our purpose of this example is to introduce a general numerical method for solving equations: The NewtonRapson method. We want to nd x, i.e. the number(s) z such that z 2 = x. (Recall that 4 = ±2.) Thus for a given value x (e.g. x = 10) we want to solve the equation f (z) = z 2 x = 0 Consider the function f (z) = z The function f is nonlinear but it can be approximated by a linear function (a straight line) in a given point. E.g. close to z = 2 the function is approximated by the line call it l(z). The linear approximation to f close to a specic point z 0 (e.g. z 0 = 2) is given by: f (z) f (z 0 ) + f (z 0 )(z z 0 ) = [f (z 0 ) f (z 0 )z 0 ] + f (z 0 )z
9 NewtonRapson method Hence the linear approximation is l(z) = [f (z 0 ) f (z 0 )z 0 ] + f (z 0 )z = a + bz, For the function f (z) = z 2 10 we have f (z) = 2z. With z 0 = 2 we have f (z 0 ) = 4 and f (z 0 ) = 6 so l(z) becomes l(z) = z The idea in NewtonRapson is the following: Suppose z 0 = 2 is our initial guess for a solution to the equation f (z) = 0 (which is dicult to solve). Now l(z) is an approximation to f and it is easy to solve l(z) = 0 : z = a b = 14 4 = 3.5 So we may take 3.5 to be a new approximation to the solution to f (z) = 0. We write z 1 = 3.5. Bisher M. Iqelan (IUG) Lecture 6: Programming Examples 1 st Semester / 38
10 NewtonRapson method Now we nd the line which approximates f close to z 1 = 3.5. The line is (check this for yourself): Solving l(z) = 0 gives l(z) = z. z = 22.25/7 = So the next approximation is z 2 = Iterate this scheme until the values for z stop changing. This is in essence the NewtonRapson method. Bisher M. Iqelan (IUG) Lecture 6: Programming Examples 1 st Semester / 38
11 NewtonRapson method Before going to programming let us again consider the solution to l(z) = a + bz = 0, i.e. z = a b. where, a = f (z 0 ) f (z 0 )z 0 and b = f (z 0 ). Inserting the latter in the former gives the form in which the NewtonRapson method is usually presented in the literature: z = a b = f (z 0) f (z 0 )z 0 f (z 0 ) = z 0 f (z 0) f (z 0 ) Bisher M. Iqelan (IUG) Lecture 6: Programming Examples 1 st Semester / 38
12 Implementing mysqrt We shall content ourself with an implementation which only returns the positive root. First, we need to implement our function f = z 2 x which is a function of z and x: f <- function(z, x) { value <- z^2 - x return(value) > f(z = 2, x = 10) [1] -6 We also need the derivative f deriv.f <- function(z) { value <- 2 * z return(value) of f (which here doesn't depend on x): Bisher M. Iqelan (IUG) Lecture 6: Programming Examples 1 st Semester / 38
13 Implementing mysqrt So now we are almost there. The NewtonRapson steps (2) become: > z0 <- 2 > x <- 10 > z1 <- z0 - f(z0, x)/deriv.f(z0) > z1 [1] 3.5 > z2 <- z1 - f(z1, x)/deriv.f(z1) > z2 [1] > z3 <- z2 - f(z2, x)/deriv.f(z2) > z3 [1] Bisher M. Iqelan (IUG) Lecture 6: Programming Examples 1 st Semester / 38
14 Implementing mysqrt It would be nice to write a single function for doing the iterations above, and such a function can be made in dierent ways: We create a simple function which performs 5 NewtonRapson steps: NRsteps <- function(x, z0) { z <- z0 for (i in 1:5) { z <- z - f(z, x)/deriv.f(z) print(z) return(z) Having done so, it is easy to implement our mysqrt function: mysqrt <- function(x, z0) { z <- NRsteps(x, z0) return(z) Bisher M. Iqelan (IUG) Lecture 6: Programming Examples 1 st Semester / 38
15 Implementing mysqrt Calling the function gives > mysqrt(x = 10, z0 = 2) [1] 3.5 [1] [1] [1] [1] [1] Clearly, no changes after 4 iterations! We want to rene our NRsteps function such that it does not always make 5 iterations. Instead it should iterate as many times as needed to obtain that the changes in the estimates is smaller than e.g We would also like the function to print the number of iterations: Bisher M. Iqelan (IUG) Lecture 6: Programming Examples 1 st Semester / 38
16 Rening mysqrt This can be done as follows: NRsteps <- function(x, z0) { z <- z0 itcount <- 1 repeat { z.new <- z - f(z, x)/deriv.f(z) if (abs(z.new - z) < 0.001) { break itcount <- itcount + 1 z <- z.new cat("nr iterations:", itcount, "\n") return(z.new) Bisher M. Iqelan (IUG) Lecture 6: Programming Examples 1 st Semester / 38
17 Rening mysqrt Having to specify a starting value is annoying. An option could be to take x itself as a default starting value. This can be implemented as: mysqrt <- function(x, z0=x) { z <- NRsteps(x, z0) return(z) > mysqrt(10) NR iterations: 5 [1] Notice that, our method is not working for x < 0. Moreover, for x = 0 the function should return an informative error message. Bisher M. Iqelan (IUG) Lecture 6: Programming Examples 1 st Semester / 38
18 Rening mysqrt This can be done as follows: mysqrt<-function(x, z0=x) { if (x < 0) { cat("can not take square root of a -ve number...\n") else { if (x == 0) { return(0) else { z <- NRsteps(x, z0) return(z) Bisher M. Iqelan (IUG) Lecture 6: Programming Examples 1 st Semester / 38
19 Testing mysqrt function Now, calling our function mysqrt() to obtain > mysqrt(-7) Can not take square root of a negative number... > mysqrt(17) NR iterations: 6 [1] > mysqrt(17) [1] 0 Bisher M. Iqelan (IUG) Lecture 6: Programming Examples 1 st Semester / 38
20 Try this one, it is as the R output This can be done as follows: mysqrt<-function(x, z0=x) { if (x < 0) { cat("[1] NaN\n","Warning message:\n","in sqrt(",x,"): NaNs produced\n") else { if (x == 0) { return(0) else { z <- NRsteps(x, z0) return(z) Bisher M. Iqelan (IUG) Lecture 6: Programming Examples 1 st Semester / 38
21 Loops in R For Loop The most commonly used loop structures in R are for, while and apply loops. Less common are repeat loops. OR, similarly; for(i in 1:n){ statements for(variable in sequence) { statements Bisher M. Iqelan (IUG) Lecture 6: Programming Examples 1 st Semester / 38
22 For loops: Examples Example: Print a statement for(i in 1:3){ print("hello R Students!") cat("i=",i,"\n") [1] "Hello R Students!" i= 1 [1] "Hello R Students!" i= 2 [1] "Hello R Students!" i= 3 Everything inside the curly brackets {... is done 3 times. Looped commands can depend on i (or anyother counter). R creates a vector i with 1:3 in it. For Loop is exible, but slow when looping over large number of elds (e.g. thousands of rows or columns) Bisher M. Iqelan (IUG) Lecture 6: Programming Examples 1 st Semester / 38
23 For loops with break statement: Example As we can see from the output, the loop terminates when it encounters the break statement. for (i in 1:5) { for (j in 1:5) { for (k in 1:5) { cat(i," ",j," ",k,"\n") if (k ==3) break Bisher M. Iqelan (IUG) Lecture 6: Programming Examples 1 st Semester / 38
24 For loops with next statement: Example A next statement is useful when we want to skip the current iteration of a loop without terminating it. On encountering next, R skips further evaluation and starts next iteration of the loop. x <- 1:5 for (i in x) { if (i == 3){ next print(i) [1] 1 [1] 2 [1] 4 [1] 5 Bisher M. Iqelan (IUG) Lecture 6: Programming Examples 1 st Semester / 38
25 For loops: Examples Calculating factorials for an integer x: x = x(x 1)(x 2) fact=function(x){ fact=1 if (x<2) {fact=1 else { for (i in 2:x) fact=fact*i return (fact) > fact(5) [1] 120 Another function without loop My.factorial <- function(x) { if (x == 0) return (1) else return (x * My.factorial(x-1)) > My.factorial(5) [1] 120 Bisher M. Iqelan (IUG) Lecture 6: Programming Examples 1 st Semester / 38
26 unique() function: Examples unique() function removes duplicated elements/rows from a vector, data frame or array. > x <- c(2:8,4:10) > unique(x) [1] > A=rbind(1:3,11:13,1:3,15:17,1:3) > unique(a) [,1] [,2] [,3] [1,] [2,] [3,] Bisher M. Iqelan (IUG) Lecture 6: Programming Examples 1 st Semester / 38
27 For loops: Examples Example: Apply this example from R documents: Exercises f = sample(letters[1:5], 10, replace=true) for( i in unique(f) ) print(i) Try these for loops: > for(objs in names(cars)) print(objs) > for(trig in c(sin,cos)) print(trig(pi)) > for (i in seq(2, 10, 3)) print(i) Bisher M. Iqelan (IUG) Lecture 6: Programming Examples 1 st Semester / 38
28 while loops This kind of looping structure is suitable when the number of times the computations contained within the loop is repeated is not known in advance, and the termination of the loop is dependent on some other criteria. The general form of the while loop is: while(cond) expr The simple or compound R expression, expr, is repeatedly executed until the logical expression cond evaluates to a FALSE value. So, when using while, we need to set up an indicator variable and change its value within each iteration. Bisher M. Iqelan (IUG) Lecture 6: Programming Examples 1 st Semester / 38
29 while loops: Examples Consider the following simplest example explaining while loop > y = 1 > while(y < 7){ print(y) y = y+1 [1] 1 [1] 2 [1] 3 [1] 4 [1] 5 [1] 6 Bisher M. Iqelan (IUG) Lecture 6: Programming Examples 1 st Semester / 38
30 while loops: Examples Let us use break statement to end or stop the loop when x=3: x <- 1 > while(x < 5) {x <- x+1; if (x == 3) break; print(x) [1] 2 Now, let us use next statement to skip one step when x=3: > x <- 1 > while(x < 5) {x <- x+1; if (x == 3) next; print(x) [1] 2 [1] 4 [1] 5 Bisher M. Iqelan (IUG) Lecture 6: Programming Examples 1 st Semester / 38
31 while loops: Examples Example:Calculation of the factorial int=4 fact=1 ind=int while (ind > 1){ fact=fact*ind ind=ind-1 > fact [1] 24 In the above example, ind is the indicator variable which change its value within each iteration. Exercise: Generalize the above code to a function call it Myfact to compute the factorial of any number. Bisher M. Iqelan (IUG) Lecture 6: Programming Examples 1 st Semester / 38
32 while loops Examples In practice, a while loop is preferred when the cond expression is used for other purposes than just counting. It can be used, for example, to determine if a terminating condition such as that the error in a computed answer has decreased to be smaller than a pre-specied level and therefore is acceptable. For example, the following loop accumulates a sum to compute exp(5) using the power series 1+x+ x 2 /2! +... expansion: > i=0; term=1; sum=1; x=5 > while(term>.0001){ i=i+1 term=x^i/factorial(i) sum=sum+term > sum [1] > exp(5) [1] Bisher M. Iqelan (IUG) Lecture 6: Programming Examples 1 st Semester / 38
33 while loops Examples In the previous example, the loop is terminated when the value of the next term to be added to the series is less than or equal to :0001. Note that this loop will not work for negative vales of x. Of course, if we knew that we need 21 terms in the series to achieve this accuracy of the result, we could have used the expression: > 1+sum(5^(1:20)/factorial(1:20)) [1] Bisher M. Iqelan (IUG) Lecture 6: Programming Examples 1 st Semester / 38
34 repeat loops The repeat loop is similar to the while loop except that the condition for termination is tested inside the loop. This allows for more than a single condition to be checked and for these conditions to occur at dierent places in the loop. The general form of the repeat loop is: repeat { expression if(condition) { break where the expression is usually an R compound expression. The expression is evaluated repeatedly so that at least one break statement must be in the loop. The loop will be exited only when a given condition is satised. and any number of these statements may appear at dierent places in the loop with dierent cond logical expressions. Bisher M. Iqelan (IUG) Lecture 6: Programming Examples 1 st Semester / 38
35 repeat loops Examples > x <- 1 > repeat { print(x) x = x+1 if (x == 7){ break [1] 1 [1] 2 [1] 3 [1] 4 [1] 5 [1] 6 Bisher M. Iqelan (IUG) Lecture 6: Programming Examples 1 st Semester / 38
36 repeat loops Examples For example the while loop in the previous example may be rewritten as follows: i=0 term=1 sum=1 x=5 repeat{ i=i+1 term=x^i/factorial(i) if(term<=.0001) break sum=sum+term > sum [1] Bisher M. Iqelan (IUG) Lecture 6: Programming Examples 1 st Semester / 38
37 repeat loops Examples Try this R code: i=0 term=1 sum=1 x=5 repeat{ i=i+1 term=x^i/factorial(i) sum=sum+term if(term<=.0001)break cat("i = ",i, "Term = ", term, "Sum = ",sum,fill=t) cat (" Final Value=", sum, fill=t) Bisher M. Iqelan (IUG) Lecture 6: Programming Examples 1 st Semester / 38
38 Evaluating Polynomials A polynomial f (x) of degree n is a function of the form f (x) = a 0 + a 1 x + a 2 x a n x n. This form is the standard method of representing polynomial functions for mathematical purposes. Actually, this form is called the power form. f (x) above can be re-written in the following representation, called Horner's rule. f (x) = a 0 + (a 1 + (a 2 + (a n 1 + a n x)... )x). Bisher M. Iqelan (IUG) Lecture 6: Programming Examples 1 st Semester / 38
39 where a is a vector containing the coecients a 1, a 2,..., a n Bisher M. Iqelan (IUG) Lecture 6: Programming Examples 1 st Semester / 38 Evaluating Polynomials Examples Consider the evaluation of the polynomial with power form: f (x) = 7 + 3x + 4x 2 9x 3 + 5x 4 + 2x 5. An expression for evaluating f(x) using Horner's rule is (3.0 + (4.0 + ( ( x) x) x) x) x which requires only 5 multiplications. (How many multiplications are there in the power form?) This representation can have the following R code: n=6; x=2; a=c(7,3,4,-9,5,2); sum= a[n] for (i in (n-1):1){ sum=sum*x+a[i] cat(" Series sum = ",sum,fill=t)
40 End of lecture 6. Thank you.!!!
STATISTICS 579 R Tutorial : Programming in R
Fall 2005 1. Conditional computation in R: STATISTICS 579 R Tutorial : Programming in R The basic control structure available in R for conditional computation is of the form if (cond) expr-1 else expr-2
More informationStatistical Programming with R
Statistical Programming with R Lecture 5: Simple Programming Bisher M. Iqelan biqelan@iugaza.edu.ps Department of Mathematics, Faculty of Science, The Islamic University of Gaza 2017-2018, Semester 1 Functions
More informationUnit 3 Decision making, Looping and Arrays
Unit 3 Decision making, Looping and Arrays Decision Making During programming, we have a number of situations where we may have to change the order of execution of statements based on certain conditions.
More informationLecture Transcript While and Do While Statements in C++
Lecture Transcript While and Do While Statements in C++ Hello and welcome back. In this lecture we are going to look at the while and do...while iteration statements in C++. Here is a quick recap of some
More informationControl Flow Structures
Control Flow Structures STAT 133 Gaston Sanchez Department of Statistics, UC Berkeley gastonsanchez.com github.com/gastonstat/stat133 Course web: gastonsanchez.com/stat133 Expressions 2 Expressions R code
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 informationLoopy stuff: for loops
R Programming Week 3 : Intro to Loops Reminder: Some of the exercises below require you to have mastered (1) the use of the cat function, and (2) the use of the source function. Loopy stuff: for loops
More informationPDS Lab Section 16 Autumn Tutorial 3. C Programming Constructs
PDS Lab Section 16 Autumn-2017 Tutorial 3 C Programming Constructs This flowchart shows how to find the roots of a Quadratic equation Ax 2 +Bx+C = 0 Start Input A,B,C x B 2 4AC False x If 0 True B x 2A
More informationGovernment Polytechnic Muzaffarpur.
Government Polytechnic Muzaffarpur. Name of the Lab: COMPUTER PROGRAMMING LAB (MECH. ENGG. GROUP) Subject Code: 1625408 Experiment: 1 Aim: Programming exercise on executing a C program. If you are looking
More informationThere are algorithms, however, that need to execute statements in some other kind of ordering depending on certain conditions.
Introduction In the programs that we have dealt with so far, all statements inside the main function were executed in sequence as they appeared, one after the other. This type of sequencing is adequate
More informationn Group of statements that are executed repeatedly while some condition remains true
Looping 1 Loops n Group of statements that are executed repeatedly while some condition remains true n Each execution of the group of statements is called an iteration of the loop 2 Example counter 1,
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 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 informationIntroduction to R. Stat Statistical Computing - Summer Dr. Junvie Pailden. July 5, Southern Illinois University Edwardsville
Introduction to R Stat 575 - Statistical Computing - Summer 2016 Dr. Junvie Pailden Southern Illinois University Edwardsville July 5, 2016 Why R R offers a powerful and appealing interactive environment
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 informationArrays: Higher Dimensional Arrays. CS0007: Introduction to Computer Programming
Arrays: Higher Dimensional Arrays CS0007: Introduction to Computer Programming Review If the == operator has two array variable operands, what is being compared? The reference variables held in the variables.
More information6.001 Notes: Section 4.1
6.001 Notes: Section 4.1 Slide 4.1.1 In this lecture, we are going to take a careful look at the kinds of procedures we can build. We will first go back to look very carefully at the substitution model,
More informationAll copyrights reserved - KV NAD, Aluva. Dinesh Kumar Ram PGT(CS) KV NAD Aluva
All copyrights reserved - KV NAD, Aluva Dinesh Kumar Ram PGT(CS) KV NAD Aluva Overview Looping Introduction While loops Syntax Examples Points to Observe Infinite Loops Examples using while loops do..
More informationDept. of CSE, IIT KGP
Control Flow: Looping CS10001: Programming & Data Structures Pallab Dasgupta Professor, Dept. of Computer Sc. & Engg., Indian Institute of Technology Kharagpur Types of Repeated Execution Loop: Group of
More informationAn interesting related problem is Buffon s Needle which was first proposed in the mid-1700 s.
Using Monte Carlo to Estimate π using Buffon s Needle Problem An interesting related problem is Buffon s Needle which was first proposed in the mid-1700 s. Here s the problem (in a simplified form). Suppose
More informationProgramming Lecture 4
Five-Minute Review 1. What are classes and objects? What is a class hierarchy? 2. What is an expression? A term? 3. What is a variable declaration? 4. What is an assignment? What is precedence? 5. What
More informationCSE100 Principles of Programming with C++
1 Instructions You may work in pairs (that is, as a group of two) with a partner on this lab project if you wish or you may work alone. If you work with a partner, only submit one lab project with both
More informationLesson 20: Every Line is a Graph of a Linear Equation
Student Outcomes Students know that any non vertical line is the graph of a linear equation in the form of, where is a constant. Students write the equation that represents the graph of a line. Lesson
More informationA Look Back at Arithmetic Operators: the Increment and Decrement
A Look Back at Arithmetic Operators: the Increment and Decrement Spring Semester 2016 Programming and Data Structure 27 Increment (++) and Decrement (--) Both of these are unary operators; they operate
More informationIntro. Speed V Growth
Intro Good code is two things. It's elegant, and it's fast. In other words, we got a need for speed. We want to find out what's fast, what's slow, and what we can optimize. First, we'll take a tour of
More informationCONTROL AND HIGHER ORDER FUNCTIONS 2
CONTROL AND HIGHER ORDER FUNCTIONS 2 COMPUTER SCIENCE 61A September 11, 2014 1 Control Control structures direct the flow of logic in a program. This can mean skipping a portion of code (conditionals)
More informationSTATISTICS 579 R Tutorial: More on Writing Functions
Fall 2005 1. Iterative Methods: STATISTICS 579 R Tutorial: More on Writing Functions Three kinds of looping constructs in R: the for loop, the while loop, and the repeat loop were discussed previously.
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 informationLecture Programming in C++ PART 1. By Assistant Professor Dr. Ali Kattan
Lecture 08-1 Programming in C++ PART 1 By Assistant Professor Dr. Ali Kattan 1 The Conditional Operator The conditional operator is similar to the if..else statement but has a shorter format. This is useful
More information21-Loops Part 2 text: Chapter ECEGR 101 Engineering Problem Solving with Matlab Professor Henry Louie
21-Loops Part 2 text: Chapter 6.4-6.6 ECEGR 101 Engineering Problem Solving with Matlab Professor Henry Louie While Loop Infinite Loops Break and Continue Overview Dr. Henry Louie 2 WHILE Loop Used to
More informationMATH2070: LAB 3: Roots of Equations
MATH2070: LAB 3: Roots of Equations 1 Introduction Introduction Exercise 1 A Sample Problem Exercise 2 The Bisection Idea Exercise 3 Programming Bisection Exercise 4 Variable Function Names Exercise 5
More informationLECTURE NOTES ON PROGRAMMING FUNDAMENTAL USING C++ LANGUAGE
Department of Software The University of Babylon LECTURE NOTES ON PROGRAMMING FUNDAMENTAL USING C++ LANGUAGE By Collage of Information Technology, University of Babylon, Iraq Samaher_hussein@yahoo.com
More informationProgramming Basics and Practice GEDB029 Decision Making, Branching and Looping. Prof. Dr. Mannan Saeed Muhammad bit.ly/gedb029
Programming Basics and Practice GEDB029 Decision Making, Branching and Looping Prof. Dr. Mannan Saeed Muhammad bit.ly/gedb029 Decision Making and Branching C language possesses such decision-making capabilities
More informationConstraint-based Metabolic Reconstructions & Analysis H. Scott Hinton. Matlab Tutorial. Lesson: Matlab Tutorial
1 Matlab Tutorial 2 Lecture Learning Objectives Each student should be able to: Describe the Matlab desktop Explain the basic use of Matlab variables Explain the basic use of Matlab scripts Explain the
More informationMODULE 2: Branching and Looping
MODULE 2: Branching and Looping I. Statements in C are of following types: 1. Simple statements: Statements that ends with semicolon 2. Compound statements: are also called as block. Statements written
More informationIntroduction to Internet of Things Prof. Sudip Misra Department of Computer Science & Engineering Indian Institute of Technology, Kharagpur
Introduction to Internet of Things Prof. Sudip Misra Department of Computer Science & Engineering Indian Institute of Technology, Kharagpur Lecture - 23 Introduction to Arduino- II Hi. Now, we will continue
More informationBuilding on the foundation. Now that we know a little about cout cin math operators boolean operators making decisions using if statements
Chapter 5 Looping Building on the foundation Now that we know a little about cout cin math operators boolean operators making decisions using if statements Advantages of Computers Computers are really
More information15-122: Principles of Imperative Computation (Section G)
15-122: Principles of Imperative Computation (Section G) Document 2 Solutions 0. Contracts This lecture was mainly about contracts and ensuring correctness of code. Josh Zimmerman There are 4 types of
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 informationRepetition Structures
Repetition Structures Chapter 5 Fall 2016, CSUS Introduction to Repetition Structures Chapter 5.1 1 Introduction to Repetition Structures A repetition structure causes a statement or set of statements
More informationCondition-Controlled Loop. Condition-Controlled Loop. If Statement. Various Forms. Conditional-Controlled Loop. Loop Caution.
Repetition Structures Introduction to Repetition Structures Chapter 5 Spring 2016, CSUS Chapter 5.1 Introduction to Repetition Structures The Problems with Duplicate Code A repetition structure causes
More informationLecture 10. Daily Puzzle
Lecture 10 Daily Puzzle Imagine there is a ditch, 10 feet wide, which is far too wide to jump. Using only eight narrow planks, each no more than 9 feet long, construct a bridge across the ditch. Daily
More informationLoops and Files. Chapter 04 MIT 12043, Fundamentals of Programming By: S. Sabraz Nawaz
Loops and Files Chapter 04 MIT 12043, Fundamentals of Programming By: S. Sabraz Nawaz Chapter Topics o The Increment and Decrement Operators o The while Loop o Shorthand Assignment Operators o The do-while
More informationChapter 5 Conditional and Iterative Statements (Part-II) To carry out repetitive task, python provides following iterative/looping statements:
Chapter 5 Conditional and Iterative Statements (Part-II) Iterative Statements To carry out repetitive task, python provides following iterative/looping statements: 1. Conditional loop while (condition
More information1 Basic Mathematical Operations
1 Basic Mathematical Operations Recall the basic operations of addition, substraction, multiplication, and division. Consider evaluating the following expression: 2+3 5 Do we add 2 and 3 first or do we
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 informationProgramming Lecture 4
Five-Minute Review 1. What is a class hierarchy? 2. Which graphical coordinate system is used by Java (and most other languages)? 3. Why is a collage a good methapher for GObjects? 4. What is a CFG? What
More information1 Unit 8 'for' Loops
1 Unit 8 'for' 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 informationCSc 372. Comparative Programming Languages. 36 : Scheme Conditional Expressions. Department of Computer Science University of Arizona
1/26 CSc 372 Comparative Programming Languages 36 : Scheme Conditional Expressions Department of Computer Science University of Arizona collberg@gmail.com Copyright c 2013 Christian Collberg 2/26 Comparison
More informationIntroduction to Programming in C Department of Computer Science and Engineering. Lecture No. #16 Loops: Matrix Using Nested for Loop
Introduction to Programming in C Department of Computer Science and Engineering Lecture No. #16 Loops: Matrix Using Nested for Loop In this section, we will use the, for loop to code of the matrix problem.
More informationLecture 1 Contracts. 1 A Mysterious Program : Principles of Imperative Computation (Spring 2018) Frank Pfenning
Lecture 1 Contracts 15-122: Principles of Imperative Computation (Spring 2018) Frank Pfenning In these notes we review contracts, which we use to collectively denote function contracts, loop invariants,
More informationProgramming Problem for the 1999 Comprehensive Exam
Programming Problem for the 1999 Comprehensive Exam Out: Monday 1/25/99 at 9:00 am Due: Friday 1/29/99 at 5:00 pm Department of Computer Science Brown University Providence, RI 02912 1.0 The Task This
More informationIntro to Programming. Unit 7. What is Programming? What is Programming? Intro to Programming
Intro to Programming Unit 7 Intro to Programming 1 What is Programming? 1. Programming Languages 2. Markup vs. Programming 1. Introduction 2. Print Statement 3. Strings 4. Types and Values 5. Math Externals
More informationFundamentals of Programming. Week 1 - Lecture 3: Loops
15-112 Fundamentals of Programming Week 1 - Lecture 3: Loops May 18, 2016 Basic Building Blocks Statements Tells the computer to do something. Data Types Data is divided into different types. Variables
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 informationFortran 90 Two Commonly Used Statements
Fortran 90 Two Commonly Used Statements 1. DO Loops (Compiled primarily from Hahn [1994]) Lab 6B BSYSE 512 Research and Teaching Methods The DO loop (or its equivalent) is one of the most powerful statements
More informationCOMP 208 Computers in Engineering
COMP 208 Computers in Engineering Lecture 14 Jun Wang School of Computer Science McGill University Fall 2007 COMP 208 - Lecture 14 1 Review: basics of C C is case sensitive 2 types of comments: /* */,
More informationPractical 4 Programming in R
Practical 4 Programming in R Q1. Here is an R implementation of Bubble sort. bubblesort
More informationQueens College, CUNY, Department of Computer Science Numerical Methods CSCI 361 / 761 Spring 2018 Instructor: Dr. Sateesh Mane.
Queens College, CUNY, Department of Computer Science Numerical Methods CSCI 36 / 76 Spring 208 Instructor: Dr. Sateesh Mane c Sateesh R. Mane 208 Lecture February 25, 208 This is a collection of useful
More informationAPCS Semester #1 Final Exam Practice Problems
Name: Date: Per: AP Computer Science, Mr. Ferraro APCS Semester #1 Final Exam Practice Problems The problems here are to get you thinking about topics we ve visited thus far in preparation for the semester
More informationChapter 1: Number and Operations
Chapter 1: Number and Operations 1.1 Order of operations When simplifying algebraic expressions we use the following order: 1. Perform operations within a parenthesis. 2. Evaluate exponents. 3. Multiply
More information1 Truth. 2 Conditional Statements. Expressions That Can Evaluate to Boolean Values. Williams College Lecture 4 Brent Heeringa, Bill Jannen
1 Truth Last lecture we learned about the int, float, and string types. Another very important object type in Python is the boolean type. The two reserved keywords True and False are values with type boolean.
More information259 Lecture 25: Simple Programming
259 Lecture 25: Simple Programming In[1]:= In[2]:= Off General::spell Off General::spell1 Note: To type a command in a Mathematica notebook, use the mouse to move the cursor until it is horizontal, click
More informationControl Structures. Lecture 4 COP 3014 Fall September 18, 2017
Control Structures Lecture 4 COP 3014 Fall 2017 September 18, 2017 Control Flow Control flow refers to the specification of the order in which the individual statements, instructions or function calls
More informationCSc 520 Principles of Programming Languages
CSc 520 Principles of Programming Languages 36 : Scheme Conditional Expressions Christian Collberg Department of Computer Science University of Arizona collberg+520@gmail.com Copyright c 2008 Christian
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 informationMAS115 R programming, Lab Class 5 Prof. P. G. Blackwell
MAS115 R programming, Lab Class 5 Prof. P. G. Blackwell 2017-18 1 Writing functions 1.1 Introduction to Functions R has a lot of built in functions that you have already used e.g. sum(), nrow(), runif(),....
More informationUnit 5. Decision Making and Looping. School of Science and Technology INTRODUCTION
INTRODUCTION Decision Making and Looping Unit 5 In the previous lessons we have learned about the programming structure, decision making procedure, how to write statements, as well as different types of
More informationü 1.1 Getting Started
Chapter 1 Introduction Welcome to Mathematica! This tutorial manual is intended as a supplement to Rogawski's Calculus textbook and aimed at students looking to quickly learn Mathematica through examples.
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 informationChapter Two: Program Design Process and Logic
Chapter Two: Program Design Process and Logic 2.1 Chapter objectives Describe the steps involved in the programming process Understand how to use flowchart symbols and pseudocode statements Use a sentinel,
More informationDecision Making and Loops
Decision Making and Loops Goals of this section Continue looking at decision structures - switch control structures -if-else-if control structures Introduce looping -while loop -do-while loop -simple for
More informationLecture 1 Contracts : Principles of Imperative Computation (Fall 2018) Frank Pfenning
Lecture 1 Contracts 15-122: Principles of Imperative Computation (Fall 2018) Frank Pfenning In these notes we review contracts, which we use to collectively denote function contracts, loop invariants,
More information3/12/2018. Structures. Programming in C++ Sequential Branching Repeating. Loops (Repetition)
Structures Programming in C++ Sequential Branching Repeating Loops (Repetition) 2 1 Loops Repetition is referred to the ability of repeating a statement or a set of statements as many times this is necessary.
More information1 Matrices and Vectors and Lists
University of Wollongong School of Mathematics and Applied Statistics STAT231 Probability and Random Variables 2014 Second Lab - Week 4 If you can t finish the log-book questions in lab, proceed at home.
More informationAnnouncements. Lab Friday, 1-2:30 and 3-4:30 in Boot your laptop and start Forte, if you brought your laptop
Announcements Lab Friday, 1-2:30 and 3-4:30 in 26-152 Boot your laptop and start Forte, if you brought your laptop Create an empty file called Lecture4 and create an empty main() method in a class: 1.00
More informationOutline. Midterm Review. Using Excel. Midterm Review: Excel Basics. Using VBA. Sample Exam Question. Midterm Review April 4, 2014
Midterm Review Larry Caretto Mechanical Engineering 209 Computer Programming for Mechanical Engineers April 4, 2017 Outline Excel spreadsheet basics Use of VBA functions and subs Declaring/using variables
More informationAn introduction to Scheme
An introduction to Scheme Introduction A powerful programming language is more than just a means for instructing a computer to perform tasks. The language also serves as a framework within which we organize
More informationStatistical Computing (36-350)
Statistical Computing (36-350) Lecture 3: Flow Control Cosma Shalizi and Vincent Vu 7 September 2011 Agenda Conditionals: Switching between doing different things Iteration: Doing similar things many times
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 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 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 informationControl Structure and Loop Statements
Control Structure and Loop Statements A C/C++ program executes in sequential order that is the way the instructions are written. There are situations when we have to skip certain code in the program and
More information3.7. Vertex and tangent
3.7. Vertex and tangent Example 1. At the right we have drawn the graph of the cubic polynomial f(x) = x 2 (3 x). Notice how the structure of the graph matches the form of the algebraic expression. The
More informationhp calculators hp 39g+ & hp 39g/40g Using Matrices How are matrices stored? How do I solve a system of equations? Quick and easy roots of a polynomial
hp calculators hp 39g+ Using Matrices Using Matrices The purpose of this section of the tutorial is to cover the essentials of matrix manipulation, particularly in solving simultaneous equations. How are
More informationIntroduction to Programming in C Department of Computer Science and Engineering. Lecture No. #43. Multidimensional Arrays
Introduction to Programming in C Department of Computer Science and Engineering Lecture No. #43 Multidimensional Arrays In this video will look at multi-dimensional arrays. (Refer Slide Time: 00:03) In
More informationProblem Solving through Programming In C Prof. Anupam Basu Department of Computer Science & Engineering Indian Institute of Technology, Kharagpur
Problem Solving through Programming In C Prof. Anupam Basu Department of Computer Science & Engineering Indian Institute of Technology, Kharagpur Lecture 18 Switch Statement (Contd.) And Introduction to
More informationSchool of Computer Science CPS109 Course Notes 5 Alexander Ferworn Updated Fall 15
Table of Contents 1 INTRODUCTION... 1 2 IF... 1 2.1 BOOLEAN EXPRESSIONS... 3 2.2 BLOCKS... 3 2.3 IF-ELSE... 4 2.4 NESTING... 5 3 SWITCH (SOMETIMES KNOWN AS CASE )... 6 3.1 A BIT ABOUT BREAK... 7 4 CONDITIONAL
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 informationITERATION AND RECURSION 3
ITERATION AND RECURSION 3 COMPUTER SCIENCE 61A June 26, 2012 1 Newton s Method Newton s method is an algorithm that is widely used to compute the zeros of functions. It can be used to approximate a root
More informationShort Version of Matlab Manual
Short Version of Matlab Manual This is an extract from the manual which was used in MA10126 in first year. Its purpose is to refamiliarise you with the matlab programming concepts. 1 Starting MATLAB 1.1.1.
More information4b: Making an auxiliary table for calculating the standard deviation
In the book we discussed the use of an auxiliary table to calculate variance and standard deviation (Table 4.3). Such a table gives much more insight in the underlying calculations than the simple number
More informationIntroduction to the Java Basics: Control Flow Statements
Lesson 3: Introduction to the Java Basics: Control Flow Statements Repetition Structures THEORY Variable Assignment You can only assign a value to a variable that is consistent with the variable s declared
More informationMidterm Exam with solutions
Midterm Exam with solutions CS227-Introduction to Scientific Computation November 8, 2011 1. The following is a transcript of a MATLAB session. >> x=1/62.5 x = 0.016000000000000 >> y=(1+x)-1 y = 0.016000000000000
More informationMAT 275 Laboratory 2 Matrix Computations and Programming in MATLAB
MATLAB sessions: Laboratory MAT 75 Laboratory Matrix Computations and Programming in MATLAB In this laboratory session we will learn how to. Create and manipulate matrices and vectors.. Write simple programs
More informationPractical 4: The Integrate & Fire neuron
Practical 4: The Integrate & Fire neuron 2014 version by Mark van Rossum 2018 version by Matthias Hennig and Theoklitos Amvrosiadis 16th October 2018 1 Introduction to MATLAB basics You can start MATLAB
More informationECE G205 Fundamentals of Computer Engineering Fall Exercises in Preparation to the Midterm
ECE G205 Fundamentals of Computer Engineering Fall 2003 Exercises in Preparation to the Midterm The following problems can be solved by either providing the pseudo-codes of the required algorithms or the
More informationMatlab and Octave: Quick Introduction and Examples 1 Basics
Matlab and Octave: Quick Introduction and Examples 1 Basics 1.1 Syntax and m-files There is a shell where commands can be written in. All commands must either be built-in commands, functions, names of
More informationDerivatives and Graphs of Functions
Derivatives and Graphs of Functions September 8, 2014 2.2 Second Derivatives, Concavity, and Graphs In the previous section, we discussed how our derivatives can be used to obtain useful information about
More informationMore about Loops and Decisions
More about Loops and Decisions 5 In this chapter, we continue to explore the topic of repetition structures. We will discuss how loops are used in conjunction with the other control structures sequence
More information