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.
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! 🚀