Loops are the backbone of repetitive logic in any C# program, and getting comfortable with for, while, and nested loops is essential before moving on to more advanced topics.
This collection of 31 C# loop exercises is designed to sharpen your skills across all difficulty levels, from simple counting loops to multi-level nested patterns.
Each exercise includes a Practice Problem, Purpose, Hint, and a full Solution with Explanation, so you understand exactly how and why each loop works.
Also, See: C# Exercises with 22 topic-wise sets and 620+ practice questions.
What You’ll Practice
- Fundamentals:
forandwhileloop structure, counters, and accumulators. - Patterns: Triangle, pyramid, and number patterns using nested loops.
- Number Theory: Prime checks, factorials, Fibonacci, GCD/LCM, and Armstrong numbers.
- Data Processing: Looping over arrays, strings, and 2D matrices.
+ Table Of Contents (31 Exercises)
Table of contents
- Exercise 1: Print 1 to 10
- Exercise 2: Countdown
- Exercise 3: Even Numbers
- Exercise 4: Odd Numbers
- Exercise 5: Sum of First N Numbers
- Exercise 6: Multiplication Table
- Exercise 7: Factorial Calculator
- Exercise 8: Sum of Digits
- Exercise 9: Count Digits
- Exercise 10: Average of Numbers
- Exercise 11: Palindrome Checker
- Exercise 12: Array Traversal
- Exercise 13: Number Guessing Game
- Exercise 14: Armstrong Number
- Exercise 15: ASCII Table
- Exercise 16: Right-Angled Triangle Pattern
- Exercise 17: Pyramid Pattern
- Exercise 18: Number Pattern
- Exercise 19: Floyd’s Triangle
- Exercise 20: Perfect Numbers
- Exercise 21: Fibonacci Series
- Exercise 22: Reverse a String
- Exercise 23: Prime Number Check
- Exercise 24: Find Primes in a Range
- Exercise 25: Power Calculator
- Exercise 26: Count Vowels and Consonants
- Exercise 27: LCM (Lowest Common Multiple)
- Exercise 28: GCD (Greatest Common Divisor)
- Exercise 29: Binary to Decimal
- Exercise 30: Decimal to Binary
- Exercise 31: Matrix Diagonal Sum
Exercise 1: Print 1 to 10
Practice Problem: Write a C# program to print numbers from 1 to 10 using a for loop.
Purpose: This exercise helps you practice the basic structure of a for loop, including initialization, condition checking, and incrementing a counter, which is the foundation for most iteration tasks in C#.
Given Input: None (the loop runs from 1 to 10).
Expected Output:
Starting sequence from 1 to 10: Current Value: 1 Current Value: 2 Current Value: 3 Current Value: 4 Current Value: 5 Current Value: 6 Current Value: 7 Current Value: 8 Current Value: 9 Current Value: 10 Number printing completed successfully.
▼ Hint
Use a for loop that starts at 1, continues while the counter is less than or equal to 10, and increases the counter by 1 each time.
▼ Solution & Explanation
Explanation:
namespace NumberUtilities: Groups the program’s classes under a named container, following standard C# project organization.class NumberPrinter: Defines the class that holds the program’s entry point and logic.static void Main(string[] args): The entry point where the C# runtime starts executing the program.for (int i = 1; i <= 10; i++): Initializesito 1, repeats the loop whileiis less than or equal to 10, and incrementsiby 1 after each iteration.Console.WriteLine($"Current Value: {i}"): Uses string interpolation to print the current value ofiin a readable, labeled format.
Exercise 2: Countdown
Practice Problem: Write a C# program to print numbers from 10 down to 1 using a while loop.
Purpose: This exercise helps you practice writing a while loop that counts downward, along with manually decrementing a variable inside the loop body.
Given Input: None (the loop runs from 10 down to 1).
Expected Output:
Starting countdown from 10 to 1: Current Value: 10 Current Value: 9 Current Value: 8 Current Value: 7 Current Value: 6 Current Value: 5 Current Value: 4 Current Value: 3 Current Value: 2 Current Value: 1 Countdown completed successfully.
▼ Hint
- Initialize a variable
i = 10before the loop. - Use a
whileloop that continues as long asi >= 1. - Decrease
iby 1 inside the loop after printing it.
▼ Solution & Explanation
Explanation:
class CountdownTimer: Defines the class that holds the program’s entry point and countdown logic.int i = 10: Initializes a counter variable at 10, the starting point of the countdown.while (i >= 1): Keeps the loop running as long asiis greater than or equal to 1.Console.WriteLine($"Current Value: {i}"): Uses string interpolation to print the current value ofiin a readable, labeled format.i--: Decreasesiby 1 on each iteration, moving the countdown toward 1.
Exercise 3: Even Numbers
Practice Problem: Write a C# program to display all even numbers between 1 and 20.
Purpose: This exercise helps you practice combining a loop with a conditional check using the modulus operator to filter values based on a rule.
Given Input: Range from 1 to 20.
Expected Output:
Finding even numbers between 1 and 20: Even Number: 2 Even Number: 4 Even Number: 6 Even Number: 8 Even Number: 10 Even Number: 12 Even Number: 14 Even Number: 16 Even Number: 18 Even Number: 20 Even number search completed successfully.
▼ Hint
- Loop through numbers from 1 to 20 using a
forloop. - Use the modulus operator
%to check if a number is divisible by 2. - If the remainder is 0, print the number.
▼ Solution & Explanation
Explanation:
class EvenNumberFinder: Defines the class that holds the program’s entry point and filtering logic.for (int i = 1; i <= 20; i++): Iterates through every number from 1 to 20.i % 2 == 0: Checks whetheriis divisible by 2 with no remainder, which means it is even.Console.WriteLine($"Even Number: {i}"): Prints the number in a labeled format only when the condition above is true.
Exercise 4: Odd Numbers
Practice Problem: Write a C# program to display all odd numbers between 1 and 20.
Purpose: This exercise reinforces the use of the modulus operator inside a loop to filter numbers, this time checking for a non-zero remainder instead of a zero one.
Given Input: Range from 1 to 20.
Expected Output:
Finding odd numbers between 1 and 20: Odd Number: 1 Odd Number: 3 Odd Number: 5 Odd Number: 7 Odd Number: 9 Odd Number: 11 Odd Number: 13 Odd Number: 15 Odd Number: 17 Odd Number: 19 Odd number search completed successfully.
▼ Hint
- Loop through numbers from 1 to 20 using a
forloop. - Use
i % 2 != 0to check if a number is odd. - Print the number whenever the condition is true.
▼ Solution & Explanation
Explanation:
class OddNumberFinder: Defines the class that holds the program’s entry point and filtering logic.for (int i = 1; i <= 20; i++): Iterates through every number from 1 to 20.i % 2 != 0: Checks whetherileaves a remainder when divided by 2, which means it is odd.Console.WriteLine($"Odd Number: {i}"): Prints the number in a labeled format only when the condition above is true.
Exercise 5: Sum of First N Numbers
Practice Problem: Write a C# program to calculate the sum of all numbers from 1 to N.
Purpose: This exercise helps you practice using a loop to accumulate a running total, a pattern commonly used in calculations such as totals, counters, and statistics.
Given Input: n = 10
Expected Output:
Calculating sum of first 10 numbers: Sum = 55 Calculation completed successfully.
▼ Hint
- Initialize a variable
sum = 0before the loop. - Use a
forloop that runs from 1 ton. - Add each value of the loop counter to
sumon every iteration.
▼ Solution & Explanation
Explanation:
class SumCalculator: Defines the class that holds the program’s entry point and accumulation logic.int sum = 0: Initializes a variable to zero to accumulate values before the loop starts.for (int i = 1; i <= n; i++): Iterates through every whole number from 1 ton.sum += i: Adds the current value ofitosumon every iteration.Console.WriteLine($"Sum = {sum}"): Prints the final accumulated total after the loop finishes.
Exercise 6: Multiplication Table
Practice Problem: Write a C# program to print the multiplication table of a number up to 10.
Purpose: This exercise helps you practice using a loop counter in an arithmetic expression and formatting each iteration’s result into a readable line of output.
Given Input: num = 5
Expected Output:
Generating multiplication table for 5: 5 x 1 = 5 5 x 2 = 10 5 x 3 = 15 5 x 4 = 20 5 x 5 = 25 5 x 6 = 30 5 x 7 = 35 5 x 8 = 40 5 x 9 = 45 5 x 10 = 50 Table generation completed successfully.
▼ Hint
- Use a
forloop with the counter running from 1 to 10. - Multiply
numby the loop counter on each iteration. - Print the number, the counter, and the result together in one line.
▼ Solution & Explanation
Explanation:
class MultiplicationTableGenerator: Defines the class that holds the program’s entry point and table-generation logic.for (int i = 1; i <= 10; i++): Runs the loop 10 times, once for each row of the table.num * i: Multipliesnumby the current loop counter to get the product for that row.Console.WriteLine($"{num} x {i} = {num * i}"): Uses string interpolation to combine the number, counter, and product into a single formatted line of output.
Exercise 7: Factorial Calculator
Practice Problem: Write a C# program to find the factorial of a number using a loop.
Purpose: This exercise helps you practice using a loop to repeatedly multiply values together, a pattern used in mathematical calculations such as factorials, powers, and products.
Given Input: num = 5
Expected Output:
Calculating factorial of 5: Factorial = 120 Calculation completed successfully.
▼ Hint
- Initialize a variable
factorial = 1, not 0, since you are multiplying. - Use a
forloop that runs from 1 tonum. - Multiply
factorialby the loop counter on each iteration.
▼ Solution & Explanation
Explanation:
class FactorialCalculator: Defines the class that holds the program’s entry point and factorial logic.long factorial = 1: Initializes the result to 1 because multiplying by 1 has no effect, andlongis used since factorials grow quickly.for (int i = 1; i <= num; i++): Iterates through every whole number from 1 tonum.factorial *= i: Multiplies the running result by the current loop counter on every iteration.Console.WriteLine($"Factorial = {factorial}"): Prints the final factorial value after the loop completes.
Exercise 8: Sum of Digits
Practice Problem: Write a C# program to calculate the sum of the digits of an integer.
Purpose: This exercise helps you practice extracting individual digits from a number using the modulus and division operators inside a loop, a common technique in number-processing problems.
Given Input: num = 123
Expected Output:
Calculating sum of digits for 123: Sum of digits = 6 Calculation completed successfully.
▼ Hint
- Use
% 10to get the last digit of a number. - Use
/ 10to remove the last digit from a number. - Repeat this process in a
whileloop until the number becomes 0, adding each digit to a running total.
▼ Solution & Explanation
Explanation:
class DigitSumCalculator: Defines the class that holds the program’s entry point and digit-processing logic.int temp = num: Copies the original number so the loop can modify it without changingnum.temp % 10: Extracts the last digit oftemp.sum += temp % 10: Adds the extracted digit to the running total.temp /= 10: Removes the last digit fromtempusing integer division.
Exercise 9: Count Digits
Practice Problem: Write a C# program to count how many digits are in a given number.
Purpose: This exercise helps you practice using a loop to repeatedly strip digits off a number while tracking how many times the loop runs, reinforcing the same digit-extraction pattern used in other number-processing tasks.
Given Input: num = 45678
Expected Output:
Counting digits in 45678: Number of digits = 5 Counting completed successfully.
▼ Hint
- Initialize a variable
count = 0before the loop. - Use a
whileloop that runs as long as the number is greater than 0. - Increment
countand divide the number by 10 on each iteration.
▼ Solution & Explanation
Explanation:
class DigitCounter: Defines the class that holds the program’s entry point and counting logic.int temp = num: Copies the original number so the loop can modify it without changingnum.while (temp > 0): Keeps looping as long as there are digits left to remove.count++: Increments the digit counter once for every digit that gets removed.temp /= 10: Removes the last digit fromtempusing integer division.
Exercise 10: Average of Numbers
Practice Problem: Write a C# program to calculate and display the average of a set of 5 numbers.
Purpose: This exercise helps you practice iterating over an array with a foreach loop, accumulating a total, and performing a division that produces a floating-point result.
Given Input: numbers = {10, 20, 30, 40, 50}
Expected Output:
Calculating average of the given numbers: Average = 30 Calculation completed successfully.
▼ Hint
- Initialize a variable
sum = 0before the loop. - Use a
foreachloop to add each element of the array tosum. - Divide
sumbynumbers.Lengthto get the average, casting todoublefor a precise result.
▼ Solution & Explanation
Explanation:
class AverageCalculator: Defines the class that holds the program’s entry point and averaging logic.int sum = 0: Initializes a variable to zero to accumulate the total before the loop starts.foreach (int number in numbers): Iterates through each element of the array, adding it tosum.(double)sum / numbers.Length: Casts the sum todoublebefore dividing by the element count so the result can include decimal precision.Console.WriteLine($"Average = {average}"): Uses string interpolation to print the calculated average to the console.
Exercise 11: Palindrome Checker
Practice Problem: Write a C# program to check if a given string reads the same backward as forward.
Purpose: This exercise helps you practice reversing a string using a character array and comparing it against the original to test for symmetry, a common pattern in string-processing problems.
Given Input: text = "radar"
Expected Output:
Checking if "radar" is a palindrome: Result: "radar" is a palindrome. Palindrome check completed successfully.
▼ Hint
- Convert the string into a character array using
ToCharArray(). - Use
Array.Reverse()to reverse the array. - Rebuild the reversed array into a string and compare it with the original.
▼ Solution & Explanation
Explanation:
class PalindromeChecker: Defines the class that holds the program’s entry point and comparison logic.text.ToCharArray(): Converts the string into an array of characters so it can be reversed.Array.Reverse(characters): Reverses the order of characters in the array in place.new string(characters): Rebuilds a string from the reversed character array.text == reversed: Compares the original string with its reversed version to determine if it reads the same both ways.
Exercise 12: Array Traversal
Practice Problem: Create an array of 5 integers and use a foreach loop to print each element multiplied by 2.
Purpose: This exercise helps you practice using a foreach loop to traverse an array and apply a calculation to each element without managing an index manually.
Given Input: numbers = {1, 2, 3, 4, 5}
Expected Output:
Traversing array and doubling each value: 1 x 2 = 2 2 x 2 = 4 3 x 2 = 6 4 x 2 = 8 5 x 2 = 10 Array traversal completed successfully.
▼ Hint
- Declare an
intarray with 5 values. - Use a
foreachloop to access each element without needing an index. - Multiply each element by 2 inside the loop and print the result.
▼ Solution & Explanation
Explanation:
class ArrayTraversal: Defines the class that holds the program’s entry point and traversal logic.int[] numbers = { 1, 2, 3, 4, 5 }: Declares and initializes an array of 5 integers.foreach (int number in numbers): Iterates through each element of the array in order.number * 2: Multiplies the current element by 2 to double its value.Console.WriteLine($"{number} x 2 = {number * 2}"): Prints the original value and its doubled result in a labeled format.
Exercise 13: Number Guessing Game
Practice Problem: Simulate a number guessing game where a target number is set between 1 and 100, and a sequence of guesses is checked in a loop, printing “too high” or “too low” hints until the correct number is found.
Purpose: This exercise helps you practice looping through a sequence of values, comparing each one against a target with conditional logic, and exiting a loop early with break once a condition is met.
Given Input: targetNumber = 42, guesses = {25, 60, 45, 40, 42}
Expected Output:
Starting number guessing game. Target is between 1 and 100: Guess: 25 Hint: Too Low Guess: 60 Hint: Too High Guess: 45 Hint: Too High Guess: 40 Hint: Too Low Guess: 42 Correct! You guessed the number. Number guessing game completed successfully.
▼ Hint
- Store the number to guess in a variable such as
targetNumber. - Loop through a set of guesses, comparing each one to the target.
- Print “too low” or “too high” based on the comparison, and stop the loop with
breakonce the guess matches.
▼ Solution & Explanation
Explanation:
int targetNumber = 42: Sets the number to be guessed using a fixed value so the program can run without interactive input.int[] guesses = { 25, 60, 45, 40, 42 }: Simulates a sequence of guesses using a predefined array.foreach (int guess in guesses): Processes each guess one at a time in order.guess < targetNumber/guess > targetNumber: Compares the guess with the target to decide whether to print a “too low” or “too high” hint.break: Stops the loop as soon as the correct guess is found.
Exercise 14: Armstrong Number
Practice Problem: Write a C# program to check if a 3-digit number is an Armstrong number.
Purpose: This exercise helps you practice extracting digits from a number, cubing each digit, and accumulating a total to compare against the original value, reinforcing digit-manipulation techniques.
Given Input: num = 153
Expected Output:
Checking if 153 is an Armstrong number: Result: 153 is an Armstrong number. Armstrong number check completed successfully.
▼ Hint
- Copy the number into a temporary variable so the original stays unchanged.
- Extract each digit using
% 10and remove it using/ 10inside awhileloop. - Cube each digit and add it to a running total, then compare the total with the original number.
▼ Solution & Explanation
Explanation:
class ArmstrongNumberChecker: Defines the class that holds the program’s entry point and digit-cubing logic.int temp = num: Copies the original number so it can be broken down without losing the original value.temp % 10: Extracts the last digit oftempon each iteration.digit * digit * digit: Cubes the extracted digit, since Armstrong numbers use the cube of each digit for 3-digit numbers.sum == num: Compares the calculated sum with the original number to determine if it is an Armstrong number.
Exercise 15: ASCII Table
Practice Problem: Write a C# program to print all uppercase letters (A-Z) alongside their corresponding ASCII values using a loop.
Purpose: This exercise helps you practice looping directly over characters and casting between char and int to reveal the underlying ASCII value of each letter.
Given Input: None (the loop runs from ‘A’ to ‘Z’).
Expected Output:
Printing uppercase letters with their ASCII values: A = 65 B = 66 C = 67 D = 68 E = 69 F = 70 G = 71 H = 72 I = 73 J = 74 K = 75 L = 76 M = 77 N = 78 O = 79 P = 80 Q = 81 R = 82 S = 83 T = 84 U = 85 V = 86 W = 87 X = 88 Y = 89 Z = 90 ASCII table printing completed successfully.
▼ Hint
- Use a
forloop with acharvariable starting at'A'and ending at'Z'. - Increment the
chardirectly, since characters in C# can be incremented like numbers. - Cast each character to
intto get its ASCII value.
▼ Solution & Explanation
Explanation:
class AsciiTablePrinter: Defines the class that holds the program’s entry point and printing logic.for (char letter = 'A'; letter <= 'Z'; letter++): Iterates through each character from'A'to'Z'using char arithmetic.(int)letter: Casts the character to its underlying integer value, which is its ASCII code.Console.WriteLine($"{letter} = {(int)letter}"): Prints the letter alongside its ASCII value.
Exercise 16: Right-Angled Triangle Pattern
Practice Problem: Write a C# program to print a right-angled triangle pattern of asterisks.
Purpose: This exercise helps you practice using nested loops, where the outer loop controls the rows and the inner loop controls how many characters are printed in each row.
Given Input: rows = 5
Expected Output:
Printing right-angled triangle pattern: * ** *** **** ***** Pattern printing completed successfully.
▼ Hint
- Use an outer loop to control the number of rows.
- Use an inner loop to print asterisks, running from 1 to the current row number.
- Print a new line after each row using
Console.WriteLine()with no arguments.
▼ Solution & Explanation
Explanation:
class RightTrianglePrinter: Defines the class that holds the program’s entry point and pattern logic.for (int i = 1; i <= rows; i++): Controls the number of rows printed, from 1 up torows.for (int j = 1; j <= i; j++): Controls how many asterisks are printed in the current row, matching the row number.Console.Write("*"): Prints an asterisk without moving to a new line, so multiple asterisks appear on the same row.Console.WriteLine(): Moves to the next line after each row is complete.
Exercise 17: Pyramid Pattern
Practice Problem: Write a C# program to print a centered pyramid pattern of asterisks.
Purpose: This exercise helps you practice combining two inner loops inside an outer loop, using one to print leading spaces for centering and another to print an increasing number of characters.
Given Input: rows = 5
Expected Output:
Printing centered pyramid pattern:
*
***
*****
*******
*********
Pattern printing completed successfully.
▼ Hint
- Use an outer loop to control the number of rows.
- Use one inner loop to print leading spaces (
rows - ispaces). - Use a second inner loop to print
(2 * i - 1)asterisks on each row.
▼ Solution & Explanation
Explanation:
class PyramidPrinter: Defines the class that holds the program’s entry point and pattern logic.for (int space = 1; space <= rows - i; space++): Prints leading spaces to center the asterisks, with fewer spaces on later rows.for (int star = 1; star <= (2 * i - 1); star++): Prints an odd number of asterisks that increases by 2 on each row, forming the pyramid shape.Console.WriteLine(): Moves to a new line after each row is complete.
Exercise 18: Number Pattern
Practice Problem: Write a C# program to print a number pattern using nested loops, where each row lists the numbers from 1 up to the row number.
Purpose: This exercise helps you practice using an inner loop to print a sequence of values that grows with each row, reinforcing the outer-loop-controls-rows, inner-loop-controls-content pattern.
Given Input: rows = 5
Expected Output:
Printing number pattern: 1 1 2 1 2 3 1 2 3 4 1 2 3 4 5 Pattern printing completed successfully.
▼ Hint
- Use an outer loop to control the number of rows.
- Use an inner loop that runs from 1 to the current row number, printing each value.
- Add a space after each number so they appear side by side on the same line.
▼ Solution & Explanation
Explanation:
class NumberPatternPrinter: Defines the class that holds the program’s entry point and pattern logic.for (int i = 1; i <= rows; i++): Controls the number of rows, from 1 up torows.for (int j = 1; j <= i; j++): Prints numbers from 1 up to the current row number.Console.Write(j + " "): Prints each number followed by a space, keeping them on the same line.Console.WriteLine(): Moves to the next line after each row is complete.
Exercise 19: Floyd’s Triangle
Practice Problem: Write a C# program to print Floyd’s Triangle up to a given number of rows.
Purpose: This exercise helps you practice maintaining a running counter across nested loops, where the value keeps increasing continuously instead of resetting on each row.
Given Input: rows = 5
Expected Output:
Printing Floyd's Triangle: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 Pattern printing completed successfully.
▼ Hint
- Use a variable such as
number, initialized to 1, outside both loops so it keeps increasing across rows. - Use an outer loop for rows and an inner loop that runs
itimes for the current row. - Print
numberand then increment it inside the inner loop.
▼ Solution & Explanation
Explanation:
class FloydsTrianglePrinter: Defines the class that holds the program’s entry point and pattern logic.int number = 1: Tracks the next value to print, starting at 1 and increasing continuously across all rows.for (int i = 1; i <= rows; i++): Controls the number of rows, from 1 up torows.for (int j = 1; j <= i; j++): Prints as many numbers as the current row requires.number++: Increments the running counter after each number is printed, so values never repeat or reset.
Exercise 20: Perfect Numbers
Practice Problem: Find and print all Perfect Numbers between 1 and 500. A number is perfect if it equals the sum of its proper divisors.
Purpose: This exercise helps you practice using nested loops to check a divisibility condition for every number in a range, a pattern used in many number theory problems.
Given Input: Range from 1 to 500.
Expected Output:
Finding perfect numbers between 1 and 500: Perfect Number: 6 Perfect Number: 28 Perfect Number: 496 Perfect number search completed successfully.
▼ Hint
- Use an outer loop to check every number from 1 to 500.
- Use an inner loop to find all proper divisors of the current number (divisors smaller than the number itself).
- Sum up the divisors and compare the sum with the original number.
▼ Solution & Explanation
Explanation:
class PerfectNumberFinder: Defines the class that holds the program’s entry point and divisor-checking logic.for (int num = 1; num <= 500; num++): Checks every number from 1 to 500 to see if it is perfect.for (int divisor = 1; divisor < num; divisor++): Checks every number smaller thannumto see if it divides evenly.num % divisor == 0: Confirms thatdivisoris a proper divisor ofnum.sum == num: Compares the sum of proper divisors with the original number to determine if it is a perfect number.
Exercise 21: Fibonacci Series
Practice Problem: Write a C# program to generate and print the first N numbers of the Fibonacci sequence.
Purpose: This exercise helps you practice tracking two running values across loop iterations and updating them together, a pattern used whenever a sequence depends on its own previous terms.
Given Input: n = 10
Expected Output: 0 1 1 2 3 5 8 13 21 34
▼ Hint
- Start with two variables representing the first two Fibonacci numbers, 0 and 1.
- Use a loop to print the current value, then calculate the next value as the sum of the two previous ones.
- Update both variables on each iteration so they always hold the two most recent terms.
▼ Solution & Explanation
Explanation:
class FibonacciSeriesGenerator: Defines the class that holds the program’s entry point and sequence logic.int first = 0, second = 1: Initializes the first two terms of the Fibonacci sequence.Console.Write(first + " "): Prints the current Fibonacci number before calculating the next one.int next = first + second: Calculates the next Fibonacci number by adding the two previous ones.first = second; second = next;: Shifts both variables forward by one position in the sequence.
Exercise 22: Reverse a String
Practice Problem: Write a C# program to print a string backward using a loop.
Purpose: This exercise helps you practice accessing individual characters of a string by index and building a new string manually, without relying on a built-in reverse method.
Given Input: text = "Hello"
Expected Output:
Reversing the string "Hello": Reversed String: olleH String reversal completed successfully.
▼ Hint
- Initialize an empty string to hold the result.
- Use a
forloop that starts attext.Length - 1and counts down to 0. - Append
text[i]to the result string on each iteration.
▼ Solution & Explanation
Explanation:
class StringReverser: Defines the class that holds the program’s entry point and reversal logic.string reversed = "": Initializes an empty string to build up the reversed result.for (int i = text.Length - 1; i >= 0; i--): Starts at the last character’s index and moves backward to the first.text[i]: Accesses the character at indexiof the original string.reversed += text[i]: Appends each character, in reverse order, to the reversed string.
Exercise 23: Prime Number Check
Practice Problem: Write a C# program to determine whether a given number is a prime number.
Purpose: This exercise helps you practice using a loop combined with a boolean flag to test a condition and exit early with break once the result is known.
Given Input: num = 29
Expected Output:
Checking if 29 is a prime number: Result: 29 is a prime number. Prime number check completed successfully.
▼ Hint
- Assume the number is prime, then try to disprove it.
- Loop from 2 up to the square root of the number, checking if it divides evenly.
- If any divisor is found, the number is not prime; use
breakto exit early.
▼ Solution & Explanation
Explanation:
class PrimeNumberChecker: Defines the class that holds the program’s entry point and primality-check logic.bool isPrime = true: Assumes the number is prime until proven otherwise.for (int i = 2; i <= Math.Sqrt(num); i++): Only checks divisors up to the square root ofnum, since a larger factor would already have a matching smaller factor found.num % i == 0: Ifnumdivides evenly byi, it has a factor other than 1 and itself, so it is not prime.break: Stops checking further divisors once a factor is found, since the result is already determined.
Exercise 24: Find Primes in a Range
Practice Problem: Write a C# program to print all prime numbers between 1 and 50.
Purpose: This exercise helps you practice combining an outer loop over a range with an inner primality check, applying the single-number prime test repeatedly across many values.
Given Input: Range from 1 to 50.
Expected Output:
Finding prime numbers between 1 and 50: Prime Number: 2 Prime Number: 3 Prime Number: 5 Prime Number: 7 Prime Number: 11 Prime Number: 13 Prime Number: 17 Prime Number: 19 Prime Number: 23 Prime Number: 29 Prime Number: 31 Prime Number: 37 Prime Number: 41 Prime Number: 43 Prime Number: 47 Prime number search completed successfully.
▼ Hint
- Use an outer loop to check every number from 2 to 50.
- Use an inner loop for each number to test divisibility up to its square root.
- Print the number only if no divisors are found in the inner loop.
▼ Solution & Explanation
Explanation:
class PrimeRangeFinder: Defines the class that holds the program’s entry point and range-scanning logic.for (int num = 2; num <= 50; num++): Checks every number from 2 to 50, since numbers below 2 cannot be prime.bool isPrime = true: Assumes each number is prime until a divisor is found.for (int i = 2; i <= Math.Sqrt(num); i++): Checks only up to the square root ofnumfor efficiency.Console.WriteLine($"Prime Number: {num}"): Prints the number only if it passed the divisor check with no factors found.
Exercise 25: Power Calculator
Practice Problem: Write a C# program to calculate the result of a base raised to an exponent without using Math.Pow().
Purpose: This exercise helps you practice implementing repeated multiplication manually with a loop, reinforcing how exponentiation works at a fundamental level.
Given Input: baseNumber = 2, exponent = 8
Expected Output:
Calculating 2 raised to the power 8: Result = 256 Power calculation completed successfully.
▼ Hint
- Initialize a result variable to 1.
- Use a loop that runs
exponenttimes. - Multiply
resultbybaseNumberon each iteration instead of callingMath.Pow().
▼ Solution & Explanation
Explanation:
class PowerCalculator: Defines the class that holds the program's entry point and exponentiation logic.long result = 1: Initializes the result to 1, since multiplying by 1 has no effect, andlongis used to safely hold larger results.for (int i = 1; i <= exponent; i++): Repeats the multiplicationexponenttimes.result *= baseNumber: Multiplies the running result bybaseNumberon each iteration, building up the power manually instead of usingMath.Pow().
Exercise 26: Count Vowels and Consonants
Practice Problem: Loop through a string and count how many vowels and consonants it has.
Purpose: This exercise helps you practice iterating over the characters of a string and classifying each one with conditional checks, a common pattern in text-processing tasks.
Given Input: text = "Programming"
Expected Output:
Counting vowels and consonants in "Programming": Vowels = 3 Consonants = 8 Vowel and consonant count completed successfully.
▼ Hint
- Convert the string to lowercase first so you only need to check one case.
- Loop through each character and compare it against the vowels a, e, i, o, u.
- If it is a letter but not a vowel, count it as a consonant.
▼ Solution & Explanation
Explanation:
class VowelConsonantCounter: Defines the class that holds the program's entry point and counting logic.text.ToLower(): Converts the string to lowercase so the vowel comparison does not need to check both cases.ch == 'a' || ch == 'e' || ...: Checks if the current character is one of the five vowels.ch >= 'a' && ch <= 'z': Confirms the character is a letter before counting it as a consonant, since it did not match the vowel check.vowelCount++ / consonantCount++: Increments the matching counter for each character processed.
Exercise 27: LCM (Lowest Common Multiple)
Practice Problem: Write a C# program to find the LCM of two numbers using a loop.
Purpose: This exercise helps you practice using an unbounded loop that checks a condition on each pass and stops with break once the target value is found.
Given Input: num1 = 4, num2 = 6
Expected Output:
Calculating LCM of 4 and 6: LCM = 12 LCM calculation completed successfully.
▼ Hint
- Start checking from the larger of the two numbers, since the LCM is never smaller than that.
- Use a loop that keeps increasing the candidate value by 1 each time.
- Stop the loop once a value is found that both numbers divide evenly into.
▼ Solution & Explanation
Explanation:
class LcmCalculator: Defines the class that holds the program's entry point and LCM logic.int max = (num1 > num2) ? num1 : num2: Starts checking from the larger of the two numbers, since the LCM can never be smaller than that.while (true): Keeps checking candidate values indefinitely until the loop is stopped from inside.max % num1 == 0 && max % num2 == 0: Checks whether the candidate value divides evenly by both numbers.break: Stops the loop as soon as a common multiple is found.
Exercise 28: GCD (Greatest Common Divisor)
Practice Problem: Write a C# program to find the GCD (HCF) of two numbers using the Euclidean algorithm.
Purpose: This exercise helps you practice implementing the Euclidean algorithm with a loop, repeatedly replacing a pair of values with the smaller value and their remainder.
Given Input: num1 = 48, num2 = 18
Expected Output:
Calculating GCD of 48 and 18: GCD = 6 GCD calculation completed successfully.
▼ Hint
- Copy both numbers into working variables so the originals stay unchanged.
- Use a
whileloop that continues as long as the second variable is not 0. - On each iteration, replace the first variable with the second, and the second with the remainder of dividing the first by the second.
▼ Solution & Explanation
Explanation:
class GcdCalculator: Defines the class that holds the program's entry point and Euclidean algorithm logic.int a = num1; int b = num2;: Copies the original values into working variables sonum1andnum2remain unchanged.while (b != 0): Continues the Euclidean algorithm until the remainder becomes 0.b = a % b: Calculates the remainder of dividingabyb, which becomes the newb.a = temp: Assigns the old value ofbtoa, shifting both variables forward in the algorithm.
Exercise 29: Binary to Decimal
Practice Problem: Write a C# program to convert a binary number into its decimal equivalent using a loop.
Purpose: This exercise helps you practice processing a string digit by digit and applying place-value logic, a core technique in number-base conversion.
Given Input: binary = "1011"
Expected Output:
Converting binary 1011 to decimal: Decimal Value = 11 Binary to decimal conversion completed successfully.
▼ Hint
- Loop through the binary string from right to left.
- Convert each character digit to a number using
binary[i] - '0'. - Multiply each digit by the current place value (starting at 1 and doubling each step) and add it to a running total.
▼ Solution & Explanation
Explanation:
class BinaryToDecimalConverter: Defines the class that holds the program's entry point and conversion logic.for (int i = binary.Length - 1; i >= 0; i--): Processes the binary string from the rightmost digit to the leftmost.binary[i] - '0': Converts the character digit into its numeric value by subtracting the character code of'0'.decimalValue += digit * placeValue: Adds the digit's contribution to the total, based on its place value.placeValue *= 2: Doubles the place value after each digit, since each binary position represents a power of 2.
Exercise 30: Decimal to Binary
Practice Problem: Write a C# program to convert a decimal number into its binary representation using a loop.
Purpose: This exercise helps you practice building a result string by repeatedly extracting remainders, reinforcing the reverse process of a binary-to-decimal conversion.
Given Input: num = 26
Expected Output:
Converting decimal 26 to binary: Binary Value = 11010 Decimal to binary conversion completed successfully.
▼ Hint
- Use a
whileloop that continues as long as the number is greater than 0. - On each iteration, get the remainder of dividing by 2 (this is the next binary digit).
- Prepend the digit to a result string, then divide the number by 2 to move to the next digit.
▼ Solution & Explanation
Explanation:
class DecimalToBinaryConverter: Defines the class that holds the program's entry point and conversion logic.int temp = num: Copies the original number so the loop can modify it without changingnum.temp % 2: Calculates the remainder when dividing by 2, which is the next binary digit.binary = remainder + binary: Prepends the new digit to the front of the result string, since binary digits are generated from least significant to most significant.temp /= 2: Removes the digit that was just processed by halving the number.
Exercise 31: Matrix Diagonal Sum
Practice Problem: Write nested loops to iterate through a 3x3 two-dimensional array and calculate the sum of its main diagonal elements.
Purpose: This exercise helps you practice iterating through a two-dimensional array with nested loops and identifying diagonal elements by comparing row and column indices.
Given Input: matrix = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}
Expected Output:
Calculating sum of main diagonal elements: Diagonal Sum = 15 Matrix diagonal sum calculation completed successfully.
▼ Hint
- Declare a 3x3 two-dimensional array using
int[,]. - Use nested loops to iterate through every row and column.
- Add an element to the sum only when its row index equals its column index.
▼ Solution & Explanation
Explanation:
class MatrixDiagonalSumCalculator: Defines the class that holds the program's entry point and diagonal-sum logic.int[,] matrix: Declares a 3x3 two-dimensional array using C#'s multidimensional array syntax.for (int row = 0; row < 3; row++)/for (int col = 0; col < 3; col++): Iterates through every row and column of the matrix using nested loops.row == col: Identifies main diagonal elements, since their row index always matches their column index.sum += matrix[row, col]: Adds the diagonal element to the running total.

Leave a Reply