Lab # 2 Loops and Logic: Objective

Download as doc, pdf, or txt
Download as doc, pdf, or txt
You are on page 1of 11

Loops and Logic Lab # 2

LAB # 2

LOOPS AND LOGIC

OBJECTIVE:
To Study Control and Iteration Statements and Math Classes.

THEORY:

2.1 CONTROL STATEMENTS


if-else statement:
The if statement is used to test the condition. It checks boolean condition: true
or false. There are various types of if statement in java.
 if statement
 if-else statement
 if-else-if ladder
 nested if statement

if Statement:
The if statement tests the condition. It executes the if block if condition is true.
Syntax:
if(condition){  
//code to be executed  

As a practical example of an if statement that includes a statement block, you
could write:

Object Oriented Programming - OOPs 1


Loops and Logic Lab # 2

if-else Statement:
The if-else statement also tests the condition. It executes the if block if
condition is true otherwise else block is executed.
Syntax:
if(condition){  
//code if condition is true  }
else{  
//code if condition is false  
}  
Leap Year Example:

if-else-if ladder Statement:


The if-else-if ladder statement executes one condition from multiple
statements.
Syntax:
if(condition1){  
//code to be executed if condition1 is true  
}else if(condition2){  
//code to be executed if condition2 is true  
}  
else if(condition3){  

Object Oriented Programming - OOPs 2


Loops and Logic Lab # 2

//code to be executed if condition3 is true  
}  
else{  
//code to be executed if all the conditions are false  
}  

Here's a program to find largest of 3 numbers:

Nested if statement:
The nested if statement represents the if block within another if block. Here,
the inner if block condition executes only when outer if block condition is true.
Syntax:
if(condition){    
     //code to be executed    
          if(condition){  
             //code to be executed       }    
}  

Object Oriented Programming - OOPs 3


Loops and Logic Lab # 2

To illustrate the nested if statement, I can modify the if from the previous
example:

Switch statement:
Use the switch statement to select one of many code blocks to be executed.

Syntax
switch(expression) {
case x:
   //code block
    break;
case y:
    // code block
    break;
  default:
    // code block
}

This is how it works:


 The switch expression is evaluated once.
 The value of the expression is compared with the values of each case.
 If there is a match, the associated block of code is executed.
 The break and default keywords are optional, and will be described later
in this chapter
The example below uses the weekday number to calculate the weekday
name:

Example
int day = 4;
switch (day) {
  case 1:
    System.out.println("Monday");
    break;
  case 2:
    System.out.println("Tuesday");
    break;
  case 3:

Object Oriented Programming - OOPs 4


Loops and Logic Lab # 2

    System.out.println("Wednesday");
    break;
  case 4:
    System.out.println("Thursday");
    break;
  case 5:
    System.out.println("Friday");
    break;
  case 6:
    System.out.println("Saturday");
    break;
  case 7:
    System.out.println("Sunday");
    break;
}

2.2 ITERATION STATEMENTS IN JAVA

Loops:
A loop allows you to execute a statement or block of statements repeatedly. The need to
repeat a block of code arises in almost every program.

Object Oriented Programming - OOPs 5


Loops and Logic Lab # 2

The For Loop:


When you know exactly how many times you want to loop through a block of
code, use the for loop .

for(initialization; condition; iteration) {


// body
}

How It Works
All the work is done in the for loop. The loop counter is i, and this is declared
and initialized within the for loop statement. The syntax of this for loop is
shown in Figure

Object Oriented Programming - OOPs 6


Loops and Logic Lab # 2

As you see, there are three elements that control the operation of the for loop,
and they appear between the parentheses that follow the keyword for. In
sequence, their purpose is to:
❑Set the initial conditions for the loop, particularly the loop counter
❑Specify the condition for the loop to continue
❑Increment the loop counter

For-Each Loop:
There is also a "for-each" loop, which is used exclusively to loop through
elements in an array:

Syntax
for (type variable : arrayname) {
  // code block to be executed
}
The While Loop:

The while loop, loops through a block of code as long as a specified condition is true:

Syntax:
while(condition) {
// body of loop
}

You can write the program for summing integers again using the while loop,
which will show you how the loop mechanism differs from the for loop:

Object Oriented Programming - OOPs 7


Loops and Logic Lab # 2

The do-while Loop:

The do/while loop is a variant of the while loop. This loop will execute the
code block once, before checking if the condition is true, then it will repeat the
loop as long as the condition is true.

Syntax:
do {
// body of loop
} while (condition);

You can write an integer-summing program with this kind of loop too:

Prorgam # 1
This java program finds factorial of a number. Entered number is checked first
if its negative then an error message is printed.

public class Factorial


{
public static void main(String args[])
{
int n=10, c, fact = 1;

if ( n < 0 )
System.out.println("Number should be non-negative.");
else
{
for ( c = 1 ; c <= n ; c++ )
fact = fact*c;
System.out.println("Factorial of "+n+" is = "+fact);
}}}

Object Oriented Programming - OOPs 8


Loops and Logic Lab # 2

2.3 MATH CLASSES


The Math class contains all the floating-point functions that are used for
geometry and trigonometry, as well as several general-purpose methods.
Math defines two double constants: E (approximately 2.72) and PI
(approximately 3.14).

The Java Math library function Math.random() generates a double value in the
range [0,1). Notice this range does not include the 1.

import java.lang.Math;
public class MathDemo
{
public static void main(String[] args)
{ double num = -4876.1874d;
double x=10.0,y=20.0;
int max=15;

// print absolute value of num


System.out.println("\nMath.abs(" + x + ")= " + Math.abs(num));

// print square root value of x

System.out.println("\nMath.sqrt(" + x + ")= " + Math.sqrt(x));

// print power value of x


System.out.println("\nMath.pow(" + x + ")= " + Math.pow(x,y));

// print exponential value of x


System.out.println("\nMath.exp(" + x + ")= " + Math.exp(x));

// print sine value of x in radian


System.out.println("\nMath.sin(" + x + ")= " + Math.sin(x));

// print maximum value


System.out.println("\nMath.max(" + x + ")= " + Math.max(x,y));

// print random value


System.out.println("\nMath.random()= " +(Math.random());
}
}

Object Oriented Programming - OOPs 9


Loops and Logic Lab # 2

LAB TASK

1. Write a program to solve quadratic equation using( if, else-if and else) .

Example:
Input a: 1
Input b: 5
Input c: 1
Expected Output :
The roots are -0.20871215252208009 and -4.7912878474779195

2. Write a program to generate Fibonacci hypothesis for 19 generations


given below.

0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181


6765

3. Write a program to read salary of an employee and designate


according to their salary using if-else ladder.

Note: 25k-35k Research Assistant


36k-50k Junior Lecturer
51k-65k Lecturer
66k-80k Assistant Professor
4. Write a Java program to read a number from the user and print
whether it is positive or negative.
Example:
Input number: 35

Object Oriented Programming - OOPs 10


Loops and Logic Lab # 2

Expected Output:
Number is positive
5. Write a program to read 3 integer values and print the greater and
lesser number respectively.

Example:
A=29
B=25
C=72
Output:
Greater number=72
Lesser number=29

Object Oriented Programming - OOPs 11

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy