29
Nov
Loop is used to execute a statement or some statements multiple times. There are 3 types of loop control in java.
- For Loop
- While Loop
- Do While Loop
For Loop
For loop pattern:
for(initialization;condition;increment){
//statement
}
A simple program in for loop:
- Write a program to show only odd numbers from 1 to 100
public class Main {
public static void main(String[] args) {
for(int i=1;i<=100;i++){
if(i%2!=0){
System.out.println(i);
}
}
}
}
2. Write a program to show first 100 prime numbers:
public class Main {
public static void main(String[] args) {
String primeNumbers = "";
for (int i = 1; i <= 100; i++)
{
int counter=0;
for(int num =1; num<=i; num++)
{
if(i%num==0)
{
counter = counter + 1;
}
}
if (counter ==2)
{
primeNumbers = primeNumbers + i + " ";
}
}
System.out.println("Prime numbers from 1 to 100 are :");
System.out.println(primeNumbers);
}
}
While loop
While loop pattern:
while(condition) { //statement; }
orinitialization; while(condition) { //statement; increment; }
A simple program in while loop:
- Write a program to find out factorial of a number.
public class Main {
public static void main(String[] args) {
int number=5;
int i=1;
int fact=1;
while(i <=number){
fact=fact*i;
i++;
}
System.out.println(fact);
}
}
Output: 120
2. Write a program to find the summation of digits.
public class Main {
public static void main(String[] args) {
int sum = 0;
Scanner s = new Scanner(System.in);
System.out.print("Enter a number:");
int num = s.nextInt();
while(num != 0)
{
int res = num % 10;
sum = sum + res;
num = num / 10;
}
System.out.println("Sum of Digits:"+sum);
}
}
Output:
Enter a number:1241
Sum of Digits:8
Do While Loop
While loop and do while loop are same just a pretty much difference that is, while loop check the condition at first and do while check the condition after executing the statement.
Pattern:
do {
// code block to be executed
}
while (condition);
A simple program in do-while loop:
- Write a program to find factorial of a number.
public static void main(String[] args) {
int number=5;
int i=1;
int fact=1;
do{
fact=fact*i;
i++;
}
while(i <=number);
System.out.println(fact);
}
Output: 120
Leave a Reply