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...
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;
}
}
Comments
Leave a comment