Programming Examples

Java program to input a positive integer number and prints the possible consecutive number combinations


A positive natural number , (for example 27) can be represented as follows:

2+3+4+5+6+7

8+9+10

13+14

where every row represents a combination of consecutive natural numbers, which add up to 27.

Write a program which inputs a positive natural number N and prints the posibale consecutive  number combinations, which when added given N.

Test your program for the following data and some random data.

Solutions 1:

import java.util.*;
public class Consecutive
{
    public static void main(String arr[])
    {
        Scanner sc=new Scanner(System.in);
        int i,j,k,n,sum;
        System.out.println("Enter a number");
        n=sc.nextInt();
        for(i=1;i<=n/2+1;i++)
        {
            sum=0;
            for(j=i;j<=n/2+1;j++)
            {
                sum=sum+j;
                if(sum==n)
                break;
            }
            if(j<=n/2+1)
            {
                for(k=i;k<=j;k++)
                System.out.print(k+" ");
                System.out.println();
            }
        }
    }
}
Solution 2: (Using Function)
import java.util.*;
class number
{
   
    int sum(int i,int num)
    {
        int s1=0;
        for(int x=i;s1<num;x++)
        {
           
                s1=s1+x;
            
        }
        return (s1);
    }
    public static void main(String args[])
    {
        Scanner sc=new Scanner (System.in);
        System.out.println("Enter a number");
        int n=sc.nextInt();
        int s;
        number obj=new number();
        for(int j=1;j<=n;j++)
        {    
        int ans=obj.sum(j,n);
        s=0;
        if(ans==n)
        {
            for(int y=j;s<n;y++)
            {
                s=s+y;
                System.out.print(y+"  ");
            }
            System.out.println();
        }
        
    }
}
}
Output

Enter a number

21

1  2  3  4  5  6  

6  7  8  

10  11  

21  


Test 2:

Enter a number
15
1 2 3 4 5 
4 5 6 
7 8 
CCC Online Test 2021 CCC Practice Test Hindi Python Programming Tutorials Best Computer Training Institute in Prayagraj (Allahabad) Best Java Training Institute in Prayagraj (Allahabad) Best Python Training Institute in Prayagraj (Allahabad) O Level Online Test in Hindi Bank SSC Railway TET UPTET Question Bank career counselling in allahabad Sarkari Naukari Notification Best Website and Software Company in Allahabad Sarkari Exam Quiz