INFORMATION & COMPUTER SCIENCE DEPARTMENT, KFUPM

ICS102, SECTIONS 52, 54 & 55  (001 Semester)

INTRODUCTION TO COMPUTING

LAB  #04 Control Structures

 

Instructor: Bashir M. Ghandi

 


Objectives:

To gain experience with:

 

1.  Relational & Logical Operators

Computers can perform both arithmetic and logical operations.  Accordingly, in addition to the arithmetic operators, Java has a number of operators that are used for logical operations. These are relational and logical operators that are shown in the tables below:

Relational Operators

Operator

Use

Return true if

>

op1 > op2

op1 is greater than op2

>=

op1 >= op2

op1 is greater than or equal to op2

<

op1 < op2

op1 is less than op2

<=

op1 <= op2

op1 is less than or equal to op2

==

op1 == op2

op1 and op2 are equal

!=

op1 != op2

op1 and op2 are not equal

Logical Operators

Operator

Use

Return true if

&&

op1 && op2

op1 and op2 are both true

||

op1 || op2

either op1 or op2 or both are true

!

! op

op is false

 

Notice that the operands for the Relational operators must be numeric (int, double, etc), whereas, the operands for the Logical operators must be boolean.

 

Like Arithmetic operators, if more than one of these operators are involved in an expression, the expression is evaluated according to Java precedence rules.  The following precedence table updates the one shown earlier (Lab02) to include relational and logical operators:

Precedence Table

postfix operators

expr++ expr--

unary operators

++expr --expr +expr -expr  !

creation or cast

new (type)expr

multiplicative

* / %

additive

+ -

relational

< > <= >=

equality

== !=

logical AND

&&

logical OR

||

assignment

= += -= *= /= %=  

 

Example1:  Evaluate the following expressions manually.

5 > 2 || 12 <= 7

T or F

5 > 2 && 12 <= 7

T or F

3 == 8 || 6 != 6

T or F

3 == 8 && 6 != 6

T or F

 

Now execute the following program and compare the result with the one you obtained manually.

public class LogicalExpressions {

     

      public static void main(String[] args) {

           

            System.out.println("Result is "+(5 > 2 || 12 <= 7));

            System.out.println("Result is "+(5 > 2 && 12 <= 7));

            System.out.println("Result is "+(3 == 8 || 6 != 6));

            System.out.println("Result is "+(3 == 8 && 6 != 6));

      }

}

 

 

2.  Selection Statements.

2.1.  if Statement.

The if or conditional statement is one of the simplest control structures.  Java provides two basic forms of the if statement.

if (test)

  statement

 

This executes the statement only when the test holds.

Note the following about if statement:

if (test) {

  statement

}

 

Example 2: The following program reads the balance of an account and an amount to withdraw and then prints the new balance.  If the new balance is negative, the program prints a warning message.

/*  reads balance and amount to withdraw and prints the new balance

    also prints a warning if the new balance is negative

*/

import TextIO;

 

public class BankAccount {

     

      static TextIO stdin = new TextIO(System.in);

     

      public static void main(String[] args) throws java.io.IOException {

            double balance, withdraw;

           

            System.out.print("Enter current balnce: ");

            balance=stdin.readDouble();

            System.out.print("Enter amount to withdraw: ");

            withdraw=stdin.readDouble();

           

            balance -= withdraw;

            System.out.println("The new balance is: "+balance);

            if (balance < 0)

               System.out.println("Invalid Transaction - please see the manager!");

      }

}

 

The second version of the if statement has the form:

if (test)

  statement1

else

  statement2

 

 

or

 

if (test) {

  statements

}

else {

  statements

}

 

if (test) is true the first statement (or first block of statements) is executed, otherwise, the second statement (or second block of statements) is execute.

 

Example 3:  The following example reads the coefficients of a quadratic equation and prints its real roots if it has any, else it prints an a warning message.

/*  reads the coefficients of a quadratic equation and prints its real roots if it has any,  else print an a warning message.

*/

import TextIO;

 

public class QuadraticEquation {

     

      static TextIO stdin = new TextIO(System.in);

     

      public static void main(String[] args) throws java.io.IOException {

           

            double a, b, c, disc, root1, root2;

           

            System.out.print("Enter values for the coefficents, a b c: ");

            a=stdin.readDouble();

            b=stdin.readDouble();

            c=stdin.readDouble();

           

            disc = b*b - 4*a*c;

            if (disc >= 0) {

                root1 = (-b+Math.sqrt(disc))/(2*a);

                root2 = (-b-Math.sqrt(disc))/(2*a);

                System.out.println("The roots are: "+root1+" and "+root2);

            }

            else

               System.out.println("Sorry, the equation has no real roots");

      }

}

 

If there are more than two options to choose from, then multiple if statements are combined like this:

   if (condition1) {
      statements1;
   }
   else if (condition2) {
      statements2;
   }
   ...
   else if (conditionn-1) {
      statementsn-1;
   }
   else {
      statementsn;
   }
 

Conditions are evaluated until a true one is found; then its statement is executed and the rest of the code is skipped.

 

Example 4: The following example reads how much a student score in an exam. and prints his letter grade

    according to some standard criteria.

/*  reads how much a student score in an exam. and prints his letter grade

    according to some standard criteria.

*/

import TextIO;

 

public class LetterGrade {

     

      static TextIO stdin = new TextIO(System.in);

     

      public static void main(String[] args) throws java.io.IOException {

           

            double score;

            char grade;

           

            System.out.print("Enter the score of the student: ");

            score=stdin.readDouble();

 

            if (score >= 90)

                  grade = 'A';

            else if (score >= 80)

                  grade = 'B';

            else if (score >= 70)

                  grade = 'C';

            else if (score >= 60)

                  grade = 'D';

            else

                  grade = 'F';

           

            System.out.println("Enter letter grade for this student is: "+grade);

      }

}

 

2.1.  switch Statement.

The switch statement is also used to select one or more branches from among a sequence of branches.  The format is:

   switch (controllingExpression) {
      case value1 : statements;
		    break;
      case value2 : statements;
		    break;
      case value :  statements;
		    break;
		.
		.
      case valuen : statements
		    break;
      default:  statements;
  }

 

 

Notice that:

 

Example 5:  The following example reads a number [1 ...7] corresponding to a week day and prints the name of that day.

/*  reads a number [1 ...7] corresponding to a week day and

    prints the name of the day.

*/

import TextIO;

 

public class DayOfWeek {

     

      static TextIO stdin = new TextIO(System.in);

     

      public static void main(String[] args) throws java.io.IOException {

            int dayNumber;

           

            System.out.print("Enter a number for the week day [1...7]");

            dayNumber = stdin.readInt();

     

            switch (dayNumber) {

                  case 1: System.out.println("Saturday");

                          break;

                  case 2: System.out.println("Sunday");

                          break;

                  case 3: System.out.println("Monday");

                          break;

                  case 4: System.out.println("Tuesday");

                          break;

                  case 5: System.out.println("Wednesday");

                          break;

                  case 6: System.out.println("Thursday");

                          break;

                  case 7: System.out.println("Friday");

                          break;

                  default:

                          System.out.println("Sorry invalid day number");

            }

      }

}

 

3.  Repetition Statements

Repetition statements are used to repeatedly execute a statement or a sequence of statements.  There are three such statements in Java; while, for and do.  In this Lab we shall consider the while loop.

 

The while loop has the following general form:

while (test)

  statement

 

or

 

while (test) {

  statements

}

 

In executing this loop, Java first evaluates the test. If the test fails, the loop terminates. Otherwise, Java executes the statements and then goes back and tries the test again. This process is repeated until the test eventually evaluates to false.

 

Note: the test in a while loop usually involves a variable which is initialized before the loop and updated inside the loop.  The updating  must be such that the test will eventually evaluates to false, otherwise the loop will not terminate –infinite loop.

Examples 6: The following example prints a table of integer numbers and their squares for integers from 1 to 10

/*  prints a table of integer numbers and their squares for

    integers from 1 to 10

*/

public class TableOfSquares {

     

  public static void main(String[] args) {

     

      int i = 0;

      while (i < 10) {

         i++;

         System.out.println(i + "\t" + Math.pow(i, 2));

      }

  }

}

 

Examples 7: The following example reads interger numbers from the user and count how many are positive and how many are negative.  The program uses 0 sa sentinel. i.e. it continues to read until 0 value is entered.

/*  reads interger numbers from the user and count how many are positive

    and how many are negative.  The program stops when a 0 value is entered.

*/

import TextIO;

 

public class InputCounter {

     

      static TextIO stdin = new TextIO(System.in);

     

      public static void main(String[] args) throws java.io.IOException {

            int positiveCount=0;

            int negativeCount=0;

            int number;

           

            System.out.print("Enter next number: ");

            number = stdin.readInt();

           

            while(number != 0) {

               if (number > 0)

                  positiveCount++;

               else

                  negativeCount++;

                 

               System.out.print("Enter next number: ");

               number = stdin.readInt();

            }

            System.out.println("Count of Positive Numbers = "+positiveCount);

            System.out.println("Count of Negative Numbers = "+negativeCount);

      }

}

 

4.  Assignments

1.        The front tires of a car should both have the same pressure. Also, the rear tires of a car should both have the same pressure (but not neccessarily the same pressure as the front tires.) Write a program that reads in the pressure of the four tires and writes a message that says if the inflation is OK or not. 

2.        A salesman is given bonus as a percentage of the sales he makes according to the following table:

SALES (RIYALS)

BONUS

SALES  <  1000.00

1 % OF SALES

1000.00 <= SALES  <  3000.00

2 % OF SALES

3000.00 <= SALES

4 % OF SALES

Write a main program to read the amount of sales and print the bonus. 

3.        Write a program that reads interger numbers from the user and prints the Times table [1 ..12] for that number.