+ 1

How do I put this "Series (0-N): 1 2 3 4 5" in...

This are the content.. Display the following number patterns: > Enter a Value: 5 > Series (0-N): 1 2 3 4 5 > Sum of Series: 15 I already finished the input of 5 and output of 15..I just can't figure out how to code that "Sum of Series..." need a help =)

29th Mar 2021, 8:53 AM
Inz
Inz - avatar
12 Réponses
+ 5
Inz - This is your required code. If you like it, please upvote it. import java.util.*; public class Series { public static void main(String args[]) { int i,n,s=0; System.out.print("Enter a Value: "); n=(new Scanner(System.in)).nextInt(); System.out.print("Series (0-N): "); for(i=1;i<=n;i++){ System.out.print(i+" "); s+=i; } System.out.print("\nSum of Series: "+s); } }
30th Mar 2021, 10:47 AM
ᗩηιηɗуα ᗩɗнιкαяι
+ 1
Define a sum variable initialised to 0. then use a for loop and for each iteration add the current number to the sum variable. If you do not want to use a loop, the most effective method is to use the Gaussian sum formula sum_n=n(n+1)/2
29th Mar 2021, 9:07 AM
John Doe
+ 1
import java.util.Scanner; public class Main { public static void main (String[] args) { Scanner sc = new Scanner(System.in); int userNumber = -1; int sum=0; while (userNumber < 1) { System.out.println("Enter a Value: "); userNumber=sc.nextInt(); } for (int number = 1; number <= userNumber; number++) { sum = sum + number; } System.out.println("The sum of Series from 1 to " + userNumber + " is " + sum); } }
29th Mar 2021, 9:25 AM
Inz
Inz - avatar
+ 1
I think it wants to show the "numbers" how it becomes the sum like 1 2 3 4 5. Is there a way to show that in the program?
29th Mar 2021, 9:48 AM
Inz
Inz - avatar
+ 1
Wow! Its done now. Thanks a lot. Appreciated.
29th Mar 2021, 10:43 AM
Inz
Inz - avatar
0
Oh sorry. Ok wait..I'm writing it now
29th Mar 2021, 9:17 AM
Inz
Inz - avatar
0
_p.r.o.g.r.a.m.m.e.r.05_ - your code is better 'coz its simplified, I hope I read it sooner 😅 'coz I was away for few days. Anyways thanks for sharing your work.
2nd Apr 2021, 12:08 AM
Inz
Inz - avatar
0
This is the complete version of the program I made with the help of some people in this thread. import java.util.Scanner; public class Main { public static void main(String[] args){ Scanner sc = new Scanner(System.in); int userNumber = -1; int sum = 0; while (userNumber < 1) { System.out.print("Enter a Value: "); userNumber = sc.nextInt(); } System.out.print("Series (0-N): "); for (int number = 1; number <= userNumber; number++) { sum = sum + number; System.out.print(" " + number); } System.out.print(System.lineSeparator()); System.out.print("Sum of Series: " + sum); } }
2nd Apr 2021, 12:10 AM
Inz
Inz - avatar