computer programming, i laboratory manual experiment #2...

11
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

Upload: others

Post on 26-Mar-2020

8 views

Category:

Documents


0 download

TRANSCRIPT

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

Experiment #2: Elementary Programming

2

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

we call them “variables”. (vary: تتغير)

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;

Experiment #2: Elementary Programming

3

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.

Experiment #2: Elementary Programming

4

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

Let's say we are required to write a program that computes the circumference of a circle ( محيط

.(الدائرة

When we write programs, we actually do two things:

1. Designing algorithms.

Experiment #2: Elementary Programming

5

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:

Experiment #2: Elementary Programming

6

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.

Experiment #2: Elementary Programming

7

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 floating-

point numbers. The following table lists them, their storage sizes and their default values:

Name Storage Size

byte 8

short 16

int 32

long 64

float 32

double 64

Numeric Operators

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.

Experiment #2: Elementary Programming

8

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:

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:

Experiment #2: Elementary Programming

9

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:

Experiment #2: Elementary Programming

10

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);

}

}

Experiment #2: Elementary Programming

11

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

😊