In this tutorial you will learn about the Java Program to print elements of an array present on even position and its application with practical example.
In this tutorial, we will learn to create a Java Program to print elements of an array present on even position using java programming.
Prerequisites
Before starting with this tutorial, we assume that you are best aware of the following Java programming concepts:
- Java Operators.
- Basic Input and Output function in Java.
- Class and Object in Java.
- Basic Java programming.
- If-else statements in Java.
- For loop in Java.
What is Even-Odd Place in array ?
Odd-Even positions in an array are those element present within even index and for odd present in odd index are called odd even place as shown in the image below. So element on 1,3,5 are even index value which is => 10,30 and 50 are even index values.
Java Program to print elements of an array present on even position
In this program we will print element in present in even position within the array using for loop. We would first declared and initialized the required variables. Next, we will find even place element in an array. Lets have a look at the code.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
// Java program to print the elements present at even position import java.util.*; public class Even { public static void main(String[] args) { //declaring variable and initialize variables int [] a = new int [] {1, 2, 3, 4, 5, 6, 7, 8, 9}; System.out.println("Elements in an array present on even position are"); //printing the values at even postion in an array[]. for (int i = 1; i < a.length; i = i+2) { //Printing result.. System.out.print(a[i] + " "); } } } |
Output
In the above program, we have first declared and initialized a set variables required in the program.
- a[]= it will hold array values
- i = for iteration.
After declaring variables we initiate values in an array[]
Algorithm
- 1: Start.
- 2: Initialize array with vales a[] = {1, 2, 3, 4, 5, 6, 7, 8, 9}
- 3: Simply print “elements of given array present at even positions”.
- 4: Repeat this step for(i=1; i< arr.length; i= i+2) unitll we reach at last position of an array.
- 5: Print a[i].
- 6: End.
with the help of for loop traverse through the array and printing elements of an array by incrementing value of i by i+2 till the last element of the array.