Sorting numbers Arrange a list of n numbers a1, a2, a3,..., an in ascending order. A solution: Using Insertion sort. What is Insertion sort? Insertion.

Slides:



Advertisements
Similar presentations
Dr. Yang, Qingxiong (with slides borrowed from Dr. Yuen, Joe) LT4: Control Flow - Loop CS2311 Computer Programming.
Advertisements

True or false A variable of type char can hold the value 301. ( F )
Introduction to Computers and Programming Lecture 4: Mathematical Operators New York University.
Chapter 4 - Control Structures: Part 1 Outline 4.4Control Structures 4.5The if Selection Structure 4.6The if/else Selection Structure 4.7The while Repetition.
Conditions What if?. Flow of Control The order of statement execution is called the flow of control Unless specified otherwise, the order of statement.
Sanjay Goel, School of Business, University at Albany, SUNY 1 MSI 692: Special Topics in Information Technology Lecture 2 Sanjay Goel University at Albany,
Introduction to Computers and Programming Lecture 5 Boolean type; if statement Professor: Evan Korth New York University.
Program Elements We can now examine the core elements of programming (as implemented in Java) We focuse on: data types variable declaration and use, constants.
Expressions An expression is a sequence of operands and operators that reduces to a single value expression operator operand An operator is a language-specific.
1 Midterm Review COMP 102. Tips l Eat a light meal before the exam l NO electronic devices (including calculators, dictionaries, phones, pagers, etc.)
JavaScript, Third Edition
CSci 142 Data and Expressions. 2  Topics  Strings  Primitive data types  Using variables and constants  Expressions and operator precedence  Data.
Copyright 2008 by Pearson Education 1 Building Java Programs Chapter 2 Lecture 2-1: Expressions and Variables reading:
Performing Computations C provides operators that can be applied to calculate expressions: example: tax is 8.5% of the total sale expression: tax =
UNIT II Decision Making And Branching Decision Making And Looping
11 Chapter 4 LOOPS AND FILES. 22 THE INCREMENT AND DECREMENT OPERATORS To increment a variable means to increase its value by one. To decrement a variable.
CIS3931 – Intro to JAVA Lecture Note Set 3 19-May-05.
Operaciones y Variables
 Value, Variable and Data Type  Type Conversion  Arithmetic Expression Evaluation  Scope of variable.
Java Primitives The Smallest Building Blocks of the Language (corresponds with Chapter 2)
Fundamentals of C and C++ Programming Control Structures and Functions.
Chapter 2: Basic Elements of Java J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design, Second Edition.
Chapter 2 Basic Elements of Java. Chapter Objectives Become familiar with the basic components of a Java program, including methods, special symbols,
Operators Using Java operators An operator takes one or more arguments and produces a new value. All operators produce a value from their.
Lecture 4 C Program Control Acknowledgment The notes are adapted from those provided by Deitel & Associates, Inc. and Pearson Education Inc.
1 CSCE 1030 Computer Science 1 Control Statements in Java.
Introduction to Computing Programming is an activity that is carried out through some programming language. Here the programming language we use is called.
Java Programming: From Problem Analysis to Program Design, 4e Chapter 2 Basic Elements of Java.
Expressions An expression is a series of variables, operators, and method calls (constructed according to the syntax of the language) that evaluates to.
Copyright 2008 by Pearson Education 1 Building Java Programs Chapter 2 Lecture 2-1: Expressions and Variables reading:
Algorithm Design.
Loops cause a section of a program to be repeated a certain number of times. The repetition continues while a condition remains true. When a condition.
1 Expressions. 2 Variables and constants linked with operators  Arithmetic expressions Uses arithmetic operators Can evaluate to any value  Logical.
Copyright 2010 by Pearson Education 1 Building Java Programs Chapter 2 Lecture 2-1: Expressions and Variables reading:
1 Lecture 5 More Programming Constructs Instructors: Fu-Chiung Cheng ( 鄭福炯 ) Associate Professor Computer Science & Engineering Tatung Institute of Technology.
CSM-Java Programming-I Spring,2005 Fundamental Data Types Lesson - 2.
Repetition Statements (Loops). 2 Introduction to Loops We all know that much of the work a computer does is repeated many times. When a program repeats.
CMPSC 16 Problem Solving with Computers I Spring 2014 Instructor: Tevfik Bultan Lecture 4: Introduction to C: Control Flow.
Java-02 Basic Concepts Review concepts and examine how java handles them.
Java Programming: From Problem Analysis to Program Design, Second Edition 1 Lecture 1 Objectives  Become familiar with the basic components of a Java.
1 1 Chapter 2 Elementary Programming. 2 2 Motivations In the preceding chapter, you learned how to create, compile, and run a Java program. Starting from.
Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Decisions and Iterations.
4 - Conditional Control Structures CHAPTER 4. Introduction A Program is usually not limited to a linear sequence of instructions. In real life, a programme.
Internet & World Wide Web How to Program, 5/e © by Pearson Education, Inc. All Rights Reserved.
Lecture 3: More Java Basics Michael Hsu CSULA. Recall From Lecture Two  Write a basic program in Java  The process of writing, compiling, and running.
Principles of Programming - NI July Chapter 4: Basic C Operators In this chapter, you will learn about: Assignment operators Arithmetic operators.
Java Language Basics.
Chapter 7: Expressions and Assignment Statements
Lecture 3 Java Operators.
Chapter 7: Expressions and Assignment Statements
Multiple variables can be created in one declaration
Assignment and Arithmetic expressions
Primitive Data, Variables, Loops (Maybe)
Intro to C Tutorial 4: Arithmetic and Logical expressions
User input We’ve seen how to use the standard output buffer
Java Programming: From Problem Analysis to Program Design, 4e
Arrays, For loop While loop Do while loop
OPERATORS (2) CSC 111.
Chapter 8 JavaScript: Control Statements, Part 2
Chapter 2: Basic Elements of Java
Chapter-3 Operators.
Expressions and Assignment
Chapter 2 Programming Basics.
Matlab Basics.
Chap 7. Advanced Control Statements in Java
OPERATORS in C Programming
Operator King Saud University
OPERATORS in C Programming
Presentation transcript:

Sorting numbers Arrange a list of n numbers a1, a2, a3,..., an in ascending order. A solution: Using Insertion sort. What is Insertion sort? Insertion sort works as follows: we look at the numbers one by one, maintaining the numbers already seen in sorted order. Each new number is inserted into its proper place in this sorted list so that the sorted order is preserved.

A solution: cont'd. Suppose the given list of numbers is 5, 7, -3, 2, 20. Following the idea above, we obtain the following sorted lists incrementally: 5 ( after inserting 5 into its proper place in an empty list !) 5, 7 (after inserting 7...) -3, 5, 7 (after inserting -3...) -3, 2, 5, 7 (after inserting 2...) -3, 2, 5, 7, 20 (after inserting ) Finally, we obtain a sorted list of all the numbers.

A program for insertion sort We address the problem of designing a program for insertion sort. The approach that we shall adopt is one of handling complexity by adding details incrementally. This is popularly known as the top-down or stepwise refinement approach to programming. A first cut in a top-down approach Step1 : Read list Step2 : Insert-Sort list Step3 : Print list

A program for insertion sort: cont'd. Top-down approach : A second cut. Step 2 : for i = 1 to n do insert a[i] into sorted(a[1], a[2],..., a[i-1]), by linear search from the high-end;..

A program for insertion sort: cont'd. Top-down approach: A third cut To insert a[i]| we first claim space for it to the right of a[i-1]| and propagate it to left if necessary. Step 2: for i = 2 to n do {set a[i-1] as current element while (position not found) do if no more elements insert a[i] and report position found }

Full-fledged program class insertion_sort{ public static void main(String arg[]) { int n=8; /* number of elements to sort */ int i, j; /* loop counters */ int key; /* element to insert */ int a[]={0,5,-1,2,8,7,3,6}; /* initialize the list */ for (j=1; j = 0 && a[ i ] > key) { a[i+1] = a[ i ]; i = i - 1; } /* find the correct position of key a[j], in the sorted list a[0],...,a[j-1] */ a[i+1] = key; /* insert key in the correct position */ } for (i=0; i<n; i++) System.out.println(a[i]);/* print the sorted list */ } }

Operators, Expressions, and Statements Operators allow us to manipulate the data represented by constants and variables Arithmetic operators: +, *, /, -, %. The first four are the familiar plus, product, division, subtraction; while the last is the modulus operator - a % b gives the remainder in the division of a by b.

Operators are used with variables and constants to build up expressions. For example, a + b - 2 is an expression. In the presence of several operators in any expression, the rules that tell us the order in which to do the operations are called precedence rules. The precedence of binary +, - are the same; so are those of *, /, %; the unary + and - also have the same precedence. The first group has lower precedence than the second which in turn have lower precedence than the third. In cases of equal precedence, arithmetic operators associate from left to right. With these rules, the expression 2 * evaluates to 2 instead of -2. Precedence of operators

Relational & Equality Operators Relational : Equality : ==, != Equality operators have higher precedence than relational but lower than arithmetic operators. Evaluation of the expression 2 < 3 != 5 gives us 0 (which is the value of false)

Logical operators The relational operators give us relational expressions which are combined using the logical operators: and (&&), or (||), not (!) For example, in the expression i >= 0 && a[ i] > key precedence order is >=, >, && The precedence of || is lower than that of &&; while both have lower precedence than the equality operators. The unary operator ! converts a non-zero operand true into false ( 0), and a 0 operand into 1.

Operators: cont'd Increment operator ++: it is a unary operator which can be prefixed or suffixed to its operand. The effect is to increase the value of its operand by 1. Thus the effect of both ++n and n++ is to increase n by 1. Decrement operator - -: it is a unary operator which can be prefixed or suffixed to its operand. The effect is to decrease the value of its operand by 1. Thus the effect of both --n and n-- is to decrease n by 1.

Expressions An expression is made up of variables, constants and operators. An arithmetic expression evaluates to a numerical value. A boolean expression is either a relational expression or a logical expression that evaluates to true or false. For example, if a, b, c are all of type int then a + b - c is an arithmetic expression, a != b is a relational one and (a c) is a logical expression.

statements A statement causes an action to be carried out. Statements are either expression statements, compound statements or control statements. Expression statement: This is an expression, terminated by a semicolon. For example: a = 3; c = a + b; n++;

statements: cont'd. Compound statements: These consist of several statements enclosed with a pair of braces For example: while (i >= 0 && a[i] > key) { a[i+1] = a[i]; i = i - 1; }

Operators Once More Assignment operator: This has the form op=. The assignment expression n = n + 2 can be written as n += 2. As such n and 2 become the operands of the operator +=. In general, if op is a binary operator, we have expr1 = expr1 op expr2, which can be written as expr1 op= expr2 so that expr1 and expr2 are the operands of the operator op= which we call the assignment operator.

Precedence among operators Operators Associativity ( ) [ ] left to right ! * type sizeof right to left * / % left to right + - left to right >= left to right == !=left to right &&left to right ||left to right ? :right to left = += -= *= /= %= left to right The precedence decreases from the top to the bottom of the table.

Operator precedence What is the answer? (assume x=1) x*x+x%2 2*x/2%4(need to know associativity) Almost all operators are left associative –This indicates in which direction the operators of the same precedence will evaluate –Assignment has right associativity x=y=2;// assigns y=2 first and then x=y –The above expression would lead to wrong answer if assignment was left associative

Type conversions The constituent variables and constants in an expression can be of different types. Then the question that naturally arises is what is the type of the value of an expression. For example, if in the expression a + b, a is of type int and b is of type float, then what is the type of the sum? Type conversion rules tell us what should be the type of the sum. We address these questions in the next couple of slides.

Type conversions: cont'd. Implicit type conversions Such conversions take place in several contexts. In arithmetic operations: When operands of an arithmetic operator have different types. For example, if a is of type int and b is of type char then the type of the result of a + b is int. The general rule here is that 'a lower' type is elevated to 'a higher' type.

Type conversions: cont'd. Across assignments: In an assignment expression the right-hand side is first evaluated; the returned value is the value of the left-hand side and also the value of the assignment expression. The type of the left-hand side and that of the assignment expression is the type of the right hand side. For example, if x is of type int and i is of char then as a result of the assignment x = i, x becomes of type char.

Type conversions: cont'd Explicit type conversions This is done by using the cast operator. The syntax is : (type-name) expression The meaning is that the type of the expression is changed to the type specified within round- brackets. For example, sin((float) n) converts the value of n to type float before passing it on to sin.

The execution flow The execution of any program starts from the first line of the program and proceeds sequentially downwards. For example, if a program has ten assignment statements, these would be executed in order of their appearance. However, in most of the programs that we would like to write,we would want to execute some statements only if some condition holds. For example, a program that takes as input marks between 0 and 100, and outputs FAIL if the marks are less than 40.

control statement We use the if control statement to achieve this. The syntax of an if statement is: if ( condition) statement The statement is executed only if the conditional expression condition is true, otherwise the control goes to the statement following the if statement. Note that the statement may actually be a compound statement, or a control statement, or a combination.

Example program public static void main(String arg[]) { int marks=20; if (marks < 40) /* fail */ System.out.println("FAIL"); }

The if-else statement When, depending on a condition, we want to execute one statement block or other, we use if-else statement. Its syntax is: if ( condition) statement1 else statement2 statement1 is executed if the condition is satisfied otherwise statement2 is executed.

Example public static void main(String arg[]) { int marks =20; if ((marks 100)) System.out.println("Out of range!"); else if (marks < 40) /* fail */ System.out.println("FAIL"); else /* pass */ System.out.println("PASS"); }

Example public static void main(String arg[]) { int a, b; a=2; b=3; System.out.println("Larger number is "); if (a > b) System.out.println("", a); else System.out.println("", b); }

if-else ladder public static void main(String arg[]) { int marks; marks=60; if ((marks 100)) System.out.println("Out of range!"); else if (marks < 40) /* fail */ System.out.println("Grade: F"); else if (marks < 70) System.out.println("Grade: B"); else System.out.println("Grade: A"); }

The ?: operator Suppose we want to assign different values to a variable depending upon whether some condition is true or not. One way to do it is, of course, using an if-else statement. There is another, more concise, way of doing this via the ?: operator. The syntax of the operator is: condition ? expn-1 : expn-2 The above expression returns the value of expression expn-1 if the conditional expression condition evaluates to true, otherwise returns the value of expn-2.

More on ‘+’ operator + operator can be used both as concatenation as well as for arithmetic addition depending on the context. Example: String s =“ajai” + “ jain” ; //concatenate ajai and jain String s = “ajai” +1955;//concatenate ajai and 1955 int i = ‘a’+3; // Arithmetic addition

An example Suppose that there were only two rates of taxes: No tax for income less than or equal to 150,000 and a flat rate of 10% above it. Then the tax calculation program is: public static void main(String arg[]) { int income; float tax; income=120000; tax = (income <= )? 0.0 : (income )*0.1; System.out.println ("tax= %f", tax); }

Correct but not advised example public static void main(String arg[]) { int income; float tax; income=350000; tax = (income <= ) ? 0.0 : ((income <= ) ? (income ) * 0.10 : ((income <= ) ? (income ) * 0.2 : (income ) * 0.3))); System.out.println ("tax= %f", tax); }

Iterations: Loops The computational power of a machine is exploited at the program level by means of constructs that repeat a set of actions again and again until some conditions are satisfied. For example, in the Insertion-sort program we repeatedly take a new element from the unsorted list, and insert it into its proper place among the elements already seen and kept in sorted order. Or consider evaluating the sine of a quantity x by using the power series expansion of sin x. C has several repetitive constructs, like the for- loop, the while- loop etc.

The while - loop Syntax: while ( expression) statement while is a key word, expression and statement are programmer-defined. Meaning of the construct: The statement is executed as long as expression evaluates to true (non-zero value)

while loop: Example.. while (i >= 0 && a[i] > key) { a[i+1] = a[i]; i = i - 1; }.. This while- loop had been used in the Insertion-sort program discussed earlier.

while - loop: example program public static void main(String arg[]) { int sum, n; sum = 0; n=523; while (n != 0) { sum += n % 10; n /= 10; } System.out.println("The sum of the digits is = ", sum) }

Positive Decimal to Binary class positiveDecimalToBinary { public static void main(String arg[]) { int n = 34, y=0, polyTerm = 1; if (n < 0) { System.out.println(“Sorry, cannot handle negative integers today!”); } else { while (n > 0) { y += (polyTerm*(n%2)); n /= 2; polyTerm *= 10; } System.out.println(“Required binary: ” + y); }

do-while do { statements } while (condition); “statements” execute at least once irrespective of condition

The for - loop The syntax: for ( expr1; expr2; expr3) statement Meaning of the construct: The initialization of the loop-control variable is done by means of the expression expr1; the second expression expr2 controls the number of times the statement that follows is executed; the third expression expr3 updates the loop control variable after each execution of the statement.

for-loop: sum of first n positive numbers public static void main(String arg[]) { int n, i; long sum; /*sum is a long integer*/ n=20; sum = 0; for(i = 1; i <= n; i++) sum += i; System.out.println("The sum is =", sum); }