Beginner DSA: Logic Building with Loops
Index - Logic Building with Loops
- PART I - Logic Building with Loops - The Minimal Beginner's Roadmap
- PART II - Logic Building with Loops β The Complete Beginner's Roadmap
PART I - Logic Building with Loops - The Minimal Beginner's Roadmap
These cover every core concept from the 87-problem roadmap.
Concept Coverage
| Question | Concepts Covered |
|---|---|
| 1 | Basic loop, counter |
| 2 | Accumulator (product) |
| 3 | Modulus trick (%10, /10) |
| 4 | Reversal + comparison |
| 5 | Loop optimization, divisibility |
| 6 | Algorithm implementation |
| 7 | Multi-variable state |
| 8 | Do-while style, tracking max |
| 9 | Nested loops |
| 10 | break and continue |
| 11 | Place value, number systems |
| 12 | Rows and columns |
| 13 | Spaces + stars, centering |
QUESTIONS
1. Basic Iteration
Multiplication Table β Print the table of a given number n.
2. Accumulation
Factorial β Calculate n!
3. Digit Manipulation (Single Comprehensive Problem)
Digit Toolkit β Given an integer, find:
- (a) Count of digits
- (b) Sum of digits
- (c) Reverse of the number
- (d) Largest digit
4. Number Property Check
Palindrome Check β Is the number equal to its reverse?
5. Optimized Loop Logic
Prime Check β Check if a number is prime (optimize to βn).
6. Mathematical Algorithm
GCD β Find the Greatest Common Divisor using the Euclidean algorithm.
7. Series & State Tracking
Fibonacci β Print the first n terms of the Fibonacci series.
8. Sentinel / Validation Loop
Stream Processing β Read integers until user enters 0, then print the total sum and maximum value.
9. Nested Loop Application
Primes in Range β Print all prime numbers between 1 and n.
10. Break & Continue (Combined)
Skip & Stop β Print 1 to 50, skip multiples of 3, stop completely if sum exceeds 100.
11. Number Conversion
Decimal to Binary β Convert a decimal number to its binary representation.
12. Basic Pattern
Right Triangle β
*
**
***
****
13. Complex Pattern
Centered Pyramid β
*
***
*****
*******
If you can solve these 13 without help, you're ready for arrays.
Logic Building with Loops β LeetCode Mapping
2 LeetCode Problems per Concept (26 total)
1. Basic Loop / Counter
Concept: simple for / while, counting iterations
-
412. Fizz Buzz Pure loop + counter + conditions
-
1929. Concatenation of Array Iterating and constructing output using a counter
2. Accumulator (Product / Sum)
Concept: running total / product
-
509. Fibonacci Number Accumulator-style update
-
1480. Running Sum of 1d Array Classic accumulator pattern
3. Digit Manipulation (%10, /10)
Concept: extracting digits
-
1295. Find Numbers with Even Number of Digits Digit counting using division
-
1281. Subtract the Product and Sum of Digits of an Integer Digit sum + digit product
4. Reversal + Comparison
Concept: reverse number and compare
-
9. Palindrome Number Exact match for your problem
-
7. Reverse Integer Reverse digits safely
5. Loop Optimization / Divisibility
Concept: stop at βn, reduce iterations
-
204. Count Primes Prime checking + optimization
-
507. Perfect Number Divisors, optimized loops
6. Algorithm Implementation
Concept: step-by-step algorithm logic
-
1979. Find Greatest Common Divisor of Array Uses Euclidean algorithm
-
914. X of a Kind in a Deck of Cards GCD-based reasoning
7. Multi-variable State
Concept: tracking multiple changing values
-
70. Climbing Stairs Two-variable state update
-
1137. N-th Tribonacci Number Multi-variable Fibonacci variant
8. Sentinel / Validation Loop
Concept: loop until condition is met, track max/sum
-
1748. Sum of Unique Elements Stream-style accumulation
-
2154. Keep Multiplying Found Values by Two Loop until condition fails
9. Nested Loops
Concept: loop inside loop
-
728. Self Dividing Numbers Nested digit checks
-
2215. Find the Difference of Two Arrays Nested scanning logic
10. break & continue
Concept: skipping & early termination
-
1822. Sign of the Product of an Array Early break on zero
-
2696. Minimum String Length After Removing Substrings Loop with break conditions
11. Place Value / Number Systems
Concept: binary, decimal, positional value
-
338. Counting Bits Binary representation
-
190. Reverse Bits Bit position manipulation
12. Rows & Columns
Concept: 2D traversal
-
1572. Matrix Diagonal Sum Row & column indexing
-
566. Reshape the Matrix Row/column mapping
13. Spaces + Stars / Centering (Pattern Thinking)
Concept: index math, symmetry (LeetCode doesnβt do stars, so closest logic problems)
-
1672. Richest Customer Wealth Row-based aggregation
-
118. Pascalβs Triangle Centered growth & symmetry logic
β Final Summary
- 26 LeetCode problems
- Each maps directly to your loop logic roadmap
- Progresses from pure loops β optimized logic β 2D thinking
PART II - Logic Building with Loops β The Complete Beginner's Roadmap
Problem Count Summary
| Phase | Topic | Problems |
|---|---|---|
| 1 | While Loop Fundamentals | 19 |
| 2 | Do-While Loop | 7 |
| 3 | For Loop | 10 |
| 4 | Nested Loops | 7 |
| 5 | Break & Continue | 6 |
| 6 | Mathematical Series & Advanced | 15 |
| 7 | Pattern Printing | 13 |
| 8 | Mixed Challenges | 10 |
| Total | 87 |
Before Data Structures & Algorithms
Who Is This For?
- Complete beginners who just learned variables,
if-else, and basic syntax - Anyone who can write code but struggles to "think through" problems
- Students preparing for coding interviews who need stronger foundations
Goal
Master iteration, dry-run thinking, digit math, and nested-loop reasoning through 80 curated problems with clear progression from basic to complex.
Prerequisites
Before starting, ensure you understand:
| Concept | Examples |
|---|---|
| Variables & Data Types | int, float, char, long |
| Operators | +, -, *, /, %, ==, !=, <, >, &&, || |
| Conditional Statements | if, else if, else |
| Basic Input/Output | Reading and printing values |
How to Use This Guide
The 3-Step Method (For Every Problem)
| Step | Action |
|---|---|
| 1. Understand | Write sample input/output. Ask: What changes each iteration? |
| 2. Dry Run | Trace variables on paper for a small value (e.g., n=4) |
| 3. Code & Test | Write code. Test edge cases: 0, 1, negative, large values |
Difficulty Legend
| Symbol | Meaning | Time |
|---|---|---|
| β | Starter β Direct application | 5β10 min |
| ββ | Thinker β Combine 2β3 ideas | 10β20 min |
| βββ | Challenger β Multi-step reasoning | 20β40 min |
Golden Rules
- Don't rush β Complete each phase before moving on
- Don't copy-paste β Type every solution yourself
- If stuck >20 minutes β Take a hint, don't guess blindly
Essential Patterns to Memorize
The Modulus Trick (Your Best Friend)
| Expression | Result |
|---|---|
n % 10 | Last digit of n |
n / 10 | Removes last digit of n |
n % 2 == 0 | Checks if n is even |
n % k == 0 | Checks if n is divisible by k |
Accumulator Pattern
- For sum: Start with
sum = 0, add each iteration - For product: Start with
product = 1, multiply each iteration
Prime Check Optimization
Check divisibility only up to βn (i.e., i * i <= n)
Dry Run Example
Problem: Sum of digits of 123
Initial: n = 123, sum = 0
Iteration 1:
digit = 123 % 10 = 3
sum = 0 + 3 = 3
n = 123 / 10 = 12
Iteration 2:
digit = 12 % 10 = 2
sum = 3 + 2 = 5
n = 12 / 10 = 1
Iteration 3:
digit = 1 % 10 = 1
sum = 5 + 1 = 6
n = 1 / 10 = 0
Loop ends β Answer: 6
PHASE 1: While Loop Fundamentals
Purpose: Master loop control, counters, accumulators, digit extraction, and basic number properties. The
whileloop is ideal when iterations depend on a condition.
Section A: Basic Counting
| # | Problem | Difficulty |
|---|---|---|
| 1 | Print numbers from 1 to 10 | β |
| 2 | Print numbers from 10 to 1 | β |
| 3 | Print all even numbers between 1 and 100 | β |
| 4 | Print the multiplication table of a given number n | β |
Section B: Accumulation (Sums & Products)
| # | Problem | Difficulty |
|---|---|---|
| 5 | Calculate sum of first n natural numbers | β |
| 6 | Calculate factorial of n | β |
| 7 | Calculate a^b without using built-in power function | ββ |
Section C: Digit Extraction
| # | Problem | Difficulty |
|---|---|---|
| 8 | Count the number of digits in an integer | β |
| 9 | Calculate sum of digits of a number | β |
| 10 | Calculate product of digits of a number | β |
| 11 | Reverse a given integer (e.g., 123 β 321) | ββ |
| 12 | Find the largest digit in a number | ββ |
| 13 | Find the smallest digit in a number | ββ |
Section D: Number Properties
| # | Problem | Difficulty |
|---|---|---|
| 14 | Check if a number is a Palindrome | ββ |
| 15 | Check if a number is Prime | ββ |
| 16 | Check if a number is an Armstrong number | ββ |
| 17 | Check if a number is a Perfect number | ββ |
| 18 | Find GCD (HCF) of two numbers using Euclidean algorithm | ββ |
| 19 | Find LCM of two numbers | ββ |
β Phase 1 Checkpoint: Can you solve problems 8β15 without looking up logic?
PHASE 2: Do-While Loop
Purpose: Understand guaranteed execution. Use
do-whilewhen code must run at least once (menus, input validation).
| # | Problem | Difficulty |
|---|---|---|
| 20 | Keep asking user for input until they enter a positive number | β |
| 21 | Read numbers until user enters 0 β print the sum | β |
| 22 | Read numbers until user enters 0 β print the maximum | ββ |
| 23 | Calculate running average until user enters a negative number | ββ |
| 24 | Menu-driven calculator: Add, Subtract, Multiply, Divide, Exit | ββ |
| 25 | Guess-the-number game with "Play again? (y/n)" option | ββ |
| 26 | Login simulation: max 3 attempts before lockout | ββ |
PHASE 3: For Loop
Purpose: Clean, structured iteration when range is known beforehand.
Section A: Range-Based Logic
| # | Problem | Difficulty |
|---|---|---|
| 27 | Print all numbers from 1 to n divisible by both 3 and 5 | β |
| 28 | Find sum of evens and sum of odds between 1 and n (separately) | β |
| 29 | Print all factors of a number n | β |
| 30 | Calculate sum of all factors of n | ββ |
Section B: Prime Variations
| # | Problem | Difficulty |
|---|---|---|
| 31 | Print all prime numbers between 1 and n | ββ |
| 32 | Print the first n prime numbers (not primes up to n) | βββ |
Section C: Series Generation
| # | Problem | Difficulty |
|---|---|---|
| 33 | Print first n terms of Fibonacci series | ββ |
| 34 | Calculate sum of squares: 1Β² + 2Β² + ... + nΒ² | ββ |
| 35 | Calculate harmonic sum: 1 + 1/2 + 1/3 + ... + 1/n | ββ |
| 36 | Print factorials from 1! to n! (reuse previous result) | ββ |
PHASE 4: Nested Loops
Purpose: Multi-dimensional thinking β foundation for matrices, patterns, and sorting algorithms.
Mental Model:
- Outer loop β controls ROWS
- Inner loop β controls COLUMNS
| # | Problem | Difficulty |
|---|---|---|
| 37 | Print multiplication tables from 1 to 10 in grid format | ββ |
| 38 | Print all coordinate pairs (x, y) where 0 β€ x β€ n and 0 β€ y β€ m | ββ |
| 39 | Print all prime numbers between 50 and 100 (outer: range, inner: prime test) | ββ |
| 40 | Find all pairs (a, b) where 1 β€ a, b β€ n such that a + b = target | ββ |
| 41 | For each number from 1 to n, count its factors | ββ |
| 42 | Find all Pythagorean triplets (a, b, c) where 1 β€ a < b < c β€ n and aΒ² + bΒ² = cΒ² | βββ |
| 43 | Print Pascal's Triangle for first N rows | βββ |
PHASE 5: Break & Continue
Purpose: Control loop flow β exit early or skip iterations.
Key Difference:
breakβ EXIT the entire loop immediatelycontinueβ SKIP current iteration, go to next
| # | Problem | Difficulty |
|---|---|---|
| 44 | Loop 1 to 100. If you find 37, print "Found" and stop | β |
| 45 | Print 1 to 50 but skip all multiples of 3 | β |
| 46 | Read up to 10 numbers. Stop immediately if any is negative | ββ |
| 47 | Add natural numbers 1+2+3+... until sum β₯ 100. Print last number added | ββ |
| 48 | Print a string excluding all vowels | ββ |
| 49 | Find the first prime number greater than n | ββ |
PHASE 6: Mathematical Series & Advanced Number Properties
Purpose: Combine loops with formulas. Build pattern recognition.
Section A: Classic Series
| # | Problem | Difficulty |
|---|---|---|
| 50 | Sum of cubes: 1Β³ + 2Β³ + ... + nΒ³ | ββ |
| 51 | Arithmetic Progression: Generate first n terms with first term a and common difference d | ββ |
| 52 | Geometric Progression: Generate first n terms with first term a and common ratio r | ββ |
| 53 | Power series: 1 + x + xΒ² + ... + xβΏ | ββ |
| 54 | Factorial series: 1! + 2! + ... + n! | ββ |
| 55 | Alternating series: 1 - 2 + 3 - 4 + 5 - ... Β± n | ββ |
Section B: Special Number Checks
| # | Problem | Difficulty |
|---|---|---|
| 56 | Check if a number is a Strong Number (sum of factorial of digits = number) | ββ |
| 57 | Check if a number is a Harshad/Niven Number (divisible by sum of its digits) | ββ |
| 58 | Check if a number is an Automorphic Number (square ends with the number) | ββ |
| 59 | Check if a number is a Happy Number (reaches 1 or enters cycle) | βββ |
| 60 | Check if two numbers are Co-Prime (GCD = 1) | ββ |
Section C: Number Conversions
| # | Problem | Difficulty |
|---|---|---|
| 61 | Convert Binary to Decimal (input like 101 β output 5) | ββ |
| 62 | Convert Decimal to Binary | ββ |
| 63 | Count set bits (1s) in binary representation of a number | ββ |
| 64 | Prime factorization of a number (e.g., 12 β 2, 2, 3) | ββ |
PHASE 7: Pattern Printing
Purpose: Mastery of nested loops through visualization. If you can print these, you truly understand rows (
i) and columns (j).
Section A: Star Patterns
| # | Pattern | Difficulty |
|---|---|---|
| 65 | Solid square: n rows of n stars | β |
| 66 | Right triangle (increasing): Row 1 has 1 star, Row 2 has 2... | β |
| 67 | Right triangle (decreasing): Row 1 has n stars... down to 1 | ββ |
| 68 | Right-aligned triangle (spaces + stars) | ββ |
| 69 | Centered pyramid | ββ |
| 70 | Diamond (pyramid + inverted pyramid) | βββ |
| 71 | Hollow square (stars only on border) | ββ |
| 72 | X pattern (both diagonals) | βββ |
Section B: Number Patterns
| # | Pattern | Difficulty |
|---|---|---|
| 73 | Number block: Row 1 prints 1111, Row 2 prints 2222... | ββ |
| 74 | Increasing triangle: 1, 12, 123, 1234... | ββ |
| 75 | Floyd's Triangle: 1, 2 3, 4 5 6... (continuous counting) | ββ |
| 76 | Binary triangle: alternating 0s and 1s | ββ |
| 77 | Palindromic number pyramid: 1, 121, 12321... | βββ |
PHASE 8: Final Mixed Challenges
Purpose: Combine 2β3 concepts per problem. Interview-style thinking.
| # | Problem | Difficulty |
|---|---|---|
| 78 | Print all palindrome numbers between 1 and N | ββ |
| 79 | Print all Armstrong numbers between 1 and N | ββ |
| 80 | Print all Perfect numbers between 1 and N | ββ |
| 81 | Find the number with maximum digit sum between 1 and N | βββ |
| 82 | Count numbers from 1 to 100 whose digit sum is even | ββ |
| 83 | Count numbers divisible by 7 but not by 5 between 1 and 500 | ββ |
| 84 | Compute series: 1!/1 + 2!/2 + 3!/3 + ... + n!/n | βββ |
| 85 | Find largest power of 2 less than n | ββ |
| 86 | Check if a number is both palindrome AND prime | βββ |
| 87 | Count occurrences of a specific digit d in a number n | ββ |
Common Mistakes & Fixes
| Mistake | Example | Fix |
|---|---|---|
| Infinite loop | while(i > 0) but forgot i-- | Always update loop variable |
| Off-by-one error | Printed 9 numbers instead of 10 | Check < vs <= carefully |
| Integer overflow | factorial(20) exceeds int range | Use long for big numbers |
| Wrong accumulator init | product = 0 then multiply | Start with 1 for products |
| Lost original value | Reversed n but needed original later | Store in temp first |
Final Checklist
Before moving to Arrays/DSA, confirm you can:
- Reverse a number without converting to string
- Write prime check using
i * i <= noptimization - Solve any digit problem using
% 10and/ 10 - Dry-run a nested loop pattern on paper
- Explain when to use
whilevsdo-whilevsfor - Solve any 5-row pattern in under 10 minutes
What's Next?
After completing this guide:
- Arrays (1D) β Traversal, min/max, frequency counting
- Strings β Character manipulation, palindrome, reversal
- Searching β Linear search β Binary search
- Sorting β Bubble, Selection (nested loops apply directly)
- 2D Arrays β Pattern printing skills transfer directly
- Recursion β Replaces loops with function calls
Final Advice: Speed comes from understanding, not memorization. If you truly understand why a loop works, you'll never forget how to write it.
Happy Coding! π