PYnative

Python Programming

  • Learn Python ▼
    • Python Tutorials
    • Python Basics
    • Python Interview Q&As
  • Exercises ▼
    • Python Exercises
    • C++ Exercises
    • C Programming Exercises
    • Java Exercises
    • C# Exercises
  • Quizzes
  • Code Editor ▼
    • Online Python Code Editor
    • Online C Compiler
    • Online C++ Compiler
    • Online Java Compiler
    • Online C# Compiler
Home » C# Exercises » C# Loops Exercises: 30 Coding Problems with Solutions

C# Loops Exercises: 30 Coding Problems with Solutions

Updated on: July 15, 2026 | Leave a Comment

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: for and while loop 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
using System;

namespace NumberUtilities
{
    class NumberPrinter
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Starting sequence from 1 to 10:");

            for (int i = 1; i <= 10; i++)
            {
                Console.WriteLine($"Current Value: {i}");
            }

            Console.WriteLine("Number printing completed successfully.");
        }
    }
}Code language: C# (cs)

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++): Initializes i to 1, repeats the loop while i is less than or equal to 10, and increments i by 1 after each iteration.
  • Console.WriteLine($"Current Value: {i}"): Uses string interpolation to print the current value of i in 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 = 10 before the loop.
  • Use a while loop that continues as long as i >= 1.
  • Decrease i by 1 inside the loop after printing it.
▼ Solution & Explanation
using System;

namespace NumberUtilities
{
    class CountdownTimer
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Starting countdown from 10 to 1:");

            int i = 10;
            while (i >= 1)
            {
                Console.WriteLine($"Current Value: {i}");
                i--;
            }

            Console.WriteLine("Countdown completed successfully.");
        }
    }
}Code language: C# (cs)

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 as i is greater than or equal to 1.
  • Console.WriteLine($"Current Value: {i}"): Uses string interpolation to print the current value of i in a readable, labeled format.
  • i--: Decreases i by 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 for loop.
  • Use the modulus operator % to check if a number is divisible by 2.
  • If the remainder is 0, print the number.
▼ Solution & Explanation
using System;

namespace NumberUtilities
{
    class EvenNumberFinder
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Finding even numbers between 1 and 20:");

            for (int i = 1; i <= 20; i++)
            {
                if (i % 2 == 0)
                {
                    Console.WriteLine($"Even Number: {i}");
                }
            }

            Console.WriteLine("Even number search completed successfully.");
        }
    }
}Code language: C# (cs)

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 whether i is 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 for loop.
  • Use i % 2 != 0 to check if a number is odd.
  • Print the number whenever the condition is true.
▼ Solution & Explanation
using System;

namespace NumberUtilities
{
    class OddNumberFinder
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Finding odd numbers between 1 and 20:");

            for (int i = 1; i <= 20; i++)
            {
                if (i % 2 != 0)
                {
                    Console.WriteLine($"Odd Number: {i}");
                }
            }

            Console.WriteLine("Odd number search completed successfully.");
        }
    }
}Code language: C# (cs)

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 whether i leaves 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 = 0 before the loop.
  • Use a for loop that runs from 1 to n.
  • Add each value of the loop counter to sum on every iteration.
▼ Solution & Explanation
using System;

namespace MathUtilities
{
    class SumCalculator
    {
        static void Main(string[] args)
        {
            int n = 10;
            int sum = 0;

            Console.WriteLine($"Calculating sum of first {n} numbers:");

            for (int i = 1; i <= n; i++)
            {
                sum += i;
            }

            Console.WriteLine($"Sum = {sum}");
            Console.WriteLine("Calculation completed successfully.");
        }
    }
}Code language: C# (cs)

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 to n.
  • sum += i: Adds the current value of i to sum on 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 for loop with the counter running from 1 to 10.
  • Multiply num by the loop counter on each iteration.
  • Print the number, the counter, and the result together in one line.
▼ Solution & Explanation
using System;

namespace MathUtilities
{
    class MultiplicationTableGenerator
    {
        static void Main(string[] args)
        {
            int num = 5;

            Console.WriteLine($"Generating multiplication table for {num}:");

            for (int i = 1; i <= 10; i++)
            {
                Console.WriteLine($"{num} x {i} = {num * i}");
            }

            Console.WriteLine("Table generation completed successfully.");
        }
    }
}Code language: C# (cs)

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: Multiplies num by 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 for loop that runs from 1 to num.
  • Multiply factorial by the loop counter on each iteration.
▼ Solution & Explanation
using System;

namespace MathUtilities
{
    class FactorialCalculator
    {
        static void Main(string[] args)
        {
            int num = 5;
            long factorial = 1;

            Console.WriteLine($"Calculating factorial of {num}:");

            for (int i = 1; i <= num; i++)
            {
                factorial *= i;
            }

            Console.WriteLine($"Factorial = {factorial}");
            Console.WriteLine("Calculation completed successfully.");
        }
    }
}Code language: C# (cs)

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, and long is used since factorials grow quickly.
  • for (int i = 1; i <= num; i++): Iterates through every whole number from 1 to num.
  • 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 % 10 to get the last digit of a number.
  • Use / 10 to remove the last digit from a number.
  • Repeat this process in a while loop until the number becomes 0, adding each digit to a running total.
▼ Solution & Explanation
using System;

namespace MathUtilities
{
    class DigitSumCalculator
    {
        static void Main(string[] args)
        {
            int num = 123;
            int sum = 0;
            int temp = num;

            Console.WriteLine($"Calculating sum of digits for {num}:");

            while (temp > 0)
            {
                sum += temp % 10;
                temp /= 10;
            }

            Console.WriteLine($"Sum of digits = {sum}");
            Console.WriteLine("Calculation completed successfully.");
        }
    }
}Code language: C# (cs)

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 changing num.
  • temp % 10: Extracts the last digit of temp.
  • sum += temp % 10: Adds the extracted digit to the running total.
  • temp /= 10: Removes the last digit from temp using 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 = 0 before the loop.
  • Use a while loop that runs as long as the number is greater than 0.
  • Increment count and divide the number by 10 on each iteration.
▼ Solution & Explanation
using System;

namespace MathUtilities
{
    class DigitCounter
    {
        static void Main(string[] args)
        {
            int num = 45678;
            int count = 0;
            int temp = num;

            Console.WriteLine($"Counting digits in {num}:");

            while (temp > 0)
            {
                count++;
                temp /= 10;
            }

            Console.WriteLine($"Number of digits = {count}");
            Console.WriteLine("Counting completed successfully.");
        }
    }
}Code language: C# (cs)

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 changing num.
  • 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 from temp using 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 = 0 before the loop.
  • Use a foreach loop to add each element of the array to sum.
  • Divide sum by numbers.Length to get the average, casting to double for a precise result.
▼ Solution & Explanation
using System;

namespace MathUtilities
{
    class AverageCalculator
    {
        static void Main(string[] args)
        {
            int[] numbers = { 10, 20, 30, 40, 50 };
            int sum = 0;

            Console.WriteLine("Calculating average of the given numbers:");

            foreach (int number in numbers)
            {
                sum += number;
            }

            double average = (double)sum / numbers.Length;

            Console.WriteLine($"Average = {average}");
            Console.WriteLine("Calculation completed successfully.");
        }
    }
}Code language: C# (cs)

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 to sum.
  • (double)sum / numbers.Length: Casts the sum to double before 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
using System;

namespace StringUtilities
{
    class PalindromeChecker
    {
        static void Main(string[] args)
        {
            string text = "radar";

            Console.WriteLine($"Checking if \"{text}\" is a palindrome:");

            char[] characters = text.ToCharArray();
            Array.Reverse(characters);
            string reversed = new string(characters);

            if (text == reversed)
            {
                Console.WriteLine($"Result: \"{text}\" is a palindrome.");
            }
            else
            {
                Console.WriteLine($"Result: \"{text}\" is not a palindrome.");
            }

            Console.WriteLine("Palindrome check completed successfully.");
        }
    }
}Code language: C# (cs)

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 int array with 5 values.
  • Use a foreach loop to access each element without needing an index.
  • Multiply each element by 2 inside the loop and print the result.
▼ Solution & Explanation
using System;

namespace ArrayUtilities
{
    class ArrayTraversal
    {
        static void Main(string[] args)
        {
            int[] numbers = { 1, 2, 3, 4, 5 };

            Console.WriteLine("Traversing array and doubling each value:");

            foreach (int number in numbers)
            {
                Console.WriteLine($"{number} x 2 = {number * 2}");
            }

            Console.WriteLine("Array traversal completed successfully.");
        }
    }
}Code language: C# (cs)

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 break once the guess matches.
▼ Solution & Explanation
using System;

namespace GameUtilities
{
    class NumberGuessingGame
    {
        static void Main(string[] args)
        {
            int targetNumber = 42;
            int[] guesses = { 25, 60, 45, 40, 42 };

            Console.WriteLine("Starting number guessing game. Target is between 1 and 100:");

            foreach (int guess in guesses)
            {
                Console.WriteLine($"Guess: {guess}");

                if (guess < targetNumber)
                {
                    Console.WriteLine("Hint: Too Low");
                }
                else if (guess > targetNumber)
                {
                    Console.WriteLine("Hint: Too High");
                }
                else
                {
                    Console.WriteLine("Correct! You guessed the number.");
                    break;
                }
            }

            Console.WriteLine("Number guessing game completed successfully.");
        }
    }
}Code language: C# (cs)

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 % 10 and remove it using / 10 inside a while loop.
  • Cube each digit and add it to a running total, then compare the total with the original number.
▼ Solution & Explanation
using System;

namespace MathUtilities
{
    class ArmstrongNumberChecker
    {
        static void Main(string[] args)
        {
            int num = 153;
            int temp = num;
            int sum = 0;

            Console.WriteLine($"Checking if {num} is an Armstrong number:");

            while (temp > 0)
            {
                int digit = temp % 10;
                sum += digit * digit * digit;
                temp /= 10;
            }

            if (sum == num)
            {
                Console.WriteLine($"Result: {num} is an Armstrong number.");
            }
            else
            {
                Console.WriteLine($"Result: {num} is not an Armstrong number.");
            }

            Console.WriteLine("Armstrong number check completed successfully.");
        }
    }
}Code language: C# (cs)

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 of temp on 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 for loop with a char variable starting at 'A' and ending at 'Z'.
  • Increment the char directly, since characters in C# can be incremented like numbers.
  • Cast each character to int to get its ASCII value.
▼ Solution & Explanation
using System;

namespace CharacterUtilities
{
    class AsciiTablePrinter
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Printing uppercase letters with their ASCII values:");

            for (char letter = 'A'; letter <= 'Z'; letter++)
            {
                Console.WriteLine($"{letter} = {(int)letter}");
            }

            Console.WriteLine("ASCII table printing completed successfully.");
        }
    }
}Code language: C# (cs)

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
using System;

namespace PatternUtilities
{
    class RightTrianglePrinter
    {
        static void Main(string[] args)
        {
            int rows = 5;

            Console.WriteLine("Printing right-angled triangle pattern:");

            for (int i = 1; i <= rows; i++)
            {
                for (int j = 1; j <= i; j++)
                {
                    Console.Write("*");
                }
                Console.WriteLine();
            }

            Console.WriteLine("Pattern printing completed successfully.");
        }
    }
}Code language: C# (cs)

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 to rows.
  • 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 - i spaces).
  • Use a second inner loop to print (2 * i - 1) asterisks on each row.
▼ Solution & Explanation
using System;

namespace PatternUtilities
{
    class PyramidPrinter
    {
        static void Main(string[] args)
        {
            int rows = 5;

            Console.WriteLine("Printing centered pyramid pattern:");

            for (int i = 1; i <= rows; i++)
            {
                for (int space = 1; space <= rows - i; space++)
                {
                    Console.Write(" ");
                }

                for (int star = 1; star <= (2 * i - 1); star++)
                {
                    Console.Write("*");
                }

                Console.WriteLine();
            }

            Console.WriteLine("Pattern printing completed successfully.");
        }
    }
}Code language: C# (cs)

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
using System;

namespace PatternUtilities
{
    class NumberPatternPrinter
    {
        static void Main(string[] args)
        {
            int rows = 5;

            Console.WriteLine("Printing number pattern:");

            for (int i = 1; i <= rows; i++)
            {
                for (int j = 1; j <= i; j++)
                {
                    Console.Write(j + " ");
                }
                Console.WriteLine();
            }

            Console.WriteLine("Pattern printing completed successfully.");
        }
    }
}Code language: C# (cs)

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 to rows.
  • 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 i times for the current row.
  • Print number and then increment it inside the inner loop.
▼ Solution & Explanation
using System;

namespace PatternUtilities
{
    class FloydsTrianglePrinter
    {
        static void Main(string[] args)
        {
            int rows = 5;
            int number = 1;

            Console.WriteLine("Printing Floyd's Triangle:");

            for (int i = 1; i <= rows; i++)
            {
                for (int j = 1; j <= i; j++)
                {
                    Console.Write(number + " ");
                    number++;
                }
                Console.WriteLine();
            }

            Console.WriteLine("Pattern printing completed successfully.");
        }
    }
}Code language: C# (cs)

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 to rows.
  • 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
using System;

namespace MathUtilities
{
    class PerfectNumberFinder
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Finding perfect numbers between 1 and 500:");

            for (int num = 1; num <= 500; num++)
            {
                int sum = 0;

                for (int divisor = 1; divisor < num; divisor++)
                {
                    if (num % divisor == 0)
                    {
                        sum += divisor;
                    }
                }

                if (sum == num && num != 0)
                {
                    Console.WriteLine($"Perfect Number: {num}");
                }
            }

            Console.WriteLine("Perfect number search completed successfully.");
        }
    }
}Code language: C# (cs)

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 than num to see if it divides evenly.
  • num % divisor == 0: Confirms that divisor is a proper divisor of num.
  • 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
using System;

namespace MathUtilities
{
    class FibonacciSeriesGenerator
    {
        static void Main(string[] args)
        {
            int n = 10;
            int first = 0, second = 1;

            Console.WriteLine($"Generating first {n} Fibonacci numbers:");

            for (int i = 1; i <= n; i++)
            {
                Console.Write(first + " ");
                int next = first + second;
                first = second;
                second = next;
            }

            Console.WriteLine();
            Console.WriteLine("Fibonacci series generation completed successfully.");
        }
    }
}Code language: C# (cs)

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 for loop that starts at text.Length - 1 and counts down to 0.
  • Append text[i] to the result string on each iteration.
▼ Solution & Explanation
using System;

namespace StringUtilities
{
    class StringReverser
    {
        static void Main(string[] args)
        {
            string text = "Hello";
            string reversed = "";

            Console.WriteLine($"Reversing the string \"{text}\":");

            for (int i = text.Length - 1; i >= 0; i--)
            {
                reversed += text[i];
            }

            Console.WriteLine($"Reversed String: {reversed}");
            Console.WriteLine("String reversal completed successfully.");
        }
    }
}Code language: C# (cs)

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 index i of 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 break to exit early.
▼ Solution & Explanation
using System;

namespace MathUtilities
{
    class PrimeNumberChecker
    {
        static void Main(string[] args)
        {
            int num = 29;
            bool isPrime = true;

            Console.WriteLine($"Checking if {num} is a prime number:");

            if (num < 2)
            {
                isPrime = false;
            }
            else
            {
                for (int i = 2; i <= Math.Sqrt(num); i++)
                {
                    if (num % i == 0)
                    {
                        isPrime = false;
                        break;
                    }
                }
            }

            if (isPrime)
            {
                Console.WriteLine($"Result: {num} is a prime number.");
            }
            else
            {
                Console.WriteLine($"Result: {num} is not a prime number.");
            }

            Console.WriteLine("Prime number check completed successfully.");
        }
    }
}Code language: C# (cs)

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 of num, since a larger factor would already have a matching smaller factor found.
  • num % i == 0: If num divides evenly by i, 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
using System;
namespace MathUtilities
{
    class PrimeRangeFinder
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Finding prime numbers between 1 and 50:");
            for (int num = 2; num <= 50; num++)
            {
                bool isPrime = true;
                for (int i = 2; i <= Math.Sqrt(num); i++)
                {
                    if (num % i == 0)
                    {
                        isPrime = false;
                        break;
                    }
                }
                if (isPrime)
                {
                    Console.WriteLine($"Prime Number: {num}");
                }
            }
            Console.WriteLine("Prime number search completed successfully.");
        }
    }
}Code language: C# (cs)

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 of num for 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 exponent times.
  • Multiply result by baseNumber on each iteration instead of calling Math.Pow().
▼ Solution & Explanation
using System;

namespace MathUtilities
{
    class PowerCalculator
    {
        static void Main(string[] args)
        {
            int baseNumber = 2;
            int exponent = 8;
            long result = 1;

            Console.WriteLine($"Calculating {baseNumber} raised to the power {exponent}:");

            for (int i = 1; i <= exponent; i++)
            {
                result *= baseNumber;
            }

            Console.WriteLine($"Result = {result}");
            Console.WriteLine("Power calculation completed successfully.");
        }
    }
}Code language: C# (cs)

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, and long is used to safely hold larger results.
  • for (int i = 1; i <= exponent; i++): Repeats the multiplication exponent times.
  • result *= baseNumber: Multiplies the running result by baseNumber on each iteration, building up the power manually instead of using Math.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
using System;

namespace StringUtilities
{
    class VowelConsonantCounter
    {
        static void Main(string[] args)
        {
            string text = "Programming";
            int vowelCount = 0;
            int consonantCount = 0;

            Console.WriteLine($"Counting vowels and consonants in \"{text}\":");

            foreach (char ch in text.ToLower())
            {
                if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u')
                {
                    vowelCount++;
                }
                else if (ch >= 'a' && ch <= 'z')
                {
                    consonantCount++;
                }
            }

            Console.WriteLine($"Vowels = {vowelCount}");
            Console.WriteLine($"Consonants = {consonantCount}");
            Console.WriteLine("Vowel and consonant count completed successfully.");
        }
    }
}Code language: C# (cs)

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
using System;

namespace MathUtilities
{
    class LcmCalculator
    {
        static void Main(string[] args)
        {
            int num1 = 4;
            int num2 = 6;
            int max = (num1 > num2) ? num1 : num2;

            Console.WriteLine($"Calculating LCM of {num1} and {num2}:");

            while (true)
            {
                if (max % num1 == 0 && max % num2 == 0)
                {
                    break;
                }
                max++;
            }

            Console.WriteLine($"LCM = {max}");
            Console.WriteLine("LCM calculation completed successfully.");
        }
    }
}Code language: C# (cs)

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 while loop 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
using System;

namespace MathUtilities
{
    class GcdCalculator
    {
        static void Main(string[] args)
        {
            int num1 = 48;
            int num2 = 18;

            Console.WriteLine($"Calculating GCD of {num1} and {num2}:");

            int a = num1;
            int b = num2;

            while (b != 0)
            {
                int temp = b;
                b = a % b;
                a = temp;
            }

            Console.WriteLine($"GCD = {a}");
            Console.WriteLine("GCD calculation completed successfully.");
        }
    }
}Code language: C# (cs)

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 so num1 and num2 remain unchanged.
  • while (b != 0): Continues the Euclidean algorithm until the remainder becomes 0.
  • b = a % b: Calculates the remainder of dividing a by b, which becomes the new b.
  • a = temp: Assigns the old value of b to a, 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
using System;

namespace NumberSystemUtilities
{
    class BinaryToDecimalConverter
    {
        static void Main(string[] args)
        {
            string binary = "1011";
            int decimalValue = 0;
            int placeValue = 1;

            Console.WriteLine($"Converting binary {binary} to decimal:");

            for (int i = binary.Length - 1; i >= 0; i--)
            {
                int digit = binary[i] - '0';
                decimalValue += digit * placeValue;
                placeValue *= 2;
            }

            Console.WriteLine($"Decimal Value = {decimalValue}");
            Console.WriteLine("Binary to decimal conversion completed successfully.");
        }
    }
}Code language: C# (cs)

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 while loop 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
using System;

namespace NumberSystemUtilities
{
    class DecimalToBinaryConverter
    {
        static void Main(string[] args)
        {
            int num = 26;
            int temp = num;
            string binary = "";

            Console.WriteLine($"Converting decimal {num} to binary:");

            if (temp == 0)
            {
                binary = "0";
            }

            while (temp > 0)
            {
                int remainder = temp % 2;
                binary = remainder + binary;
                temp /= 2;
            }

            Console.WriteLine($"Binary Value = {binary}");
            Console.WriteLine("Decimal to binary conversion completed successfully.");
        }
    }
}Code language: C# (cs)

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 changing num.
  • 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
using System;

namespace ArrayUtilities
{
    class MatrixDiagonalSumCalculator
    {
        static void Main(string[] args)
        {
            int[,] matrix = {
                { 1, 2, 3 },
                { 4, 5, 6 },
                { 7, 8, 9 }
            };

            int sum = 0;

            Console.WriteLine("Calculating sum of main diagonal elements:");

            for (int row = 0; row < 3; row++)
            {
                for (int col = 0; col < 3; col++)
                {
                    if (row == col)
                    {
                        sum += matrix[row, col];
                    }
                }
            }

            Console.WriteLine($"Diagonal Sum = {sum}");
            Console.WriteLine("Matrix diagonal sum calculation completed successfully.");
        }
    }
}Code language: C# (cs)

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.

Filed Under: C# Exercises

Did you find this page helpful? Let others know about it. Sharing helps me continue to create free Python resources.

TweetF  sharein  shareP  Pin

About Vishal

I’m Vishal Hule, the Founder of PYnative.com. As a Python developer, I enjoy assisting students, developers, and learners. Follow me on Twitter.

Related Tutorial Topics:

C# Exercises

All Coding Exercises:

C Exercises
C++ Exercises
Python Exercises
Java Exercises
C# Exercises

Python Exercises and Quizzes

Free coding exercises and quizzes cover Python basics, data structure, data analytics, and more.

  • 15+ Topic-specific Exercises and Quizzes
  • Each Exercise contains 25+ questions
  • Each Quiz contains 25 MCQ
Exercises
Quizzes

Leave a Reply Cancel reply

your email address will NOT be published. all comments are moderated according to our comment policy.

Use <pre> tag for posting code. E.g. <pre> Your entire code </pre>

In: C# Exercises
TweetF  sharein  shareP  Pin

  C# Exercises

  • C# Exercise for Beginners
  • C# Loops Exercise
  • C# Array Exercise
  • C# String Exercise
  • C# OOP Exercise
  • C# Structs, Records and Enums Exercise
  • C# Collections Exercise
  • C# List Exercise
  • C# Dictionary Exercise
  • C# LINQ Exercise
  • C# Exception Handling Exercise
  • C# File Handling Exercise
  • C# Date and Time Exercise
  • C# Generics Exercise
  • C# Lambda Expressions Exercise
  • C# Delegates and Events Exercise
  • C# Extension Methods Exercise
  • C# Regex Exercise
  • C# Pattern Matching Exercise
  • C# Iterators and Yield Exercise
  • C# Indexers and Operator Overloading Exercise
  • C# Random Data Generation Exercise

All Coding Exercises

Python Exercises C Exercises C++ Exercises Java Exercises C# Exercises

About PYnative

PYnative.com is for Python lovers. Here, You can get Tutorials, Exercises, and Quizzes to practice and improve your Python skills.

Follow Us

To get New Python Tutorials, Exercises, and Quizzes

  • Twitter
  • Facebook
  • Sitemap

Explore Python

  • Learn Python
  • Python Basics
  • Python Databases
  • Python Exercises
  • Python Quizzes
  • Online Python Code Editor
  • Python Tricks

Coding Exercises

  • C Exercises
  • C++ Exercises
  • Python Exercises
  • Java Exercises
  • C# Exercises

Legal Stuff

  • About Us
  • Contact Us

We use cookies to improve your experience. While using PYnative, you agree to have read and accepted our:

  • Terms Of Use
  • Privacy Policy
  • Cookie Policy

Copyright © 2018–2026 pynative.com