Find the sum of all the integers in the row number N



Given a pyramid of consecutive integers:
1
2 3
4 5 6
7 8 9 10
11 12 13 14 15
16 17 18 19 20 21
......
Find the sum of all the integers in the row number N.
For example:
The row #3: 4 + 5 + 6 = 15
The row #5: 11 + 12 + 13 + 14 + 15 = 65
Solution:

public class ConsecutiveNumberPattern {
public static void main(String[] args) {
System.out.println(countrownums(6));
}
public static int countrownums(int rowno)
{
if(rowno==1)
return 1;
int sum=0;
int val=((rowno*(rowno-1))/2)+1;
//Here val gives the starting number of the row number passed as an argument
for(int i=1;i<=rowno;i++)
{
sum+=val++;
}
return sum;
}
}

Post a Comment