Question:
How to Print alternate elements of an array?

Summary:

Suppose we have an array or a word with “N” number of the alphabet. We have to use Java code to print all the alternative numbers or digits available in that alphabet.


Solution:

Here is the code:

//User function Template for Java


// arr[] is the array 

// n is the number of elements in array.

class GfG

{

    public static void print(int arr[], int n)

    {

        for(int i=0;i<n;i++){

            if(i%2==0){

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

            }

        }

    }

}


Explanation:

  1. Function Definition: The code defines a class named GfG with a static method print, which takes two parameters: an array of integers arr[] and an integer n representing the number of elements in the array.


  1. Iteration Over Array: Within the print method, a for loop is used to iterate through the array elements. It starts from index 0 and continues until i is less than n.


  1. Conditional Printing: Inside the loop, an if statement checks if the current index i is even using the condition i % 2 == 0. If i is even, the element at index i of the array arr[] is printed using System.out.print(arr[i] + " ").


  1. Method Conclusion: The method ends after closing the if statement and the for loop. This code effectively prints every element at an even index of the input array, separated by spaces.


Answered by: >kvijaysunanda007

Credit: >GeekforGeeks


Suggested blogs:

>Python Error Solved: load_associated_files do not load a txt file

>Python Error Solved: pg_config executable not found

>Set up Node.js & connect to a MongoDB Database Using Node.js

>Setting up a Cloud Composer environment: Step-by-step guide

>What is microservice architecture, and why is it better than monolithic architecture?

>What is pipe in Angular?

>What makes Python 'flow' with HTML nicely as compared to PHP?

>What to do when MQTT terminates an infinite loop while subscribing to a topic in Python?

>Creating custom required rule - Laravel validation

>How to configure transfers for different accounts in stripe with laravel?


Submit
0 Answers

What Our Clients Say About Us

Client satisfaction is our ultimate goal. Here are some kind words of our precious clients they have used to express their satisfaction with our service.

Why Choose Us ?

We endow businesses with flexible engagement models based on their unique needs. Our strength lies in state-of-the-art technology and affordable consulting services. Try us for fast POCs, full-fledged applications, or technology consulting. Always available for your service.