how to display the output like this? Output : 1+0+3+2+5+4+7+6+9+8=45 ? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 7

how to display the output like this? Output : 1+0+3+2+5+4+7+6+9+8=45 ?

What's wrong with my code , so it can't display code like that https://code.sololearn.com/c7mqA8l32mpG/?ref=app

21st Feb 2019, 1:00 PM
Iren
Iren - avatar
5 Answers
+ 16
//this is alternate way : ● use condition if(a%2==0) then add 3 to a else substract 1 from a //will look like a=a%2==0?a+3:a-1; ● you can run value loop from 1 to 9 (ranging b from 1 to 9) ● using some variable sum, keep the sum of all values of a //will look like sum+=a; //alternate way for finding sum, after loop will get over we will get max value of b.(below we will be using final value of b) ●using basic maths for sum, there is alternate pattern of odd even terms here ■ basically its sum of N terms will be summation (N-1) that is N*(N-1)/2 if N is even //so if b if odd, then sum = (b+1)*b/2, as b is (N-1) ■ if N is odd, then there will be (N-1)/2 even terms there, so sum of non-odd terms will be (N-1)*(N-3)/4 & there will be (N+1)/2 odd terms, so sum of odd terms will be {(N+1)/2}^2 //so if b is even, then sum = {b*(b-2) + (b+2)^2}/4 //ie, sum=b%2==0?(b*(b-2) + (b+2)*(b+2))/4 : (b+1)*b/2; //by this you will not even need to make variable sum.
23rd Feb 2019, 10:54 AM
Gaurav Agrawal
Gaurav Agrawal - avatar
+ 14
After seeing your code, if you want a for odd & b for even, then need of change in conditions in for loop, change in initialization of b as 0 not 1 & the change in position of updation statement for a. //here is corrected code : int a=1; //initialize b with 0 for (int b=0;b<=8;b+=2){ System.out.print(a + " " + b + " "); a+=2; //change in position of updation statement for a } //as max value of b will be (N-2) where N is total number of terms ● see the alternate way also please, using that way you can avoid making a variable sum. //though you need to replace "b" by "a" in last equation as a will be having final value as (N-1).
23rd Feb 2019, 11:12 AM
Gaurav Agrawal
Gaurav Agrawal - avatar
+ 4
1) b has the first value 1. If you want to print 0 you need to start from 0 2) a=a+2; is applied before print. You need to use 'a' argument inside print and increase 'a' value after printing. 3)to display 45 you need to use additional argument to save the sum of the loop. Int sum for example 4)to display plus add string between a and b. a +"+"+b
21st Feb 2019, 1:31 PM
Earl_Grey
Earl_Grey - avatar
+ 4
Thank you for the explanation and his help.
23rd Feb 2019, 3:28 PM
Iren
Iren - avatar
- 2
C++++++ kim bor
22nd Feb 2019, 1:37 PM
A.N.A Lutsfer Uz Bek Legiyon
A.N.A Lutsfer  Uz Bek Legiyon - avatar