Java Loop

Published by Admin on

A Java loop is a programming structure that execute repeatedly a particular block of code, based on a given Boolean condition

Following types of loop :-

Sr.No.Loops NameDescription
1.for loop It is recommended when number of iteration is fixed. It is a repetition control structure.
2.while loopIt is control flow structure. Repeats a statement or group of statements until a certain condition is met (test expression is false). It is tests the condition before executing the loop.
3.do while loopDo-While loop main difference with other loop is that it will execute the code block once, its not check any condition to execute block of code once. It’s tests the condition at the end of the loop body.

1. For loop

Syntax

for (statement 1; statement 2; statement 3) {
    // this is code block
}

Statement 1 :- is executed (one time) before the execution of the code block.
Statement 2 :- defines the condition for executing the code block.
Statement 3 :- is executed (every time) after the code block has been executed.

Example

for (int iq= 0; iq < 10; iq++) {
    // execute this block 10 times. print output 0 to 9
    System.out.println(iq);
}

2. while loop

The while loop through a block of code as long as a specified condition is true.

Syntax

while (boolean condition) {
   // this is code block
}

Example

int i = 0;
while (i < 10) {
    // execute this block 10 times. print output 0 to 9
    System.out.println(i);
    i++;
}

3. do while loop

The do while loop is iterate a part of the program several times. This loop will execute the block of code once, without checking if the condition is true, then it will repeat the loop as long as the condition is true.

Syntax

do {
    // this is code block
}
while(condition);

Example

int i = 0;
do {
    // execute this block 10 times. print output 0 to 9
    System.out.println(i);
    i++;
}
while (i < 10);

Question :-

  • What is Java Loop?
  • Write a program to print numbers from 1 to 20.
  • Write a program to calculate the sum of first 20 natural number.
  • How many types are java loops?
  • Which loop is faster in Java?
  • What is while loop example in Java?
  • How does while loop work in Java?
  • What is a for loop and while loop?
  • What is Deference between while loop and do while loop in Java?


0 Comments

Leave a Reply

LinkedIn
LinkedIn
Share
Instagram
Follow by Email
YouTube
YouTube
Telegram
RSS