מבוא למדעי המחשב, סמסטר א', תשע"א תרגול מס' 2

Slides:



Advertisements
Similar presentations
CS110 Programming Language I
Advertisements

Introduction to Computer Programming Decisions If/Else Booleans.
Some basic I/O.
Lecture 4 Types & Expressions COMP1681 / SE15 Introduction to Programming.
1 The First Step Learning objectives write Java programs that display text on the screen. distinguish between the eight built-in scalar types of Java;
LAB 10.
Computer Programming Lab(4).
MSc IT Programming Methodology (2). MODULE TEAM Dr Aaron Kans Dr Sin Wee Lee.
Introduction to Programming Prof. Rommel Anthony Palomino Department of Computer Science and Information Technology Spring 2011.
Java Basics. Java High-level language  More readable for humans  Need to be translated to machine language for execution Compilers  CPU-independent.
Basic Java Programming CSCI 392 Week Two. Stuff that is the same as C++ for loops and while loops for (int i=0; i
Java Keywords  Reserved Words Part of the Java language Examples: public, static, void  Pre-defined Java Identifiers Defined in Java Libraries Examples:
CS 115 OBJECT ORIENTED PROGRAMMING I LECTURE 4 part 3 GEORGE KOUTSOGIANNAKIS.
Chapter 2 Elementary Programming
Making Decisions Chapter 5.  Thus far we have created classes and performed basic mathematical operations  Consider our ComputeArea.java program to.
Boolean expressions, part 2: Logical operators. Previously discussed Recall that there are 2 types of operators that return a boolean result (true or.
Using Data Within a Program Chapter 2.  Classes  Methods  Statements  Modifiers  Identifiers.
Lecture 3 Decisions (Conditionals). One of the essential features of computer programs is their ability to make decisions. Like a train that changes tracks.
An Introduction to Java – Part 1 Dylan Boltz. What is Java?  An object-oriented programming language  Developed and released by Sun in 1995  Designed.
The if-else statement. The if-else statement in Java The if-else statement is the second conditional statement in Java The if-else statement selects one.
OOP (pre) Basic Programming. Writing to Screen print will display the string to the screen, the following print statement will be appended to the previous.
CSM-Java Programming-I Spring,2005 Fundamental Data Types Lesson - 2.
SELF STUDY. IF STATEMENTS SELECTION STRUCTURE if selection statement if … else selection statement switch selection statement.
CSCI S-1 Section 4. Deadlines for Homework 2 Problems 1-8 in Parts C and D – Friday, July 3, 17:00 EST Parts E and F – Tuesday, July 7, 17:00 EST.
Boolean expressions, part 1: Compare operators. Compare operators Compare operators compare 2 numerical values and return a Boolean (logical) value A.
A Sample Program public class Hello { public static void main(String[] args) { System.out.println( " Hello, world! " ); }
A Introduction to Computing II Lecture 1: Java Review Fall Session 2000.
import java.util.Scanner; class myCode { public static void main(String[] args) { Scanner input= new Scanner(System.in); int num1; System.out.println(“Enter.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved Elementary Programming.
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.
1 Flow of Control Chapter 5. 2 Objectives You will be able to: Use the Java "if" statement to control flow of control within your program.  Use the Java.
Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Decisions and Iterations.
1 BUILDING JAVA PROGRAMS CHAPTER 5 PROGRAM LOGIC AND INDEFINITE LOOPS.
Chapter 2: Data and Expressions. Variable Declaration In Java when you declare a variable, you must also declare the type of information it will hold.
1 Lecture # 2. * Introducing Programming with an Example * Identifiers, Variables, and Constants * Primitive Data Types * Byte, short, int, long, float,
Java Keywords  Reserved Words Part of the Java language Examples: public, static, void  Pre-defined Java Identifiers Defined in Java Libraries Examples:
CPSC 233 Tutorial January 21 st /22 nd, Linux Commands.
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.
CompSci 230 S Programming Techniques
CIS3931 – Intro to JAVA Lecture Note Set 2 17-May-05.
Exercise 1- I/O Write a Java program to input a value for mile and convert it to kilogram. 1 mile = 1.6 kg. import java.util.Scanner; public class MileToKg.
Elementary Programming
Lecture Notes – Basics (Ch1-6)
Chapter 6 More Conditionals and Loops
User input We’ve seen how to use the standard output buffer
TK1114 Computer Programming
The switch Statement The switch statement provides another way to decide which statement to execute next The switch statement evaluates an expression,
SELECTION STATEMENTS (1)
An Introduction to Java – Part I
Chapter 2.
BIT115: Introduction to Programming
הרצאה 3 אלמנטים בסיסיים בשפה
Escape Sequences What if we wanted to print the quote character?
While Statement.
Chapter 6 More Conditionals and Loops
مساق: خوارزميات ومبادئ البرمجة الفصل الدراسي الثاني 2016/2015
An Introduction to Java – Part I, language basics
בתרגול הקודם אתר הקורס (הודעות, פרטי סגל הקורס, עבודות, פורום, מערכת הגשת תרגילים וכו') שימוש בחלון ה-command, פקודות בסיסות קוד Java: הידור (= קומפילציה)
Fundamentals 2.
AP Java Review If else.
Java Basics.
Self study.
Building Java Programs
Lecture Notes – Week 2 Lecture-2
Chapter 3 Selections Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved.
AP Java Review If else.
Repetition Statements
Building Java Programs
Names of variables, functions, classes
Building Java Programs
Presentation transcript:

מבוא למדעי המחשב, סמסטר א', תשע"א תרגול מס' 2 נושאים משתנים וטיפוסים אופרטורים פונקציות מתמטיות מהמחלקה Math המרת טיפוסים תנאים ולולאות

הקדמה תכנית מחשב נכתבת כטקסט בקובץ. הטקסט כתוב בשפת תכנות והוא מכיל את ההוראות המהוות את התוכנית. התוכנית עוברת תהליך הנקרא הידור ואחריה ניתן להפעיל את התוכנית. בקורס זה נכתוב תוכניות בשפה Java תוכניות ב Java נשמרות בקבצים בעלי סיומת java.

תוכנית ראשונה הקלידו את התוכנית הבאה בקובץ Hello.java. שימו לב לסימני פיסוק, ואותיות גדולות וקטנות. // This program prints "Hello World!" on the screen public class Hello { public static void main(String[] args) { System.out.println("Hello World!"); } הערה. לא חלק מהתוכנית. מוסיפים הערות כדי לעזור לקורא להבין מה התוכנית מבצעת. ניתן לסמן הערה ע"י // או /* */ class – הגדרה של מחלקה. כל תוכנית Java ממוקמת בתוך מחלקה. Hello – שם המחלקה מופיע מיד אחרי המילה class. נהוג לבחור שם משמעותי. שם המחלקה מתחיל באות גדולה. הגדרת המחלקה מופיעה בין סוגריים מסולסלות {} (שורה 2 עד שורה 6). public static void main(String[] args) – הכותרת של הפונקציה הראשית main. הקוד הרשום בפונקציה main מכתיב את סדר ריצת הפעולות בתוכנית. פקודת הדפסה. הטקסט המודפס מופיע בתוך גרשיים “Hello World!”. כל פקודה מסתיימת בתו ;

משתנים וטיפוסים* מהו משתנה? משתנה (variable) הוא יחידת מידע המאחסנת ערך במהלך ריצת התוכנית. ניתן להשתמש במשתנים על מנת לשמור ערכים, ולקבלם בשלב מאוחר יותר בתוכנית. ניתן לבצע פעולות חישוביות בעזרת משתנים. לכל משתנה יש טיפוס (type). הטיפוס קובע אילו סוגי ערכים המשתנה יכול להכיל.

הגדרת משתנים* יש להכריז על שמו של המשתנה וטיפוסו. למשל זוהי הגדרה על משתנה בשם num מטיפוס int (מספר שלם). int num; אפשר להגדיר מספר משתנים מאותו טיפוס בשורה אחת. int num1, num2;

*טווח הכרה של משתנה טווח ההכרה של משתנה (scope) הוא האזור בתוכנית שבו המשתנה מוגדר וניתן להשתמש בו. טווח ההכרה של משתנה תלוי בבלוק בו הוא מוגדר (בלוק מצוין ע"י סוגריים מסולסלים). טווח ההכרה של המשתנה מתחיל בשורה שבו המשתנה מוגדר ומסתיים בסוף הבלוק שבו נמצאת הגדרת המשתנה.

*פעולת השמה פעולת השמה (assignment) נותנת ערך למשתנה. = הוא סימן פעולת השמה, משמאל שם המשתנה ומימין הערך. פעולת השמה חייבת להופיע בתוך טווח ההכרה של המשתנה. למשל, הפקודה הבאה נותנת ערך 3 למשתנה num. num = 3; ניתן להגדיר את המשתנה ולבצע השמה בשורה אחת: int num1 = 1;

דוגמה: public class Example1 { public static void main(String[] args){ משתנים הגדרה שמות סקופ השמה פלט דוגמה: public class Example1 { public static void main(String[] args){ int num; num = 3; int num1 = 1, num2; num2 = num1; System.out.println("num = " + num); System.out.println("num1 = " + num1); System.out.println("num2 = " + num2); } scope of num scope of num1 and num2 הפלט (output) של התוכנית: num = 3 num1 = 1 num2 = 1

טיפוסים טיפוס של משתנה קובע: אילו ערכים יכול המשתנה להכיל מהן הפעולות שניתן לבצע על המשתנה רקע הזיכרון במחשב הוא זיכרון בינארי (binary). ביט (bit)- יחידת זיכרון בינארית. ביט יכול להיות 0 או 1. זיכרון המחשב נמדד ביחידות בסיסיות הנקראות בתים (bytes). 1 byte = 8 bit משתנים מאוחסנים בזיכרון המחשב נשמרים בבתים. מספר הבתים שדורש אחסון של משתנה תלוי בטיפוסו. לצורך הבנה מלאה של הנושא עליכם לקרוא באופן עצמאי על הנושא, התחלה טובה היא: Binary - Wikipedia.

טיפוסים פרימיטיביים טיפוסים נומריים שלמים 2. טיפוסים ממשיים הטיפוסים נומריים מייצגים מספרים שלמים: byte, short, int, long למשל: long longNum, longNum2; byte byteNum = 125; longNum = 1234567890; 2. טיפוסים ממשיים הטיפוסים הממשיים הם double, float. double doubleNum; doubleNum = 3.75; בתרגול זה נדון בטיפוסים הבסיסיים הנקראים טיפוסים פרימיטיביים.

טיפוסים פרימיטיביים 3. טיפוסים לוגיים 4. תווים הטיפוס הלוגי נקרא boolean. משתנים מטיפוס זה בעלי ערך true או false. boolean indicator; indicator = true; 4. תווים תו: char. סימן בודד התחום בגרשיים בודדות (למשל, 'a', 'A'). לפני סימן מיוחד יש תו backslash (למשל, newline '\n', tab '\t' , backspace '\b') char capitalN; capitalN = 'N';

טבלת סיכום טיפוסים מספריים מספר ה bytes ערכים byte 1 -27 עד 27-1 short 2 -215 עד 215-1 int 4 -231 עד 231-1 long 8 -263 עד 263-1 float double

קבועים קבוע (constant) הוא יחידת מידע המאחסנת ערך במהלך ריצת התוכנית. קבוע דומה למשתנה; ההבדל הוא שערכו של קבוע לא יכול להשתנות במהלך התוכנית מרגע שהקבוע קיבל את ערכו הראשוני. דוגמה: final int PASS_GRADE = 56; int grade; grade = PASS_GRADE; מתי כדאי להשתמש בקבוע? כאשר יש ערך קבוע שנמצא בשימוש רב בתוכנית. הגדרת קבוע בדומה להגדרת משתנה, בתוספת המילה השמורה final . נהוג להשתמש באותיות גדולות בשמות של קבועים.

אופרטורים על משתנים וערכים ניתן לבצע פעולות שונות, בהתאם לטיפוס. אופרטורים מבצעים חישוב ומחזירים תוצאה. אופרטורים אריתמטיים על משתנים וערכים מטיפוסים נומריים וממשיים אפשר לבצע פעולות אריתמטיות:

דוגמה 1 /* This program demonstrates addition and multiplication between integers. */ public class OperatorsExample1{ public static void main(String[] args){ int a = 3, b = 5; int c; c = a + b; System.out.println("c = "+ c); c = c * 2; } פלט התוכנית: c =8 c =16 c = 8 c = 16

דוגמה 2* התוכנית הבאה מדגימה את סדר הפעולות של הפעולות האריתמטיות: public class OperatorsExample { public static void main(String[] args) { int a = 18; int b = 42; int first = (a + b) * 2; int second = a + b * 2; System.out.println("first number is:" + first); System.out.println("second number is:" + second); } first number is:120 second number is:102

דוגמה 3 Enter a 3-digit number: 951 The reverse number is 159 import java.util.Scanner; /* This program accepts a 3-digit number from the user * reverses the digits and prints the result */ public class Reverse { public static void main(String[] args) { // Read a number from the user. Scanner sc = new Scanner(System.in); System.out.print("Enter a 3-digit number:"); int num = sc.nextInt(); // divide the number into ones, tens and hundreds. int ones = num % 10; int tens = (num % 100) / 10; int hundreds = num / 100; // calculate the reverse number int reverseNum = (ones * 100) + (tens * 10) + hundreds; System.out.println("The reverse number is " + reverseNum); } הסבר: השורה הראשונה import java.util.Scanner; טוענת את ספרית הScanner, המאפשר את פקודת קריאת הנתון מהמשתמש בשורה num = sc.nextInt();. דוגמה של ריצת התוכנית: Enter a 3-digit number: 346 The reverse number is 643 Enter a 3-digit number: 951 The reverse number is 159

אופרטורים יחסיים ב Java יש 6 אופרטורים המשווים בין שני מספרים ונותנים תשובה בוליאנית (true או false). Operator Name Description x < y Less than true if x is less than y, otherwise false. x > y Greater than true 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 Equal true if x equals y, otherwise false. x != y Not Equal true if x is not equal to y, otherwise false. שימו לב: לא להתבלבל בין פעולת השמה (=) לבין אופרטור שוויון (==).

דוגמה Enter the first number:10 Enter the second number:20 import java.util.Scanner; // This program compares two numbers with relational operators public class RelationalOperators { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.print("Enter the first number:"); int x = sc.nextInt(); System.out.print("Enter the second number:"); int y = sc.nextInt(); System.out.println("x<y is " + (x < y)); System.out.println("x>y is " + (x > y)); System.out.println("x<=y is " + (x <= y)); System.out.println("x>=y is " + (x >= y)); System.out.println("x==y is " + (x == y)); System.out.println("x!=y is " + (x != y)); } דוגמת ריצה: Enter the first number: 3 Enter the second number: 5 x<y is true x>y is false x<=y is true x>=y is false x==y is false x!=y is true Enter the first number:10 Enter the second number:20 x<y is true x>y is false x<=y is true x>=y is false x==y is false x!=y is true

אופרטורים לוגיים אופרטורים לוגיים פועלים על ערכים מטיפוס לוגי (בוליאני) וגם נותנים תשובה בוליאנית (true או false). Operator Name Description x && y And True 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 Not True if x is false, otherwise false.

דוגמה Enter the first number:10 Enter the second number:9 import java.util.Scanner; // This program demonstrates logical operators. // It reads two integers from the user and checks if // they are larger than 10. public class LogicalOperators { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.print("Enter the first number:"); int x = sc.nextInt(); System.out.print("Enter the second number:"); int y = sc.nextInt(); System.out.println("(y<10)&&(x<10) is " + ((y<10) && (x<10))); System.out.println("(y<10)||(x<10) is " + ((y<10) || (x<10))); boolean state; state = ((y < 10) || (x < 10)); System.out.println("state is " + state); } למשל, אם המשתמש יכניס כקלט את המספרים 6 ו 12 נקבל: Enter the first number: 6 Enter the second number: 12 (y<10)&(x<10) is false (y<10)|(x<10) is true state is true Enter the first number:10 Enter the second number:9 (y<10)&&(x<10) is false (y<10)||(x<10) is true state is true

המחלקה Math המחלקה Math מאגדת בתוכה פונקציות מתמטיות שימושיות וקבועים. Math.abs(x) – ערך מוחלט של x. Math.max(x1,x2), Math.min(x1, x2) – המינימום והמקסימום (בהתאמה) בין x1 ו x2. Math.pow(x, y) – מחשב את x בחזקת y (xy). Math.sqrt(x) – שורש ריבועי של x. Math.random() – מחזיר מספר אקראי בין 0 ל 1. Math.PI – קבוע המייצג את הערך  (3.14159...)

דוגמה public class UseMath { public static void main(String[] args){ // This is an example of using Math methods double x = Math.abs(-3); x = Math.pow(x, 2 ); x = Math.max(x, Math.PI); System.out.println("max( (|-3|)^2 , Pi ) = " + x ); x = Math.random(); System.out.println("A random number between 0 and 1: "+ x); } max( (|-3|)^2 , Pi ) = 9.0 A random number between 0 and 1: 0.9764623048094814 המחלקה Math ומחלקות רבות נוספות כלולות בספריות Java הכלולות בהתקנת Java. מידע מפורט על מחלקת Math ומחלקות נוספות הכלולות ב Java ניתן למצוא בקישור http://java.sun.com/j2se/1.4.2/docs/api/java/lang/Math.html.

המרת טיפוס (Casting) לכל משתנה ב Java יש טיפוס ספציפי. מה קורה כאשר מערבים טיפוסים שונים בביטוי? במקרים מסוימים Java מטפלת בטיפוסים השונים באופן אוטומטי ובפעמים אחרות אנחנו חייבים לבצע המרה מפורשת של טיפוס נתונים אחד לאחר. המרות אוטומטיות כאשר מבצעים פעולה אריתמטית הערך המתקבל הינו בעל טיפוס מסוים. אם כך המרכיבים מאותו טיפוס אז הטיפוס המתקבל בפעולה הינו זהה. long y, w; long z = w + y; הערך של הביטוי x+y הינו מטיפוס long.

המרת טיפוס (Casting) כאשר מרכיבי הביטוי הינם מטיפוסים שונים הביטוי המתקבל יהיה מהטיפוס של המרכיב הכולל ביותר. הסדר של טיפוסים המספרים מן הפחות כולל לכולל ביותר הינו: byte, int, long, float, double. דוגמה האופרטור / עובד אחרת בהתאם לטיפוסים עליהם הוא מופעל. 5.0/2 --> 2.5 5.0/2.0 --> 2.5 5/2.0 --> 2.5 5/2 --> 2

המרת טיפוס (Casting) 2. המרות יזומות int i = 5; ניתן לבצע המרת טיפוס ע"י שימוש בפעולת השמה. הביטוי הימני עובר המרה לטיפוס של המשתנה המופיע בצד שמאל של ההשמה. int i = 5; double d; d = i; // d is 5.0 המרה כזו אפשרית רק כאשר הטיפוס של המשתנה בצד שמאל כללי יותר מהטיפוס של הביטוי בצד ימין.

המרת טיפוס (Casting) במקרה ההפוך, כאשר הטיפוס של המשתנה בצד שמאל כללי פחות מהטיפוס של הביטוי בצד ימין, נשתמש באופרטור ה type cast : (<type>). double d = 5.3; int i ; i = (int) d; // i is 5 שימוש נוסף באופרטור ה type cast הוא כאשר רוצים למנוע איבוד של חלק השבר בחלוקה של מספרים שלמים: double d; int x = 5, y = 2 ; d = ((double) x)/y; d = (double) x/y; הערה: שני השורות התחתונות מבצעות את אותו הדבר. פעולת ה type cast קודמת לאופרטור /. כאשר לא ברורה הקדימות רצוי להוסיף סוגריים.

משפט if-else משפט if-else הוא מבנה בסיסי בשפה המאפשר לשלוט בזרימת התוכנית. למשפט זה יש שני צורות: if (<condition>){ <statement> } <statement> } else { <alternative> הסבר: תחילה התנאי <condition> מוערך. אם ערכו true מתבצע <statement>. אחרת מתבצע < alternative> (אם יש במשפט else).

דוגמה ל- if import java.util.Scanner; public class Triangle {   public class Triangle { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.print("Enter the first number:"); double a = sc.nextInt(); System.out.print("Enter the second number:"); double b = sc.nextInt(); System.out.print("Enter the third number:"); double c = sc.nextInt(); if ((a + b <= c) || (a + c <= b) || (b + c <= a)){ System.out.println("There is no triangle with these sides."); } else{ System.out.println("There is a triangle with these sides."); בדוק אם שלושה מספרים נתונים הם אורכי צלעותיו של משולש. כאשר יש צורך לבצע מספר פקודות בתוך ה <statement> משתמשים בסוגריים מסולסלות.

לולאות לולאת while while (<condition>) { <statement> } לולאה מאפשרת לחזור על פעולות מספר פעמים כל עוד תנאי כלשהו מתקיים. לולאת while while (<condition>) { <statement> } לולאת for for(<initial>; <condition> ; <update>) { <statement> הסבר while: תחילה התנאי <condition> מוערך. אם ערכו true מתבצע <statement> והתנאי מוערך שוב וחוזר חלילה. עד אשר התנאי <condition> מוערך וערכו false. הסבר for : פעולת <initial> מתבצעת פעם יחידה. תנאי <condition> מוערך. אם ערכו true מתבצע <statement> ולאחר מכן <update> וחזרה ל 2. אם ערכו של <condition> false, הלולאה מסתיימת.

דוגמה* import java.util.Scanner;   // compute n! using while and for sentences. public class Factorial { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.print("Enter a non-negative number:"); int n = sc.nextInt(); int i = 1; // 1. using while int fact = 1; while (i <= n) { fact = fact * i; i = i + 1; } System.out.println("n!=" + fact); // 2. using for fact = 1; for (i = 1; i <= n; i = i + 1){

הערות על כתיבת קוד מכיוון שקטעי הקוד אותם נכתוב בקורס הזה ובכלל נקראים יותר מפעם אחת ישנם מספר כללים עליהם יש לשמור בכדי לדאוג שהקוד יהיה קריא וניתן להבנה מהירה שמות משתנים כאשר ניתן שמות למשתנים בתוכנית שלנו, יש לדאוג לתת שמות בעלי משמעות. שמות משתנים תמיד יתחילו באות קטנה ובנוסף, במידה ושם המשתנה מכיל יותר ממילה אחת, יש להשתמש באותיות גדולות בכדי לסמן התחלה של כל מילה (מוסכמה זו נקראת CamelCase). int numberOfStudentsEating; //better then nOSE הערות בקוד יש חשיבות גדולה לתוספת של הערות על קטע קוד, יש לתאר מה מטרת קטע הקוד בקצרה. עימוד (אינדנטציה) שימוש בעימוד על ידי הוספת טאבים לאחר פתיחת בלוק של קוד עוזרים להפוך את הקוד לקריא ומובן יותר (ניתן להבין את החלוקה לבלוקים).