هذه تجربتي للسؤال ونصحوني هل الحل صحيح ولا غلط هذا هو السؤال
Write a complete Java program that prints the following series. You have to ask the user
to enter the last number in the series.
The Sum = -2+4-6+8-10+12-14+16-18+20... To the last number
Use the standard classes to enter the last number and to display the output.
You may assume that the last number is not less than 1
Use meaningful variables’ name and add comments
كيف أحل هذا السؤال عن طرق for loop
import java.util.Scanner;
public class mohammed {
public static void main(String[] args) {
int number;
int i = 2;
int output;
System.out.print("enter a number");
Scanner scanner = new Scanner(System.in);
number = scanner.nextInt();
if(number < 1)
{
System.out.print("wrong number, enter a number that is bigger than 1");
number = scanner.nextInt();
}
System.out.print("the sum = ");
while(i<=number)
{
if ((i-2)%4==0)
{
output = -1*i;
System.out.print(output);
}//end if.
else if (i%4==0)
{
output = i;
System.out.print("+"+output);
}
i+=2;
}
}
}