In: Computer Science
find the summation of the sequence of number 1,2,3...n,where n ranges from 1 to 100.use type long.Display the results in a tabular format that shows n and the corresponding sum. If this were a product instead of sum, what difficulty might you encounter with the variable that accumulates the product?
import java.util.Scanner; public class DisplaySum { public static void main(String[] args) { Scanner in = new Scanner(System.in); System.out.println("Enter value of n: "); int n = in.nextInt(); long sum = 0; System.out.printf("\n\n%-10s%-20s\n", "Terms", "Sum"); for (int i = 1; i <= n; i++) { sum += i; System.out.printf("%-10d%-20d\n", i, sum); } } }
************************************************** If instead of sum, we take product, then the value of long will very easily be filled.. Like if we take n=20, We will have around 15-16 zeroes at the end of the product.. which will easily fill the range of the long values Thanks for your question. We try our best to help you with detailed answers, But in any case, if you need any modification or have a query/issue with respect to above answer, Please ask that in the comment section. We will surely try to address your query ASAP and resolve the issue.
Please consider providing a thumbs up to this question if it helps you. by Doing that, You will help other students, who are facing similar issue.