Basic Problem Solving & Logic Practice Sheet (C++)
1. Fibonacci Series
Print the first N Fibonacci numbers.
Logic: Add the last two numbers to get the next.
Code:
int a = 0, b = 1;
for (int i = 0; i < n; ++i) {
cout << a << ' ';
int temp = a + b;
a = b;
b = temp;
2. Reverse a String
Logic: Use two-pointer or std::reverse.
Code:
reverse([Link](), [Link]());
3. Find Largest in Array
Loop through and compare each value.
Code:
int maxVal = arr[0];
for (int i = 1; i < n; ++i)
if (arr[i] > maxVal) maxVal = arr[i];
4. Count 1s in Binary
Use bitwise AND with 1 and shift right.
Code:
while (n) { count += n & 1; n >>= 1; }
5. Palindrome Checker
Check characters from both ends moving inward.
Code:
while (i < j) if (s[i++] != s[j--]) return false;
6. Factorial
Multiply 1 to n.
Code:
int fact = 1;
for (int i = 2; i <= n; ++i) fact *= i;
7. Check Prime Number
Try dividing from 2 to sqrt(n).
Code:
for (int i = 2; i * i <= n; ++i)
if (n % i == 0) return false;
8. Swap Without Temp
Use arithmetic:
a = a + b; b = a - b; a = a - b;
9. Find Duplicate in Array
Use set to track seen numbers.
if ([Link](arr[i])) return arr[i];
10. Sum of Digits
Add digits using % 10 and / 10.
Code:
while (n) { sum += n % 10; n /= 10; }
11. Even and Odd Printer
Loop through 1 to N using i += 2.
12. Array Reversal
Use two-pointer method:
while (start < end) swap(arr[start++], arr[end--]);
13. Count Vowels in String
Check each character if it's a, e, i, o, u.
14. Print Prime Numbers 1 to N
Loop through each number and use isPrime(n).
15. GCD of Two Numbers
Use Euclidean Algorithm:
while (b != 0) { int temp = b; b = a % b; a = temp; }