Accept a number from the user and put into a loop to find the Consecutive Numbers and store the numbers in a string. Now print the string a result.
import java.util.*;
class Consecutive
{
public static void main()
{
Scanner sc = new Scanner(System.in);
System.out.println("Enter the number:");
int num = sc.nextInt();
int sum;
String str;
for(int i=1;i<num;i++)
{
sum=0;
str="";
for(int k=i;k<num;k++)
{
sum += k;
if(str.equals(""))
{
str += k;
}
else
{
str += "+" + k;
}
if (sum==num)
{
System.out.println(str);
}
else if(sum>num)
{
break;
}
}
}
}
}
Enter the number:
15
1+2+3+4+5
4+5+6
7+8