Saturday , 21 April 2018
Latest Posts
Home » Class 12 » Program to print the possible consecutive number combinations

# Program to print the possible consecutive number combinations

#### Question:

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

#### Programming Code:

```/**
* The class ISC06PQ1 inputs a number and prints all the series of consecutive natural numbers whose
sum equals the number
* @author : www.javaforschool.com
* @Program Type : BlueJ Program - Java
* @Question Year : ISC Practical 2006 Question 1
*/

import java.io.*;
class ISC06PQ1
{
public static void main(String args[])throws IOException
{
System.out.print("Enter a number : "); //inputting the number

int sum=0,c=0,j=0;
for(int i=1;i<n;i++)
{
sum=i;
j=i+1;

/* adding consecutive natural numbers till sum is less than the given number */

while(sum<n)
{
sum=sum+j;
j++;
}

/* when the above while condition is false, then either the sum is equal to
that number or is greater than that number
So, we will be printing the series of consecutive numbers only if the sum is
equal to that number

Note: variable 'i' is keeping record of the first number of the series and
variable 'j' is keeping record of the last number of the series */

if(sum==n)
{
for(int k=i;k<j;k++)
{
if(k==i)
System.out.print(k);
else
System.out.print(" + "+k);
}
System.out.println();
}
}
}
}```

#### Output:

1. Enter a number : 15

1 + 2 + 3 + 4 + 5
4 + 5 + 6
7 + 8

2. Enter a number : 95

5 + 6 + 7 + 8 + 9 + 10 + 11 + 12 + 13 + 14
17 + 18 + 19 + 20 + 21
47 + 48

## ISC 2017 Computer Science Solution + Examiner’s Comments – From the Council

Solution of ISC 2017 Computer science Paper as provided by the Council for the Indian School Certificate Examinations.