INFORMATION & COMPUTER SCIENCE DEPARTMENT, KFUPM

ICS102, SECTIONS 65  (002 Semester)

INTRODUCTION TO COMPUTING

LAB  #01 Primitive Types & Arithmetic Expressions

 

Instructor: Bashir M. Ghandi

 

Objectives:

To gain experience with:

 

1.  Primitive data types

All data in Java falls into one of two categories: primitive data and objects.

 

By default, whole number for which the type is not specified, e.g: 125,  are automatically represented as type int.

Similarly, the default representation for floating point numbers is double.  If you specifically wish to request for a float, you must append your number with f or F. e.g. 12.5f

2.  Declaring and Using Variables.

A variable declaration is a request to the system to allocate memory for data values to be stored.  It involves specifying the type and a name for the variable.  The type is used by the system to know how many bytes of memory to allocate and the name is used by the programmer to refer to the allocated memory.

e.g.     int age;

 

         int numberOfStudents;

 

         double average;

 

If you have an initial value to assign to your variables, you can do so at the point of declaration as follows:

int numberOfStudents = 25;

3.  Arithmetic Operators

Arithmetic operators and parenthesis are used to form arithmetic expressions.  Evaluation starts from the most inner parenthesis.  At any parentheisis the evaluation is according to priority rules.  Operators of same priority are evaluated from left to right.

Operator

Meaning

Priority (Precedence)

-

unary minus

highest

+

unary plus

highest

*

multiplication

middle

/

division

middle

%

remainder

middle

+

addition

low

-

subtraction

low

The operators give different result depending on the type of the operands. E.g.

20.0 – 12.0 / 10.0 = 20.0 – 1.2 = 18.8
20 – 12 / 10 = 20 –1 = 19

 

4.  Assignment Statement:

Variables are called variables because we can change their values any number of times within a program.

One way of assigning or changing the value of a variable is using the assignment statement, which has the form:

variable = expression;

the expression can be a literal value (e.g. 25), another variable, or an expression involving both literals and variables.  E.g.

int first, second;

double average;

first = 10;

second = 20;

average = (first+second)/2.0

 

If a data value is not going to change in a program, it is declared to be a constant using the final keyword.  Constants are conventionally declared using capital letters.  E.g.  final double PI = 3.1415;

 

5.  The Math class

Many mathematical functions and constants are included in the Java library.  They are included in the Math class:

E :  The double value that is closer than any other to e, the base of the natural logarithms.

PI  The double value that is closer than any other to pi

abs(a)           Returns the absolute value of a                a can be double, float, int or long.

cos(double a)           Returns the trigonometric cosine of an angle in radians.

exp(double a)    Returns the exponential number e (i.e., 2.718...) raised to the power of a double value.

log(double a)      Returns the natural logarithm (base e) of a double value.

max(a, b)      Returns the greater of two values        a and b can double, float, int or long.

min(a, b)      Returns the smaller of two values        a and b can double, float, int or long..

pow(double a, double b)   Returns value of the first argument raised to the power of the second.

random()  Returns a double value with a positive sign, greater than or equal to 0.0 and less than 1.0.

round(a)     Returns the closest long to the argument             the argument can be double or float.

sin(double a)         Returns the trigonometric sine of an angle in radians.

sqrt(double a)       Returns the correctly rounded positive square root of a double value.

tan(double a)        Returns the trigonometric tangent of an angle in radians.

toDegrees(double angrad)   Converts an angle in radians to the equivalent angle in degrees.

toRadians(double angdeg)   Converts an angle in degrees to the equivalent angle in radians.

To access any of these methods, we need to prefix it with the name of the class, Math.  e.g

root = Math.sqrt(20.0);

 

6.  Comments.

Comments are English sentences inserted in a program to explain its purpose.  We can insert comments to explain the purpose of a class, a method or a variable.

Any message enclosed inside  /* … */  is treated as a comment and is therefore ignored by the compiler.  This type of comment can span more than one line.

 

Any message following double slash, // up to the end of line is also considered a comment.  Notice that this type of comment cannot span more than one line.  It is therefore called line comment.  It is often used to comment variables.

 

You are expected to write comments explaining each program you write in this course.  You are also expected to comment any variable whose purpose is not obvious from its name.

 

7.  Indentation.

Indentation involves using tabs, spaces and blank lines to group related statements together.

We shall push the statements inside a class, method or structures statements such as if, while, etc by at least three or four spaces.

Similarly, we shall separate between variable declarations and method declarations by a blank line.  Adjacent methods should also be separated by a blank line.

 

8.  Naming convention.

Java programmers follow a set conventions in naming classes, methods, variables, etc.  See the following link for details.

Java naming conventions.

You are expected to follow these conventions in all your programs for this course.

 

9.  Examples

Example 1:

The following program reads two int values from the user and prints the following

·         Their sum

·         Their difference

·         Their product

·         Their average

·         Their distance (absolute difference)

·         Their Maximum

·         Their Minimum

 

/* computes the sum, difference, product, max, min and absolute values of two integer numbers */

public class Arithmetic {

     

      /* Method comments are placed here  - may not be necessary for the main method */

      public static void main(String[] args) {

           

            int num1 = 15;  //first integer variable

int num2 = 19;  //second integer variable

           

            System.out.println("The sum is: " + (num1+num2));

            System.out.println("The difference is: " + (num1-num2));

            System.out.println("The product is: " + (num1*num2));

            System.out.println("The average is: " + ((num1+num2)/2.0));

            System.out.println("The distance is: " + Math.abs(num1-num2));

            System.out.println("The maximum is: " + Math.max(num1,num2));

            System.out.println("The minimum is: " + Math.min(num1,num2));

      }

}

 

Example2:

The following program prints a table of sine and cosine for angles between 0 to 90o  using interval of 30 degrees

 

/* prints a table of sine and cosine for angles between 0 to 90o

   using interval of 30 degrees.

*/

 

public class SineCosineTable {

     

      public static void main (String[] args) {

                                int inDegrees = 0;  //angle in degrees

            double inRadians = 2*Math.PI*inDegrees/180; //angle in radians;

 

            System.out.println("ANGLE"+"\t"+"SINE"+"\t"+"COSINE");

            System.out.println(inDegrees+"\t"+Math.sin(inRadians)+"\t"+

 Math.cos(inRadians));

            inDegrees += 30;

            inRadians = 2*Math.PI*inDegrees/180;

            System.out.println(inDegrees+"\t"+Math.sin(inRadians)+ “\t”

Math.cos(inRadians));

            inDegrees += 30;

            inRadians = 2*Math.PI*inDegrees/180;

            System.out.println(inDegrees+"\t"+Math.sin(inRadians)+"\t"+

 Math.cos(inRadians));

            inDegrees += 30;

            inRadians = 2*Math.PI*inDegrees/180;

            System.out.println(inDegrees+"\t"+Math.sin(inRadians)+"\t"+

 Math.cos(inRadians));

      }

}

 

 10.  Assignments

 

1.        Copy the above examples from my computer (icswww), compile and test run them.  Make sure you understand what is going on in each of them.

 

2.        Write a program that computes each of the following given a radius:

·         The area of a circle of that radius              pr2

·         The circumference of a circle of that radius  2pr

·         The volume of a sphere of that radius  4/3 pr3

·         The surface area of a sphere of that radius   4pr2

3.        Write a program that prints a table of Centigrade and Fahrenheit temperatures for Fahrenheit temperature from 30 to 80 using interval of 10.

 

Hint:  centigrade = 5/9(fahrenheit-32)

4.        Write a program that given two times in 24 hours format, prints the difference between the two times in hours and minutes.  You can assume that the second time is later than the first.

 

Hint: You need to use the remainder operator, %