Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
130 views

Example Program Based On Java Loop Statement

The document provides examples of using while, do-while, and for loops in Java programs. It demonstrates how to iterate through numbers, print text multiple times, calculate sums, and find mid-values using these different loop structures. Key differences between while and do-while loops are explained. Infinite loops and using break statements to exit loops early are also discussed. A variety of programs showcase the various looping capabilities in Java.

Uploaded by

Amol Adhangale
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
130 views

Example Program Based On Java Loop Statement

The document provides examples of using while, do-while, and for loops in Java programs. It demonstrates how to iterate through numbers, print text multiple times, calculate sums, and find mid-values using these different loop structures. Key differences between while and do-while loops are explained. Infinite loops and using break statements to exit loops early are also discussed. A variety of programs showcase the various looping capabilities in Java.

Uploaded by

Amol Adhangale
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 14

Example Program based on Java while loop statement

1. Let’s create a simple Java program to display the numbers from 1 to 5 by


using while loop.
Program code 1:
package javaProgram;
public class WhileLoopEx {
public static void main(String[] args)
{
int i = 1; // Initialization.
while(i <= 5)
{
System.out.println(i);
i++; // Increment.
}
}
}

Output:
1
2
3
4
5

2. Let’s create a simple Java program to print a “Hello World!” four times on
the console using a while loop.
Program code 2:
package javaProgram;
public class WhileLoopEx {
public static void main(String[] args)
{
int i = 1;
while(i <= 4)
{
System.out.println("Hello World!");
i++;
}
}
}

Output:
Hello World!
Hello World!
Hello World!
Hello World!

3. Let’s create a Java program to display numbers from 5 to 1 by using while


loop statement.
Program code 3:
package javaProgram;
public class WhileLoopEx {
public static void main(String[] args)
{
int i = 5;
while(i >= 1)
{
System.out.println(i);
i--; // decrement.
}
}
}
Output:
5
4
3
2
1

4. Let’s consider an example program where we will add the number from 1 to
10 using while loop and display the sum on the console.
Program code 4:
package javaProgram;
public class Test {
public static void main(String[ ] args)
{
int sum = 0, i = 1;
while (i <= 10) {
sum = sum + i;
i++;
}
System.out.println("sum is " + sum); // sum is 55
}}

In this example program, the variable i is initially set to 1 and the sum initially
set to 0. When the conditional expression (i < 10) is true, the program adds i
to the sum. Then, the variable i incremented to 2.
Again, the conditional expression evaluates to true. If it is true, the program
adds i to sum. The variable is once again incremented to 3.
This process continues up to 10. Each time the program adds i to sum if the
condition is true. After 10 iterations, the control of execution exits the loop.
Therefore, the sum is 1 + 2 + 3 + … + 10 = 55.

While loop without Body Example Program


5. Let’s take another example program where the body of while loop will be
empty. In this example, we will calculate the mid-value between i and j where i
is equal to 10 and y is equal to 20.
Look at the following program source code to understand better.
Program code 5:
package javaProgram;
public class Test {
public static void main(String[] args)
{
int x = 10, y = 20;
while (++x < --y); // No body in this loop.
System.out.println("Mid value is " + x);
}
}

Output:
Mid value is 15

This example program finds the mid-value between x and y. Let’s understand
how the while loop in the program works.
a. Initially, the value of x is set to 10 and y set to 20. These initially set values
compare with one another. If the value of x is less than the value of y, the loop
repeats.
b. Now, the value of x increments by 1, and the value of y decrements by 1.
These new values then compare with one another. If the new value of x is still
less than the new value of y, the loop once again repeats.
c. This process continues until the value of x is equal to or greater than the
value of y.
d. When the value of x is equal to or greater than the value of y, the loop
stops.
e. Upon exit from the loop, the variable x will hold a value that is midway
between the original values of x and y.
As you can observe in the program, there is no need for a loop body. All the
action happens within the conditional expression itself.
Example Program based on do while loop in Java

1. Let’s take a simple example program where we will display numbers from 1
to 6.
Program code 1:
package javaProgram;
public class Test {
public static void main(String[] args)
{
int x;
x = 1; // starting number is 1.
do {
System.out.println(x); // print x value.
x++; // increment x value by 1.
} while(x <= 6); // This statement will execute as long as x <= 6.
}
}

Output:
1
2
3
4
5
6

a. In this example, the value of x is initially set to 1. Therefore, it is displayed


1.
b. Now, x++ statement will increment the value of x by 1, hence the value of x
becomes 2. The conditional boolean expression x<=10 is tested.
c. Since this condition is true, the flow of execution will go back and the value
of x, i.e. 2 will be displayed on the console.
d. Then the x value once again incremented and becomes 3. Since 3 is also
less than 10, the flow once again goes back and displays x value.
e. In this way, this process continues until the value of x is less than or equal
to 6.

f. As the value of x is greater than 6, the condition will be false and the loop
will be terminated.

2. Let’s another example program based on do while statement where we will


display the multiplication table.
Program code 2:
package javaProgram;
public class Test {
public static void main(String[] args)
{
int row, column;
System.out.println("Multiplication Table \n");
row = 1; // Initialization.
do {
column = 1;
do{
int x = row * column;
System.out.printf("%4d", + x);
column = column + 1;
}while(column <= 5);
System.out.println("\n");
row = row + 1;
} while(row <= 5);
}
}

Output:
Multiplication Table:
1 2 3 4 5
2 4 6 8 10
3 6 9 12 15
4 8 12 16 20
5 10 15 20 25

In this example program, do-while loop is in nested form and produces the
following output.
Program code 3:
package javaProgram;
import java.util.Scanner;
public class Test {
public static void main(String[] args)
{
int num = 0, sum = 0;

// Create an object of Scanner class to take input.


Scanner sc = new Scanner(System.in);

// Continue reading data until the input is 0.


do {
// Read the next input.
System.out.println("Enter an integer number");
num = sc.nextInt();
sum = sum + num;
} while(num != 0);
System.out.println("Sum of numbers: " +sum);
}
}

Output:
Enter an integer number
20
Enter an integer number
10
Enter an integer number
5
Enter an integer number
40
Enter an integer number
0
Sum of numbers: 75

Difference between while loop and do-while loop

The difference between while loop and do-while loop in Java is as follows:
1. In the case of while loop, first test condition is verified and then executes
the statements inside the while block.
In the case of do-while loop, first statements inside do block are executed and
then the test condition is verified.
2. If the test condition is false for first time, then block of statement executed
zero times.
If the test condition is false for the first time, then the block of statement
executed at least once time.
3. In the while syntax, while statement is at the top.
In the do-while syntax, while statement is at the bottom.

Example Program based on for loop statement

1. Let’s take an example program where we will display numbers from 1 to 5


and from 5 to 1.
Program code 1:
package javaProgram;
public class Test {
public static void main(String[] args)
{
System.out.println("Displaying numbers from 1 to 5:");
for(int i = 1; i <=5; i++) { // Here, i++ is increment operator.
System.out.println(i);
}
System.out.println("Displaying numbers from 5 to 1:");
for(int j = 5; j > 0; j--) { // Here, j-- is decrement operator.
System.out.println(j);
}
}}

Output:
Displaying numbers from 1 to 5:
1
2
3
4
5
Displaying numbers from 5 to 1:
5
4
3
2
1

We can also write the same for loop like this:


int i = 1;
for(; i <= 5;) {
System.out.println(i);
i++;
}

2. Let’s take another program where we will calculate the sum of squares of
integer numbers from 1 to 5 using for loop statement. Look at the following
source code to understand better.
Program code 2:
package javaProgram;
public class Test {
public static void main(String[] args)
{
int i = 1;
int sum = 0;
for(; i <= 5;) {
sum = sum + i*i;
i++;
}
System.out.println("Sum: " +sum);
}
}

Output:
Sum: 55

Infinite For Loop in Java

Consider the following example code of a program.


int x = 1;
for(; ;)
{
System.out.println(x);
x++;
}

In this example, there is no test condition in the for statement that tells where
to stop. So, the code will execute without stoppage. This loop is called infinite
loop in Java. We should avoid to make an infinite loop.
By mistake, if we make infinite for loop in java program, we can stop it using
break statement. It can be used to come out of loop.

Infinite For loop Example Programs

Let’s take an example program based on infinite for loop where we will display
the sum of cubes of numbers from 1 to 5.
Program code 3:
package javaProgram;
public class Test {
public static void main(String[] args)
{
int i = 1;
int sum = 0;
for(; ;){
sum = sum + i * i * i;
i++;
if(i >= 5) break; // If the i value exceeds 5, then come out of this loop.
}
System.out.println("Sum: " +sum);
}
}

Output:
Sum: 100

Let’s take an example program where we will initialize two variables in for
statement and will display numbers from 1 to 5 and 5 to 1 simultaneously.
Program code 4:
package javaProgram;
public class Test {
public static void main(String[] args)
{
int i, j;
for(i = 1, j = 5; i <= 5; i++, j--)
{
System.out.println(i+ "\t" +j);
}
}}

Output:
1 5
2 4
3 3
4 2
5 1

In this loop, we have used two initialization expressions (i = 1, and j = 5) and


two iteration expressions (i++, and j–). But there is only one test conditional
expression (i < = 5).
This for loop will print i values from 1 to 5 whereas, the values of j will
simultaneously change from 5 to 1.

Note:
1. The for loop can have more than one initialization expression and iteration
expression. This feature cannot apply in other loops. Each expression must
be separated from the next by a comma.
Let’s take one more program based on this point.
Program code 5:
package javaProgram;
public class Test {
public static void main(String[] args)
{
int x, y;
for(x = 1, y = 5; x < y; x++, y--)
{
System.out.println("x = " + x);
System.out.println("y = " + y);
}
}}

Output:
x=1
y=5
x=2
y=4

In this example program, the initialization portion consists of two control


variables x and y that have been separated by comma. The two comma
separated expressions (x++ and y–) in the iteration portion are executed each
time the loop repeats.

2. The test condition in for loop statement can also have compound relation.
Let’s understand it with the help of an example program.
Program code 6:
package javaProgram;
public class Test {
public static void main(String[] args)
{
int x = 1, sum = 0;
for(x = 1; x < 20 && sum < 20; x++){
sum = sum + x;
}
System.out.println("Sum: " +sum);
}
}

Output:
Sum: 21

In this example, the loop will be executed until both conditions x < 20 and sum
< 20 are true. The sum is evaluated within the body of loop.
3. It is also possible to use expressions in the initialization and increment
portions. For example, this type of statement for(x = (a + b)/5; x > 10; x = x/5)
is perfectly valid.
4. When we declare control variable inside a for statement, the scope of that
variable is ended after the ending of for loop. It means that the control variable
defined inside a for statement is a local variable that cannot be accessed from
outside the loop.
Program code 7:
public class Test {
public static void main(String[] args)
{
for(int x = 1; x < 10; x++){
System.out.println(x); // No error.
}
System.out.println(x); // Compile time error.
}
}

You might also like