Friday, December 28, 2012

BlueJ Program To Display All Combinations Of Consecutive Natural Numbers



This is a BlueJ program to input a positive natural number N and output all combinations of consecutive natural number,which add up to give N example: N=15 output:
1 2 3 4 5
4 5 6
7 8



import java.io.*;
class Suddha
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
 int i,j,n,sum,index=0,n1;
 int arr[]=new int[50];
 public void show()throws Exception
 {
     System.out.println("Enter the number:");
     n=Integer.parseInt(br.readLine());
     for(i=1;i< n;i++)

{
          sum=0;
       n1=i;
      while(n1 < n)      {
           sum=sum+n1;
       arr[index++]=n1;
       if(sum>n)
       {
           index=0;
           break;
    }
       else if(sum==n)
       {
            for(j=0;j< index;j++)

            System.out.print(" "+arr[j]);
            System.out.println();
            index=0;
            break;
        }
   n1++;
}
}
   
}
public static void main(String args[]) throws Exception
{
Suddha ob=new Suddha();
ob.show();
}
}


Related PostBlueJ Programs on Number

No comments:

Post a Comment

Subscribe via email

Enter your email address:

Delivered by FeedBurner