for loops in java with examples

0

for loops are a way to repeat execution of same code for specific times.

its written in this way:

for(the counter;the condition of continue;counter change after every round)

{

here is the code to be repeated

}

All Contributions

Write a program to calculate the sum of the following series where n is an input integer entered by the user. 1 + 1/2 + 1/3 + 1/4 + 1/5 +…………1/n

public class Exercise1 { 
 public static void main(String[] args) 
 { 
Scanner input = new Scanner(System.in); 
int number; // To hold number of terms 
double sum = 0; 
System.out.print("Enter number of terms of series: "); 
number = input.nextInt(); 
for(int i = 1; i <= number; i++) 
 { 
 sum += 1.0/i; 
 } 
 System.out.println("sum: " + sum); 
 }

write java program to print all even numbers between 0 to 100

for(int i=0;i<=100;i++)
{
 if(i%2==0)
  System.out.println(i); 
}

write java program that print all odd numbers between 0 to 100, but print it descently

for(int i=100;i>=0;i--)
{
 if(i%2!=0)
  System.out.println(i); 
}

write java program to print all odd numbers between 0 to 100

for(int i=0;i<=100;i++)
{ 
 if(i%2!=0)
  System.out.println(i);
}

write java program to print the numbers from 1 to 100   --  use for loop

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

total contributions (6)

New to examplegeek.com?

Join us