//Program to find sum of first n (entered by user) natural numbers
import java.util.Scanner;
public class abc {
public static void main(String[] args) {
int num, count, tot = 0;
System.out.println("Enter the value of n:");
//Scanner is used for reading user input
Scanner scan = new Scanner(System.in);
//nextInt() method reads integer entered by user
num = scan.nextInt();
//closing scanner after use
scan.close();
for(count = 1; count <= num; count++){
tot = tot + count;
}
System.out.println("Sum of first "+num+" natural numbers is: "+tot);
}
}
Output:-
Enter the value of n:
5
Sum of first 5 natural numbers is: 15
import java.util.Scanner;
public class abc {
public static void main(String[] args) {
int num, count, tot = 0;
System.out.println("Enter the value of n:");
//Scanner is used for reading user input
Scanner scan = new Scanner(System.in);
//nextInt() method reads integer entered by user
num = scan.nextInt();
//closing scanner after use
scan.close();
for(count = 1; count <= num; count++){
tot = tot + count;
}
System.out.println("Sum of first "+num+" natural numbers is: "+tot);
}
}
Output:-
Enter the value of n:
5
Sum of first 5 natural numbers is: 15
0 comments:
Post a Comment