4. Write a program that will input a number and will display the numbers from 1 to input number. Then compute the sum and average of the numbers. Use while / do while / for loop. Ex. Enter a number 5 Output: 1 2 3 4 5 Sum: 15 Average :3
Sun Dec 08 2024 11:18:22 GMT+0000 (Coordinated Universal Time)
Saved by
@John_Almer
package sumsandaverage;
import java.util.Scanner;
public class SumsAndAverage {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter a number: ");
int n = input.nextInt();
int sum = 0;
for (int i = 1; i <= n; i++) {
System.out.print(i + " ");
sum += i;
}
double average = (double) sum / n;
System.out.println("\nSum: " + sum);
System.out.println("Average: " + average);
}
}
content_copyCOPY
Comments