Computer Programming, I. Laboratory Manual. Experiment #2. Elementary Programming

Similar documents
CEN 414 Java Programming

Chapter 2 ELEMENTARY PROGRAMMING

Chapter 2. Elementary Programming

Computer Programming, I. Laboratory Manual. Experiment #3. Selections

Chapter 2 Elementary Programming

Elementary Programming

Chapter 2 Elementary Programming. Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved.

Tester vs. Controller. Elementary Programming. Learning Outcomes. Compile Time vs. Run Time

Motivations. Chapter 2: Elementary Programming 8/24/18. Introducing Programming with an Example. Trace a Program Execution. Trace a Program Execution

Datatypes, Variables, and Operations

Entry Point of Execution: the main Method. Elementary Programming. Learning Outcomes. Development Process

Introduction to Computers. Laboratory Manual. Experiment #3. Elementary Programming, II

Lecture Notes. System.out.println( Circle radius: + radius + area: + area); radius radius area area value

Chapter 2 Elementary Programming

Computer Programming, I. Laboratory Manual. Experiment #4. Mathematical Functions & Characters

Programming with Java

JAVA Programming Concepts

Data and Variables. Data Types Expressions. String Concatenation Variables Declaration Assignment Shorthand operators. Operators Precedence

Full file at

Basic computer skills such as using Windows, Internet Explorer, and Microsoft Word. Chapter 1 Introduction to Computers, Programs, and Java

Arrays. Eng. Mohammed Abdualal

Data Types and the while Statement

Chapter 2 Primitive Data Types and Operations. Objectives

Entry Point of Execution: the main Method. Elementary Programming. Compile Time vs. Run Time. Learning Outcomes

Zheng-Liang Lu Java Programming 45 / 79

Introduction to Java Applications

PRIMITIVE VARIABLES. CS302 Introduction to Programming University of Wisconsin Madison Lecture 3. By Matthew Bernstein

Chapter 2 Elementary Programming

Introduction to Computer Programming

Chapter 2: Data and Expressions

Fundamentals of Programming Data Types & Methods

Computer Programming, I. Laboratory Manual. Experiment #6. Loops

Motivations 9/14/2010. Introducing Programming with an Example. Chapter 2 Elementary Programming. Objectives

Computer Programming : C++

Java Foundations: Introduction to Program Design & Data Structures, 4e John Lewis, Peter DePasquale, Joseph Chase Test Bank: Chapter 2

Chapter 2 Primitive Data Types and Operations

4 WORKING WITH DATA TYPES AND OPERATIONS

3. Java - Language Constructs I

COMP 202 Java in one week

Building Java Programs. Chapter 2: Primitive Data and Definite Loops

Chapter 2: Data and Expressions

JAVA Ch. 4. Variables and Constants Lawrenceville Press

CONTENTS: Compilation Data and Expressions COMP 202. More on Chapter 2

COMP 202. Java in one week

false, import, new 1 class Lecture2 { 2 3 "Data types, Variables, and Operators" 4

Arithmetic and IO. 25 August 2017

I. Variables and Data Type week 3

Introduction to Java Unit 1. Using BlueJ to Write Programs

Building Java Programs

Chapter 3 Selections. Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved.

Welcome to the Primitives and Expressions Lab!

Chapter 3 Syntax, Errors, and Debugging. Fundamentals of Java

Control Statements: Part 1

Eng. Mohammed S. Abdualal

CS110: PROGRAMMING LANGUAGE I

Lesson 02 Data Types and Statements. MIT 12043, Fundamentals of Programming By: S. Sabraz Nawaz Senior Lecturer in MIT Department of MIT FMC, SEUSL

More Things We Can Do With It! Overview. Circle Calculations. πr 2. π = More operators and expression types More statements

AP Computer Science Unit 1. Writing Programs Using BlueJ

Computer Programming, I. Laboratory Manual. Experiment #7. Methods

BASIC ELEMENTS OF A COMPUTER PROGRAM

UNIT- 3 Introduction to C++

Mid Term Exam 1. Programming I (CPCS 202) Instructor: M. G. Abbas Malik Date: Sunday November 3, 2013 Total Marks: 50 Obtained Marks:

A very simple program. Week 2: variables & expressions. Declaring variables. Assignments: examples. Initialising variables. Assignments: pattern

Data Conversion & Scanner Class

Program Fundamentals

Module 2 - Part 2 DATA TYPES AND EXPRESSIONS 1/15/19 CSE 1321 MODULE 2 1

Section 2.2 Your First Program in Java: Printing a Line of Text

Chapter 3: Operators, Expressions and Type Conversion

Elementary Programming. CSE 114, Computer Science 1 Stony Brook University

CS 302: Introduction to Programming

12/22/11. Java How to Program, 9/e. Help you get started with Eclipse and NetBeans integrated development environments.

Object-Oriented Programming

AP Computer Science Unit 1. Writing Programs Using BlueJ

Course Outline. Introduction to java

Computational Expression

Computer Programming, I. Laboratory Manual. Final Exam Solution

Basics of Java Programming

CS313D: ADVANCED PROGRAMMING LANGUAGE

Simple Java Reference

C++ PROGRAMMING. For Industrial And Electrical Engineering Instructor: Ruba A. Salamh

Assoc. Prof. Dr. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved.

JAVA PROGRAMMING LAB. ABSTRACT In this Lab you will learn to define and invoke void and return java methods

Reading Input from Text File

Define a method vs. calling a method. Chapter Goals. Contents 1/21/13

Chapter 2: Data and Expressions

CS 115 Exam 1, Fall 2015 Thu. 09/24/2015

CIS133J. Working with Numbers in Java

2/9/2012. Chapter Four: Fundamental Data Types. Chapter Goals

COMP Primitive and Class Types. Yi Hong May 14, 2015

Objectives. Chapter 2: Basic Elements of C++ Introduction. Objectives (cont d.) A C++ Program (cont d.) A C++ Program

Chapter 2: Basic Elements of C++

Chapter 2: Basic Elements of C++ Objectives. Objectives (cont d.) A C++ Program. Introduction

Expressions and Variables

CS111: PROGRAMMING LANGUAGE II

AP Computer Science Unit 1. Programs

download instant at Introduction to C++

JAVA OPERATORS GENERAL

Professor: Sana Odeh Lecture 3 Python 3.1 Variables, Primitive Data Types & arithmetic operators

Topic 4 Expressions and variables

Computer Programming, I. Laboratory Manual. Experiment #5. Strings & Text Files Input

Transcription:

Think Twice Code Once The Islamic University of Gaza Engineering Faculty Department of Computer Engineering Fall 2017 ECOM 2005 Khaleel I. Shaheen Computer Programming, I Laboratory Manual Experiment #2 Elementary Programming

Variables Variables are used to store values to be used later in a program. They are called variables because their values can be changed. The value referenced by a variable may vary, that s why (تتغير (vary: we call them variables. The variable declaration tells the compiler to allocate appropriate memory space for the variable based on its data type. Variables are for representing data of a certain type. To use a variable: 1. Declare it by telling the compiler its name 2. What type of data it can store The syntax for declaring a variable is datatype variablename; Here are some examples of variables declaration: int count; // Declare count to be an integer variable double radius; // Declare radius to be a double variable If variables are of the same type, they can be declared together, as follows: datatype variable1, variable2,..., variablen; The variables are separated by commas. For example int i, j, k; // Declare i, j, and k as int variables Variables often have initial values. You can declare a variable and initialize it in one step as follows: int age = 20; Which is equivalent to this code: int age; age = 20; 2

You can also use a shorthand form to declare and initialize variables of the same type together. For example, int i = 1, j = 2, k = 3; A variable must be declared and initialized before it can be used. If we tried to run this code, int y = x + 1; We will get the following error Error: java: cannot find symbol symbol: variable x Identifiers Identifiers are the names that identify the elements such as classes, methods, and variables in a program. All identifiers must obey the following rules: 1. An identifier is a sequence of characters that consists of letters, digits, underscores (_), and dollar signs ($). 2. An identifier must start with a letter, an underscore (_), or a dollar sign ($). It cannot start with a digit. 3. An identifier cannot be a reserved word. 4. An identifier cannot be true, false, or null. 5. An identifier can be of any length. Java is case sensitive, so, width, Width, and WIDTH are all different identifiers. You cannot use spaces in identifiers, so if a name consists of several words, concatenate them into one, making the first word lowercase and capitalizing the first letter of each subsequent word, like squarearea. This style is called camelcase. Assignment Statements An assignment statement designates a value for a variable. An assignment statement can be used as an expression in Java. 3

After a variable is declared, you can assign a value to it by using an assignment statement. In Java, the equal sign (=) is used as the assignment operator. The syntax for assignment statements is as follows: variable = expression; An expression represents a computation involving values, variables, and operators that evaluates to a value. Here are some assignment statements: int y = 1; // Assign 1 to variable y double radius = 1.0; // Assign 1.0 to variable radius int x = 5 * (3 / 2); // Assign the value of the expression to x x = y + 1; // Assign the addition of y and 1 to x double area = radius * radius * 3.14159; // Compute area The variable name must be to the left of the assignment operator. 1 = x; // Wrong If a value is assigned to multiple variables, you can use this syntax: i = j = k = 1; which is equivalent to this code below. But note that variables must be already declared. k = 1; j = k; i = j; In mathematics, x = 2 * x + 1 denotes an equation. However, in Java, x = 2 * x + 1 is an assignment statement that evaluates the expression 2 * x + 1 and assigns the result to x. Writing a simple Java program محيط ( circle Let's say we are required to write a program that computes the circumference of a.(الدائرة When we write programs, we actually do two things: 1. Designing algorithms. 4

2. Translating algorithms into programming instructions, or code. An algorithm describes how a problem is solved by listing the actions that need to be taken and the order of their execution. The algorithm for calculating the circumference of a circle: 1. Get the radius. 2. Compute the circumference using this formula: circumference = 2 * π * radius 3. Print the result. In the first step, the radius must be stored in the program. So, we are going to use variables in order to store the radius value and access it. In the second step, we compute the circumference using the formula and store the result in another variable. Finally, we print the result of circumference on the screen. Here is the complete program: public class ComputeArea { public static void main(string[] args) { double radius = 20; double circumference = 2 * 3.14159 * radius; System.out.println("circumference for the circle is: " + circumference); Reading Input from the Console In the previous code, the radius is fixed in the source code. To use a different radius, you have to modify the source code and recompile it. This is not convenient, so instead you can use the Scanner class for console input. Scanner input = new Scanner(System.in); To invoke a method on an object is to ask the object to perform a task. You can invoke the nextdouble() method to read a double value as follows: 5

double radius = input.nextdouble(); After rewriting the code to accept input from user: public class ComputeArea { public static void main(string[] args) { Scanner input = new Scanner(System.in); System.out.print("Enter the radius: "); double radius = input.nextdouble(); double circumference = 2 * 3.14159 * radius; System.out.println("circumference for the circle is: " + circumference); Named Constants A named constant is an identifier that represents a permanent value. The value of a variable may change during the execution of a program, but a named constant, or simply constant, represents permanent data that never changes. The syntax for declaring a constant: final datatype CONSTANTNAME = value; A constant must be declared and initialized in the same statement. The word final is a Java keyword for declaring a constant. final double PI = 3.14159; Benefits of using constants: If the value is used in different locations, you don t have to repeatedly type it. If you have to change the value, you need to change one location where the constant is declared. Descriptive identifiers make the program easy to read. Naming Conventions Sticking with the Java naming conventions makes your programs easy to read and avoids errors. 6

Make sure that you choose descriptive names with straightforward meanings for the variables, constants, classes, and methods in your program. Here are the conventions for naming variables, methods, and classes: Use lowercase for variables and methods. If a name consists of several words, concatenate them into one, making the first word lowercase and capitalizing the first letter of each subsequent word, radius and criclearea. Capitalize the first letter of each word in a class name, ComputeArea. Capitalize every letter in a constant, and use underscores between words, PI and MAX_VALUE. Numeric Data Types Every data type has a range of values. The compiler allocates memory space for each variable or constant according to its data type. Java has six numeric types for integers and floatingpoint numbers. The following table lists them, their storage sizes and their default values: Numeric Operators Name Storage Size byte 8 short 16 int 32 long 64 float 32 double 64 The operators for numeric data types include the standard arithmetic operators: addition,)+( subtraction ( ), multiplication (*), division (/), and remainder.)%( When both operands of a division are integers, the result of the division is the quotient and the fractional part is truncated. 7

System.out.println(10 / 3); //prints 3 System.out.println(10.0 / 3); //prints 3.3335 The % operator yields the remainder after division. 7 % 3 yields 1, 3 % 7 yields 3, 12 % 4 yields 0. Operator Precedence Java expressions are evaluated in the same way as arithmetic expressions: multiplication, division, and remainder operators are applied first, addition and subtraction operators are applied last. Evaluate the following expression using Java Solution: 25 + 15 3 10 9 % 6 + 2 6 3 + 1 System.out.println(25 + 15*3 - (10.0/(2*6)) + (9 % 6 / 3) + 1); Augmented Assignment Operators The operators +, -, *, /, and % can be combined with the assignment operator to form augmented operators. Operator Name Example Equivalent += Addition Assignment i += 8; i = i + 8; -= Subtraction Assignment i -= 8; i = i 8; *= Multiplication Assignment i *= 8; i = i * 8; /= Division Assignment i /= 8; i = i / 8; %= Remainder Assignment i %= 8; i = i % 8; Show the output of the following code: 8

double a = 6.5; a += a + 1; System.out.println(a); a = 6; a /= 2; System.out.println(a); Increment and Decrement Operators The increment operator (++) and decrement operator ( ) are for incrementing and decrementing a variable by 1. Lab Work Ex1: Write a program that reads a Celsius degree in a double value from the console, then converts it to Fahrenheit and displays the result. The formula for the conversion is as follows: fahrenheit = (9 / 5) * celsius + 32 Hint: In Java, 9 / 5 is 1, but 9.0 / 5 is 1.8. Solution: 9

import java.util.scanner; public class F2C { public static void main(string[] args) { Scanner input = new Scanner(System.in); System.out.print("Enter a temperature in Celsius: "); double celsius = input.nextdouble(); double fahrenheit = (9.0 / 5) * celsius + 32; System.out.println(celsius + " Celsius is " + fahrenheit + " Fahrenheit"); Ex2: Write a program that reads an integer between 0 and 999 and adds all the digits in the integer. For example, if an integer is 932, the sum of all its digits is 14. Hint: Use the % operator to extract digits, and use the / operator to remove the extracted digit. For instance, 932 % 10 = 2 and 932 / 10 = 93. Solution: import java.util.scanner; public class SumDigits { public static void main(string[] args) { Scanner input = new Scanner(System.in); System.out.print("Enter a number 0-999: "); int number = input.nextint(); int digit1 = number % 10; number = number / 10; int digit2 = number % 10; number = number / 10; int digit3 = number % 10; System.out.println(digit1 + digit2 + digit3); 10

Homework 1. (2.7) Write a program that prompts the user to enter the minutes (e.g., 1 billion), and displays the number of years and days for the minutes. For simplicity, assume a year has 365 days. Enter the number of minutes: 1000000000 1000000000 minutes is approximately 1902 years and 214 days 2. (2.14) Body Mass Index (BMI) is a measure of health on weight. It can be calculated by taking your weight in kilograms and dividing by the square of your height in meters. Write a program that prompts the user to enter a weight in pounds and height in inches and displays the BMI. Note that one pound is 0.45359237 kilograms and one inch is 0.0254 meters. Here is a sample run: Enter weight in pounds: 95.5 Enter height in inches: 50 BMI is 26.8573 3. (2.23) Write a program that prompts the user to enter the distance to drive, the fuel efficiency of the car in miles per gallon, and the price per gallon, and displays the cost of the trip. Here is a sample run: Enter the driving distance: 900.5 Enter miles per gallon: 25.5 Enter price per gallon: 3.55 The cost of driving is $125.36 Good Luck 11