Consecutive Sum – ISC Practical 2006 Java Program

Question 1

 A positive natural number, (for e.g. 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 possible consecutive number combinations, which when added give N.

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

SAMPLE DATA

INPUT:

N = 9

OUTPUT:

4 + 5

2 + 3+ 4

INPUT:

N = 15

OUTPUT:

7 +8

1 +2+ 3+ 4+ 5

4 +5+ 6

INPUT:

N = 21

OUTPUT:

10+ 11

1+ 2+ 3+ 4+ 5+ 6

6+ 7+ 8

import java.util.Scanner;
class ConsecutiveSum
{
    public static void main(String args[])
    {
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter a number");
        int n=sc.nextInt();
        
        for(int i=1; i<=n/2; i++)
        {
            int sum=i;
            String s=""+i;
            int x=i+1;
            do{
                sum+=x;
                s=s+" + "+x;
                x++;
            }while(sum<n);
            
            if(sum==n)
                System.out.println(s);
        }
    }
}

Leave a Comment

Your email address will not be published. Required fields are marked *