Welcome To The World Of Java

This site will teach you the basics of Java. It is not necessary to have any prior programming experience.

Print Series 1, -3, 5, -7, …………n terms in Java.

Somdeb Burman | 11:26:00 AM | 1 comments

import java.util.Scanner;
public class OddSeries 
{
 public static void main(String args[]) 
  {
  Scanner sc = new Scanner(System.in);
  System.out.print("Enter the number of terms: ");
  int n = sc.nextInt();
  int i = 1, c, f = 1;                            // i for odd nos, c for counter, f for flag
  for (c = 1; c <= n; c++) {
   if (f % 2 == 0) {
    System.out.print(-i + " ");
   } else {
    System.out.print(i + " ");
   }
   i += 2;
   f++;
  }                                                  //Loop ends
 }
}


Output:


Enter the number of terms: 6

1  -3  5  -7  9  -11...... 
BUILD SUCCESSFUL (total time: 6 seconds)

Java Resources are available for Download from below

Category: , , , ,

1 comment: