Answer to Question #288498 in Java | JSP | JSF for Zeref

Question #288498

Write a program to display sum of the following series:

1-3+5-7+9.....n terms

Using following method prototype:

int  series(int n)


If Input is given the above series i.e. 1-3+5-7+9

then output will be 5...


1
Expert's answer
2022-01-18T08:37:44-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*2; 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