Back
import java.util.Scanner;
public class example5 {
public static void main(String[] args)
{
int c; //Counter variable
int n; //starting number
int sum; //Variable used for storing accumulation
//INPUT
System.out.println("Example 4");
System.out.println("Enter n:");
n = readInt();
//PROCESSING AND CALCULATIONS
sum = 0;
c=1;
while (c<=n)
{
//Accumulate the totals into the variable sum
//Could also write sum += c (Take the last total of sum and add c)
sum = sum + c;
}
//OUTPUT
System.out.println("Sum of 1 + 2 + .. + n = " + sum);
}
public static int readInt()
{
Scanner sc = new Scanner(System.in);
int x = sc.nextInt();
return x;
}
}
Top |