Computer Science 2. Conditionals and Loops

Total Page:16

File Type:pdf, Size:1020Kb

Computer Science 2. Conditionals and Loops COMPUTER SCIENCE COMPUTER SCIENCE SEDGEWICK/WAYNE SEDGEWICK/WAYNE PART I: PROGRAMMING IN JAVA PART I: PROGRAMMING IN JAVA Computer Science 2. Conditionals & Loops •Conditionals: the if statement Computer 2. Conditionals and loops •Loops: the while statement Science •An alternative: the for loop An Interdisciplinary Approach •Nesting R O B E R T S E D G E W I C K 1.3 KEVIN WAYNE •Debugging http://introcs.cs.princeton.edu CS.2.A.Loops.If Context: basic building blocks for programming Conditionals and Loops Control flow • The sequence of statements that are actually executed in a program. any program you might want to write • Conditionals and loops enable us to choreograph control flow. objects true boolean 1 functions and modules statement 1 graphics, sound, and image I/O false statement 2 statement 1 arrays boolean 2 true statement 2 conditionalsconditionals and loops statement 3 Math text I/O false statement 4 statement 3 primitive data types assignment statements This lecture: to infinity and beyond! Previous lecture: straight-line control flow control flow with conditionals and a loop equivalent to a calculator [ previous lecture ] [this lecture] 3 4 The if statement Example of if statement use: simulate a coin flip Execute certain statements depending on the values of certain variables. • Evaluate a boolean expression. public class Flip • If true, execute a statement. { • The else option: If false, execute a different statement. public static void main(String[] args) { if (Math.random() < 0.5) System.out.println("Heads"); Example: if (x > y) max = x; Example: if (x < 0) x = -x; else else max = y; System.out.println("Tails"); % java Flip } Heads } true true x < 0 ? false x > y ? false % java Flip Heads x = -x; max = x; max = y; % java Flip Tails % java Flip Heads Replaces x with the absolute value of x Computes the maximum of x and y 5 6 Example of if statement use: 2-sort Pop quiz on if statements Q. What does this program do? Q. Add code to this program that puts a, b, and c in numerical order. public class TwoSort public class ThreeSort { { public static void main(String[] args) public static void main(String[] args) { { int a = Integer.parseInt(args[0]); int a = Integer.parseInt(args[0]); int b = Integer.parseInt(args[1]); int b = Integer.parseInt(args[1]); % java ThreeSort 1234 99 1 if (b < a) int c = Integer.parseInt(args[2]); 1 { % java TwoSort 1234 99 99 int t = a; alternatives for if and else 99 1234 a = b; can be a sequence of 1234 statements, enclosed in braces b = t; % java ThreeSort 99 1 1234 } % java TwoSort 99 1234 1 System.out.println(a); 99 99 System.out.println(b); 1234 System.out.println(a); 1234 } System.out.println(b); } System.out.println(c); } } A. Reads two integers from the command line, then prints them out in numerical order. 7 8 Pop quiz on if statements Example of if statement use: error checks Q. Add code to this program that puts a, b, and c in numerical order. public class IntOps { public static void main(String[] args) public class ThreeSort { % java IntOps 5 2 { 5 + 2 = 7 public static void main(String[] args) int a = Integer.parseInt(args[0]); { int b = Integer.parseInt(args[1]); 5 * 2 = 10 int a = Integer.parseInt(args[0]); int sum = a + b; 5 / 2 = 2 int b = Integer.parseInt(args[1]); % java ThreeSort 1234 99 1 int prod = a * b; 5 % 2 = 1 int c = Integer.parseInt(args[2]); 1 System.out.println(a + " + " + b + " = " + sum); if (b < a) % java IntOps 5 0 A. 99 System.out.println(a + " * " + b + " = " + prod); { int t = a; a = b; b = t; } 1234 5 + 0 = 5 makes a smaller if (b == 0) System.out.println("Division by zero"); if (c < a) than b 5 * 0 = 0 else System.out.println(a + " / " + b + " = " + a / b); { int t = a; a = c; c = t; } makes a smaller % java ThreeSort 99 1 1234 Division by zero if (c < b) than both b and c 1 if (b == 0) System.out.println("Division by zero"); Division by zero { int t = b; b = c; c = t; } makes b smaller 99 else System.out.println(a + " % " + b + " = " + a % b); System.out.println(a); than c 1234 } System.out.println(b); System.out.println(c); } } } Good programming practice. Use conditionals to check for and avoid runtime errors. 9 10 COMPUTER SCIENCE COMPUTER SCIENCE SEDGEWICK/WAYNE SEDGEWICK/WAYNE PART I: PROGRAMMING IN JAVA PART I: PROGRAMMING IN JAVA Image sources http://commons.wikimedia.org/wiki/File:Calculator_casio.jpg http://en.wikipedia.org/wiki/File:Buzz-lightyear-toy-story-3-wallpaper.jpg http://www.ncbi.nlm.nih.gov/pmc/articles/PMC2789164/#!po=30.0000 [181e306f1.jpg] 2. Conditionals & Loops •Conditionals: the if statement •Loops: the while statement •An alternative: the for loop •Nesting •Debugging CS.2.A.Loops.If CS.2.B.Loops.While The while loop Example of while loop use: print powers of two A trace is a table of variable values after each statement. Execute certain statements repeatedly until certain conditions are met. public class PowersOfTwo i v i <= n • Evaluate a boolean expression. i = 0; { 0 1 true If true, execute a sequence of statements. • public static void main(String[] args) 1 2 true • Repeat. v = 1; { int n = Integer.parseInt(args[0]); 2 4 true int i = 0; 3 8 true i <= n ? false Example: int v = 1; 4 16 true int i = 0; while (i <= n) int v = 1; true { 5 32 true while (i <= n) System.out.println(v); System.out.println(v); 6 64 true { i = i + 1; % java PowersOfTwo 6 7 128 false 1 System.out.println(v); v = 2 * v; i = i + 1; 2 i = i + 1; } 4 v = 2 * v; } 8 } v = 2 * v; 16 } 32 64 Prints the powers of two from 20 to 2n . Prints the powers of two from 20 to 2n . [stay tuned for a trace] 13 14 Pop quiz on while loops Pop quiz on while loops Q. Anything wrong with the following code? Q. Anything wrong with the following code? public class PQwhile public class PQwhile { { public static void main(String[] args) public static void main(String[] args) { { Q. What does it do (without the braces)? int n = Integer.parseInt(args[0]); int n = Integer.parseInt(args[0]); int i = 0; int i = 0; int v = 1; int v = 1; A. Goes into an infinite loop. while (i <= n) while (i <= n) System.out.println(v); { System.out.println(v); i = i + 1; i = i + 1; % java PQwhile 6 v = 2 * v; v = 2 * v; } 1 } } 1 1 challenge: figure out } } how to stop it 1 on your computer 1 1 1 A. Yes! Needs braces. 1 1 1 15 1 16 Example of while loop use: implement Math.sqrt() Example of while loop use: implement Math.sqrt() Goal. Implement square root function. % java Sqrt 60481729.0 Newton-Raphson method to compute √c 7777.0 Scientists studied % java Sqrt 2.0 • Initialize t0 = c. computation well before 1.4142136 • Repeat until ti = c/ti (up to desired precision): the onset of the computer. Set ti+1 to be the average of ti and c / ti. Newton-Raphson method to compute √c Isaac Newton 1642-1727 • Initialize t0 = c. if t = c/t then t2 = c public class Sqrt • Repeat until ti = c/ti (up to desired precision): { Set ti+1 to be the average of ti and c / ti. public static void main(String[] args) { double EPS = 1E-15; error tolerance (15 places) % java Sqrt 60481729.0 i ti 2/ti average 7777.0 double c = Double.parseDouble(args[0]); 0 2 1 1.5 double t = c; % java Sqrt 2.0 1 1.5 1.3333333 1.4166667 while (Math.abs(t - c/t) > t*EPS) 1.414213562373095 t = (c/t + t) / 2.0; 2 1.4166667 1.4117647 1.4142157 System.out.println(t); 3 1.4142157 1.4142114 1.4142136 } } 4 1.4142136 1.4142136 computing the square root of 2 to seven places 17 18 Newton-Raphson method COMPUTER SCIENCE SEDGEWICK/WAYNE PART I: PROGRAMMING IN JAVA Explanation (some math omitted) • Goal: find root of function f(x) (value of x for which f(x) = 0). use f(x) = x2 − c for √c Image sources • Start with estimate t0. http://www.sciencecartoonsplus.com • Draw line tangent to curve at x = ti . http://en.wikipedia.org/wiki/Isaac_Newton • Set ti+1 to be x-coordinate where line hits x-axis. y = f(x) http://www.onlinemathtutor.org/help/wp-content/uploads/math-cartoon-28112009.jpg • Repeat until desired precision. root: f(x) = 0 ti+3 ti+2 ti+1 ti 19 CS.2.B.Loops.While COMPUTER SCIENCE The for loop SEDGEWICK/WAYNE PART I: PROGRAMMING IN JAVA An alternative repetition structure. Why? Can provide code that is more compact and understandable. • Evaluate an initialization statement. • Evaluate a boolean expression. • If true, execute a sequence of statements, then execute an increment statement. 2. Conditionals & Loops • Repeat. •Conditionals: the if statement Example: initialization statement Every for loop has an equivalent while loop: int v = 1; int v = 1; •Loops: the while statement for ( int i = 0; i <= n; i++ ) int i = 0; •An alternative: the for loop { boolean expression while ( i <= n; ) System.out.println( i + " " + v ); { •Nesting v = 2*v; System.out.println( i + " " + v ); increment statement •Debugging } v = 2*v; i++; Prints the powers of two from 20 to 2n } CS.2.C.Loops.For 22 Examples of for loop use Example of for loop use: subdivisions of a ruler sum i int sum = 0; 1 1 Create subdivisions of a ruler to 1/N inches.
Recommended publications
  • C++ Programming: Program Design Including Data Structures, Fifth Edition
    C++ Programming: From Problem Analysis to Program Design, Fifth Edition Chapter 5: Control Structures II (Repetition) Objectives In this chapter, you will: • Learn about repetition (looping) control structures • Explore how to construct and use count- controlled, sentinel-controlled, flag- controlled, and EOF-controlled repetition structures • Examine break and continue statements • Discover how to form and use nested control structures C++ Programming: From Problem Analysis to Program Design, Fifth Edition 2 Objectives (cont'd.) • Learn how to avoid bugs by avoiding patches • Learn how to debug loops C++ Programming: From Problem Analysis to Program Design, Fifth Edition 3 Why Is Repetition Needed? • Repetition allows you to efficiently use variables • Can input, add, and average multiple numbers using a limited number of variables • For example, to add five numbers: – Declare a variable for each number, input the numbers and add the variables together – Create a loop that reads a number into a variable and adds it to a variable that contains the sum of the numbers C++ Programming: From Problem Analysis to Program Design, Fifth Edition 4 while Looping (Repetition) Structure • The general form of the while statement is: while is a reserved word • Statement can be simple or compound • Expression acts as a decision maker and is usually a logical expression • Statement is called the body of the loop • The parentheses are part of the syntax C++ Programming: From Problem Analysis to Program Design, Fifth Edition 5 while Looping (Repetition)
    [Show full text]
  • Compiler Construction Assignment 3 – Spring 2018
    Compiler Construction Assignment 3 { Spring 2018 Robert van Engelen µc for the JVM µc (micro-C) is a small C-inspired programming language. In this assignment we will implement a compiler in C++ for µc. The compiler compiles µc programs to java class files for execution with the Java virtual machine. To implement the compiler, we can reuse the same concepts in the code-generation parts that were done in programming assignment 1 and reuse parts of the lexical analyzer you implemented in programming assignment 2. We will implement a new parser based on Yacc/Bison. This new parser utilizes translation schemes defined in Yacc grammars to emit Java bytecode. In the next programming assignment (the last assignment following this assignment) we will further extend the capabilities of our µc compiler by adding static semantics such as data types, apply type checking, and implement scoping rules for functions and blocks. Download Download the Pr3.zip file from http://www.cs.fsu.edu/~engelen/courses/COP5621/Pr3.zip. After unzipping you will get the following files Makefile A makefile bytecode.c The bytecode emitter (same as Pr1) bytecode.h The bytecode definitions (same as Pr1) error.c Error reporter global.h Global definitions init.c Symbol table initialization javaclass.c Java class file operations (same as Pr1) javaclass.h Java class file definitions (same as Pr1) mycc.l *) Lex specification mycc.y *) Yacc specification and main program symbol.c *) Symbol table operations test#.uc A number of µc test programs The files marked ∗) are incomplete. For this assignment you are required to complete these files.
    [Show full text]
  • PDF Python 3
    Python for Everybody Exploring Data Using Python 3 Charles R. Severance 5.7. LOOP PATTERNS 61 In Python terms, the variable friends is a list1 of three strings and the for loop goes through the list and executes the body once for each of the three strings in the list resulting in this output: Happy New Year: Joseph Happy New Year: Glenn Happy New Year: Sally Done! Translating this for loop to English is not as direct as the while, but if you think of friends as a set, it goes like this: “Run the statements in the body of the for loop once for each friend in the set named friends.” Looking at the for loop, for and in are reserved Python keywords, and friend and friends are variables. for friend in friends: print('Happy New Year:', friend) In particular, friend is the iteration variable for the for loop. The variable friend changes for each iteration of the loop and controls when the for loop completes. The iteration variable steps successively through the three strings stored in the friends variable. 5.7 Loop patterns Often we use a for or while loop to go through a list of items or the contents of a file and we are looking for something such as the largest or smallest value of the data we scan through. These loops are generally constructed by: • Initializing one or more variables before the loop starts • Performing some computation on each item in the loop body, possibly chang- ing the variables in the body of the loop • Looking at the resulting variables when the loop completes We will use a list of numbers to demonstrate the concepts and construction of these loop patterns.
    [Show full text]
  • 7. Control Flow First?
    Copyright (C) R.A. van Engelen, FSU Department of Computer Science, 2000-2004 Ordering Program Execution: What is Done 7. Control Flow First? Overview Categories for specifying ordering in programming languages: Expressions 1. Sequencing: the execution of statements and evaluation of Evaluation order expressions is usually in the order in which they appear in a Assignments program text Structured and unstructured flow constructs 2. Selection (or alternation): a run-time condition determines the Goto's choice among two or more statements or expressions Sequencing 3. Iteration: a statement is repeated a number of times or until a Selection run-time condition is met Iteration and iterators 4. Procedural abstraction: subroutines encapsulate collections of Recursion statements and subroutine calls can be treated as single Nondeterminacy statements 5. Recursion: subroutines which call themselves directly or indirectly to solve a problem, where the problem is typically defined in terms of simpler versions of itself 6. Concurrency: two or more program fragments executed in parallel, either on separate processors or interleaved on a single processor Note: Study Chapter 6 of the textbook except Section 7. Nondeterminacy: the execution order among alternative 6.6.2. constructs is deliberately left unspecified, indicating that any alternative will lead to a correct result Expression Syntax Expression Evaluation Ordering: Precedence An expression consists of and Associativity An atomic object, e.g. number or variable The use of infix, prefix, and postfix notation leads to ambiguity An operator applied to a collection of operands (or as to what is an operand of what arguments) which are expressions Fortran example: a+b*c**d**e/f Common syntactic forms for operators: The choice among alternative evaluation orders depends on Function call notation, e.g.
    [Show full text]
  • While Statement in C
    While Statement In C EnricoIs Reg alwaysdisheartening deplete or his novel aspects when chagrined luminesced disputatiously, some crayfishes he orbits clump so temporizingly? grindingly. Solid Ring-necked and comose Bennet Brendan tarnishes never tensehalf-and-half his Stuttgart! while Thank you use a counter is a while loop obscures the condition which is evaluated to embed videos in while c program C while loops statement allows to repeatedly run at same recipient of code until a wrap is met while loop is empty most basic loop in C programming while loop. We then hand this variable c in the statement block and represent your value for each. While adultery in C Set of instructions given coil the compiler to night set of statements until condition becomes false is called loops. If it is negative number added to the condition in c language including but in looping structures, but is executed infinite loop! While Loop Definition Example & Results Video & Lesson. While talking in C Know Program. What is the while eternal in C? A while loop around loop continuously and infinitely until the policy inside the parenthesis becomes false money must guard the. C while and dowhile Loop Programiz. Programming While Loop. The widow while redeem in the C language is basically a post tested loop upon the execution of several parts of the statements can be repeated by reckless use children do-while. 43 Loops Applications in C for Engineering Technology. Do it Loop in C Programming with Examples Phptpoint. Statements and display control C Tutorials Cpluspluscom. Do while just in c example program.
    [Show full text]
  • A Survey of Hardware-Based Control Flow Integrity (CFI)
    A survey of Hardware-based Control Flow Integrity (CFI) RUAN DE CLERCQ∗ and INGRID VERBAUWHEDE, KU Leuven Control Flow Integrity (CFI) is a computer security technique that detects runtime attacks by monitoring a program’s branching behavior. This work presents a detailed analysis of the security policies enforced by 21 recent hardware-based CFI architectures. The goal is to evaluate the security, limitations, hardware cost, performance, and practicality of using these policies. We show that many architectures are not suitable for widespread adoption, since they have practical issues, such as relying on accurate control flow model (which is difficult to obtain) or they implement policies which provide only limited security. CCS Concepts: • Security and privacy → Hardware-based security protocols; Information flow control; • General and reference → Surveys and overviews; Additional Key Words and Phrases: control-flow integrity, control-flow hijacking, return oriented programming, shadow stack ACM Reference format: Ruan de Clercq and Ingrid Verbauwhede. YYYY. A survey of Hardware-based Control Flow Integrity (CFI). ACM Comput. Surv. V, N, Article A (January YYYY), 27 pages. https://doi.org/10.1145/nnnnnnn.nnnnnnn 1 INTRODUCTION Today, a lot of software is written in memory unsafe languages, such as C and C++, which introduces memory corruption bugs. This makes software vulnerable to attack, since attackers exploit these bugs to make the software misbehave. Modern Operating Systems (OSs) and microprocessors are equipped with security mechanisms to protect against some classes of attacks. However, these mechanisms cannot defend against all attack classes. In particular, Code Reuse Attacks (CRAs), which re-uses pre-existing software for malicious purposes, is an important threat that is difficult to protect against.
    [Show full text]
  • Repetition Structures
    24785_CH06_BRONSON.qrk 11/10/04 9:05 M Page 301 Repetition Structures 6.1 Introduction Goals 6.2 Do While Loops 6.3 Interactive Do While Loops 6.4 For/Next Loops 6.5 Nested Loops 6.6 Exit-Controlled Loops 6.7 Focus on Program Design and Implementation: After-the- Fact Data Validation and Creating Keyboard Shortcuts 6.8 Knowing About: Programming Costs 6.9 Common Programming Errors and Problems 6.10 Chapter Review 24785_CH06_BRONSON.qrk 11/10/04 9:05 M Page 302 302 | Chapter 6: Repetition Structures The applications examined so far have illustrated the programming concepts involved in input, output, assignment, and selection capabilities. By this time you should have gained enough experience to be comfortable with these concepts and the mechanics of implementing them using Visual Basic. However, many problems require a repetition capability, in which the same calculation or sequence of instructions is repeated, over and over, using different sets of data. Examples of such repetition include continual checking of user data entries until an acceptable entry, such as a valid password, is made; counting and accumulating running totals; and recurring acceptance of input data and recalculation of output values that only stop upon entry of a designated value. This chapter explores the different methods that programmers use to construct repeating sections of code and how they can be implemented in Visual Basic. A repeated procedural section of code is commonly called a loop, because after the last statement in the code is executed, the program branches, or loops back to the first statement and starts another repetition.
    [Show full text]
  • Control-Flow Analysis of Functional Programs
    Control-flow analysis of functional programs JAN MIDTGAARD Department of Computer Science, Aarhus University We present a survey of control-flow analysis of functional programs, which has been the subject of extensive investigation throughout the past 30 years. Analyses of the control flow of functional programs have been formulated in multiple settings and have led to many different approximations, starting with the seminal works of Jones, Shivers, and Sestoft. In this paper, we survey control-flow analysis of functional programs by structuring the multitude of formulations and approximations and comparing them. Categories and Subject Descriptors: D.3.2 [Programming Languages]: Language Classifica- tions—Applicative languages; F.3.1 [Logics and Meanings of Programs]: Specifying and Ver- ifying and Reasoning about Programs General Terms: Languages, Theory, Verification Additional Key Words and Phrases: Control-flow analysis, higher-order functions 1. INTRODUCTION Since the introduction of high-level languages and compilers, much work has been devoted to approximating, at compile time, which values the variables of a given program may denote at run time. The problem has been named data-flow analysis or just flow analysis. In a language without higher-order functions, the operator of a function call is apparent from the text of the program: it is a lexically visible identifier and therefore the called function is available at compile time. One can thus base an analysis for such a language on the textual structure of the program, since it determines the exact control flow of the program, e.g., as a flow chart. On the other hand, in a language with higher-order functions, the operator of a function call may not be apparent from the text of the program: it can be the result of a computation and therefore the called function may not be available until run time.
    [Show full text]
  • An Introduction to Programming in Simula
    An Introduction to Programming in Simula Rob Pooley This document, including all parts below hyperlinked directly to it, is copyright Rob Pooley ([email protected]). You are free to use it for your own non-commercial purposes, but may not copy it or reproduce all or part of it without including this paragraph. If you wish to use it for gain in any manner, you should contact Rob Pooley for terms appropriate to that use. Teachers in publicly funded schools, universities and colleges are free to use it in their normal teaching. Anyone, including vendors of commercial products, may include links to it in any documentation they distribute, so long as the link is to this page, not any sub-part. This is an .pdf version of the book originally published by Blackwell Scientific Publications. The copyright of that book also belongs to Rob Pooley. REMARK: This document is reassembled from the HTML version found on the web: https://web.archive.org/web/20040919031218/http://www.macs.hw.ac.uk/~rjp/bookhtml/ Oslo 20. March 2018 Øystein Myhre Andersen Table of Contents Chapter 1 - Begin at the beginning Basics Chapter 2 - And end at the end Syntax and semantics of basic elements Chapter 3 - Type cast actors Basic arithmetic and other simple types Chapter 4 - If only Conditional statements Chapter 5 - Would you mind repeating that? Texts and while loops Chapter 6 - Correct Procedures Building blocks Chapter 7 - File FOR future reference Simple input and output using InFile, OutFile and PrintFile Chapter 8 - Item by Item Item oriented reading and writing and for loops Chapter 9 - Classes as Records Chapter 10 - Make me a list Lists 1 - Arrays and simple linked lists Reference comparison Chapter 11 - Like parent like child Sub-classes and complex Boolean expressions Chapter 12 - A Language with Character Character handling, switches and jumps Chapter 13 - Let Us See what We Can See Inspection and Remote Accessing Chapter 14 - Side by Side Coroutines Chapter 15 - File For Immediate Use Direct and Byte Files Chapter 16 - With All My Worldly Goods..
    [Show full text]
  • 6Up with Notes
    Notes CSCE150A Computer Science & Engineering 150A Problem Solving Using Computers Lecture 05 - Loops Stephen Scott (Adapted from Christopher M. Bourke) Fall 2009 1 / 1 [email protected] Chapter 5 CSCE150A 5.1 Repetition in Programs 5.2 Counting Loops and the While Statement 5.3 Computing a Sum or a Product in a Loop 5.4 The for Statement 5.5 Conditional Loops 5.6 Loop Design 5.7 Nested Loops 5.8 Do While Statement and Flag-Controlled Loops 5.10 How to Debug and Test 5.11 Common Programming Errors 2 / 1 Repetition in Programs CSCE150A Just as the ability to make decisions (if-else selection statements) is an important programming tool, so too is the ability to specify the repetition of a group of operations. When solving a general problem, it is sometimes helpful to write a solution to a specific case. Once this is done, ask yourself: Were there any steps that I repeated? If so, which ones? Do I know how many times I will have to repeat the steps? If not, how did I know how long to keep repeating the steps? 3 / 1 Notes Counting Loops CSCE150A A counter-controlled loop (or counting loop) is a loop whose repetition is managed by a loop control variable whose value represents a count. Also called a while loop. 1 Set counter to an initial value of 0 2 while counter < someF inalV alue do 3 Block of program code 4 Increase counter by 1 5 end Algorithm 1: Counter-Controlled Loop 4 / 1 The C While Loop CSCE150A This while loop computes and displays the gross pay for seven employees.
    [Show full text]
  • A Short Introduction to Ocaml
    Ecole´ Polytechnique INF549 A Short Introduction to OCaml Jean-Christophe Filli^atre September 11, 2018 Jean-Christophe Filli^atre A Short Introduction to OCaml INF549 1 / 102 overview lecture Jean-Christophe Filli^atre labs St´ephaneLengrand Monday 17 and Tuesday 18, 9h{12h web site for this course http://www.enseignement.polytechnique.fr/profs/ informatique/Jean-Christophe.Filliatre/INF549/ questions ) [email protected] Jean-Christophe Filli^atre A Short Introduction to OCaml INF549 2 / 102 OCaml OCaml is a general-purpose, strongly typed programming language successor of Caml Light (itself successor of Caml), part of the ML family (SML, F#, etc.) designed and implemented at Inria Rocquencourt by Xavier Leroy and others Some applications: symbolic computation and languages (IBM, Intel, Dassault Syst`emes),static analysis (Microsoft, ENS), file synchronization (Unison), peer-to-peer (MLDonkey), finance (LexiFi, Jane Street Capital), teaching Jean-Christophe Filli^atre A Short Introduction to OCaml INF549 3 / 102 first steps with OCaml Jean-Christophe Filli^atre A Short Introduction to OCaml INF549 4 / 102 the first program hello.ml print_string "hello world!\n" compiling % ocamlopt -o hello hello.ml executing % ./hello hello world! Jean-Christophe Filli^atre A Short Introduction to OCaml INF549 5 / 102 the first program hello.ml print_string "hello world!\n" compiling % ocamlopt -o hello hello.ml executing % ./hello hello world! Jean-Christophe Filli^atre A Short Introduction to OCaml INF549 5 / 102 the first program hello.ml
    [Show full text]
  • Chapter 6 Flow of Control
    Chapter 6 Flow of Control 6.1 INTRODUCTION “Don't you hate code that's In Figure 6.1, we see a bus carrying the children to not properly indented? school. There is only one way to reach the school. The Making it [indenting] part of driver has no choice, but to follow the road one milestone the syntax guarantees that all after another to reach the school. We learnt in Chapter code is properly indented.” 5 that this is the concept of sequence, where Python executes one statement after another from beginning to – G. van Rossum the end of the program. These are the kind of programs we have been writing till now. In this chapter Figure 6.1: Bus carrying students to school » Introduction to Flow of Control Let us consider a program 6-1 that executes in » Selection sequence, that is, statements are executed in an order in which they are written. » Indentation The order of execution of the statements in a program » Repetition is known as flow of control. The flow of control can be » Break and Continue implemented using control structures. Python supports Statements two types of control structures—selection and repetition. » Nested Loops 2021-22 Ch 6.indd 121 08-Apr-19 12:37:51 PM 122 COMPUTER SCIENCE – CLASS XI Program 6-1 Program to print the difference of two numbers. #Program 6-1 #Program to print the difference of two input numbers num1 = int(input("Enter first number: ")) num2 = int(input("Enter second number: ")) diff = num1 - num2 print("The difference of",num1,"and",num2,"is",diff) Output: Enter first number 5 Enter second number 7 The difference of 5 and 7 is -2 6.2 SELECTION Now suppose we have `10 to buy a pen.
    [Show full text]