Computer Science, asked by BrainlyProgrammer, 4 months ago

WAP in JAVA using Scanner class to print the natural combination which adds up to the number
Example:
Enter a number:-
15
Output:-
1,2,3,4,5
4,5,6
7,8​

Answers

Answered by anindyaadhikari13
4

Answer:-

This is the required program.

import java.util.*;

class Java

{

public static void main(String args[])

{

Scanner sc=new Scanner(System.in);

System.out.print("Enter a number: ");

int n=sc.nextInt();

int s;

for(int i=1;i<n;i++)

{

s=0;

for(int j=i;j<n;j++)

{

s+=j;

if(s==n)

{

for(int k=i;k<j;k++)

System.out.print(k+" + ");

System.out.print(j+"="+n+"\n");

break;

}

}// end of inner loop.

}// end of outer loop

}// end of main()

}//end of class

Output:-

Enter a number: 15

1+2+3+4+5=15

4+5+6=15

7+8=15

Answered by Oreki
2

import java.util.Scanner;  

public class ConsecutiveNumberSum {

   public static void main(String[ ] args) {

       System.out.print("Enter a number - ");

       int num = new Scanner(System.in).nextInt( );

       for (int i = 1; i < num; i++) {

           StringBuffer number = new StringBuffer( );

           number.append(i).append(" ");

           int sum = i;

           for (int j = i + 1; sum < num; j++) {

               number.append(j).append(" ");

               sum += j;

               if (sum == num)

                   System.out.println(number.toString( ));

           }

       }

   }

}

Attachments:
Similar questions