Answer to Question #285710 in Java | JSP | JSF for ____

Question #285710

WAP in Java to display sum of the following series: 1-3+5-7+9.....n terms


Using following method prototype:


int series(int n)

1
Expert's answer
2022-01-09T02:20:34-0500


import java.util.Scanner;


public class App {


	/**
	 * The start point of the program
	 * 
	 * @param args
	 * 
	 */
	public static void main(String[] args) {
		Scanner keyBoard = new Scanner(System.in);
		System.out.print("Enter the N: ");
		int N = keyBoard.nextInt();


		System.out.print("Sum: " + series(N));


		keyBoard.close();
	}


	static int series(int n) {
		int sum = 0;
		int counter = 0;
		for (int i = 1; i <= n; i += 2) {
			if (counter % 2 == 0) {
				sum += i;
			} else {
				sum -= i;
			}
			counter++;
		}
		return sum;
	}
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog