Assignment: Module 03- Part 02
![]() |
Assignment: Module 03- Part 02 |
Write a class LoopExample2 to display the output as below using control structures
Input:
Enter the no of terms3
Output:
sum of first 3 numbers=6
import java.util.Scanner;
public class LoopExample2 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter the number of terms: ");
int n = sc.nextInt();
int sum = 0;
for (int i = 1; i <= n; i++) {
sum += i;
}
System.out.println("Sum of first " + n + " numbers = " + sum);
}
}
And here is an example of the output when the user inputs 3:
Enter the number of terms: 3
Sum of first 3 numbers = 6