1 Gentle Introduction to Programming Assaf Zaritsky Summer 2009.

Slides:



Advertisements
Similar presentations
 Control structures  Algorithm & flowchart  If statements  While statements.
Advertisements

C Programming for engineers Teaching assistant: Ben Sandbank Home page:
Selection Statements Selects statements to execute based on the value of an expression The expression is sometimes called the controlling expression Selection.
Programing Concept Ken Youssefi/Ping HsuIntroduction to Engineering – E10 1 ENGR 10 Introduction to Engineering (Part A)
Announcements The first graded lab will be posted Sunday 2/15 and due Friday 2/27 at midnight It is brand new, so please don’t hand in last semester’s.
1 Gentle Introduction to Programming Session 2: Functions.
Loops – While, Do, For Repetition Statements Introduction to Arrays
1 Gentle Introduction to Programming Assaf Zaritsky Summer 2010.
1 Agenda - Loops while for for & while Nested Loops do-while Misc. & Questions.
1 Agenda Variables (Review) Example Input / Output Arithmetic Operations Casting Char as a Number (if time allow)
1 Gentle Introduction to Programming Session 2: Functions.
C++ Programming Language Day 1. What this course covers Day 1 – Structure of C++ program – Basic data types – Standard input, output streams – Selection.
1 Computing for Engineers in Python Autumn
Chapter 9 Interactive Multimedia Authoring with Flash - Introduction to Programming “Computers and Creativity” Richard D. Webster, COSC 109 Instructor.
1 Programming for Engineers in Python Autumn Lecture 2: More Basics.
High-Level Programming Languages: C++
EGR 2261 Unit 4 Control Structures I: Selection  Read Malik, Chapter 4.  Homework #4 and Lab #4 due next week.  Quiz next week.
Introduction to Python
General Computer Science for Engineers CISC 106 Lecture 02 Dr. John Cavazos Computer and Information Sciences 09/03/2010.
Created by, Author Name, School Name—State FLUENCY WITH INFORMATION TECNOLOGY Skills, Concepts, and Capabilities.
Outlines Chapter 3 –Chapter 3 – Loops & Revision –Loops while do … while – revision 1.
Programming for Engineers in Python Sawa 2015 Lecture 1: Introduction to Python 1.
DEPARTMENT OF COMPUTER SCIENCE & TECHNOLOGY FACULTY OF SCIENCE & TECHNOLOGY UNIVERSITY OF UWA WELLASSA 1 CST 221 OBJECT ORIENTED PROGRAMMING(OOP) ( 2 CREDITS.
Programing Concept Ken Youssefi/Ping HsuIntroduction to Engineering – E10 1 ENGR 10 Introduction to Engineering (Part A)
1 Agenda Administration Background Our first C program Working environment Exercise Memory and Variables.
UniMAP Sem1-08/09EKT120: Computer Programming1 Week 1 – Lecture 1.
Programming for Engineers in Python Sawa 2015 Lecture 2: Lists and Loops 1.
Chapter 4: Control Structures I (Selection). Objectives In this chapter, you will: – Learn about control structures – Examine relational operators – Discover.
Chapter 4: Control Structures I (Selection). Objectives In this chapter, you will: – Learn about control structures – Examine relational and logical operators.
Basics of Java IMPORTANT: Read Chap 1-6 of How to think like a… Lecture 3.
Chapter 8 High-Level Programming Languages. 8-2 Chapter Goals Describe the translation process and distinguish between assembly, compilation, interpretation,
Programming for Beginners Martin Nelson Elizabeth FitzGerald Lecture 5: Software Design & Testing; Revision Session.
PHP Logic. Review: Variables Variables: a symbol or name that stands for a value – Data types ( Similar to C++ or Java): Int, Float, Boolean, String,
CPS120: Introduction to Computer Science Decision Making in Programs.
6/3/2016 CSI Chapter 02 1 Introduction of Flow of Control There are times when you need to vary the way your program executes based on given input.
An Introduction to Java – Part 1 Dylan Boltz. What is Java?  An object-oriented programming language  Developed and released by Sun in 1995  Designed.
Algorithm Design.
8-1 Compilers Compiler A program that translates a high-level language program into machine code High-level languages provide a richer set of instructions.
Introduction to Python Dr. José M. Reyes Álamo. 2 Three Rules of Programming Rule 1: Think before you program Rule 2: A program is a human-readable set.
1 Programming a Computer Lecture Ten. 2 Outline  A quick introduction to the programming language C  Introduction to software packages: Matlab for numerical.
Chapter 4: Control Structures I (Selection). Objectives In this chapter, you will: – Learn about control structures – Examine relational and logical operators.
Agenda Perform Quiz #1 (20 minutes) Loops –Introduction / Purpose –while loops Structure / Examples involving a while loop –do/while loops Structure /
CSCI 1226 FALL 2015 MIDTERM #1 REVIEWS.  Types of computers:  Personal computers  Embedded systems  Servers  Hardware:  I/O devices: mice, keyboards,
1 Agenda If Statement True/False Logical Operators Nested If / Switch Exercises & Misc.
UniMAP Sem2-10/11 DKT121: Fundamental of Computer Programming1 Introduction to C – Part 1.
COMP Loop Statements Yi Hong May 21, 2015.
CMPSC 16 Problem Solving with Computers I Spring 2014 Instructor: Tevfik Bultan Lecture 4: Introduction to C: Control Flow.
1 Lecture03: Control Flow 9/24/2012 Slides modified from Yin Lou, Cornell CS2022: Introduction to C.
1. COMPUTERS AND PROGRAMS Rocky K. C. Chang September 6, 2015 (Adapted from John Zelle’s slides)
Why Repetition? Read 8 real numbers and compute their average REAL X1, X2, X3, X4, X5, X6, X7, X8 REAL SUM, AVG READ *, X1, X2, X3, X4, X5, X6, X7, X8.
IST 210: PHP LOGIC IST 210: Organization of Data IST210 1.
CS1010: Programming Methodology
Review A program is… a set of instructions that tell a computer what to do. Programs can also be called… software. Hardware refers to… the physical components.
1 Agenda  Unit 7: Introduction to Programming Using JavaScript T. Jumana Abu Shmais – AOU - Riyadh.
CPSC 233 Tutorial January 21 st /22 nd, Linux Commands.
IST 210: PHP Logic IST 210: Organization of Data IST2101.
Chapter 10 Programming Fundamentals with JavaScript
REPETITION CONTROL STRUCTURE
Week 1 – Session 1 Pn. Yasmin Yacob 04 – KUKUM Sem2-06/07
Chapter 4 LOOPS © Bobby Hoggard, Department of Computer Science, East Carolina University / These slides may not be used or duplicated without permission.
Chapter 10 Programming Fundamentals with JavaScript
Programming Funamental slides
1) C program development 2) Selection structure
3 Control Statements:.
Introduction to Programming
High Level Programming Languages
Computer Science Core Concepts
Lecture 13 Introduction to High-Level Programming (S&G, §§7.1–7.6)
Introduction to Programming
REPETITION Why Repetition?
Presentation transcript:

1 Gentle Introduction to Programming Assaf Zaritsky Summer 2009

2 Administration September 6-17 Odd week days 9:00 – 13:30 דן דויד 001 No grading Web: Check what’s new! My

3 Course Description This course will provide a gentle introduction to programming using Scala for highly motivated students with little or no prior experience in programming

4 Objective Bridge the gap for students without prior programming knowledge

5 Course Description Lectures will be interactive featuring in-class exercises with lots of support You are expected to work hard!

6 Course Plan SessionMaterial 1Basic concepts in CS and programming, basic Scala 2Basic Scala (cont.), Functions 3Recursion 4Arrays, sorting algorithms 5Lists 6Object oriented programming

7 Course Plan – More Admin. Faculty guests lectures Today: pretty intense, from Tuesday – (maybe) more relaxed Lab sessions – today! 14:30-15:30 15:30-16:30

8 Questions?

9 Agenda for Today Administration General introduction The Scala programming language: Variables and Types Operators Branching and Repetition Compiler, Interpreter Working environment Home work

10 Basic Terms Computer Science Computer Hardware / Software Algorithm Input / Output Pseudo-Code Programming Language Computer Program

11 Computer Science ענף מדעי העוסק בלימוד הבסיס התיאורטי למידע ולחישוביות, והחלתם על מערכות מחשב "מדעי המחשב אינם עוסקים במחשב יותר משאסטרונומיה עוסקת בטלסקופ", דייקסטרה

12 Computer מכונה המעבדת נתונים על פי רצף פקודות נתון מראש מחשב = חומרה + תכנה מעבדאמצעי פלט אמצעי קלט זכרון (עכבר, מקלדת, דיסק קשיח) (מדפסת, מסך, דיסק קשיח)

13 Algorithm סדרת פעולות סופית לביצוע משימה מסויימת Algorithm InputOutput

14 סופית אלגוריתם: סדרת פעולות סופית לביצוע משימה מסוימת תרשים זרימה

15 Pseudo Code תיאור מצומצם ולא רשמי לאלגוריתם. מיועד לקריאה של בני אדם

16 Example

17 Programming Language Machine-readable artificial language designed to express computations that can be performed by a computer

18 Machine Code (Language) Computers understand only machine language Basically looks like a sequence of 1’s and 0’s Very inconvenient to work with and non intuitive All other computer languages were created for human convenience The computer does not understand C/C#/Java/Scala Must be “translated” into machine language

19 There are Many Programming Languages Over 500 different computer languages are listed by Wikipedia

20

21 Language Selection Goal Runtime vs. Development time Operating systems Platforms

22 Computer Program מימוש של אלגוריתם באמצעות שפת תכנות

23 Computer Program (more technically) A sequence of processor instructions designed to achieve a specific purpose The instructions are executed sequentially. No instruction is executed before the previous has been completed

24 Agenda for Today Administration General introduction The Scala programming language: Variables and Types Operators Branching and Repetition Compiler, Interpreter Working environment Home work

25 Scala History Created by Martin Odersky at EPFL Released Jan 2004 Twitter lately switched large portions of their code to Scala (and intend to convert the rest) Over 4000 downloads per month

26 Why Scala? Semester A: Scheme Semester B: Java Scala language has some features similar to Scheme and some to Java Scala is cool!

27 Hello World!

28 My First Scala Program: Hello World! Hello.scala

29 Memory

30 Memory (Cont.) The computer memory is composed of a long list of bits Bits are grouped into bytes and words Every byte is numbered sequentially This number is called an address

31 Variables and Types משתנה (variable): יחידת מידע המאכסנת ערך במהלך ריצת התכנית ניתן ל"גשת" למשתנה (לשנות או לקבל את ערכו) ניתן לבצע פעולות חשבוניות (ואחרות) בעזרת משתנים לכל משתנה מוגדר טיפוס (type) שקובע אילו סוגי ערכים המשתנה יכול להכיל (דוגמאות: מספר שלם, מספר ממשי, תו)

32 Define Variables Use var to declare variables: var x : Int = 3 var y : Int = 5 var z : Int = x + y var s1 : String = “Hello World” define variable variable name typevalue assignment operator Variable x “is of type” Int and is assigned the value 3

33 Why do We Need Variables? Computer programs manipulate data Data is given as input or calculated throughout the program To be later accessed, variables must be remembered Thus, variables are stored in the memory Variable name  memory address

34 Types טיפוס של משתנה קובע: אילו ערכים יכול המשתנה להכיל מהן הפעולות שניתן לבצע על המשתנה מספר הבתים (יחידה בסיסית של זכרון המחשב) שדורש אחסון של משתנה בזכרון תלוי בטיפוסו

35 Some Basic Types

36 Why Do We Need Different Types? Saving memory Execution speed Makes compiler “life” easier

37 Define Variables Int: var x : Int = 5 Double: var pi : Double = 3.14 Boolean: var term : Boolean = true Char: var c : Char = ‘A’ String: var st : String = “I want a break!”

38 Arithmetic Operators

39 Example 1 var a : Int = 3 var b: Int = 5 var c : Int = a + b println(c) c = c * 2 println(c) var first : Int = (a + b) * 2 var second : Int = a + b * 2 println(first) println(second)

40 Example 2 // Demonstrate strings addition var s1 : String = “He” var s2 : String = “llo” var s3 : String = s1 + s2 println(s3) var s4 : String = s3 + “ World ” var c : Char = ‘!’ println(s c)

41 Example 3 // Reverse a 3-digits number println( “ Enter a 3-digit number ” ) var num : Int = Console.readInt() // read a number from the user var ones : Int = num % 10 var tens : Int = (num % 100) / 10 var hundreds : Int = num / 100 var reverseNum : Int = (ones * 100) + (tens * 10) + hundreds println( “ the reverse number is “ + reverseNum)

42 Rational Operators OperatorNameDescription x < y Less thantrue if x is less than y, otherwise false. x > y Greater thantrue if x is greater than y, otherwise false. x <= y Less than or equal to true if x is less than or equal to y, otherwise false. x >= y Greater than or equal to true if x is greater than or equal to y, otherwise false. x == y Equaltrue if x equals y, otherwise false. x != y Not Equaltrue if x is not equal to y, otherwise false. Compares two numbers and returns a Boolean

43 Example // Demonstrate rational operators println( “ Enter the first number ” ) var x : Int = Console.readInt() println( “ Enter the second number ” ) var y : Int = Console.readInt() println( “ x < y is “ + (x < y)) println( “ x > y is “ + (x > y)) println( “ x <= y is “ + (x <= y)) println( “ x >= y is “ + (x >= y)) println( “ x == y is “ + (x == y)) println( “ x != y is “ + (x != y))

44 Logical Operators Operates on two Booleans and returns a Boolean OperatorNameDescription x && y AndTrue if both x and y are true, otherwise false. x || y Or True if at least one of x or y are true, otherwise false. ! X NotTrue if x is false, otherwise false.

45 &&, ||, != && || !

46 Example // Demonstrate logical operators println( “ Enter the first number ” ) var x : Int = Console.readInt() println( “ Enter the second number ” ) var y : Int = Console.readInt() println( “ (x < 10) && (y < 10) is “ + ((x < 10) && (y < 10))) println( “ (x < 10) || (y < 10) is “ + ((x < 10) || (y < 10))) var state : Boolean = ((x < 10) || (y < 10) ) println( “ state is “ + state)

47 All Examples at BasicExamples.scala

48 Operators in Scala

49 Flow Control Usually a program is executed line after line in order It is reasonable to expect different execution orders on different inputs Computer games Illegal input Control structures if-else for loop while loop

50 Conditional Statement: if Used to execute conditionally a statement (or block of code) Syntax: if (expression) statement If expression is true, statement is executed statement can be replaced by a block of statements, enclosed in curly braces

51 if-else Statement if (expression) statement 1 else statement 2 if expression is true, statement 1 is executed. if expression is false, statement 2 is executed both statements can be (and very often are) replaced by blocks of statements (“compound statements”)

52 Example // Demonstrate logical operators println( “ Enter the first number ” ) var a : Int = Console.readInt() println( “ Enter the second number ” ) var b : Int = Console.readInt() println( “ Enter the third number ” ) var c : Int = Console.readInt() if ((a + b <= c) || (a + c <= b) || (b + c <= a)) println( “ There is no triangle with these sides ” ) else println( “ There is a triangle with these sides ” )

53 Example if (price > 100) if (price < 200) println(“reasonable price”) if (price > 100 && price < 200) println(“reasonable price”)

54 Loops Used to repeat the same instructions until a stop criterion is met for, while loops: while ( ) for ( )

55 Example - while // factorial println( “ Enter a non-negative number ” ) var n : Int = Console.readInt() var fact : Int = 1 var i : Int = 1 while (i <= n) { fact = fact * i i = i + 1 } println(n + “ ! = “ + fact)

56 Example - for // factorial println( “ Enter a non-negative number ” ) var n : Int = Console.readInt() var fact : Int = 1 for (i <- 1 to n) { fact = fact * i } println( “ n! = “ + fact)

57 Examples at Factorial.scala

58 Example - Prime // Find whether a number is a prime println( “ Enter a non-negative number ” ) var n : Int = Console.readInt() var j : Int = 2 var stop : Boolean = false while ((j <= n/2) && !stop) { stop = (n%j == 0) j = j + 1 } if (!stop) { println(n) } Prime.scala

59 When to use for/while? Some applications are more natural to for, and others to while for is more suited when something is performed a predefined number of times, or when iterating over a list of objects while is more suited if the number of iterations is not known in advance (e.g., asking for legal input from a user)

60 Infinite Loops What are they? Beware of them

61 Questions How do I write…? Is it legal to…? What happens if I write…? Try it yourself!

62 Agenda for Today Administration General introduction The Scala programming language: Variables and Types Operators Branching and Repetition Compiler, Interpreter Working environment Home work

63 Compiler

64 Interpreter

65 Interpreter The Read/Evaluate/Print Loop Read an expression Compute its value Print the result Repeat the above The Environment

66 Compiler = Clerk " ראש קטן "

67 Runtime

68 Hybrid Approaches

69 Hello World ;-)

70 Agenda for Today Administration General introduction The Scala programming language: Variables and Types Operators Branching and Repetition Compiler, Interpreter Working environment Home work

71 Working Environment Interpreter vs. scripts vs. Eclipse Home vs. labs VS.

72 Setting Home Download Java ( ) Download Scala ( ) Download Eclipse ( ) Set Scala plugin to Eclipse ( ) Start programming

73 Download Java

74 Download Scala

75 Download Scala

76 Use the Interpreter Type Scala from the command prompt (linux) or using “run” (windows)

77 Download Eclipse

78 Set Scala Plugin to Eclipse

79 Set Scala Plugin to Eclipse (new)

80 Set Scala Plugin to Eclipse (new)

81 Open Eclipse – Set Workspace

82 Open Eclipse

83 Define New Project

84 If you don’t find the Scala new project… File  New  Project

85 New Object

86 Write Some Code

87 Run output

88 Agenda for Today Administration General introduction The Scala programming language: Variables and Types Operators Branching and Repetition Compiler, Interpreter Working environment Home work

89 Exercise 0 Write your first “Hello World!” program in Scala: Use the interpreter In Eclipse Make sure it compiles and executes properly

90 Fibonacci Fibonacci series 0, 1, 1, 2, 3, 5, 8, 13, 21, 34 Definition: fib(0) = 1 fib(1) = 1 fib(n) = fib(n-1) + fib(n-2) en.wikipedia.org/wiki/Fibonacci_number

91 סלט פיבונאצ'י

92 Exercise 1 Write a program that receives from the user an integer n > 0 and prints to the screen the n th Fibonacci number a.Use a “for” loop b.Use a “while” loop

93 Exercise 2 Write a program that receives from the user two integers 0 < n1 < n2 and prints to the screen all prime numbers between n1 and n2 Divide the problem to smaller sub-problems: How would you traverse over all the numbers between n1 and n2? How would you be sure that a given number is a prime?

94 Want More Exercises ?

95 Exercise – Integer Division Input: Two integers – A and B Output: How many times A contains B (it is the result of the integer division A/B) Do not use the operators ‘/’, ‘*’ Solution:

96 Exercise – Power of Two Input: integer A Output: is there an integer N such that A == 2^N? Solution:

97 Write a program that prints an upside-down half triangle of *. The height of the pyramid is the input. ***** *** ** **** * Exercise – Triangle Printout