You are on page 1of 20

1.

OBJECTIVES:
Since this tutorial has been designed for novices to help them learn the fundamental
functioning of loops and their structure in Java, the primary goals of this research effort are
as follows:
 To comprehend what loops are
 To understand the functions of the for, while, and do while loops.
 How may loops be used in a package?
 What are the math interfaces in Java?
 To comprehend the entire idea of loops in Java with the use of coding examples

2.LOOPS:
Loops are basically of three types that we discuss here it includes:
a) for loop
b) while loop
c) do while loop

3.INTRODUCTION:
In programming languages, looping is a program that allows the execution of a set of
instructions/functions repeatedly until some condition evaluates to true. Java provides three
methods for loop execution includes for, while and do while loop. While all of the methods
provide identical fundamental functionality, they differ in syntax and condition checking time.
USE OF LOOPS IN JAVA:
A loop is present in every programming language. Without loop, a programming language is
incomplete, and it is the most frequent and commonly used in code. The loop is the foundation of
language. So we'll look into java loops. In Java, loops are used to continuously execute a
statement block until the condition is met. We may run the code multiple times or until the
condition is met by utilising the loop. When a programmer wishes to repeat the execution of a
statement or a group of statements, loops come in handy. We'll go through all of Java's loops in
this post. Loops are a component of Java's Control structure. We may regulate the elapsed time
in Java by using loops.

for loop:
The for-loop structure is written in a more linear direction. Unlike a while loop, a for statement
consumes the setup, condition, and increment/decrement on a single line, resulting in a shorter,
easier to debug looping structure.
 Syntax:

for (initialization condition; testing condition;


increment/decrement)
{
statement(s)
}

 Working steps :
For loop working is mainly consists of five steps
I. Initialization
II. Testing of a loop
III. Execution statement for loop
IV. Loop increment or decrement
V. for loop termination
Initialization condition:
This is where we set the value of the variable we're working with. It begins a for loop. A variable
that has already been declared or one that is solely local to the loop can be utilized.
Testing Condition:
It's used to see if a loop's exit condition is correct. It has to return a true or false value. It's also an
Entry Control Loop since the condition is verified before the loop statements are executed.
Execution of Statements:
The statements in the loop body are performed after the condition is assessed to true.
Increment/Decrement:
It is used to update a variable for the next iteration.
Loops termination:
The loop ends when the condition is false, signaling the end of its life cycle.
 EXAMPLES:
I.
// Java program to illustrate for loop.
class forLoopDemo
{
public static void main(String args[])
{
// for loop begins when x=2
// and runs till x <=4
for (int x = 2; x <= 4; x++)
System.out.println("Value of x:" + x);
}
}
OUTPUT:

 Loop Enhanced:
Java also has a new version of the for loop, which was introduced in Java 5. It is easier to cycle
through the items of a collection or array using Enhanced for loop. It is rigid and should only be
used when it is necessary to loop through the items in a sequential fashion without knowing the
index of the presently processed element. Also, when the enhanced for loop is used, the
object/variable is immutable, which means that the values in the array cannot be modified. This
makes it a read-only loop, as opposed to ordinary loops where values can be updated. Instead of
the genus, we propose using this version of the for statement.
 Syntax:

for (T element:Collection obj/array)


{
statement(s)
}

 EXAMPLE:
// Java program to illustrate enhanced for loop
public class enhancedforloop
{
    public static void main(String args[])
    {
        String array[] = {"Ron", "Harry", "Hermoine"};
  
        //enhanced for loop
        for (String x:array)
        {
            System.out.println(x);
        }
  
        /* for loop for same function
        for (int i = 0; i < array.length; i++)
        {
            System.out.println(array[i]);
        }
        */
    }LK
}
OUTPUT:Y

Questions:
QSTN 1:
Backcounting from ten using for loop?
package loops;
public class ForLoopExample {
public static void main(String args[]){
for(int i=10; i>1; i--){
System.out.println("The value of i is: "+i);
}
}

OUTPUT:

QSTN 2:

Program to print fibonacci series using for loop?

Code:
package loops;

public class JavaExample {


public static void main (String[] args) {

int count = 7, num1 = 0, num2 = 1;


System.out.print("Fibonacci Series of "+count+" numbers:");

for (int i = 1; i <= count; ++i)


{
System.out.print(num1+" ");

/* On each iteration, we are assigning second number


* to the first number and assigning the sum of last two
* numbers to the second number
*/
int sumOfPrevTwo = num1 + num2;
num1 = num2;
num2 = sumOfPrevTwo;
}
}

}
OUTPUT:

QSTN 3:

Find Fictorial using for loop?

CODE:
package loops;

public class ForLoopExampl3 {


public static void main(String args[]){
int arr[]={2,11,45,9};
//i starts with 0 as array index starts with 0 too
for(int i=0; i<arr.length; i++){
System.out.println(arr[i]);
}
}

OUTPUT:

QSTN 4:

Using enhanced for loop write a program that incrments the numbers in the array

Array: 2,11,45,9

CODE:
package loops;

public class ForLoopExampl4 {


public static void main(String args[]){
int arr[]={2,11,45,9};
//i starts with 0 as array index starts with 0 too
for(int i=0; i<arr.length; i++){
System.out.println(arr[i]);
}
}

OUTPUT:

QSTN 5:

 Program to calculate the sum of natural numbers using for loop?


CODE:
package loops;

public class ForLoopexample5 {


public static void main(String[] args) {

int num = 10, count, total = 0;

for(count = 1; count <= num; count++){


total = total + count;
}

System.out.println("Sum of first 10 natural numbers is: "+total);


}

OUTPUT:
WHILE LOOP:

A while loop is a control flow statement that allows code to be performed over and over
again depending on a Boolean condition. The while loop is similar to an if statement that
repeats itself.

 Syntax:

while (boolean condition)


{
loop statements...
}

 Working steps:
1.The condition is checked first in the while loop.
2.The loop body statements are performed if it evaluates to true; otherwise, the first statement
after the loop is executed. As a result, it's also known as the Entry Control Loop.
3.The statements in the loop body are performed after the condition is evaluated to true. The
update value for the variable being processed for the following iteration is usually included in the
statements.
4.The loop ends when the condition turns false, marking the end of its life cycle.

 EXAMPLE:
CODE:
// Java program to illustrate while loop
package loops;

public class Whileloop {


public static void main(String args[])
{
int x = 1;

// Exit when x becomes greater than 4


while (x <= 4)
{
System.out.println("Value of x:" + x);

// Increment the value of x for


// next iteration
x++;}
}}
OUTPUT:

INFINITE LOOP:
When creating any type of looping, one of the most common errors is to assume that it will
never end, that is, the loop will run indefinitely. When the condition fails for whatever reason,
this occurs.
 EXAMPLE:
CODE:
Java program to illustrate various pitfalls?
package loops;

public class WhileLoopex {


public static void main (String[] args)
{

// infinite loop because condition is not apt


// condition should have been i>0.
for (int i = 5; i != 0; i -= 2)
{
System.out.println(i);
}
int x = 5;

// infinite loop because update statement


// is not provided.
while (x == 5)
{
System.out.println("In the loop");
}
}

}
OUTPUT:

QUESTIONS:
QSTN 1:
Write backward counting from 30 using while loop?
package loops;

public class WhileLoopex1 {


public static void main (String args[]){
int i=30;
while(i>1) {
System.out.println(i);
i--;
}
}

}
OUTPUT:
QSTN 2:
Write a code to find fabiconni series using while loop?
Code:
package loops;

public class Whileloopex2 {


public static void main(String[] args) {

int count = 7, num1 = 0, num2 = 1;


System.out.print("Fibonacci Series of "+count+" numbers:");

int i=1;
while(i<=count)
{
System.out.print(num1+" ");
int sumOfPrevTwo = num1 + num2;
num1 = num2;
num2 = sumOfPrevTwo;
i++;
}
}

OUTPUT:

QSTN 3:
Program finds the factorial of input number using while loop}
Code:
package loops;
import java.util.Scanner;
public class Whileloopex3 {
public static void main(String[] args) {

//We will find the factorial of this number


int number;
System.out.println("Enter the number: ");
Scanner scanner = new Scanner(System.in);
number = scanner.nextInt();
scanner.close();
long fact = 1;
int i = 1;
while(i<=number)
{
fact = fact * i;
i++;
}
System.out.println("Factorial of "+number+" is: "+fact);
}

}
OUTPUT:

QSTN 4:

Use iterating and displaying array elements using while loop?

Array: 7,15,6,87,54
package loops;

public class WhileLoopex4 {


public static void main (String args[]){
int arr[]={7,15,6,87,54};
//i starts with 0 as array index starts with 0 too
int i=0;
while(i<4) {
System.out.println(arr[i]);
i++;
}
}

}
OUTPUT:

QSTN 5:

Write a program that prompts the user to input an integer and then outputs the
number with the digits reversed. For example, if the input is 12345, the output
should be 54321.
package loops;
import java.util.Scanner;
public class WhileLoopex5 {
public static void main(String[] args)
{
Scanner console = new Scanner(System.in);

int number;
int reverse = 0;

System.out.print("Enter the number ");


number = console.nextInt();

int temp = number;


int remainder = 0;

while(temp>0)
{
remainder = temp % 10;
reverse = reverse * 10 + remainder;
temp /= 10;
}

System.out.println("Reverse of " + number + " is " + reverse);


}}
OUTPUT:
DO WHILE LOOP:

Do while loop is identical to while loop with the exception that it checks for conditions after
executing the statements, making it an Exit Control Loop.

 Syntax:

do
{
statements..
}
 EXAMPLE:
while (condition);
CODE:
QUESTIONS:
QSTN 1:
Write a backword counting from 0 to 100 using do while loop?
CODE:
package loops;

public class DoWhileex1 {


public static void main(String args[]){
int i=100;
do{
System.out.println(i);
i--;
}while(i>1);

}}

OUTPUT:

QSTN 2:
Write a a program that incremented in array
54,6,8,32,91
package loops;

public class DoWhileex2 {


public static void main(String args[]){
int arr[]={54,6,8,32,91};
//i starts with 0 as array index starts with 0
int i=0;
do{
System.out.println(arr[i]);
i++;
}while(i<4);
}

OUTPUT:
QSTN 3:
package loops;
import java.util.Scanner;
public class DoWhileex3 {
public static void main(String[] args)
{
Scanner console = new Scanner(System.in);
int number;
char choice;
int evenSum = 0;
int oddSum = 0;
do
{
System.out.print("Enter the number ");
number = console.nextInt();
if( number % 2 == 0)
{
evenSum += number;
}
else
{
oddSum += number;
}
System.out.print("Do you want to continue y/n? ");
choice = console.next().charAt(0);
}while(choice=='y' || choice == 'Y');
System.out.println("Sum of even numbers: " + evenSum);
System.out.println("Sum of odd numbers: " + oddSum);
}

OUTPUT:
QSTN 4:

Write a program to calculate HCF of Two given number.


package loops;
import java.util.Scanner;
public class DoWhileex4 {
public static void main(String[] args)
{
Scanner console = new Scanner(System.in);

int dividend, divisor;


int remainder, hcf = 0;

System.out.print("Enter the first number ");


dividend = console.nextInt();

System.out.print("Enter the second number ");


divisor = console.nextInt();

do
{
remainder = dividend % divisor;

if(remainder == 0)
{
hcf = divisor;
}
else
{
dividend = divisor;
divisor = remainder;
}
}while(remainder != 0);

System.out.println("HCF: " + hcf);


}

}
OUTPUT:

QSTN 5:
Write a do-while loop that asks the user to enter two numbers. The numbers
should be added and the sum displayed. The loop should ask the user whether
he or she wishes to perform the operation again. If so, the loop should repeat;
otherwise it should terminate. 
package loops;
import java.util.Scanner;
public class DoWhileex5 {
public static void main(String[] args)
{
Scanner console = new Scanner(System.in);

int number1, number2;


char choice;

do
{
System.out.print("Enter the first number ");
number1 = console.nextInt();

System.out.print("Enter the second number ");


number2 = console.nextInt();

int sum = number1 + number2;


System.out.println("Sum of numbers: " + sum);

System.out.print("Do you want to continue y/n? ");


choice = console.next().charAt(0);

System.out.println();

}while(choice=='y' || choice == 'Y');


}
OUTPUT:

You might also like