Problem solving is the heart of programming. It’s not just about writing code — it’s about thinking logically, breaking down complex problems into simple steps, and developing a competitive mindset to solve problems efficiently. This skill is crucial for school exams, coding competitions (like CodeChef, LeetCode, Google Code Jam), and real-world software development.

This module covers:

  1. Logic Building – The foundation of problem solving
  2. Competitive Thinking – Advanced strategies for timed contests

Perfect for your C++ course — from Class 5 students learning basic patterns to BS students preparing for placement interviews.

Logic Building in C++

Logic building is the ability to think step-by-step and translate real-world problems into C++ code. It’s like solving a puzzle — you understand the pieces, then assemble them correctly.

What is Logic Building?

  • Definition: Converting a problem description into a sequence of logical steps (algorithm) that a computer can follow.
  • Why Important?: Even simple programs require logical thinking. Without it, you write random code that doesn’t work.

The Problem Solving Process (Step-by-Step)

Step 1: Understand the Problem

  • Read the problem 3 times.
  • Identify: Input (what goes in), Output (what comes out), Constraints (limits).
  • Ask: “What does success look like?”

Example Problem: “Find the sum of first N natural numbers.”

  • Input: N = 5
  • Output: 15 (1+2+3+4+5)
  • Constraints: 1 ≤ N ≤ 100

Step 2: Write Pseudocode

Pseudocode is like English instructions — no need for exact C++ syntax yet.

text
 
ALGORITHM SumNaturalNumbers:
    INPUT: N (number of terms)
    sum = 0
    FOR i FROM 1 TO N:
        sum = sum + i
    OUTPUT: sum
    END
 
 

Step 3: Choose Data Structures

  • Simple problems: Use basic variables (int, float) or arrays.
  • Pattern problems: Use loops (for, while).
  • String problems: Use string class.

Step 4: Write C++ Code

Convert pseudocode to actual C++.

C++
 
#include <iostream>
using namespace std;

int main() {
    int N;
    cout << "Enter N: ";
    cin >> N;
    
    int sum = 0;
    for (int i = 1; i <= N; i++) {
        sum += i;  // sum = sum + i
    }
    
    cout << "Sum = " << sum << endl;
    return 0;
}
 
 

Step 5: Test Your Solution

  • Test with small inputs first (N=1, N=2).
  • Check edge cases (N=0, N=100).
  • Verify expected output.

Common Logic Building Patterns (For Class 5–12)

 
 
Pattern TypeWhen to UseExample ProblemsC++ Tools Used
Basic ArithmeticSimple calculationsSum, average, factorialint, float, loops
Pattern PrintingVisual patterns, loops practiceTriangle, pyramid, diamondNested for loops, cout
Array ProcessingLists of numbers/stringsMax/min, reverse, sortArrays, for loops
String ManipulationText processingPalindrome, vowel count, reversestring, char arrays
RecursionProblems with self-similar structureFactorial, Fibonacci, Tower of HanoiRecursive functions
 

Pattern Printing Examples (Great for Class 5–10)

1. Right Triangle (Class 5–7)

text
 
*
**
***
****
 
 
C++
 
#include <iostream>
using namespace std;

int main() {
    int rows = 4;
    
    for (int i = 1; i <= rows; i++) {
        for (int j = 1; j <= i; j++) {
            cout << "*";
        }
        cout << endl;  // New line after each row
    }
    
    return 0;
}
 
 

2. Number Triangle (Class 8–10)

text
 
1
12
123
1234
 
 
C++
 
for (int i = 1; i <= 4; i++) {
    for (int j = 1; j <= i; j++) {
        cout << j;  // Print numbers 1 to i
    }
    cout << endl;
}
 
 

Practice Problems for Logic Building

 
 
LevelProblem TypeDifficultyTime to Solve
Class 5–7Basic arithmetic, simple patternsEasy10–15 min
Class 8–10Array processing, string patternsMedium20–30 min
Class 11–12Recursion, two-pointer techniqueHard30–45 min
 

Starter Problems:

  1. Print first 10 Fibonacci numbers
  2. Check if a number is prime
  3. Find largest of three numbers
  4. Reverse a string without using reverse() function

Competitive Thinking

Competitive programming trains you to solve problems quickly and efficiently under time pressure. It’s like mental gymnastics for programmers.

What is Competitive Programming?

  • Definition: Solving algorithmic problems within time limits (usually 1–2 hours).
  • Platforms: CodeChef, LeetCode, HackerRank, Codeforces, AtCoder
  • Benefits: Improves problem-solving, coding speed, interview preparation

Competitive Thinking Strategies

1. The 3-Question Framework

For every problem, ask:

  1. What data structure? (array, vector, map, stack, queue)
  2. What algorithm? (sorting, searching, dynamic programming, greedy)
  3. What complexity? (O(n), O(n²), O(log n) — must fit time limit)

2. Input-Output Analysis

Always start here — 80% of competitive problems are solved by understanding I/O correctly.

Example Problem: “Given N numbers, find their sum”

text
 
Input:
First line: N (number of test cases)
For each test case:
First line: T (numbers in this test case)
Second line: T integers

Output:
For each test case, print the sum
 
 
C++
 
int main() {
    int N;
    cin >> N;  // Number of test cases
    
    for (int test = 0; test < N; test++) {
        int T;
        cin >> T;  // Numbers in this test case
        
        long long sum = 0;  // Use long long for large sums
        for (int i = 0; i < T; i++) {
            int num;
            cin >> num;
            sum += num;
        }
        
        cout << sum << endl;
    }
    
    return 0;
}
 
 

3. Brute Force First, Optimize Later

Strategy: Write a simple solution first (even if slow), then optimize.

Example: Find two numbers in array that sum to target

C++
 
// Brute Force - O(n²) - Good for small N
for (int i = 0; i < n; i++) {
    for (int j = i+1; j < n; j++) {
        if (arr[i] + arr[j] == target) {
            return {i, j};
        }
    }
}

// Optimized - O(n) using hash map (BS level)
unordered_map<int, int> seen;
for (int i = 0; i < n; i++) {
    int complement = target - arr[i];
    if (seen.count(complement)) {
        return {seen[complement], i};
    }
    seen[arr[i]] = i;
}
 
 

Common Competitive Programming Patterns

 
 
Problem TypeTechnique UsedTime ComplexityExample Problems
Sorting Problemssort() functionO(n log n)Closest numbers, median finding
Two PointersLeft + right pointersO(n)Subarray sum, pair sum
Sliding WindowDynamic window sizeO(n)Maximum sum subarray of size K
Binary SearchDivide and conquerO(log n)Find first/last occurrence
Dynamic ProgrammingMemoization/TabulationO(n) or O(n²)Fibonacci, knapsack, LCS
 

Fast Input/Output for Competitions

Default cin/cout can be slow for large inputs. Use these optimizations:

C++
 
// Fast I/O Setup
#include <iostream>
#include <ios>
using namespace std;

int main() {
    ios_base::sync_with_stdio(false);  // Disable sync with C stdio
    cin.tie(NULL);                     // Untie cin from cout
    
    int n;
    cin >> n;
    // ... rest of code
}
 
 

Debugging in Competitions (Time-Saver!)

 
 
SituationQuick Debug Technique
Wrong AnswerAdd cout statements to trace variables
Time Limit ExceededCheck loop complexity (O(n²) → O(n log n))
Runtime ErrorCheck array bounds, null pointers
No OutputVerify cout statements, endl usage
 

Practice Roadmap (For Your Website)

Phase 1: Logic Building (1 Month)

  • Week 1–2: Basic patterns, loops, conditionals
  • Week 3–4: Arrays, strings, simple recursion

Daily Practice: 2–3 problems, 30–45 minutes

Phase 2: Competitive Thinking (2 Months)

  • Week 5–8: Sorting, searching, two-pointers
  • Week 9–12: Dynamic programming, greedy algorithms

Weekly Practice: 10–15 problems + 1 full contest

Phase 3: Contest Preparation (Ongoing)

  • Participate in weekly contests (CodeChef Starters, LeetCode Weekly)
  • Analyze mistakes from previous contests
  • Learn from editorial solutions

Sample Competitive Problem: “Chef and Snacks”

Problem: Chef has N snacks, each with cost Ci and rating Ri. He wants to buy exactly K snacks with maximum total rating within budget B.

Constraints:

  • 1 ≤ N ≤ 1000
  • 1 ≤ K ≤ N
  • 1 ≤ Ci, Ri ≤ 1000
  • 1 ≤ B ≤ 10^6

Approach:

  1. Calculate rating per cost: Ri/Ci
  2. Sort snacks by this ratio (descending)
  3. Pick top K snacks if total cost ≤ B
C++
 
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

int main() {
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);
    
    int T;
    cin >> T;  // Test cases
    
    while (T--) {
        int N, K, B;
        cin >> N >> K >> B;
        
        vector<pair<double, int>> snacks;  // {rating/cost, index}
        for (int i = 0; i < N; i++) {
            int C, R;
            cin >> C >> R;
            snacks.push_back({(double)R/C, i});
        }
        
        // Sort by rating/cost ratio (descending)
        sort(snacks.rbegin(), snacks.rend());
        
        int total_cost = 0;
        int count = 0;
        
        // Pick top K snacks
        for (int i = 0; i < min(K, N); i++) {
            // Find actual cost of this snack
            int idx = snacks[i].second;
            // ... (need to store costs separately)
            // For simplicity, assume we track costs
            
            if (total_cost <= B) {
                count++;
            } else {
                break;
            }
        }
        
        cout << count << endl;
    }
    
    return 0;
}