Skip to main content

Program for pascals triangle in ruby

Pascal triangle

Ruby Program for pascals triangle. Here mentioned other language solution.

#  Ruby program 
#  for printing Pascal's triangle patterns

#  Printing Pascal's triangle patterns by number of rows
def pascalTriangle(row) 
	#  Loop controlling variables
	i = 0
	j = 0
	k = 0
	i = 0
	#  Loop from 0..n
	while (i < row) 
		j = i + 1
		#  Print initial white space
		while (j < row) 
			#  include space
			print("\t")
			j += 1
		end

		j = 0
		#  Print resultant value
		while (j <= i) 
			if (j == 0 || i == 0) 
				#  Set initial values
				k = 1
			else
 
				#  Pascal's triangle number calculation
				k = k * (i - j + 1) / j
			end

			#  Display the value of calculate number
			print("\t", k.to_s ,"\t")
			j += 1
		end

		#  Include new line
		print("\n")
		i += 1
	end

	#  Include new line
	print("\n")
end

def main() 
	#  Test
	#  When Row : 6
	pascalTriangle(6)
	#  When Row : 10
	pascalTriangle(10)
end

main()

Output

						1	
					1		1	
				1		2		1	
			1		3		3		1	
		1		4		6		4		1	
	1		5		10		10		5		1	

										1	
									1		1	
								1		2		1	
							1		3		3		1	
						1		4		6		4		1	
					1		5		10		10		5		1	
				1		6		15		20		15		6		1	
			1		7		21		35		35		21		7		1	
		1		8		28		56		70		56		28		8		1	
	1		9		36		84		126		126		84		36		9		1	





Comment

Please share your knowledge to improve code and content standard. Also submit your doubts, and test case. We improve by your feedback. We will try to resolve your query as soon as possible.

New Comment