If I enter number 5 then output should be as below.
Output = 5*5 - 4*4 + 3*3 - 2*2 + 1*1
If I enter 4 then
Output = 4*4 - 3*3 + 2*2 - 1*1
Below is code.
First Method :
Second Method :
Output = 5*5 - 4*4 + 3*3 - 2*2 + 1*1
If I enter 4 then
Output = 4*4 - 3*3 + 2*2 - 1*1
Below is code.
First Method :
public class JavaExampleSeries { public static void main(String[] args) { int number = 5; long output = 0; int counter = 1; if(number%2==0) { for(int i=number; i>=1; i--) { if(counter%2==0) { output = output - i*i; } else { output = output + i*i; } counter++; } } else { for(int i=number; i>1; i--) { if(counter%2==0) { output = output - i*i; } else { output = output + i*i; } counter++; } output = output+1; } System.out.println("Output is : " + output); } }
Second Method :
public class JavaExampleSeries { public static void main(String[] args) { int number = 5; long output = 0; int iterations = number/2; for(int i=1; i<=iterations; i++) { output = output + ((number*number)-((number-1)*(number-1))); number = number-2; } if(number%2>0) { output = output+1; } System.out.println("Output is : " + output); } }
No comments:
Post a Comment