CBSE Class 12-Information Technology (802) Java Programs Simplified

Phurden Lepcha
By -
0

 Program #1

Write a program in Java to print the square of every alternate number of an array.

Source code:
public class SquareAlternateNumbers
{
    public static void main(String[ ] args)
    {
         int[ ] numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};  //Example Array
        for(int i = 0; i < numbers.length; i++)
        {
            if(i % 2 != 0)  //Check if the index is odd (alternate)
            {
                int square = numbers [i] * numbers [i];
                System.out.println(" Square of " +numbers[i] +" is " +square);
            }
        }  
    }
}

Output:
            Square of 2 is 4
            Square of 4 is 16
            Square of 6 is 36
            Square of 8 is 64
            Square of 10 is 100


Tags:

Post a Comment

0Comments

Post a Comment (0)