
In this code, the user is prompted to enter a positive integer. Then, a for loop is used to iterate from 1 to the given number (n
). The loop adds each number to the sum
variable. Finally, the result is printed to the console.
Note that the code assumes the user will enter a positive integer. You can add additional input validation if necessary.
import java.util.Scanner;
public class Naturenumber {
public static void main(String []args){
Scanner Sc = new Scanner(System.in);
System.out.println("enter the any number");
int n = Sc.nextInt();
int Sum = 0;
for(int i=0; i<=n; i++)
{
Sum = Sum + i;
}
System.out.println("Sum is "+Sum);
}
}
WITHOUT USING SCANNER
public class Nature1 {
public static void main(String [] args){
int n = 4;
int Sum = 0;
for(int i=0;i<=n;i++)
{
Sum = Sum + i;
}
System.out.println("Sum is "+Sum);
}
}
output is 10