Introduction:-
Welcome back to our programming journey! In this blog post, we'll explore one of the most powerful and essential concepts in programming: loops. Loops allow us to execute a block of code repeatedly, saving us from writing redundant code. We'll dive into the three main types of loops in Java—`for`, `while`, and `do-while` —and provide practical examples to solidify your understanding.
Understanding Loops:-
Loops are fundamental to programming as they help us automate repetitive tasks. Imagine having to print a message multiple times or process a list of items without loops—it would be a cumbersome and error-prone process.
1. The `for` Loop:
The `for` loop is used when you know the number of times you want to repeat an action.
for (int i = 1; i <= 5; i++) {
System.out.println("Iteration: " + i);
}
This is a example of `for` loop:-
//import this java class to take input from the user
import java.util.*;
public class forLoop {
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
System.out.println(" Enter number : ");
int n = sc.nextInt();
System.out.println("The table is: ");
for(int i=1; i<=10; i++){
int z = n*i;
System.out.println(n + "*" + i + " = " +z);
}
}
}
In the for loop first check conditions if condition is false then it does not execute but if condition is true then it will execute.2. While loop:- In the `while loop` first check conditions if condition is false then it does not execute but if condition is true then it will execute. The `while loop` is used when you want to repeat an action as long as a certain condition is `true`.
//import this java class to take input from the user
import java.util.*;
public class forLoop {
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
System.out.println(" Enter your name : ");
String str = sc.nextLine();
System.out.println("Your name is: ");
int i=1;
while(i<=10){
System.out.println("Latest blog with Jayram");
i++;
}
}
}//import this java class to take input from the user
import java.util.*;
public class forLoop {
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
System.out.println(" Enter your name : ");
String str = sc.nextLine();
System.out.println("Your name is: ");
int i=1;
do{
System.out.println("Jayram");
i++;
}
while(i<=5);
}
}
Comments
Post a Comment