For Loop For loop executes group of Java statements as long as the boolean condition eval uates to true.
For loop combines three elements which we generally use: initialization statemen t, boolean expression and increment or decrement statement. For loop syntax for( <initialization> ; <condition> ; <statement> ){ <Block of statements>; } The initialization statement is executed before the loop starts. It is generally used to initialize the loop variable. Condition statement is evaluated before each time the block of statements are ex ecuted. Block of statements are executed only if the boolean condition evaluates to true. Statement is executed after the loop body is done. Generally it is being used to increment or decrement the loop variable. Following example shows use of simple for loop. for(int i=0 ; i < 5 ; i++) { System.out.println( i is : + i); } It is possible to initialize multiple variable in the initialization block of th e for loop by separating it by comma as given in the below example. for(int i=0, j =5 ; i < 5 ; i++) It is also possible to have more than one increment or decrement section as well as given below. for(int i=0; i < 5 ; i++, j--) However it is not possible to include declaration and initialization in the init ialization block of the for loop. Also, having multiple conditions separated by comma also generates the compiler error. However, we can include multiple condition with && and || logical operato rs. Calculate Average value of Array elements using Java Example /* Calculate Average value of Array elements using Java Example This Java Example shows how to calculate average value of array elements. */ public class CalculateArrayAverageExample { public static void main(String[] args) { //define an array int[] numbers = new int[]{10,20,15,25,16,60,100}; /* * Average value of array elements would be * sum of all elements/total number of elements */ //calculate sum of all array elements int sum = 0;
for(int i=0; i < numbers.length ; i++) sum = sum + numbers[i]; //calculate average value double average = sum / numbers.length; System.out.println("Average value of array elements is : " + average); } } /* Output of Calculate Average value of Array elements using Java Example w ould be Average value of array elements is : 30 */ Declare multiple variables in for loop Example /* Declare multiple variables in for loop Example This Java Example shows how to declare multiple variables in Java For loop using declaration block. */ public class DeclaringMultipleVariablesInForLoopExample { public static void main(String[] args) { /* * Multiple variables can be declared in declaration block of for lo op. */ for(int i=0, j=1, k=2 ; i<5 ; i++) System.out.println("I : " + i + ",j : "+ j + ", k : " + k); /* * Please note that the variables which are declared, should be of same type * as in this example int. */ //THIS WILL NOT COMPILE //for(int i=0, float j; i < 5; i++); } } Fibonacci Series Java Example /* Fibonacci Series Java Example This Fibonacci Series Java Example shows how to create and print Fibonacci Series using Java. */ public class JavaFibonacciSeriesExample { public static void main(String[] args) { //number of elements to generate in a series int limit = 20;
long[] series = new long[limit]; //create first 2 series elements series[0] = 0; series[1] = 1; //create the Fibonacci series and store it in an array for(int i=2; i < limit; i++){ series[i] = series[i-1] + series[i-2]; } //print the Fibonacci series numbers System.out.println("Fibonacci Series upto " + limit); for(int i=0; i< limit; i++){ System.out.print(series[i] + " "); } } } /* Output of the Fibonacci Series Java Example would be Fibonacci Series upto 20 0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181 */ Generate Pyramid For a Given Number Example Submitted By: mhack_rances(viado) /* Generate Pyramid For a Given Number Example This Java example shows how to generate a pyramid of numbers for given number using for loop example. */ import java.io.BufferedReader; import java.io.InputStreamReader; public class GeneratePyramidExample { public static void main (String[] args) throws Exception{ BufferedReader keyboard = new BufferedReader (new InputS treamReader (System.in)); System.out.println("Enter Number:"); int as= Integer.parseInt (keyboard.readLine()); System.out.println("Enter X:"); int x= Integer.parseInt (keyboard.readLine()); int y = 0; for(int i=0; i<= as ;i++){ for(int j=1; j <= i ; j++){ System.out.print(y + "\t"); y = y + x; } System.out.println(""); }
} } /* Output of this example would be Enter Number: 5 Enter X: 1 0 1 3 6 10 2 4 7 11
5 8 12
9 13
14
---------------------------------------------Enter Number: 5 Enter X: 2 0 2 6 12 20 4 8 14 22
10 16 24
18 26
28
---------------------------------------------Enter Number: 5 Enter X: 3 0 3 9 18 30 */ java Palindrome /* en number is palindrome number or not. */ public class JavaPalindromeNumberExample { public static void main(String[] args) { //array of numbers to be checked int numbers[] = new int[]{121,13,34,11,22,54}; //iterate through the numbers 6 12 21 33
15 24 36
27 39
42
Number Example Java Palindrome Number Example This Java Palindrome Number Example shows how to find if the giv
for(int i=0; i < numbers.length; i++){ int number = numbers[i]; int reversedNumber = 0; int temp=0; /* * If the number is equal to it's reversed numbe r, then * the given number is a palindrome number. * * For example, 121 is a palindrome number while 12 is not. */ //reverse the number while(number > 0){ temp = number % 10; number = number / 10; reversedNumber = reversedNumber * 10 + t emp; } if(numbers[i] == reversedNumber) System.out.println(numbers[i] + " is a p alindrome number"); else System.out.println(numbers[i] + " is not a palindrome number"); } } } /* Output of Java Palindrome Number Example would be 121 is a palindrome number 13 is not a palindrome number 34 is not a palindrome number 11 is a palindrome number 22 is a palindrome number 54 is not a palindrome number */ List Even Numbers Java Example /* List Even Numbers Java Example This List Even Numbers Java Example shows how to find and list e ven numbers between 1 and any given number. */ public class ListEvenNumbers { public static void main(String[] args) { //define limit int limit = 50; System.out.println("Printing Even numbers between 1 and " + limit);
for(int i=1; i <= limit; i++){ // if the number is divisible by 2 then it is ev en if( i % 2 == 0){ System.out.print(i + " "); } } } } /* Output of List Even Numbers Java Example would be Printing Even numbers between 1 and 50 2 4 6 8 10 12 14 16 18 20 22 24 26 28 30 32 34 36 38 40 42 44 46 48 50 */ List Odd Numbers Java Example /* List Odd Numbers Java Example This List Odd Numbers Java Example shows how to find and list od d numbers between 1 and any given number. */ public class ListOddNumbers { public static void main(String[] args) { //define the limit int limit = 50; System.out.println("Printing Odd numbers between 1 and " + limit); for(int i=1; i <= limit; i++){ //if the number is not divisible by 2 then it is odd if( i % 2 != 0){ System.out.print(i + " "); } } } } /* Output of List Odd Numbers Java Example would be Printing Odd numbers between 1 and 50 1 3 5 7 9 11 13 15 17 19 21 23 25 27 29 31 33 35 37 39 41 43 45 47 49 */ Prime Numbers Java Example /* Prime Numbers Java Example This Prime Numbers Java example shows how to generate prime numb ers between 1 and given number using for loop. */
public class GeneratePrimeNumbersExample { public static void main(String[] args) { //define limit int limit = 100; System.out.println("Prime numbers between 1 and " + limi t); //loop through the numbers one by one for(int i=1; i < 100; i++){ boolean isPrime = true; //check to see if the number is prime for(int j=2; j < i ; j++){ if(i % j == 0){ isPrime = false; break; } } // print the number if(isPrime) System.out.print(i + " "); } } } /* Output of Prime Numbers example would be Prime numbers between 1 and 100 1 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97 */ Java Pyramid 1 Example /* Java Pyramid 1 Example This Java Pyramid example shows how to generate pyramid or trian gle like given below using for loop. * ** *** **** ***** */ public class JavaPyramid1 { public static void main(String[] args) { for(int i=1; i<= 5 ;i++){ for(int j=0; j < i; j++){ System.out.print("*"); }
//generate a new line System.out.println(""); } } } /* Output of the above program would be * ** *** **** ***** */ Java Pyramid 2 Example /* Java Pyramid 2 Example This Java Pyramid example shows how to generate pyramid or trian gle like given below using for loop. ***** **** *** ** * */ public class JavaPyramid2 { public static void main(String[] args) { for(int i=5; i>0 ;i--){ for(int j=0; j < i; j++){ System.out.print("*"); } //generate a new line System.out.println(""); } } } /* Output of the example would be ***** **** *** ** * */ Java Pyramid 3 Example /* Java Pyramid 3 Example This Java Pyramid example shows how to generate pyramid or trian gle like given below using for loop.
* ** *** **** ***** ***** **** *** ** * */ public class JavaPyramid3 { public static void main(String[] args) { for(int i=1; i<= 5 ;i++){ for(int j=0; j < i; j++){ System.out.print("*"); } //generate a new line System.out.println(""); } //create second half of pyramid for(int i=5; i>0 ;i--){ for(int j=0; j < i; j++){ System.out.print("*"); } //generate a new line System.out.println(""); } } } /* Output of the example would be * ** *** **** ***** ***** **** *** ** * */ Java Pyramid 4 Example /* Java Pyramid 4 Example This Java Pyramid example shows how to generate pyramid or trian gle like
given below using for loop. 1 12 123 1234 12345 */ public class JavaPyramid4 { public static void main(String[] args) { for(int i=1; i<= 5 ;i++){ for(int j=0; j < i; j++){ System.out.print(j+1); } System.out.println(""); } } } /* Output of the example would be 1 12 123 1234 12345 */ Java Pyramid 6 Example /* Java Pyramid 6 Example This Java Pyramid example shows how to generate pyramid or trian gle like given below using for loop. ***** **** *** ** * * ** *** **** ***** */ public class JavaPyramid6 { public static void main(String[] args) { //generate upper half of the pyramid
for(int i=5; i>0 ;i--){ for(int j=0; j < i; j++){ System.out.print("*"); } //create a new line System.out.println(""); } //generate bottom half of the pyramid for(int i=1; i<= 5 ;i++){ for(int j=0; j < i; j++){ System.out.print("*"); } //create a new line System.out.println(""); } } } /* Output of the example would be ***** **** *** ** * * ** *** **** ***** */ Read Number from Console and Check if it is a Palindrome Number /* Read Number from Console and Check if it is a Palindrome Number This Java example shows how to input the number from console and check if the number is a palindrome number or not. */ import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class InputPalindromeNumberExample { public static void main(String[] args) { System.out.println("Enter the number to check.."); int number = 0; try { //take input from console
BufferedReader br = new BufferedReader(new Input StreamReader(System.in)); //parse the line into int number = Integer.parseInt(br.readLine()); } catch(NumberFormatException ne) { System.out.println("Invalid input: " + ne); System.exit(0); } catch(IOException ioe) { System.out.println("I/O Error: " + ioe); System.exit(0); } System.out.println("Number is " + number); int n = number; int reversedNumber = 0; int temp=0; //reverse the number while(n > 0){ temp = n % 10; n = n / 10; reversedNumber = reversedNumber * 10 + temp; } /* * if the number and it's reversed number are same, the number is a * palindrome number */ if(number == reversedNumber) System.out.println(number + " is a palindrome nu mber"); else System.out.println(number + " is not a palindrom e number"); } } /* Output of the program would be Enter the number to check.. 121 Number is 121 121 is a palindrome number */ Simple For loop Example /* Simple For loop Example This Java Example shows how to use for loop to iterate in Java program . */ public class SimpleForLoopExample {
public static void main(String[] args) { /* Syntax of for loop is * * for(<initialization> ; <condition> ; <expression> ) * <loop body> * * where initialization usually declares a loop variable, condition is a * boolean expression such that if the condition is true, loop body will be * executed and after each iteration of loop body, expression is exe cuted which * usually increase or decrease loop variable. * * Initialization is executed only once. */ for(int index = 0; index < 5 ; index++) System.out.println("Index is : " + index); /* * Loop body may contains more than one statement. In that case the y should * be in the block. */ for(int index=0; index < 5 ; index++) { System.out.println("Index is : " + index); index++; } /* * Please note that in above loop, index is a local variable whose scope * is limited to the loop. It can not be referenced from outside t he loop. */ } } /* Output would be Index is : 0 Index is : 1 Index is : 2 Index is : 3 Index is : 4 Index is : 0 Index is : 2 Index is : 4 */ sorting Java Bubble Sort Descending Order Example /* Java Bubble Sort Descending Order Example This Java bubble sort example shows how to sort an array of int in descending
order using bubble sort algorithm. */ public class BubbleSortDescendingOrder { public static void main(String[] args) { //create an int array we want to sort using bubble sort algorithm int intArray[] = new int[]{5,90,35,45,150,3}; //print array before sorting using bubble sort algorithm System.out.println("Array Before Bubble Sort"); for(int i=0; i < intArray.length; i++){ System.out.print(intArray[i] + " "); } //sort an array in descending order using bubble sort al gorithm bubbleSort(intArray); System.out.println(""); //print array after sorting using bubble sort algorithm System.out.println("Array After Bubble Sort"); for(int i=0; i < intArray.length; i++){ System.out.print(intArray[i] + " "); } } private static void bubbleSort(int[] intArray) { /* * In bubble sort, we basically traverse the array from first * to array_length - 1 position and compare the element with the next one. * Element is swapped with the next element if the next element is smaller. * * * * * * * * * * * * last index. * * Repeat the same steps for array[1] to array[n-1] * */ int n = intArray.length; int temp = 0; Bubble sort steps are as follows. Compare array[0] & array[1] If array[0] < array [1] swap it. Compare array[1] & array[2] If array[1] < array[2] swap it. ... Compare array[n-1] & array[n] if [n-1] < array[n] then swap it. After this step we will have smallest element at the
for(int i=0; i < n; i++){ for(int j=1; j < (n-i); j++){ if(intArray[j-1] < intArray[j]){ //swap the elements! temp = intArray[j-1]; intArray[j-1] = intArray[j]; intArray[j] = temp; } } } } } /* Output of the Bubble Sort Descending Order Example would be Array Before Bubble Sort 5 90 35 45 150 3 Array After Bubble Sort 150 90 45 35 5 3 */ Java Bubble Sort Example /* Java Bubble Sort Example This Java bubble sort example shows how to sort an array of int using bubble sort algorithm. Bubble sort is the simplest sorting algorithm. */ public class BubbleSort { public static void main(String[] args) { //create an int array we want to sort using bubble sort algorithm int intArray[] = new int[]{5,90,35,45,150,3}; //print array before sorting using bubble sort algorithm System.out.println("Array Before Bubble Sort"); for(int i=0; i < intArray.length; i++){ System.out.print(intArray[i] + " "); } //sort an array using bubble sort algorithm bubbleSort(intArray); System.out.println(""); //print array after sorting using bubble sort algorithm System.out.println("Array After Bubble Sort"); for(int i=0; i < intArray.length; i++){ System.out.print(intArray[i] + " "); } }
private static void bubbleSort(int[] intArray) { /* * In bubble sort, we basically traverse the array from first * to array_length - 1 position and compare the element with the next one. * Element is swapped with the next element if the next element is greater. * * * * * * * * * * * * ast index. * * Repeat the same steps for array[1] to array[n-1] * */ int n = intArray.length; int temp = 0; for(int i=0; i < n; i++){ for(int j=1; j < (n-i); j++){ if(intArray[j-1] > intArray[j]){ //swap the elements! temp = intArray[j-1]; intArray[j-1] = intArray[j]; intArray[j] = temp; } } } } } /* Output of the Bubble Sort Example would be Array Before Bubble Sort 5 90 35 45 150 3 Array After Bubble Sort 3 5 35 45 90 150 */ Break Statement Break statement is one of the several control statements Java provide to control the flow of the program. As the name says, Break Statement is generally used to break the loop of switch statement. Bubble sort steps are as follows. Compare array[0] & array[1] If array[0] > array [1] swap it. Compare array[1] & array[2] If array[1] > array[2] swap it. ... Compare array[n-1] & array[n] if [n-1] > array[n] then swap it. After this step we will have largest element at the l
Please note that Java does not provide Go To statement like other programming la nguages e.g. C, C++. Break statement has two forms labeled and unlabeled. Unlabeled Break statement This form of break statement is used to jump out of the loop when specific condi tion occurs. This form of break statement is also used in switch statement. For example, for(int var =0; var < 5 ; var++) { System.out.println( Var is : + var); if(var == 3) break; } In above break statement example, control will jump out of loop when var becomes Labeled Break Statement The unlabeled version of the break statement is used when we want to jump out of a single loop or single case in switch statement. Labeled version of the break statement is used when we want to jump out of nested or multiple loops. For example, Outer: for(int var1=0; var1 < 5 ; var1++) { for(int var2 = 1; var2 < 5; var2++) { System.out.println( var1: + var1 + , var2: + var2); if(var1 == 3) break Outer; } } Java break statement example /* Java break statement example. This example shows how to use java break statement to terminate the lo op. */ public class JavaBreakExample { public static void main(String[] args) { /* * break statement is used to terminate the loop in java. The follow ing example * breaks the loop if the array element is equal to true. * * After break statement is executed, the control goes to the statem ent * immediately after the loop containing break statement. */ int intArray[] = new int[]{1,2,3,4,5}; System.out.println("Elements less than 3 are : "); for(int i=0; i < intArray.length ; i ++) { if(intArray[i] == 3) break; else
System.out.println(intArray[i]); } } } /* Output would be Elements less than 3 are : 1 2 */ Java break statement with label example /* Java break statement with label example. This example shows how to use java break statement to terminate the la beled loop. The following example uses break to terminate the labeled loop while s earching two dimensional int array. */ public class JavaBreakWithLableExample { public static void main(String[] args) { int[][] intArray = new int[][]{{1,2,3,4,5},{10,20,30,40,50}}; boolean blnFound = false; System.out.println("Searching 30 in two dimensional int array.."); Outer: for(int intOuter=0; intOuter < intArray.length ; intOuter++) { Inner: for(int intInner=0; intInner < intArray[intOuter].length; intInner ++) { if(intArray[intOuter][intInner] == 30) { blnFound = true; break Outer; } } } if(blnFound == true) System.out.println("30 found in the array"); else System.out.println("30 not found in the array"); } } /* Output would be Searching 30 in two dimensional int array.. 30 found in the array */
Do While loop Example /* Do While loop Example This Java Example shows how to use do while loop to iterate in Java pr ogram. */ public class DoWhileExample { public static void main(String[] args) { /* * Do while loop executes statment until certain condition become fa lse. * * * * * * * * * op body. * So loop will be executed at least once even if the condition is f alse. */ int i =0; do { System.out.println("i is : " + i); i++; }while(i < 5); } } /* Output would be i is : 0 i is : 1 i is : 2 i is : 3 i is : 4 */ Determine If Year Is Leap Year Java Example /* Determine If Year Is Leap Year Java Example This Determine If Year Is Leap Year Java Example shows how to determine whether the given year is leap year or not. */ public class DetermineLeapYearExample { public static void main(String[] args) { //year we want to check Syntax of do while loop is do <loop body> while(<condition>); where <condition> is a boolean expression. Please not that the condition is evaluated after executing the lo
int year = 2004; //if year is divisible by 4, it is a leap year if((year % 400 == 0) || ((year % 4 == 0) && (year % 100 != 0))) System.out.println("Year " + year + " is a leap year"); else System.out.println("Year " + year + " is not a l eap year"); } } /* Output of the example would be Year 2004 is a leap year */ Compare Two Numbers Java Example /* Compare Two Numbers Java Example This Compare Two Numbers Java Example shows how to compare two n umbers using if else if statements. */ public class CompareTwoNumbers { public static void main(String[] args) { //declare two numbers to compare int num1 = 324; int num2 = 234; if(num1 > num2){ System.out.println(num1 + " is greater than " + num2); } else if(num1 < num2){ System.out.println(num1 + " is less than " + num 2); } else{ System.out.println(num1 + " is equal to " + num2 ); } } } /* Output of Compare Two Numbers Java Example would be 324 is greater than 234 */ Continue Statement Continue statement is used when we want to skip the rest of the statement in the body of the loop and continue with the next iteration of the loop. There are two forms of continue statement in Java. Unlabeled Continue Statement Labeled Continue Statement Unlabeled Continue Statement
This form of statement causes skips the current iteration of innermost for, whil e or do while loop. For example, for(int var1 =0; var1 < 5 ; var1++) { for(int var2=0 ; var2 < 5 ; var2++) { if(var2 == 2) continue; System.out.println( var1: } } In above example, when var2 becomes 2, the rest of the inner for loop body will be skipped. Labeled Continue Statement Labeled continue statement skips the current iteration of the loop marked with t he specified label. This form is used with nested loops. For example, Outer: for(int var1 =0; var1 < 5 ; var1++) { for(int var2=0 ; var2 < 5 ; var2++) { if(var2 == 2) continue Outer; System.out.println( var1: } } In the above example, when var2 becomes 2, rest of the statements in body of inn er as well outer for loop will be skipped, and next iteration of the Outer loop will be execute Java continue statement example /* Java continue statement example. This example shows how to use java continue statement to skip the iter ation of the loop. */ public class JavaContinueExample { public static void main(String[] args) { /* * Continue statement is used to skip a particular iteration of the loop */ int intArray[] = new int[]{1,2,3,4,5}; System.out.println("All numbers except for 3 are :"); + var1 + , var2: + var2); + var1 + , var2: + var2);
for(int i=0; i < intArray.length; i++) { if(intArray[i] == 3) continue; else System.out.println(intArray[i]); } } } /* Output would be All numbers except for 3 are : 1 2 4 5 */0