Dremendo Tag Line

Print the number series 1 -2 3 -4 5 using while loop in Java

while Loop - Question 5

In this question, we will see how to print the number series 1 -2 3 -4 5 -6... up to nth term in Java programming using while loop. To know more about while loop click on the while loop lesson.

Q5) Write a program in Java to print the number series given below using while loop.

1 -2 3 -4 5 -6... up to nth term

Program

import java.util.Scanner;

public class Q5
{
    public static void main(String args[])
    {
        int i=1,s=1,n;
        Scanner sc=new Scanner(System.in);

        System.out.print("Enter nth term ");
        n=sc.nextInt();

        while(i<=n)
        {
            System.out.print(i*s + " ");
            s=s*-1;		// changing the sign
            i=i+1;
        }
    }
}

Output

Enter nth term 10
1 -2 3 -4 5 -6 7 -8 9 -10
video-poster