Saturday 20 November 2021

Q4_even_odd_array

even_odd

4. Java Program to print the elements of an array present on even position and odd position

In this program, we need to kwon the given array element indexing that is how to indetife to odd position and even positon element which is ? . This can be accomplished by looping through the array and store the elements of the array into the odd and even element array at the corresponding position.

Original array

23 4 31 8 5

Even position

23 31 5

odd position

4 8

Algorithm

  • 1.START
  • 2.INITIALIZE arr1[] ={1, 2, 3, 4, 5}
  • 3.start for loop
  • 4.if(i%2==0) is even position
  • 5.if(i%2!=0) is odd position
  • 4.display array

Program

class Q4_odd_even {

public static void main(String[] args)

//declare array

int arr[]={23, 4 ,31, 8, 5};

System.out.println("original array is");

for(int i=0;i< arr.length;i++)

{

System.out.print(arr[i] + " ");

}

//display even position of array

System.out.println("even postiton of array element \n");

for(int i=0;i< arr.length;i++)

{

if(i%2==0)

{

System.out.print(arr[i] + " ");

}

}

//display odd position element of array

System.out.println("odd postiton of array element \n");

for(int i=0;i< arr.length;i++)

{

if(i%2!=0)

{

System.out.print(arr[i] + " ");

}

}

output

original array is:

23 4 31 8 5

even position of array is:

23 31 5

odd position of array is:

4 8

Next Topic

No comments:

Post a Comment

How do you select data from a table in SQL?

Create Table How do you select data a table in SQL? The SELECT statement is used to se...