You can use i += 2;
which is same as i = i + 2;
, instead of using i++;
.
But this won’t give you the output you expect. So, there has to be made several changes in your code to get the expected result.
- First initialise the value of
i
to 1.
int i = 1;
- Then, change the
while loop
statement to,
while (i <= (2 * n - 1)){
// Your Code
}
- Finally, use
i += 2;
as your increment statement.
The full code is shown below.
import java.util.Scanner;
public class Main
{
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Please enter a positive number :");
int n = input.nextInt();
int i = 1;
int sum = 0;
while (i<=(2 * n - 1))
{
sum += i ;
i += 2;
}
System.out.println("Sum = " + sum);
}
}