Write a Java method to display the first 50 pentagonal numbers


This Java program calculates and prints the first 50 pentagonal numbers in a formatted output, with 10 numbers per line. The formula used to compute the pentagonal number is (i * (3 * i - 1))/2, where i is the index of the pentagonal number. Here's how the program works:

  • The program initializes a variable count to 1 to keep track of the number of pentagonal numbers printed so far.
  • The program uses a for loop to iterate through the first 50 index values of the pentagonal numbers.
  • Inside the loop, the program computes the value of the pentagonal number using the formula (i * (3 * i - 1))/2 and prints it using System.out.printf with a formatted width of 6.
  • After printing each pentagonal number, the program checks if count is a multiple of 10. If so, it prints a newline character to start a new line.
  • Finally, the program increments the count variable to keep track of the number of pentagonal numbers printed so far.

Source Code

import java.util.Scanner;
public class Pentagonal_Number
{
	public static void main(String[] args)
	{
		int count = 1;
		for(int i = 1; i <= 50; i++)
		{
			System.out.printf("%-6d",(i * (3 * i - 1))/2);
			if(count % 10 == 0)
			{				
				System.out.println();
			}
			count++;
		}
	}
}

Output

1     5     12    22    35    51    70    92    117   145
176   210   247   287   330   376   425   477   532   590
651   715   782   852   925   1001  1080  1162  1247  1335
1426  1520  1617  1717  1820  1926  2035  2147  2262  2380
2501  2625  2752  2882  3015  3151  3290  3432  3577  3725

Example Programs