/*
Name: I M A Nerd
Date: 4/17/2008
Description: This program will accept an integer via a command line
argument and then calculate the sum of the numbers from 1 up to
that integer. The sum will be displayed to the monitor.
This exercise demonstrates the use of command line arguments and a for loop.
It also shows how to pass an integer as a parameter to a method.
UPDATE: an additional method has been added that prints the multiples of
the value specified at the command prompt through 100
*/
public class SumFrom1ToN
{
public static void main(String [] args)
{
int n, sum;
n = Integer.parseInt(args[0]);
sum = sumNumbers(n);
System.out.println("The sum of numbers from 1 through " + n
+ " is " + sum);
//NEW!
printMultiples(n);
}
/*
This method will sum the numbers from 1 through the value passed in to the
variable num. The sum is then returned from the method
Precondition: num is greater than 0
Postcondition: the sum contains the correct value
*/
public static int sumNumbers(int num)
{
int sum = 0;
for (int i = 1; i <= num; ++i)
{
sum = sum + i;
}
//System.out.println(sum);
return sum;
}
//this method was just to show how to quickly "stub" out a method
public static int demo()
{
int sum = 0;
return sum;
}
/*
This method will print the multiples through 100 of the value passed in the variable
num.
Precondition: num is greater than 0
Postcondition: the multiples through 100 of num have been displayed
*/
public static void printMultiples(int num)
{
System.out.println("\nThe multiples through 100 of the number " + num + " are: ");
for (int multiple = num; multiple <= 100; multiple += num)
{
System.out.println(multiple);
}
}
}