A Programming Essentials

Total Page:16

File Type:pdf, Size:1020Kb

A Programming Essentials A Programming Essentials This appendix covers the basic elements of the programming languages, which are essential for developing NS2 simulation programs. These include Tcl/OTcl which is the basic building block of NS2 and AWK which can be used for post simulation analysis. A.1 Tcl Programming Tcl is a general purpose scripting language. While it can do anything other languages could possibly do, its integration with other languages has proven even more powerful. Tcl runs on most of the platforms such as Unix, Windows, and Mac. The strength of Tcl is its simplicity. It is not necessary to declare a data type for variable prior to the usage. At runtime, Tcl interprets the codes line by line and converts the string into appropriate data type (e.g., integer) on the fly. A.1.1 Program Invocation Tcl can be invoked from a shell command prompt with the following syntax: tclsh [<filename> <arg0> <arg1> ...] where tclsh is mandatory. Other input arguments are optional. When the above command is invoked without input argument, the shell enters Tcl en- vironment where it waits for the Tcl statements line by line. If <filename> is specified, Tcl will interpret the text specified in the file whose name is <filename> line by line. In addition, if <arg0> <arg1> ... are specified, they will be placed in a list variable (see Section A.1.3) argv.Inthemain program, <argi> can be retrieved by executing “lindex $argv $i”. 390 A Programming Essentials A.1.2 A Simple Example To get a feeling about the language, we look at Example A.1 below: Example A.1. The following Tcl script, “convert.tcl”, converts tempera- tures from Fahrenheit to Celsius. The conversion starts at 0 degree (Fahren- heit), proceeds with a step of 25 degrees (Fahrenheit), and stops when the temperature exceeds 140 degrees (Fahrenheit). The program prints out the converted temperature in Celsius as long as the temperature in Fahrenheit does not exceed 140 degrees. # convert.tcl # Fahrenheit to Celsius Conversion 1 proc tempconv {} { 2 set lower 0 3 set upper 140 4 set step 25 5 set fahr $lower 6 while {fahr < $upper} { 7 set celsius [expr 5*($fahr - 32)/9] 8 puts "Fahrenheit / Celsius : $fahr / $celsius" 9 set fahr [expr $fahr + $step] 10 } 11 } The details of the above example are as follows. The symbol # here denotes the beginning of a line comment. The reserved word proc in Line 1 declares a procedure tempconv{} which takes no input argument. The procedure also defines four local variables (i.e., lower, upper, step,andfahr) and assigns values to them using the reserved word set followed by the name and its as- signed value (Lines 2–5). Note here that, to refer to the value of a variable, the reserved character $ is used in front of the variable (e.g., set fahr $lower). The keyword expr in Line 9 informs the Tcl interpreter to interpret the fol- lowing string as a mathematical expression. The while loop in Lines 6–10 controls the iteration of the procedure through the test expression enclosed in a double quotation mark. The command puts in Line 8 prints out the string contained within the quotation mark. If the name of the script is convert.tcl, the script can be executed by typing the following on a shell prompt: >>tclsh convert.tcl Fahrenheit / Celsius : 0 / -17.778 Fahrenheit / Celsius : 25 / -3.889 Fahrenheit / Celsius : 50 / 10 Fahrenheit / Celsius : 75 / 23.889 Fahrenheit / Celsius : 100 / 37.778 Fahrenheit / Celsius : 125 / 51.667 A.1 Tcl Programming 391 Alternatively, since NS2 is written in Tcl, the following invocation would lead to the same result. >>ns convert.tcl A.1.3 Variables and Data Types Data Types As an interpreter, Tcl does not need to define data type of variables. Instead, it stores everything in string and interprets them based on the context. Example A.2. Consider the following Tcl codes: # vars.tcl 1 set a "10+1" 2 set b "5" 3 set c $a$b 4 set d [expr $a$b] 5 puts $c 6 puts $d 7 unset c 8 puts $c After executing the Tcl script “vars.tcl”, the following result should appear on the screen: >>tclsh vars.tcl 10+15 25 Here, variable c is simply a string “10+15”, whereas variable d is 25 ob- tained by numerically evaluating the string “10+15”storedinvariablec. Therefore, we may conclude that everything is treated as a string unless spec- ified otherwise [26]. Variable Assignment and Retrieval Tcl stores a value in a variable using the reserved word “set”. The value stored in a variable can be retrieved by placing a character “$”infrontofa variable name. In addition, a reserved word “unset” is used to clear the value stored in a variable. Example A.3. Insert the following two lines into the end of the codes in Example A.2. 7 unset c 8 puts $c 392 A Programming Essentials After executing the Tcl script “vars.tcl”, the following result should appear on the screen: >>tclsh vars.tcl 10+15 25 can’t read "c": no such variable while executing "puts c" (file "var.tcl" line 8) Clearly after being unset,variablec stores nothing. Printing the variable would result in a runtime error. Bracketing There are four type of bracketing in Tcl. These are used to group a series of strings. Tcl interprets strings inside different types of bracket differently. Suppose a variable $var stores a value 10. Tcl interprets a statement “expr $var + 1” with four different bracketing differently. • Curly braces ({expr $var + 1}): Tcl interprets this statement as it is. • Quotation marks ("expr $var + 1"): Tcl interpolates the variable var in the string. This statement would be interpreted as “expr 10 + 1”. • Square brackets ([expr $var + 1]): Tcl regards a square bracket in the same way that C++ regards a parenthesis. It interprets the string in a square bracket before interpreting the entire line. This statement would be interpreted as “11”. • Parentheses ((expr $var + 1)): Tcl uses a parentheses for indexing an array and for invoking built-in mathematical function. Example A.4. Insert the following two lines into the end of the codes in Example A.2. 7 puts -nonewline {{}: } 8 puts {expr $c} 9 puts -nonewline {"": } 10 puts "expr $c" 11 puts -nonewline {[]: } 12 puts [expr $c] After executing the Tcl script “vars.tcl”, the following result should appear on the screen: >>tclsh vars.tcl 10+15 25 A.1 Tcl Programming 393 {}: expr $c "": expr 10+15 []: 25 When bracketing with “{}”, Tcl interprets the string as it is; The result in this case is “expr $c”. The string $c is replaced with its value when bracketing with “""”. The result in this case is “expr 10+15”. Finally, “[]”identifies the sequence of execution. The string “expr $c” is executed first. The result in this case is “25”. Global Variables In Example A.1, we briefly mentioned about local variables. But what was missing there is the notion of global variables. Global variables are common and used extensively throughout a program. These variables can be called upon by any procedure in the program. Example A.5 shows an example use of global variables. Example A.5 (Global variables). set PI 3.1415926536 proc perimeter {radius} { global PI expr 2*$PI*$radius } Since “PI” is defined outside of the procedure perimeter,thekeyword global is used here to make “PI” global and available within the procedure. When called upon, this procedure simply calculates the perimeter of a circle based on the supplied input radius. Finally, we note here that no default values are automatically assigned to variables. Any attempt to call an unini- tialized variable would lead to a runtime error. Array An array is a special variable which can be used to store a collection of items. An array stores both the indexes and the values as strings. For example, index “0” is not a number, but a numeric string. By default, an array in Tcl is an associative array. Example A.6 below shows various ways of string manipulation. Example A.6 (Array assignment). # Numeric indexing set arr(0) 1 set arr(1) 3 set arr(1) 5 394 A Programming Essentials # String indexing set wlan(datarate) 54000000 set wlan(protocol) "tcp" Lists A list is an ordered collection of elements such as numbers, strings or even lists themselves. The key list manipulations are shown below: • List creation: A list can be created in various ways as shown in Exam- ple A.7 below. Example A.7. The following two statement are equivalent (i) set mylist "1 2 3" (ii) set mylist {123} From the above, a list can be created in three ways. First, it can be created by the reserved word list which takes list members as input arguments. Alternatively, it can be created by embracing the members within a pair of curly braces or a pair of quotation marks. • Member retrieval: The following command returns the nth (= {0, 1, ···}) element in a list mylist: lindex $mylist $n • Member setting: The following command sets the value of the nth ele- ment in a list mylist to be <value>: lset $mylist $n $value • Group retrieval: The following command returns a list whose members are the nth member through the mth member of a list mylist: lrange $mylist $n $m • Appending the list: The following command attaches a list alist to the end of a list mylist: lappend $mylist $alist A.1.4 Input/Output Tcl employs a so-called Tcl channel to receive an input using a command gets or to send an output using a command puts.
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]
  • 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]
  • 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]
  • While and Do-While Loops
    While and Do-While Loops 15-110 Summer 2010 Margaret Reid-Miller Loops • Within a method, we can alter the flow of control using either conditionals or loops. • The loop statements while, do-while, and for allow us execute a statement(s) over and over. • Like a conditional, a loop is controlled by a boolean expression that determines how many times the statement is executed. E.g., You may want to calculate the interest paid on a mortgage for each year of the loan term. Summer 2010 15-110 (Reid-Miller) The while statement • The form of the while statement is while (<boolean_expression>) <statement> • If boolean_expression evaluates to true, then statement is executed. • Then, the boolean_expression is evaluated again. If it evaluates to true, statement is executed again. • This repetition continues until the boolean_expression evaluates to false. How is the while loop different from the if statement? Summer 2010 15-110 (Reid-Miller) The if Flowchart false boolean_expression true statement (body of loop) Summer 2010 15-110 (Reid-Miller) The while Flowchart false boolean_expression true statement (body of loop) Summer 2010 15-110 (Reid-Miller) A Example n = 5 while i output 0 Print n asterisks! i < n ? *! 1 int i = 0; ! i < n ? while (i < n) { ! ! **! System.out.print(“*”);! 2 i < n ? !i++;! ***! }! 3 i < n ? System.out.println();! ****! 4 i < n ? *****! 5 i < n ? ***** Summer 2010 15-110 (Reid-Miller) The Loop Control Variable • The variable i (known as the loop control variable) is used in three ways: it is initialized, tested, and updated.!
    [Show full text]
  • Chapter 5: Conditionals and Loops Lab Exercises
    Chapter 5: Conditionals and Loops Lab Exercises Topics Lab Exercises Boolean expressions PreLab Exercises The if statement Computing a Raise The switch statement A Charge Account Statement Activities at Lake LazyDays Rock, Paper, Scissors Date Validation Conditional Operator Processing Grades The while statement PreLab Exercises Counting and Looping Powers of 2 Factorials A Guessing Game Iterators & Reading Text Files Baseball Statistics The do statement More Guessing Election Day The for statement Finding Maximum and Minimum Values Counting Characters Using the Coin Class Drawing with loops and conditionals A Rainbow Program Determining Event Sources Vote Counter, Revisited Dialog Boxes Modifying EvenOdd.java A Pay Check Program Checkboxes & Radio Buttons Adding Buttons to StyleOptions.java Chapter 5: Conditionals and Loops 65 Prelab Exercises Sections 5.1-5.3 1. Rewrite each condition below in valid Java syntax (give a boolean expression): a. x > y > z b. x and y are both less than 0 c. neither x nor y is less than 0 d. x is equal to y but not equal to z 2. Suppose gpa is a variable containing the grade point average of a student. Suppose the goal of a program is to let a student know if he/she made the Dean's list (the gpa must be 3.5 or above). Write an if... else... statement that prints out the appropriate message (either "Congratulations—you made the Dean's List" or "Sorry you didn't make the Dean's List"). 3. Complete the following program to determine the raise and new salary for an employee by adding if ..
    [Show full text]
  • PYTHON LOOPS Rialspo Int.Co M/Pytho N/Pytho N Lo O Ps.Htm Copyrig Ht © Tutorialspoint.Com
    PYTHON LOOPS http://www.tuto rialspo int.co m/pytho n/pytho n_lo o ps.htm Copyrig ht © tutorialspoint.com There may be a situation when you need to execute a block of code several number of times. In g eneral, statements are executed sequentially: The first statement in a function is executed first, followed by the second, and so on. Prog ramming lang uag es provide various control structures that allow for more complicated execution paths. A loop statement allows us to execute a statement or g roup of statements multiple times and following is the g eneral form of a loop statement in most of the prog ramming lang uag es: Python prog ramming lang uag e provides following types of loops to handle looping requirements. Click the following links to check their detail. Loop Type Description while loop Repeats a statement or g roup of statements while a g iven condition is true. It tests the condition before executing the loop body. for loop Executes a sequence of statements multiple times and abbreviates the code that manag es the loop variable. nested loops You can use one or more loop inside any another while, for or do..while loop. Loop Control Statements: Loop control statements chang e execution from its normal sequence. When execution leaves a scope, all automatic objects that were created in that scope are destroyed. Python supports the following control statements. Click the following links to check their detail. Control Statement Description break statement Terminates the loop statement and transfers execution to the statement immediately following the loop.
    [Show full text]
  • Smalltalk Tutorial for Java Programmers!
    SmallTalk Tutorial for Java Programmers! SmallTalk Tutorial for Java Programmers! Giovanni Giorgi <[email protected]> Jan 2002 A small paper to teach yourself the incredible Smalltalk language! It's so easy, it's so fun! 1. Introduction ● 1.1 Revision history ● 1.2 Conventions used in this paper ● 1.3 Distribution Policy ● 1.4 Why Smalltalk? ● 1.5 Background Required 2. Why Smalltalk is so strange? (or a brief history of Smalltalk) ● 2.1 Download Right Now! ● 2.2 Hello world in Smalltalk ● 2.3 Big Numbers ● 2.4 Code Blocks ● 2.5 The while loop 3. Main Differences between Java and Smalltalk http://daitanmarks.sourceforge.net/or/squeak/squeak_tutorial.html (1 of 2) [1/7/2002 20:44:13] SmallTalk Tutorial for Java Programmers! ● 3.1 Java Versus Smalltalk ● 3.2 Types? No thank you!! ● 3.3 The Squeak base library compared with Java ● 3.4 The Smalltalk Code database ● 3.5 Multiple-Inheritance 4. Ending Words ● 4.1 Going on ● 4.2 Commercial and free products list ● 4.3 References http://daitanmarks.sourceforge.net/or/squeak/squeak_tutorial.html (2 of 2) [1/7/2002 20:44:13] SmallTalk Tutorial for Java Programmers!: Introduction 1. Introduction This paper will teach you the basics of Smalltalk80 language. This tutorial suites the needs of C and Java programmers. But the tutorial can be understanded by everyone knowing a bit of C and/or OOP concepts, as we'll see. Because I will refer a lot to other books and use a lot of technical terms, I'll try to enjoy you while reading.
    [Show full text]
  • C Programming Tutorial
    C Programming Tutorial C PROGRAMMING TUTORIAL Simply Easy Learning by tutorialspoint.com tutorialspoint.com i COPYRIGHT & DISCLAIMER NOTICE All the content and graphics on this tutorial are the property of tutorialspoint.com. Any content from tutorialspoint.com or this tutorial may not be redistributed or reproduced in any way, shape, or form without the written permission of tutorialspoint.com. Failure to do so is a violation of copyright laws. This tutorial may contain inaccuracies or errors and tutorialspoint provides no guarantee regarding the accuracy of the site or its contents including this tutorial. If you discover that the tutorialspoint.com site or this tutorial content contains some errors, please contact us at [email protected] ii Table of Contents C Language Overview .............................................................. 1 Facts about C ............................................................................................... 1 Why to use C ? ............................................................................................. 2 C Programs .................................................................................................. 2 C Environment Setup ............................................................... 3 Text Editor ................................................................................................... 3 The C Compiler ............................................................................................ 3 Installation on Unix/Linux ............................................................................
    [Show full text]
  • Iterating in Perl: Loops
    Iterating in Perl: Loops - Computers are great for doing repetitive tasks. - All programming languages come with some way of iterating over some interval. - These methods of iteration are called ‘loops’. - Perl comes with a variety of loops, we will cover 4 of them: 1. if statement and if-else statement 2. while loop and do-while loop 3. for loop 4. foreach loop if statement Syntax: - if the conditional is ‘true’ then the if(conditional) body of the statement (what’s in { between the curly braces) is …some code… executed. } #!/usr/bin/perl -w $var1 = 1333; Output? if($var1 > 10) 1333 is greater than 10 { print “$var1 is greater than 10\n”; } exit; if-else statement Syntax: -if the conditional is ‘true’ then execute if(conditional) the code within the first pair of curly { braces. …some code… } - otherwise (else) execute the code in else the next set of curly braces { …some different code… } Output? #!/usr/bin/perl -w 13 is less than 100 $var1 = 13; if($var1 > 100) { print “$var1 is greater than 100\n”; } else { print “$var1 is less than 100\n”; } exit; Comparisons that are Allowed - In perl you can compare numbers and strings within conditionals - The comparison operators are slightly different for each one - The most common comparison operators for strings: syntax meaning example lt Less than “dog” lt “cat” False! d > c gt Greater than “dog” gt “cat” True! d > c le Less than or equal to “dog” le “cat” False! d > c ge Greater than or equal to “dog” ge “cat” True! d > c eq Equal to “cat” eq “cat” True! c = c ne Not equal to “cat” eq “Cat”
    [Show full text]
  • Control Structures in Perl
    Control Structures in Perl Controlling the Execution Flow in a Program Copyright 20062009 Stewart Weiss Control flow in programs A program is a collection of statements. After the program executes one statement, it "moves" to the next statement and executes that one. If you imagine that a statement is a stepping stone, then you can also think of the execution flow of the program as a sequence of "stones" connected by arrows: statement statement 2 CSci 132 Practical UNIX with Perl Sequences When one statement physically follows another in a program, as in $number1 = <STDIN>; $number2 = <STDIN>; $sum = $number1 + $number2; the execution flow is a simple sequence from one statement to the next, without choices along the way. Usually the diagrams use rectangles to represent the statements: stmt 1 stmt 2 stmt 3 3 CSci 132 Practical UNIX with Perl Alteration of flow Some statements alter the sequential flow of the program. You have already seen a few of these. The if statement is a type of selection, or branching, statement. Its syntax is if ( condition ) { block } in which condition is an expression that is evaluated to determine if it is true or false. If the condition is true when the statement is reached, then the block is executed. If it is false, the block is ignored. In either case, whatever statement follows the if statement in the program is executed afterwards. 4 CSci 132 Practical UNIX with Perl The if statement The flow of control through the if statement is depicted by the following flow-chart (also called a flow diagram): if true ( condition) if-block false next statement 5 CSci 132 Practical UNIX with Perl Conditions The condition in an if statement can be any expression.
    [Show full text]
  • 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.
    [Show full text]