Welcome to ICSE Java Answers. Ask any questions you have related to Java and we will answer them.
Java is a registered trademark of Oracle. This site is in no way related to or endorsed by Oracle.

Calculate the sum of series 9 + 99 + 8 + 89 + 7 ... to n terms

0 votes
asked by Abhishek
edited by Ranjith

1 Answer

0 votes

The series can be expressed in the following way

Start with num = 9.  Add num and (num * 10 + 9) to the sum. Decrement num and repeat.

import java.util.Scanner;

public class Series {
	public static void main(String[] args) {
		Scanner scanner = new Scanner(System.in);
		System.out.print("Enter n: ");
		int n = scanner.nextInt();
		int sum = 0;
		int num = 9;
		for (int i = 1; i <= n; i++) {
			System.out.println("Adding " + num + " to sum");
			sum = sum + num;
			i++;
			if (i > n) {
				break;
			}
			int term = num * 10 + 9;
			System.out.println("Adding " + term + " to sum");
			sum = sum + term;
			num--;
		}
		System.out.println("Sum = " + sum);

	}
}

Output

Enter n: 6
Adding 9 to sum
Adding 99 to sum
Adding 8 to sum
Adding 89 to sum
Adding 7 to sum
Adding 79 to sum
Sum = 291

 

answered by Ranjith (2,683 points)
...