Question 1)
Write a Program to find the summation of n numbers.
Answer :-
import java.util.Scanner;
public class SummationOfNNumbersFormula {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// Prompt the user to enter the number of elements
System.out.print("Enter the number of elements: ");
int n = scanner.nextInt();
// Prompt the user to enter the numbers
System.out.println("Enter the elements:");
int sum = 0;
for (int i = 1; i <= n; i++) {
int num = scanner.nextInt();
sum += num;
}
// Calculate the summation using the formula
int summation = n * (n + 1) / 2;
// Display the summation
System.out.println("Sum of the numbers: " + summation);
scanner.close();
}
}
0 Comments