Click here to Skip to main content
16,004,882 members
Please Sign up or sign in to vote.
1.00/5 (3 votes)
See more:
Print the following as output

Output:
1+2+3+4+5=15

What I have tried:

Java
sum=0;
int n,n1; 
sum=sum+(n+n1);
{
System.out.println(sum);
}
Posted
Updated 4-Feb-20 14:38pm
v3
Comments
phil.o 31-Jan-20 10:24am    
You forgot to tell what you have tried, and what you are having troubles with.
Yaswanth Kummar 31-Jan-20 10:36am    
Int n1,n2;
Sum=0;
Sum=sum+(-n1+n2)
{
System.out.println(sum);
}

But i want the output along with the series

First off, you are goign to need to store the series somewhere, and individual variables - as you show with n1 and n2 in your sample - aren't going to help.
I'd suggest that you look at creating an array of values instead of individual variables.

You can then set up a loop to process each value.
Before the loop, set the sum to zero, and create a string variable containing an empty string "" - call it separator.
Inside the loop, add the value to the sum, then print separator and the value. Then set separator to "+".
After the loop, print "=" and the sum

But this is your homework, so I'll give you no code!
 
Share this answer
 
v2
Quote:
How to print the sum along with the series

Your code is nowhere near what you want it to do. So o,ly the print part.
By using System.out.println you ensure that you will print only 1 thing per line. You should try System.out.print to avoid a new line after each part to print.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900