Print Nth Row of Pascal Triangle
Print a zero-based Pascal-triangle row with recursive combinations. Students calculate each nCr and trace edge values that stop the recursive branching.
1# Helper function2def ncr(n, r):3 if r == 0 or r == n:4 return 15 return ncr(n - 1, r - 1) + ncr(n - 1, r)67# Take n8n = int(input("Enter row number: "))910# Print row11print(f"Row {n}:")12for r in range(n + 1):13 print(ncr(n, r), end=" ")14print()
Output
Enter row number: 5 Row 5: 1 5 10 10 5 1
In this one
- Index Pascal rows from zero
- Reuse recursive combinations
- Recognize repeated subproblems
How it works
- 1
Read row number n.
- 2
For every r from zero through n, call ncr.
- 3
Print each returned row entry in order.
Edge cases
What does row zero contain?
What does row zero contain?
One entry: 1.
Are row numbers one-based?
Are row numbers one-based?
No. The top row is zero.
What's going on
The requested row n contains n + 1 entries. The outer loop calls ncr(n, r) for r from zero through n.
The helper returns one at either edge and adds the two parent combinations inside. Row three is 1 3 3 1. Pending additions use the call stack, and repeated subproblems make large rows expensive; this is not a memoized or iterative implementation.
What does row zero contain? One entry: 1.
Are row numbers one-based? No. The top row is zero.
Quiz
Tap an option. The answer stays hidden until you pick.
Question 1
What stops each recursive branch?
Pick an answer to check it.
Question 2
What does row zero contain?
Pick an answer to check it.
Questions people ask
What does row zero contain?
One entry: 1.
Are row numbers one-based?
No. The top row is zero.
What stops each recursive branch?
r == 0 or r == n.
๐Related Content
- ๐
Phase 6 - Learn Concepts
Review Phase 6 concepts and explanations
- ๐
Phase 6 - Quiz
Test your Phase 6 understanding with quiz questions
- ๐ป
Phase 6 - All Practice Problems
Explore all practice problems for Phase 6
- ๐
Master Your Logic Building - Complete Course
Browse all phases and tutorials
- ๐ง
Logic Building Overview
Learn about the complete logic building curriculum