Skip to content
Tutorials Center
My learning

Topics

Lesson 179 of 182 ยท Practice and Review

Practice Problems: Fundamentals

Fifteen graded C# problems on types, control flow, strings, methods and collections. Every problem has a hint and a full solution with tests you can run.

Reading about C# is not the same as writing it. This page gives you fifteen problems on the fundamentals, ordered from warm-up to tricky. Each one has a statement, a hint for when you are stuck, and a complete runnable solution with a few test lines, so you can see the program work and change it.

The best way to use the page: read the statement, open an empty editor (or the editor in the solution and delete the code), and try to solve it before you read the hint. Only then compare with the solution. If your answer differs but passes the same tests, that is fine; there are usually several good solutions. After you finish, think about the edge cases: empty input, one element, negative numbers, null.

A routine that works for every problem: restate the task in your own words, write down two or three example inputs with the expected outputs, write the simplest code that could work, then run it against your examples and one nasty edge case.

Part 1: types and control flow

Problem 1: FizzBuzz with a twist (easy)

Print the numbers from 1 to 15. For multiples of 3 print Fizz, for multiples of 5 print Buzz, for multiples of both print FizzBuzz. Put everything on one line separated by spaces.

Hint. Test the "both" case first, or build the word by appending Fizz and Buzz separately and falling back to the number when the word is empty. A switch expression on a tuple (i % 3, i % 5) also works well.

C# Solution 1: FizzBuzz

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

The tuple switch checks both remainders at once, so there is no way to forget the combined case. This expression-style code is typical modern C#; see switch.

Problem 2: Temperature table (easy)

Print a table that converts Celsius values from -10 to 30 in steps of 10 to Fahrenheit. Each line must look like -10.0 C = 14.0 F, with the numbers right-aligned and one decimal.

Hint. The formula is f = c * 9 / 5 + 32. Use a for loop with step 10 and alignment plus format in the interpolation hole: {value,7:F1}.

C# Solution 2: temperature table

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Using 9.0 makes the division floating point. With 9 / 5 and int operands the result would be 1, a classic bug: integer division throws away the fraction. See operators and output formatting.

Problem 3: Sum the valid numbers (easy)

Read lines from standard input until there are no more. Each line should contain an integer. Add up the valid ones, count the invalid ones and print both.

Hint. Console.ReadLine() returns null at the end of the input. Use int.TryParse so a bad line does not throw an exception.

C# Solution 3: sum valid numbers

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

The blank line counts as invalid, because the empty string is not a number. If you wanted to skip blanks silently, test string.IsNullOrWhiteSpace(line) first. More in Reading input.

Problem 4: Primes up to n (medium)

Write a method List<int> PrimesUpTo(int n) that returns every prime number up to and including n. Make it fast enough for n = 100000.

Hint. Trial division works, but the Sieve of Eratosthenes is much faster: keep a bool[], and for each prime cross out its multiples starting at p * p.

C# Solution 4: sieve of Eratosthenes

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

The long in the loop avoids an int overflow of p * p for large n. There are 9592 primes below 100000. The sieve costs about O(n log log n), while trial division would be roughly O(n sqrt n).

Problem 5: Collatz length (medium)

For a positive integer, repeat: if it is even, halve it; if it is odd, multiply by 3 and add 1. Stop at 1. Return the number of steps. Then find which starting number below 30 has the longest chain.

Hint. Use long for the running value, because the numbers can grow beyond int.MaxValue for some starts. Track the best start with two variables.

C# Solution 5: Collatz

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Part 2: strings

Problem 6: Reverse the words (easy)

Given a sentence, return it with the order of the words reversed. Words are separated by one or more spaces; the result should use single spaces and have no leading or trailing space.

Hint. Split(' ', StringSplitOptions.RemoveEmptyEntries) handles repeated spaces. Then reverse and join.

C# Solution 6: reverse the words

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Problem 7: Palindrome checker (medium)

A phrase is a palindrome if it reads the same forwards and backwards when you ignore case and anything that is not a letter or digit. Write bool IsPalindrome(string text).

Hint. You do not need to build a reversed copy: move two indexes towards each other, skipping characters that fail char.IsLetterOrDigit.

C# Solution 7: palindrome

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

The two-pointer version uses no extra memory. Compare it with the shorter but allocating version in Working with strings.

Problem 8: Caesar cipher (medium)

Write string Shift(string text, int amount) that shifts every letter forward by amount positions in the alphabet, wrapping around, keeping case, and leaving other characters alone. A negative amount decodes.

Hint. For a lowercase letter, compute (c - 'a' + amount) % 26 and add 'a' back. Careful: in C# % can be negative for negative operands, so normalize with ((x % 26) + 26) % 26.

C# Solution 8: Caesar cipher

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Problem 9: Character frequencies (medium)

Count how often each letter occurs in a text, ignoring case and non-letters. Print the letters in alphabetical order as letter:count.

Hint. A SortedDictionary<char, int> keeps keys ordered, so no extra sort is needed. GetValueOrDefault makes counting a one-liner.

C# Solution 9: letter frequencies

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Part 3: methods

Problem 10: Min, max and average in one call (easy)

Write a method that takes an int[] and returns the minimum, maximum and average as a named tuple. For an empty array, throw an ArgumentException.

Hint. The return type (int Min, int Max, double Average) gives the caller named fields. Loop once; do not call Min(), Max() and Average() separately unless you prefer clarity over a single pass.

C# Solution 10: tuple return

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

The long accumulator avoids overflow when summing many large ints. See Tuples and Exceptions.

Problem 11: Greatest common divisor, recursively (medium)

Write int Gcd(int a, int b) using Euclid's algorithm with recursion, then use it to reduce a fraction to lowest terms.

Hint. Gcd(a, 0) is a, and otherwise Gcd(a, b) equals Gcd(b, a % b).

C# Solution 11: GCD and fractions

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Each call shrinks the second argument, so the recursion always ends. See Recursion.

Problem 12: Try-pattern parser (medium)

Write bool TryParsePoint(string text, out (int X, int Y) point) for text like "3,4" or " 10 , -2 ". Return false instead of throwing for bad input.

Hint. Split on the comma, require exactly two parts, Trim each, and combine two int.TryParse calls with &&. Assign default to the out parameter on every failure path.

C# Solution 12: TryParsePoint

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Part 4: collections

Problem 13: Remove duplicates, keep the order (easy)

Return a new list that contains each value of the input once, in the order of first appearance.

Hint. HashSet<T>.Add returns false when the item is already present, so it works as a combined test and insert.

C# Solution 13: stable distinct

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

LINQ's Distinct() does the same and also keeps first-seen order, but writing it once shows you what it does. See Sets.

Problem 14: Second largest (medium)

Return the second largest distinct value of an array, or null if there are fewer than two distinct values. Do it in one pass without sorting.

Hint. Keep two variables, largest and second, both nullable. For each value: if it is bigger than largest, shift largest into second; else if it is different from largest and bigger than second, replace second.

C# Solution 14: second largest

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Using int? instead of int.MinValue as the "nothing yet" marker avoids a bug when the array legitimately contains int.MinValue. See Nullable value types.

Problem 15: Top words (hard)

Given a text, find the three most frequent words (case-insensitive, letters and apostrophes only). Break ties alphabetically. Print word: count.

Hint. Split with a regular expression such as [^a-z']+ after lower-casing, count with a dictionary, then sort by count descending and word ascending. Never rely on dictionary order for output.

C# Solution 15: top three words

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

the appears four times, a three times and and twice. If two words had the same count, the alphabetical tie-break would make the output deterministic. See Regular expressions and LINQ operators.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does 7 / 2 evaluate to when both operands are int?

    Integer division discards the fractional part, so 7 / 2 is 3. Use 7 / 2.0 or cast one operand to double to get 3.5.
  2. 2. Which call tells you at the end of standard input that there are no more lines?

    ReadLine returns null once the input is exhausted. An empty string means the user entered an empty line.
  3. 3. Why is int? a better 'nothing found yet' marker than int.MinValue when searching for a maximum?

    A sentinel value can collide with real data. A nullable has a separate 'no value' state that no real number can imitate.
  4. 4. What does HashSet<T>.Add return when the item is already in the set?

    Add returns true only if the item was new. That makes it a handy 'have I seen this?' test and insert in one call.
  5. 5. In C#, what is -7 % 26?

    The remainder takes the sign of the left operand, so -7 % 26 is -7. To get a result in 0..25 use ((x % 26) + 26) % 26.

Summary

  • Prefer TryParse over Parse for user input, and remember that ReadLine() returns null at the end of input.
  • Integer division truncates; make one operand double or decimal when you need a fraction.
  • Tuple switches, sets, sorted dictionaries and named tuple returns turn many small problems into a few readable lines.
  • The % operator keeps the sign of the left operand; normalize it for modular arithmetic.
  • Use nullable value types as "no value yet" markers instead of magic numbers.
  • Never depend on Dictionary ordering for output; sort explicitly.

Next: Practice Problems: OOP, LINQ and Async