0% found this document useful (0 votes)
148 views

Topic 1 Basics: Add Two Numbers

This document contains code examples for various basic C# exercises involving conditional statements and arithmetic operations. It includes methods to add and multiply numbers, convert between Celsius and Fahrenheit, perform elementary arithmetic operations, check if results are equal, use modulo operations, calculate cubes, swap numbers, find absolute values, check divisibility, verify if strings contain uppercase letters, and compare sums and products to a third value. Each method is demonstrated with input/output examples. The document covers basic programming concepts in C# like conditional logic, arithmetic, and parameter passing to methods.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
148 views

Topic 1 Basics: Add Two Numbers

This document contains code examples for various basic C# exercises involving conditional statements and arithmetic operations. It includes methods to add and multiply numbers, convert between Celsius and Fahrenheit, perform elementary arithmetic operations, check if results are equal, use modulo operations, calculate cubes, swap numbers, find absolute values, check divisibility, verify if strings contain uppercase letters, and compare sums and products to a third value. Each method is demonstrated with input/output examples. The document covers basic programming concepts in C# like conditional logic, arithmetic, and parameter passing to methods.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 57

C# Exercises

TOPIC 1
Basics
Add two numbers
Given three numbers, write a method that adds two first ones and multiplies them by a
third one.
Expected Input and Output
AddAndMultiply(2, 4, 5) → 30
using System;

namespace CSharpExercises.Basics
{
class AddAndMultiplyTask
{
public static double AddAndMultiply(double a, double b, double c)
{
return (a + b) * c;
}

public static void Main()


{
Console.WriteLine(AddAndMultiply(3, 6, 35)); // 315
Console.WriteLine(AddAndMultiply(-12, 5, 17)); // -119
Console.WriteLine(AddAndMultiply(-40, 50, 60)); // 600
Console.WriteLine(AddAndMultiply(1.7, 9.9, 0.01)); // 0.116
}
}
}

Celsius to Fahrenheit
Given a temperature in Celsius degrees, write a method that converts it to Fahrenheit
degrees. Remember that temperature below -271.15°C (absolute zero) does not exist!
Expected Input and Output
CtoF(0) → "T = 32F"
CtoF(100) → "T = 212F"
CtoF(-300) → "Temperature below absolute zero!"
using System;

namespace CSharpExercises.Basics
{
class CtoFTask
{
public static string CtoF(double celsius)
{
double fahrenheit;

if (celsius < -273.15)


return "Temperature below absolute zero!";

fahrenheit = celsius * 1.8 + 32;


1
C# Exercises

return $"T = {fahrenheit}F";


}

public static void Main()


{
Console.WriteLine(CtoF(0)); // T = 32F
Console.WriteLine(CtoF(-300)); // Temperature below absolute zero!
Console.WriteLine(CtoF(28.5)); // T = 83.3F
}
}
}

Elementary operations
Given two integers, write a method that returns results of their elementary arithmetic
operations: addition, substraction, multiplication, division. Remember that you can't
divide any number by 0!
Expected Input and Output
ElementaryOperations(3, 8) → 11, -5, 24, 0.375
using System;

namespace CSharpExercises.Basics
{
class ElementaryOperationsTask
{
public static string ElementaryOperations(int a, int b)
{
int addition = a + b;
int substraction = a - b;
int multiplication = a * b;
double division;

if (b != 0)
division = a / (double)b;
else // assume that division by 0 returns 0
division = 0;

return String.Format($"a + b = {addition}, a - b = {substraction}, a * b =


{multiplication}, a / b = {division}");
}

public static void Main()


{
Console.WriteLine(ElementaryOperations(36, 15));
// a + b = 51, a - b = 21, a * b = 540, a / b = 2.4
Console.WriteLine(ElementaryOperations(-375, 25));
// a + b = -350, a - b = -400, a * b = -9375, a / b = -15
}
}
}

2
C# Exercises
Is result the same
Given two different arithmetic operations (addition, substraction, multiplication,
division), write a method that checks if they return the same result.
Expected Input and Output
IsResultTheSame(2+2, 2*2) → true
IsResultTheSame(9/3, 16-1) → false
using System;

namespace CSharpExercises.Basics
{
class IsResultTheSameTask
{
public static bool IsResultTheSame(double a, double b)
{
return a == b;
}

public static void Main()


{
Console.WriteLine(IsResultTheSame(3 * 3, 18 / 2)); // True
Console.WriteLine(IsResultTheSame(3 + 7, 12 - 8)); // False
Console.WriteLine(IsResultTheSame(3 * 7 * 8, 256 / 2 / 3)); // False
}
}
}

Modulo operations
Given three integers, write a method that returns first number divided modulo by second
one and these divided modulo by third one.
Expected Input and Output
ModuloOperations(8, 5, 2) → 1
using System;

namespace CSharpExercises.Basics
{
class ModuloOperationsTask
{
public static int ModuloOperations(int a, int b, int c)
{
return a % b % c;
}

public static void Main()


{
Console.WriteLine(ModuloOperations(542, 28, 7)); // 3
Console.WriteLine(ModuloOperations(33, 10, 2)); // 1
Console.WriteLine(ModuloOperations(2634, 892, 55)); // 25
}
}
}

3
C# Exercises
The cube of
Given a number, write a method that returns its cube.
Expected Input and Output
TheCubeOf(2) → 8
TheCubeOf(-5.5) → -166.375
using System;

namespace CSharpExercises.Basics
{
class TheCubeOfTask
{
public static double TheCubeOf(double num)
{
return num * num * num;
}

public static void Main()


{
Console.WriteLine(TheCubeOf(15)); // 3375
Console.WriteLine(TheCubeOf(0.25)); // 0.015625
Console.WriteLine(TheCubeOf(-12)); // -1728
Console.WriteLine(TheCubeOf(-0.1)); // -0.001
}
}
}

Swap two numbers


Given two integers, write a method that swaps them using temporary variable.
Expected Input and Output
SwapTwoNumbers(87, 45) → "Before: a = 87, b = 45; After: a = 45, b = 87"
SwapTwoNumbers(-13, 2) → "Before: a = -13, b = 2; After: a = 2, b = -13"
using System;

namespace CSharpExercises.Basics
{
class SwapTwoNumbersTask
{
public static string SwapTwoNumbers(int a, int b)
{
string before = $"Before: a = {a}, b = {b}; ";
int temp;

temp = b;
b = a;
a = temp;

string after = $"After: a = {a}, b = {b}";


return before + after;
}

public static void Main()


{
4
C# Exercises
Console.WriteLine(SwapTwoNumbers(23, 15));
// Before: a = 23, b = 15; After: a = 15, b = 23
Console.WriteLine(SwapTwoNumbers(-123, 999));
// Before: a = -123, b = 999; After: a = 999, b = -123
Console.WriteLine(SwapTwoNumbers(0, 333));
// Before: a = 0, b = 333; After: a = 333, b = 0
}
}
}

TOPIC 2
Conditional statements
Absolute value
Given an integer, write a method that returns its absolute value.
Expected Input and Output
AbsoluteValue(6832) → 6832
AbsoluteValue(-392) → 392
using System;

namespace CSharpExercises.Conditional_statements
{
class AbsoluteValueTask
{
static int AbsoluteValue(int number)
{
return number >= 0 ? number : number * -1;
}

static void Main(string[] args)


{
Console.WriteLine(AbsoluteValue(-690543)); // 690543
Console.WriteLine(AbsoluteValue(2744)); // 2744
Console.WriteLine(AbsoluteValue(0)); // 0
Console.WriteLine(AbsoluteValue(-23)); // 23
}
}
}

5
C# Exercises
Divisible by 2 or 3
Given two integers, write a method that returns their multiplication if they are both
divisible by 2 or 3, otherwise returns their sum.
Expected Input and Output
DivisibleBy2Or3(15, 30) → 450
DivisibleBy2Or3(2, 90) → 180
DivisibleBy2Or3(7, 12) → 19
using System;

namespace CSharpExercises.Conditional_statements
{
class DivisibleBy2Or3Task
{
static int DivisibleBy2Or3(int a, int b)
{
return (a % 2 == 0 && b % 2 == 0 || a % 3 == 0 && b % 3 == 0) ? a * b : a
+ b;
}

static void Main(string[] args)


{
Console.WriteLine(DivisibleBy2Or3(2, 18)); // 36
Console.WriteLine(DivisibleBy2Or3(7, 0)); // 7
Console.WriteLine(DivisibleBy2Or3(33, 9)); // 297
Console.WriteLine(DivisibleBy2Or3(-72, 54)); // -3888
Console.WriteLine(DivisibleBy2Or3(24, -80)); // -1920
Console.WriteLine(DivisibleBy2Or3(444, 0)); // 0
}
}
}

If consists of uppercase letters


Given a 3 characters long string, write a method that checks if it consists only of
uppercase letters.
Expected Input and Output
IfConsistsOfUppercaseLetters("xyz") → false
IfConsistsOfUppercaseLetters("DOG") → true
IfConsistsOfUppercaseLetters("L9#") → false
using System;

namespace CSharpExercises
{
class Program
{
static bool IfConsistsOfUppercaseLetters(string str)
{
return (str[0] >= 65 && str[1] >= 65 && str[2] >= 65) && (str[0] <= 90 &&
str[1] <= 90 && str[2] <= 90);

6
C# Exercises
}

static void Main(string[] args)


{
Console.WriteLine(IfConsistsOfUppercaseLetters("drY")); // False
Console.WriteLine(IfConsistsOfUppercaseLetters("LOL")); // True
Console.WriteLine(IfConsistsOfUppercaseLetters("N0t")); // False
Console.WriteLine(IfConsistsOfUppercaseLetters("$1r")); // False
}
}
}

If greater than third one


Given an array of 3 integers, write a method that checks if multiplication or sum of two
first numbers is greater than third one.
Expected Input and Output
IfGreaterThanThirdOne([2, 7, 12]) → true
IfGreaterThanThirdOne([-5, -8, 50]) → false
using System;

namespace CSharpExercises.Conditional_statements
{
class IfGreaterThanThirdOneTask
{
static bool IfGreaterThanThirdOne(int[] arr)
{
return arr[0] + arr[1] > arr[2] || arr[0] * arr[1] > arr[2];
}

static void Main(string[] args)


{
Console.WriteLine(IfGreaterThanThirdOne(new int[] { 2, 8, 20 }));
// False
Console.WriteLine(IfGreaterThanThirdOne(new int[] { 10, 5, 22 }));
// True
Console.WriteLine(IfGreaterThanThirdOne(new int[] { -15, -25, 100 }));
// True
Console.WriteLine(IfGreaterThanThirdOne(new int[] { 11, 15, 166 }));
// False
}
}
}

7
C# Exercises
If number is even
Given an integer, write a method that checks if it is even.
Expected Input and Output
IfNumberIsEven(721) → false
IfNumberIsEven(1248) → true
using System;

namespace CSharpExercises.Loops
{
class IfNumberIsEvenTask
{
static bool IfNumberIsEven(int num)
{
return num % 2 == 0;
}

static void Main(string[] args)


{
Console.WriteLine(IfNumberIsEven(8)); // True
Console.WriteLine(IfNumberIsEven(54749)); // False
Console.WriteLine(IfNumberIsEven(-43234670)); // True
Console.WriteLine(IfNumberIsEven(0)); // True
Console.WriteLine(IfNumberIsEven(-950541901)); // False
Console.WriteLine(IfNumberIsEven(2140872324)); // True
}
}
}

If sorted ascending
Given an array of three integers, write a method that checks if they are sorted in
ascending order.
Expected Input and Output
IfSortedAscending([3, 7, 10])→ true
IfSortedAscending([74, 62, 99])→ false
using System;

namespace CSharpExercises.Conditional_statements
{
class IfSortedAscendingTask
{
static bool IfSortedAscending(int[] arr)
{
return arr[0] <= arr[1] && arr[1] <= arr[2];
}

static void Main(string[] args)


{
Console.WriteLine(IfSortedAscending(new int[] { 3, 6, 9 })); // True
Console.WriteLine(IfSortedAscending(new int[] { 34, 17, 90 })); // False
Console.WriteLine(IfSortedAscending(new int[] { -50, -24, -1 })); // True
}

8
C# Exercises
}
}

If has neighbour
Given three letter long string, write a method that checks if at least one neighbour of
middle letter is its neighbour in the alphabet.
Expected Input and Output
IsLonelyIsland("XYZ") → True
IsLonelyIsland("GWK") → False
using System;

namespace CSharpExercises.Conditional_statements
{
class IfHasNeighbourTask
{
public static bool IfHasNeighbour(string word)
{
return word[0] == word[1] - 1 || word[0] == word[1] + 1 || word[2] ==
word[1] - 1 || word[2] == word[1] + 1;
}

public static void Main()


{
Console.WriteLine(IfHasNeighbour("DCA")); // True
Console.WriteLine(IfHasNeighbour("PRT")); // False
}
}
}

Positive, negative or zero


Given a number, write a method that checks if it is positive, negative or zero.
Expected Input and Output
PositiveNegativeOrZero(5.24) → positive
PositiveNegativeOrZero(0.0) → zero
PositiveNegativeOrZero(-994.53) → negative
using System;

namespace CSharpExercises.Conditional_statements
{
class PositiveNegativeOrZeroTask
{
static string PositiveNegativeOrZero(double num)
{
if (num > 0.0)
return "Positive";
else if (num < 0.0)
return "Negative";

return "Zero";

9
C# Exercises
}

static void Main(string[] args)


{
Console.WriteLine(PositiveNegativeOrZero(3.14)); // Positive
Console.WriteLine(PositiveNegativeOrZero(0.0)); // Zero
Console.WriteLine(PositiveNegativeOrZero(-200.003)); // Negative
}
}
}

If year is leap
Given a year as integer, write a method that checks if year is leap.
Expected Input and Output
IfYearIsLeap(2016) → true
IfYearIsLeap(2018) → false
using System;

namespace CSharpExercises.Conditional_statements
{
class IfYearIsLeapTask
{
static bool IfYearIsLeap(int year)
{
return (year % 4 == 0 && year % 100 != 0) || year % 400 == 0;
}

static void Main(string[] args)


{
Console.WriteLine(IfYearIsLeap(2020)); // True
Console.WriteLine(IfYearIsLeap(1719)); // False
Console.WriteLine(IfYearIsLeap(2000)); // True
Console.WriteLine(IfYearIsLeap(1412)); // True
Console.WriteLine(IfYearIsLeap(1582)); // False
}
}
}

10
C# Exercises
If number contains 3
Write a method that checks if given number (positive integer) contains digit 3. Do not
convert number to other type. Do not use built-in functions like Contains(), StartsWith(),
etc.
Expected Input and Output
IfNumberContains3(7201432) → true
IfNumberContains3(87501) → false
using System;

namespace CSharpExercises.Conditional_statements
{
class IfNumberContains3Task
{
public static bool IfNumberContains3(int number)
{
while (number > 0)
{
if (number % 10 == 3)
return true;

number /= 10;
}

return false;
}

public static void Main()


{
Console.WriteLine(IfNumberContains3(5384562)); // true
Console.WriteLine(IfNumberContains3(0)); // false
Console.WriteLine(IfNumberContains3(390462)); // true
}
}
}

11
C# Exercises
TOPIC 3
Loops
Multiplication table
Write a method that prints 10 by 10 multiplication table. Remember about readibility
(spaces in the right place).
Expected Input and Output
1 2 3 4 5 6 7 8 9 10
2 4 6 8 10 12 14 16 18 20
3 6 9 12 15 18 21 24 27 30
4 8 12 16 20 24 28 32 36 40
5 10 15 20 25 30 35 40 45 50
6 12 18 24 30 36 42 48 54 60
7 14 21 28 35 42 49 56 63 70
8 16 24 32 40 48 56 64 72 80
9 18 27 36 45 54 63 72 81 90
10 20 30 40 50 60 70 80 90 100
using System;

namespace CSharpExercises.Loops
{
class MultiplicationTableTask
{
static void MultiplicationTable()
{
for (int i = 1; i <= 10; i++)
{
for (int j = 1; j <= 10; j++)
{
if (i == 1)
{
if (i * j < 10)
Console.Write($" {i * j} ");
else
Console.Write($"{i * j} ");
}
else if (i > 1 && i < 10)
{
if (i * j < 10)
Console.Write($" {i * j} ");
else
Console.Write($"{i * j} ");
}
else
Console.Write($"{i * j} ");
}
Console.WriteLine();
}
}

static void Main(string[] args)


{
MultiplicationTable();
12
C# Exercises
// 1 2 3 4 5 6 7 8 9 10
// 2 4 6 8 10 12 14 16 18 20
// 3 6 9 12 15 18 21 24 27 30
// 4 8 12 16 20 24 28 32 36 40
// 5 10 15 20 25 30 35 40 45 50
// 6 12 18 24 30 36 42 48 54 60
// 7 14 21 28 35 42 49 56 63 70
// 8 16 24 32 40 48 56 64 72 80
// 9 18 27 36 45 54 63 72 81 90
//10 20 30 40 50 60 70 80 90 100
}
}
}

Fractions sum
Given an integer n, write a method that returns sum of series 1 + (½)² + (⅓)² + ... + (1⁄n)².
Do not use library function!
Expected Input and Output
FractionsSum(3) → 1.36111111111111
FractionsSum(5) → 1.46361111111111
using System;

namespace CSharpExercises.Loops
{
class FractionsSumTask
{
static double FractionsSum(int num)
{
double sum = 0.0;
for (int i = 1; i <= num; i++)
sum += (1 / (double)(i * i));

return sum;
}

static void Main(string[] args)


{
Console.WriteLine(FractionsSum(2)); // 1.25
Console.WriteLine(FractionsSum(7)); // 1.5117970521542
Console.WriteLine(FractionsSum(10)); // 1.54976773116654
}
}
}

13
C# Exercises
Sort array ascending
Given an array of integers, write a method that returns sorted array in ascending order.
Expected Input and Output
SortArrayAscending([9, 5, 7, 2, 1, 8]) → [1, 2, 5, 7, 8, 9]
using System;

namespace CSharpExercises.Loops
{
class SortArrayAscendingTask
{
static int[] SortArrayAscending(int[] arr)
{
int temp;
for (int i = 0; i < arr.Length - 1; i++)
{
for (int j = 0; j < arr.Length - 1; j++)
{
if (arr[j] > arr[j + 1])
{
temp = arr[j + 1];
arr[j + 1] = arr[j];
arr[j] = temp;
}
}
}

return arr;
}

static void Main(string[] args)


{
int[] sortedArr = SortArrayAscending(new int[] { 0, -23, 9, 18, -51, 1,
90, 57, -1, 25 });

foreach (var s in sortedArr)


Console.Write($"{s} "); // -51 -23 -1 0 1 9 18 25 57 90
}
}
}

14
C# Exercises
The biggest number
Given an array of integers, write a method that returns the biggest number in this
array.
Expected Input and Output
TheBiggestNumber([190, 291, 145, 209, 280, 300]) → 291
TheBiggestNumber([-9, -2, -7, -8, -4]) → -2
using System;

namespace CSharpExercises.Loops
{
class TheBiggestNumberTask
{
static int TheBiggestNumber(int[] numArr)
{
int theBiggest = numArr[0];

for (int i = 1; i < numArr.Length; i++)


if (numArr[i] > theBiggest)
theBiggest = numArr[i];

return theBiggest;
}

static void Main(string[] args)


{
Console.WriteLine(TheBiggestNumber(new int[] { 9, 4, 8, 1, 0, 2 }));
// 9
Console.WriteLine(TheBiggestNumber(new int[] { -34, -54, -7, -40, -123, -
99 }));
// -7
Console.WriteLine(TheBiggestNumber(new int[] { 1009, 998, 1090, 3000,
2934, 4888 }));
// 4888
}
}
}

15
C# Exercises
Two 7s next to each other
Given an array of positive digits, write a method that returns number of times that two
7's are next to each other in an array.
Expected Input and Output
Two7sNextToEachOther([ 8, 2, 5, 7, 9, 0, 7, 7, 3, 1]) → 1
Two7sNextToEachOther([ 9, 4, 5, 3, 7, 7, 7, 3, 2, 5, 7, 7 ]) → 3
using System;

namespace CSharpExercises.Loops
{
class Two7sNextToEachOtherTask
{
static int Two7sNextToEachOther(int[] arr)
{
int adjacent7s = 0;
for (int i = 0; i < arr.Length - 1; i++)
if (arr[i] == 7 && arr[i + 1] == 7)
adjacent7s++;

return adjacent7s;
}

static void Main(string[] args)


{
Console.WriteLine(Two7sNextToEachOther(new int[] { 7, 7, 8, 4, 3, 7, 2, 1,
0, 7 }));
// 1
Console.WriteLine(Two7sNextToEachOther(new int[] { 4, 7, 8, 2, 0, 5, 2, 7,
5, 8 }));
// 0
Console.WriteLine(Two7sNextToEachOther(new int[] { 7, 7, 7, 0, 2, 6, 4, 8,
6, 5, 2, 7, 7 }));
// 3
}
}
}

16
C# Exercises
Three increasing adjacent
Given an array of numbers, write a method that checks if there are three adjacent
numbers where second is greater by 1 than the first one and third is greater by 1 than
the second one.
Expected Input and Output
ThreeIncreasingAdjacent([45, 23, 44, 68, 65, 70, 80, 81, 82 ]) → True
ThreeIncreasingAdjacent([7, 3, 5, 8, 9, 3, 1, 4 ]) → False
using System;

namespace CSharpExercises.Loops
{
class ThreeIncreasingAdjacentTask
{
static bool ThreeIncreasingAdjacent(int[] arr)
{
bool found = false;
for (int i = 1; i <= arr.Length - 2; i++)
if (arr[i - 1] + 1 == arr[i] && arr[i + 1] - 1 == arr[i])
found = true;

return found;
}

static void Main(string[] args)


{
Console.WriteLine(ThreeIncreasingAdjacent(new int[] { 7, 8, 9, 2, 4, 5, 0
}));
// True
Console.WriteLine(ThreeIncreasingAdjacent(new int[] { -9, 0, -1, -6, -5, -
4, -8, 0 }));
// True
Console.WriteLine(ThreeIncreasingAdjacent(new int[] { 15, 17, 14, 11, 18,
19, 16, 16 }));
// False
}
}
}

17
C# Exercises
Return even numbers
Write a method that returns a string of even numbers greater than 0 and less than 100.
Expected Input and Output
ReturnEvenNumbers() → "2 4 6 8 10 12 14 16 18 20 22 24 26 28 30 32 34 36 38 40
42 44 46 48 50 52 54 56 58 60 62 64 66 68 70 72 74 76 78 80 82 84 86 88 90 92 94 96
98"
using System;

namespace CSharpExercises.Loops
{
class ReturnEvenNumbersTask
{
static string ReturnEvenNumbers()
{
string str = string.Empty;
for (int i = 1; i < 100; i++)
if (i % 2 == 0)
str += i + " ";

return str;
}

static void Main(string[] args)


{
Console.WriteLine(ReturnEvenNumbers());
// 2 4 6 8 10 12 14 16 18 20 22 24 26 28 30 32 34 36 38 40 42 44 46 48 50
52 54 56 58 60 62 64 66 68 70 72 74 76 78 80 82 84 86 88 90 92 94 96 98
}
}
}

Sieve of Eratosthenes
Given an integer n (n>2), write a method that returns prime numbers from range [2, n].
Expected Input and Output
SieveOfEratosthenes(30) → [2, 3, 5, 7, 11, 13, 17, 19, 23, 29]
using System;

namespace CSharpExercises.Loops
{
class SieveOfEratosthenesTask
{
static bool[] SieveOfEratosthenes(int n)
{
bool[] array = new bool[n];

for (int i = 2; i < n; i++)


array[i] = true;

for (int j = 2; j * j <= n; j++)


if (array[j] == true)
for (int k = j * j; k < n; k += j)
array[k] = false;

18
C# Exercises
return array;
}

static void Main(string[] args)


{
var arrayOfPrimes = SieveOfEratosthenes(100);
for (int i = 0; i < arrayOfPrimes.Length; i++)
if (arrayOfPrimes[i] != false)
Console.Write($"{i} ");
// 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97
}
}
}

Draw hourglass
Write a method that draws hourglass shape like below.
Expected Input and Output
DrawHourglass() →

***********
*********
*******
*****
***
*
***
*****
*******
*********
***********
using System;

namespace CSharpExercises.Loops
{
class DrawHourglassTask
{
static void DrawHourglass()
{
for (var i = 0; i <= 10; i++)
{
for (var j = 0; j < (i <= 5 ? i : 10 - i); j++)
Console.Write(" ");
for (var k = i <= 5 ? i : 10 - i; k <= (i <= 5 ? 10 - i : i); k++)
Console.Write("*");
for (var m = 10 - i; m < 10; m++)
Console.Write(" ");

Console.WriteLine();
}
}

static void Main(string[] args)

19
C# Exercises
{
DrawHourglass();
}
}
}

Draw parallelogram
Write a method that draws parallelogram shape like below.
Expected Input and Output
DrawParallelogram() →
***************
***************
***************
***************
***************
using System;

namespace CSharpExercises.Loops
{
class DrawParallelogramTask
{
static void DrawParallelogram()
{
for (var j = 0; j < 5; j++)
{
for (var k = 0; k < 5 - j; k++)
Console.Write(" ");
for (var m = 0; m < 15; m++)
Console.Write("*");

Console.WriteLine();
}
}

static void Main(string[] args)


{
DrawParallelogram();
}
}
}

Draw Christmas tree


Write a method that draws Christmas tree shape like below.
Expected Input and Output
DrawChristmasTree() →
*
***
*****

20
C# Exercises
*******
*
***
*****
*******
*
***
*****
*******
using System;

namespace CSharpExercises.Loops
{
class DrawChristmasTreeTask
{
static void DrawChristmasTree()
{
for (var i = 0; i < 3; i++)
{
for (var j = 0; j < 7; j += 2)
{
for (var k = 0; k < (7 - j) / 2; k++)
Console.Write(" ");
for (var m = 0; m <= j; m++)
Console.Write("*");
for (var n = (7 - j) / 2; n < 7; n++)
Console.Write(" ");

Console.WriteLine();
}
}
}

static void Main(string[] args)


{
DrawChristmasTree();
}
}
}

21
C# Exercises
Extract string
Given a string, write a method that returns substring from between two double hash
signs (#).
Expected Input and Output
ExtractString("##abc##def") → "abc"
ExtractString("12####78") → empty string
ExtractString("gar##d#en") → empty string
ExtractString("++##--##++") → "--"
using System;

namespace CSharpExercises.Loops
{
class ExtractStringTask
{
static string ExtractString(string word)
{
string extractedWord = string.Empty;
bool firstOccurrence = false;
bool secondOccurrence = false;

for (int i = 0; i <= word.Length - 1; i++)


{
if (word[i] == '#' && word[i + 1] == '#')
{
firstOccurrence = true;
for (int j = i + 2; j <= word.Length - 1; j++)
{
if (word[j] == '#' && word[j + 1] == '#')
{
secondOccurrence = true;
return extractedWord;
}
extractedWord += word[j];
}
}
}

return string.Empty;
}

static void Main(string[] args)


{
Console.WriteLine(ExtractString("kFp##jFoRj##pL"));
// jFoRj
Console.WriteLine(ExtractString("abc##def"));
// /empty string/
Console.WriteLine(ExtractString("##123456789##"));
// 123456789
Console.WriteLine(ExtractString("no####thing"));
// /empty string/
Console.WriteLine(ExtractString("++##--##++"));
// /--/
}
}
}

22
C# Exercises
Full sequence of letters
Given a string of two letters, where first one occurs before the second in the alphabet,
write a method that returns full sequence of letters starting from first and ending at the
second one.
Expected Input and Output
FullSequenceOfLetters("ds") → "defghijklmnopqrs"
FullSequenceOfLetters("or") → "opqr"
using System;

namespace CSharpExercises.Loops
{
class FullSequenceOfLettersTask
{
static string FullSequenceOfLetters(string word)
{
string fullSequence = string.Empty;
for (int i = word[0], j = 0; i <= word[1]; i++, j++)
fullSequence += (char)(word[0] + j);

return fullSequence;
}

static void Main(string[] args)


{
Console.WriteLine(FullSequenceOfLetters("bg"));
// bcdefg
Console.WriteLine(FullSequenceOfLetters("xy"));
// xy
Console.WriteLine(FullSequenceOfLetters("az"));
// abcdefghijklmnopqrstuvwxyz
}
}
}

Longest strictly increasing sequence


Given an array of integers, write a method that returns value of the longest strictly
increasing sequence of numbers.
Expected Input and Output
LongestStrictlyIncreasingSequence([0, 3, 4, 5, 6, 4, 9]) → 3
LongestStrictlyIncreasingSequence([7, 7, 7, 7, 7]) → 0
using System;

namespace CSharpExercises.Loops
{
class LongestStrictlyIncreasingSequenceTask
{
static int LongestStrictlyIncreasingSequence(int[] array)
{
int tempLongest = 0;
int longest = 0;

23
C# Exercises
for (int i = 0; i < array.Length - 1; i++)
{
if (array[i + 1] > array[i])
tempLongest++;
else
tempLongest = 0;

if (tempLongest > longest)


longest = tempLongest;
}

return longest;
}

static void Main(string[] args)


{
Console.WriteLine(LongestStrictlyIncreasingSequence(new int[] { 4, 7, 2,
6, 4, 5, 6, 7, 8, 0, 7, 1, 2, 3 }));
// 4
Console.WriteLine(LongestStrictlyIncreasingSequence(new int[] { 1, 0, 1,
0, 1, 0, 1, 0, 1, 0 }));
// 1
Console.WriteLine(LongestStrictlyIncreasingSequence(new int[] { 2, 3, 4,
5, 6, 7, 8 }));
// 6
Console.WriteLine(LongestStrictlyIncreasingSequence(new int[] { 1, 1, 1,
1, 1, }));
// 0
}
}
}

Bits to number
Write a method that takes non-empty string of bits as an argument and returns number
as integer.
Expected Input and Output
BitsToNumber("1") → 1
BitsToNumber("100010") → 34
using System;

namespace CSharpExercises
{
class BitsToNumberTask
{
static int BitsToNumber(string bits)
{
var number = 0;

for (var i = 0; i < bits.Length; i++)


number += (int)(char.GetNumericValue(bits[i]) * Math.Pow(2,
bits.Length - i - 1));

return number;
}

static void Main(string[] args)


{

24
C# Exercises
Console.WriteLine(BitsToNumber("0")); // 0
Console.WriteLine(BitsToNumber("00001011000001")); // 705
Console.WriteLine(BitsToNumber("10001110001010100")); // 72288
}
}
}

Digits sum
Given a non-negative number, write a method that returns sum of its digits.
Expected Input and Output
DigitsSum(5434) → 16
DigitsSum(904861) → 28
using System;

namespace CSharpExercises
{
class DigitsSumTask
{
public static int DigitsSum(uint number)
{
int sum = 0;
int i = 10;
int j = 1;

while (number / j >= 1)


{
sum += (int)(number % i / j);

i *= 10;
j *= 10;
}

return sum;
}

static void Main(string[] args)


{
Console.WriteLine(DigitsSum(5)); // 5
Console.WriteLine(DigitsSum(1029584739)); // 48
Console.WriteLine(DigitsSum(99999999)); // 72
}
}
}

25
C# Exercises
Sum and average
Given two integers n and m (n <= m), write a method that returns sum of all integers
and average from range [n, m].
Expected Input and Output
SumAndAverage(11, 66) → "Sum: 2156, Average: 38.5"
SumAndAverage(-10, 0) → "Sum: -55, Average: -5"
using System;

namespace CSharpExercises.Loops
{
class SumAndAverageTask
{
static string SumAndAverage(int lowest, int highest)
{
int sum = 0;
int range = 0;
double average = 0.0;
for (int i = lowest; i <= highest; i++)
{
sum += i;
range++;
}

average = sum / (double)range;

return string.Format($"Sum: {sum}, Average: {average}");


}

static void Main(string[] args)


{
Console.WriteLine(SumAndAverage(20, 21)); // Sum: 41 Average: 20,5
Console.WriteLine(SumAndAverage(55, 55)); // Sum: 55 Average: 55
Console.WriteLine(SumAndAverage(0, 100)); // Sum: 5050 Average: 50
}
}
}

Sum double only


Given an array of objects, write a method that returns sum of objects of double type.
Expected Input and Output
SumDoubleOnly(["abc", 5.6, 14, 'c', true, 'x', false, 567, 2.22]) → 7.82
using System;

namespace CSharpExercises.Loops
{
class SumDoubleOnlyTask
{
static double SumDoubleOnly(object[] obj)
{
double sum = 0.0;
for (int i = 0; i < obj.Length; i++)
if (obj[i] is double)

26
C# Exercises
sum += (double)obj[i];

return sum;
}

static void Main(string[] args)


{
Console.WriteLine(SumDoubleOnly(new object[] { 8.9, "dog", 6, 'c', null,
15.99, 745, true }));
// 24.89
}
}
}

Draw triangle
Write a method that draws triangle shape like below.
Expected Input and Output
DrawTriangle() →
*
**
***
****
*****
******
*******
********
*********
**********
using System;

namespace CSharpExercises.Loops
{
class DrawTriangleTask
{
static void DrawTriangle()
{
for (int i = 0; i < 10; i++)
{
for (int j = 10; j > i; j--)
Console.Write(" ");
for (int k = 10; k >= 10 - i; k--)
Console.Write("*");

Console.WriteLine();
}
}

static void Main(string[] args)


{
DrawTriangle();
}
}
}

27
C# Exercises
To the power of
Given two integers, write a method that returns first number raised to the power of
second one.
Expected Input and Output
ToThePowerOf(-2, 3) → -8
ToThePowerOf(5, 5) → 3125
using System;

namespace CSharpExercises.Loops
{
class ToThePowerOfTask
{
static double ToThePowerOf(int b, int exp)
{
double result = 1;
if (exp == 0)
return 1;

for (int i = 1; exp > 0 ? i <= exp : i <= exp * (-1); i++)
result *= b;

return exp > 0 ? result : 1 / result;


}

static void Main(string[] args)


{
Console.WriteLine(ToThePowerOf(10, 0)); // 1
Console.WriteLine(ToThePowerOf(5, -2)); // 0.04
Console.WriteLine(ToThePowerOf(8, -8)); // 5.96046447753906E-08
Console.WriteLine(ToThePowerOf(0, 5)); // 0
}
}
}

Letters balance
Given a string, write a method that checks if there are exactly the same letters on the
left side and right side of the string. Assume string length is even and letters don't
repeat on each side.
Expected Input and Output
LettersBalance("fgvgvf") → true
LettersBalance("lampsmpser") → false
using System;

namespace CSharpExercises.Loops
{
class LettersBalanceTask
{
static bool LettersBalance(string word)
{
bool isBalanced;

28
C# Exercises
for (int i = 0; i < word.Length / 2; i++)
{
isBalanced = false;
for (int j = word.Length - 1; j >= word.Length / 2; j--)
if (word[i] == word[j])
isBalanced = true;

if (!isBalanced)
return false;
}

return true;
}

static void Main(string[] args)


{
Console.WriteLine(LettersBalance("kfdfdk")); // True
Console.WriteLine(LettersBalance("reyjer")); // False
Console.WriteLine(LettersBalance("wkxzcsazsckawx")); // True
Console.WriteLine(LettersBalance("pkmqsdedeskgqm")); // False
}
}
}

Replace two words


Given a string in which two words are separated by a char, write a method that
replaces these two words.
Expected Input and Output
ReplaceWords("abc_xyz", '_') → xyz_abc
ReplaceWords("trolling.master", '.') → master.trolling
using System;

namespace CSharpExercises.Loops
{
class ReplaceWordsTask
{
public static string ReplaceWords(string word, char ch)
{
string firstWord = string.Empty;
string secondWord = string.Empty;

for (int i = 0; i <= word.Length - 1; i++)


{
if (word[i] != ch)
secondWord += word[i];
else
{
for (int j = i + 1; j <= word.Length - 1; j++)
firstWord += word[j];
break;
}
}

return firstWord + ch + secondWord;


}

static void Main(string[] args)

29
C# Exercises
{
Console.WriteLine(ReplaceWords("dog_octopus", '_'));
// octopus_dog
Console.WriteLine(ReplaceWords("a.b", '.'));
// b.a
Console.WriteLine(ReplaceWords("good very", ' '));
// very good
}
}
}

Digital root
Given a non-negative number, write a method that returns its digital root. From
Wikipedia - digital root is a value obtained by an iterative process of summing digits,
on each iteration using the result from the previous iteration to compute a digit sum.
The process continues until a single-digit number is reached.
Expected Input and Output
DigitalRoot(83) → 2
DigitalRoot(40002938) → 8
using System;

namespace CSharpExercises.Loops
{
class DigitalRootTask
{
public static int DigitalRoot(uint number)
{
while (number / 10 != 0)
{
uint sum = 0;
int i = 10;
int j = 1;

while (number / j >= 1)


{
sum += (uint)(number % i / j);

i *= 10;
j *= 10;
}

number = sum;
}

return (int)number;
}

static void Main(string[] args)


{
Console.WriteLine(DigitalRoot(5)); // 5
Console.WriteLine(DigitalRoot(1029584739)); // 3
Console.WriteLine(DigitalRoot(99999999)); // 9
}
}
}

30
C# Exercises
TOPIC 4
Strings
Check brackets sequence
Given a sequence of brackets, write a method that checks if it has the same number of
opening and closing brackets.
Expected Input and Output
CheckBracketsSequence("((()))") → true
CheckBracketsSequence("()(())(") → false
CheckBracketsSequence(")") → false
using System;

namespace CSharpExercises.Strings
{
class CheckBracketsSequenceTask
{
static bool CheckBracketsSequence(string sequence)
{
int check = 0;

for (int i = 0; i < sequence.Length; i++)


check = sequence[i] == '(' ? ++check : --check;

return check == 0;
}

static void Main(string[] args)


{
Console.WriteLine(CheckBracketsSequence("((()()()))"));
// True
Console.WriteLine(CheckBracketsSequence(")"));
// False
Console.WriteLine(CheckBracketsSequence(")(())("));
// True
Console.WriteLine(CheckBracketsSequence("()())()"));
// False
Console.WriteLine(CheckBracketsSequence("((()(((()())))())())"));
// True
}
}
}

31
C# Exercises
Add separator
Given a string and a separator, write a method that adds separator between each
adjacent characters in a string.
Expected Input and Output
AddSeparator("ABCD", "^") → "A^B^C^D^"
AddSeparator("chocolate", "-") → "c-h-o-c-o-l-a-t-e"
using System;

namespace CSharpExercises.Strings
{
class AddSeparatorTask
{
static string AddSeparator(string word, string separator)
{
string separatedWord = string.Empty;

for (int i = 0; i < word.Length; i++)


separatedWord += i < word.Length - 1 ? word[i] + separator :
word[i].ToString();

return separatedWord;
}

static void Main(string[] args)


{
Console.WriteLine(AddSeparator("computer", "_")); // c_o_m_p_u_t_e_r
Console.WriteLine(AddSeparator("$*(#", " ")); // $ * ( #
Console.WriteLine(AddSeparator("AC", "B")); // ABC
Console.WriteLine(AddSeparator("octopus", "X")); // oXcXtXoXpXuXs
}
}
}

Is palindrome
Given a string, write a method that checks if it is a palindrome (is read the same
backward as forward). Assume that string may consist only of lower-case letters.
Expected Input and Output
IsPalindrome("eye") → true
IsPalindrome("home") → false
using System;

namespace CSharpExercises.Strings
{
class IsPalindromeTask
{
static bool IsPalindrome(string str)
{
for (int i = 0; i < str.Length / 2; i++)
{
if (str[i] != str[str.Length - 1 - i])
{

32
C# Exercises
return false;
}
}

return true;
}

static void Main(string[] args)


{
Console.WriteLine(IsPalindrome("madam")); // True
Console.WriteLine(IsPalindrome("123454321")); // True
Console.WriteLine(IsPalindrome("apple")); // False
Console.WriteLine(IsPalindrome("Never Odd Or Even")); // True
Console.WriteLine(IsPalindrome("Curabitur vel est diam")); // False
Console.WriteLine(IsPalindrome("x")); // True
}
}
}

Length of string
Given a string, write a method that returns its length. Do not use library methods!
Expected Input and Output
LengthOfAString("computer") → 8
LengthOfAString("ice cream") → 9
using System;

namespace CSharpExercises.Strings
{
class LengthOfAStringTask
{
static int LengthOfAString(string str)
{
int length = 0;
foreach (char c in str)
{
length++;
}

return length;
}

static void Main(string[] args)


{
Console.WriteLine(LengthOfAString("Lorem ipsum dolor sit amet")); //26
Console.WriteLine(LengthOfAString(string.Empty)); //0
Console.WriteLine(LengthOfAString("conse12ctetur ")); //14
}
}
}

String in reverse order


Given a string, write a method that returns that string in reverse order.
Expected Input and Output

33
C# Exercises
StringInReverseOrder("qwerty") → "ytrewq"
StringInReverseOrder("oe93 kr") → "rk 39eo"
using System;

namespace CSharpExercises.Strings
{
class StringInReverseOrderTask
{
static string StringInReverseOrder(string str)
{
string reverseString = string.Empty;
for (int i = str.Length - 1; i >= 0; i--)
{
reverseString += str[i];
}

return reverseString;
}

static void Main(string[] args)


{
Console.WriteLine(StringInReverseOrder("Vivamus commodo quam at purus "));
// surup ta mauq odommoc sumaviV
Console.WriteLine(StringInReverseOrder("34 ( 9 9@*"));
// *@9 9 ( 43
Console.WriteLine(StringInReverseOrder("malesuada"));
// adauselam
}
}
}

Sum digits in string


Given a string, write a method which returns sum of all digits in that string. Assume
that string contains only single digits.
Expected Input and Output
SumDigitsInString("1q2w3e") → 6
SumDigitsInString("L0r3m.1p5um") → 9
SumDigitsInString("") → 0
using System;

namespace CSharpExercises.Strings
{
class SumDigitsInStringTask
{
static int SumDigitsInString(string str)
{
var sum = 0;

for (var i = 0; i < str.Length; i++)


if (char.IsDigit(str[i]))
sum += (int)char.GetNumericValue(str[i]);

return sum;
}
34
C# Exercises

public static void Main()


{
Console.WriteLine(SumDigitsInString("aaa5aa5aa5a5a")); // 20
Console.WriteLine(SumDigitsInString("10r3m1p5um")); // 10
Console.WriteLine(SumDigitsInString("tt")); // 0
}
}
}

Make uppercase
Given a string, write a method that returns new string in which every odd letter of the
word is uppercase. String may consist of one or more words.
Expected Input and Output
MakeUppercase("modem") → "MoDeM"
MakeUppercase("BookWorm") → "BoOkWoRm"
MakeUppercase("Aliquam dolor nisl?") → "AlIqUaM DoLoR NiSl?"
using System;

namespace CSharpExercises.Strings
{
class MakeUppercaseTask
{
public static string MakeUppercase(string word)
{
int letterIndex = 0;
string uppercaseWord = string.Empty;

for (int i = 0; i < word.Length; i++)


{
if (word[i] >= 'a' && word[i] <= 'z' && letterIndex % 2 == 0)
{
letterIndex++;
uppercaseWord += (char)(word[i] - 32);
}
else if (word[i] != ' ')
{
letterIndex++;
uppercaseWord += word[i];
}
else
{
letterIndex = 0;
uppercaseWord += word[i];
}
}
return uppercaseWord;
}

public static void Main()


{
Console.WriteLine(MakeUppercase("very short sentence."));
// VeRy ShOrT SeNtEnCe.
Console.WriteLine(MakeUppercase("motorcycle"));
// MoToRcYcLe
Console.WriteLine(MakeUppercase("Events And Delegates"));

35
C# Exercises
// EvEnTs AnD DeLeGaTeS
}
}
}

Mix two strings


Given two strings, write a method that returns one string made of two strings. First
letter of new string is first letter of first string, second letter of new string is first letter
of second string and so on.
Expected Input and Output
MixTwoStrings("aaa", "BBB") → "aBaBaB"
MixTwoStrings("good one", "111") → "g1o1o1d one"
using System;

namespace CSharpExercises.Strings
{
class MixTwoStringsTask
{
static string MixTwoStrings(string word1, string word2)
{
string mixedWord = string.Empty;

for (int i = 0; i < (word1.Length > word2.Length ? word1.Length :


word2.Length); i++)
{
if (i < word1.Length)
mixedWord += word1[i];
if (i < word2.Length)
mixedWord += word2[i];
}

return mixedWord;
}

static void Main(string[] args)


{
Console.WriteLine(MixTwoStrings("DoG", "ElEpHaNt"));
// DEolGEpHaNt
Console.WriteLine(MixTwoStrings("The tallest", "XXXXXXXXXX"));
// TXhXeX XtXaXlXlXeXsXt
}
}
}

36
C# Exercises
Number of words
Given a string, write a method that counts its number of words. Assume there are no
leading and trailing whitespaces and there is only single whitespace between two
consecutive words.
Expected Input and Output
NumberOfWords("This is sample sentence") → 4
NumberOfWords("OK") → 1
using System;

namespace CSharpExercises.Strings
{
class NumberOfWordsTask
{
static int NumberOfWords(string str)
{
int numberOfWords = 0;
for (int i = 1; i < str.Length; i++)
{
numberOfWords = (char.IsWhiteSpace(str[i]) ? numberOfWords + 1 :
numberOfWords);
}

return numberOfWords + 1;
}

static void Main(string[] args)


{
Console.WriteLine(NumberOfWords("Mauris consectetur urna sit amet risus
ultricies rutrum."));
// 8
Console.WriteLine(NumberOfWords("Quisque M"));
// 2
Console.WriteLine(NumberOfWords("Xor"));
// 1
}
}
}

Revert words order


Given a string, write a method that returns new string with reverted words order. Pay
attention to the punctuation at the end of the sentence (period).
Expected Input and Output
RevertWordsOrder("John Doe.") → "Doe John."
RevertWordsOrder("A, B. C") → "C B. A,"
using System;

namespace CSharpExercises.Strings
{
class RevertWordsOrderTask
{

37
C# Exercises
static string RevertWordsOrder(string str)
{
string[] strArray = str.Split(' ');
int len = strArray.Length;

for (int i = 0; i < len / 2; i++)


{
string temp = strArray[i];

if (i == 0)
{
strArray[i] = strArray[len - 1].Remove(strArray[len - 1].Length -
1);
strArray[len - 1] = temp + strArray[len -
1].Substring(strArray[len - 1].Length - 1);
}
else
{
strArray[i] = strArray[len - 1 - i];
strArray[len - 1 - i] = temp;
}
}

return string.Join(" ", strArray);


}

static void Main(string[] args)


{
Console.WriteLine(RevertWordsOrder("Proin in odio viverra, accumsan purus
vel, placerat elit!"));
// elit placerat vel, purus accumsan viverra, odio in Proin!
Console.WriteLine(RevertWordsOrder("Cras iaculis tortor justo."));
// justo tortor iaculis Cras.
}
}
}

How many occurrences


Given a string and substring, write a method that returns number of occurrences of
substring in the string. Assume that both are case-sensitive. You may need to use
library function here.
Expected Input and Output
HowManyOccurrences("do it now", "do") → 1
HowManyOccurrences("empty", "d") → 0
using System;

namespace CSharpExercises.Strings
{
class HowManyOccurrencesTask
{
static int HowManyOccurrences(string str, string subStr)
{
int found;
int total = 0;
for (int i = 0; i < str.Length; i++)
{
found = str.IndexOf(subStr, i);
38
C# Exercises

if (found > -1)


{
total++;
i = found;
}
}

return total;
}

static void Main(string[] args)


{
Console.WriteLine(HowManyOccurrences("He is a good boy, he would never do
that!", "he"));
// 1
Console.WriteLine(HowManyOccurrences("104 593 00-930 720193", "93"));
// 3
Console.WriteLine(HowManyOccurrences("xyz", "a"));
// 0
}
}
}

Sort characters descending


Given a string, write a method that returns array of chars (ASCII characters) sorted in
descending order.
Expected Input and Output
SortCharactersDescending("onomatopoeia") → tpoooonmieaa
SortCharactersDescending("fohjwf42os") → wsoojhff42
using System;

namespace CSharpExercises.Strings
{
class SortCharactersDescendingTask
{
static char[] SortCharactersDescending(string str)
{
char[] charArray = str.ToCharArray();
char ch;

for (int i = 1; i < str.Length; i++)


{
for (int j = 0; j < str.Length - 1; j++)
{
if (charArray[j] < charArray[j + 1])
{
ch = charArray[j];
charArray[j] = charArray[j + 1];
charArray[j + 1] = ch;
}
}
}

return charArray;
}

static void Main(string[] args)


39
C# Exercises
{
Console.WriteLine(SortCharactersDescending("Aliquam pulvinar aliquam
libero, in fringilla erat."));
// vuuutrrrrqqponnnmmlllllliiiiiiigfeebaaaaaaA.,
Console.WriteLine(SortCharactersDescending("Thi2 12 5@mpl3 Str!nG~"));
// ~trpnmlihTSG@53221!
}
}
}

Compress string
Given a non-empty string, write a method that returns it in compressed format.
Expected Input and Output
CompressString("kkkktttrrrrrrrrrr") → "k4t3r10"
CompressString("p555ppp7www") → "p153p371w3"
using System;

namespace CSharpExercises
{
class Program
{
public static string CompressString(string str)
{
var count = 0;
var last = str[0];
var newStr = string.Empty;

foreach (var s in str)


{
if (s == last)
{
count++;
}
else
{
newStr += last.ToString() + count;
last = s;
count = 1;
}
}

newStr += last.ToString() + count;

return newStr;
}

static void Main(string[] args)


{
Console.WriteLine(CompressString("aaaabbcccccdaa"));
// a4b2c5d1a2
Console.WriteLine(CompressString("948kro"));
// 914181k1r1o1
Console.WriteLine(CompressString("$999j*#jjjfYyyy"));
// $193j1*1#1j3f1Y1y3
}
}
}

40
C# Exercises

TOPIC 5
Recursion
Digits multiplication
Given a positive integer, write a method that returns multiplication of all digits in the
number.
Expected Input and Output
DigitsMultiplication(456) → 120
DigitsMultiplication(123) → 6
using System;

namespace CSharpExercises.Recursion
{
class DigitsMultiplicationTask
{
static int DigitsMultiplication(int num)
{
return num > 10 ? num % 10 * DigitsMultiplication(num / 10) : num % 10;
}

static void Main(string[] args)


{
Console.WriteLine(DigitsMultiplication(1234)); // 24
Console.WriteLine(DigitsMultiplication(94632)); // 1296
Console.WriteLine(DigitsMultiplication(222222222)); // 512
}
}
}

Factorial
Given a non-negative integer, write a method that returns factorial of a number.
Expected Input and Output
Factorial(4) → 24
Factorial(7) → 5040
using System;

namespace CSharpExercises.Recursion
{
class FactorialTask
{
static long Factorial(int num)
{
return num == 0 || num == 1 ? 1 : num * Factorial(num - 1);
}

static void Main(string[] args)


{
Console.WriteLine(Factorial(5)); // 120
41
C# Exercises
Console.WriteLine(Factorial(1)); // 1
Console.WriteLine(Factorial(14)); // 87178291200
Console.WriteLine(Factorial(0)); // 1
Console.WriteLine(Factorial(20)); // 2432902008176640000
}
}
}

Fibonacci number
Given a non-negative integer, write a method that returns n-th element of Fibonacci
sequence.
Expected Input and Output
FibonacciNumber(3) → 2
FibonacciNumber(7) → 13
using System;

namespace CSharpExercises.Recursion
{
class FibonacciNumberTask
{
static int FibonacciNumber(int num)
{
return num <= 1 ? num : FibonacciNumber(num - 2) + FibonacciNumber(num -
1);
}

static void Main(string[] args)


{
Console.WriteLine(FibonacciNumber(10)); // 55
Console.WriteLine(FibonacciNumber(0)); // 0
Console.WriteLine(FibonacciNumber(20)); // 6765
Console.WriteLine(FibonacciNumber(13)); // 233
}
}
}

Numbers multiplication
Given two integers a and b (a <= b) as range, write a method that returns
multiplication of numbers from given range.
Expected Input and Output
NumbersMultiplication(5, 7) → 210
NumbersMultiplication(50, 50) → 50
using System;

namespace CSharpExercises.Recursion
{
class NumbersMultiplicationTask
{
static int NumbersMultiplication(int from, int to)
{
while (from == to)
42
C# Exercises
{
return from;
}

return from * NumbersMultiplication(from + 1, to);


}

static void Main(string[] args)


{
Console.WriteLine($"{NumbersMultiplication(1, 5)}"); // 120
Console.WriteLine($"{NumbersMultiplication(-27, -22)}"); // 213127200
Console.WriteLine($"{NumbersMultiplication(44, 44)}"); // 44
}
}
}

To the power of (recursion)


Given two integers, write a method that returns first number raised to the power of
second number.
Expected Input and Output
ToThePowerOfRecursion(2, 3) → 8
ToThePowerOfRecursion(5, 2) → 25
using System;

namespace CSharpExercises.Recursion
{
class ToThePowerOfRecursionTask
{
static int ToThePowerOfRecursion(int b, int exp)
{
return exp == 0 ? 1 : exp > 1 ? b * ToThePowerOfRecursion(b, exp - 1) : b;
}

static void Main(string[] args)


{
Console.WriteLine(ToThePowerOfRecursion(10, 0)); // 1
Console.WriteLine(ToThePowerOfRecursion(3, 7)); // 2187
Console.WriteLine(ToThePowerOfRecursion(2, 10)); // 1024
}
}
}

String in reverse order (recursion)


Given a string, write a method that prints it in reverse order.
Expected Input and Output
StringInReverseOrderRecursion("abcde") → "edcba"
StringInReverseOrderRecursion("Sed lectus est, elementum ut urna eu") → "ue anru
tu mutnemele ,tse sutcel deS"
using System;

namespace CSharpExercises.Recursion

43
C# Exercises
{
class StringInReverseOrderRecursionTask
{
static string StringInReverseOrderRecursion(string str)
{
return str.Length > 0 ? str[str.Length - 1] +
StringInReverseOrderRecursion(str.Substring(0, str.Length - 1)) : str;
}

static void Main(string[] args)


{
var str1 = "A";
var str2 = "34 ( 9 9@*";
var str3 = "eMpIrE";
var str4 = string.Empty;

Console.WriteLine(StringInReverseOrderRecursion(str1)); // A
Console.WriteLine(StringInReverseOrderRecursion(str2)); // *@9 9 ( 43
Console.WriteLine(StringInReverseOrderRecursion(str3)); // ErIpMe
Console.WriteLine(StringInReverseOrderRecursion(str4)); //
}
}
}

Is palindrome (recursion)
Given a string, write a method that checks if it is a palindrome. String length may be
>= 0.
Expected Input and Output
IsPalindromeRecursion("xx") → true
IsPalindromeRecursion("pendrive") → false
using System;

namespace CSharpExercises.Recursion
{
class IsPalindromeRecursionTask
{
static bool IsPalindromeRecursion(string str)
{
if (str.Length == 1 || (str.Length == 2 && str[0] == str[1]))
return true;
else if (str.Length > 1)
{
if (str[0] != str[str.Length - 1])
return false;

return IsPalindromeRecursion(str.Substring(1, str.Length - 2));


}

return false;
}

static void Main(string[] args)


{
Console.WriteLine(IsPalindromeRecursion("aa")); // True
Console.WriteLine(IsPalindromeRecursion("dad")); // True
Console.WriteLine(IsPalindromeRecursion("apple")); // False
Console.WriteLine(IsPalindromeRecursion("deleveled")); // True

44
C# Exercises
Console.WriteLine(IsPalindromeRecursion("")); // False
Console.WriteLine(IsPalindromeRecursion("hannah")); // True
Console.WriteLine(IsPalindromeRecursion("X")); // True
}
}
}

Minimum element
Given an array of integers and array's length, write a method that returns its minimum
element.
Expected Input and Output
MinimumElement([8, 5, 9], 3) → 5
MinimumElement([-2, -9, 2, -3, 1, 0], 6) → -9
using System;

namespace CSharpExercises.Recursion
{
class MinimumElementTask
{
static int MinimumElement(int[] arr, int size)
{
if (size == 1)
{
return arr[0];
}

return arr[size - 1] < MinimumElement(arr, size - 1) ? arr[size - 1] :


MinimumElement(arr, size - 1);
}

static void Main(string[] args)


{
Console.WriteLine(MinimumElement(new int[] { 7, 2, 9, 5, 4 }, 5));
// 2
Console.WriteLine(MinimumElement(new int[] { -45, -6, 39, 96, -20, 0, -100
}, 7));
// -100
Console.WriteLine(MinimumElement(new int[] { 830, 905, 999, 831, 920, 900
}, 6));
// 830
}
}
}

TOPIC 6
Library functions
Negative or positive
Given a number, write a method that returns number to the power of 2 if negative or
square root if positive or zero.
Expected Input and Output

45
C# Exercises
NegativeOrPositive(-2) → 4
NegativeOrPositive(6.25) → 2.5
using System;

namespace CSharpExercises.Library_functions
{
class NegativeOrPositiveTask
{
public static double NegativeOrPositive(double num)
{
return num < 0 ? Math.Pow(num, 2) : Math.Sqrt(num);
}

public static void Main()


{
Console.WriteLine(NegativeOrPositive(72946)); // 270.085171751431
Console.WriteLine(NegativeOrPositive(-4.726)); // 22.335076
Console.WriteLine(NegativeOrPositive(0)); // 0
Console.WriteLine(NegativeOrPositive(3.334)); // 1.82592442340859
Console.WriteLine(NegativeOrPositive(-59)); // 3481
}
}
}

Replace x with y
Write a method that replaces every letter 'y' in the string with 'x'. Assume that string
contains only lower case letters.
Expected Input and Output
ReplaceXWithY("yellow") → "xellow"
ReplaceXWithY("mushroom") → "mushroom"
using System;

namespace CSharpExercises.Library_functions
{
class ReplaceXWithYTask
{
public static string ReplaceXWithY(string word)
{
string[] words = word.Split(' ');

for (int i = 0; i < words.Length; i++)


if (words[i].Contains("y"))
words[i] = words[i].Replace("y", "x");

return String.Join(" ", words);


}

public static void Main()


{
Console.WriteLine(ReplaceXWithY("yyy"));
// xxx
Console.WriteLine(ReplaceXWithY("strawberry youghurt"));
// strawberrx xoughurt
Console.WriteLine(ReplaceXWithY("tym ryhosx oifg 6 t6 ypeg ergh"));
// txm rxhosx oifg 6 t6 xpeg ergh
46
C# Exercises
Console.WriteLine(ReplaceXWithY(""));
// /empty string/
}
}
}

To lower or to upper
Given a string which has at least two words separated by space, write a method that
changes first word in the string to upper case, second to lower case and so on.
Expected Input and Output
ToLowerOrToUpper("this is it") → "THIS is IT"
using System;

namespace CSharpExercises.Library_functions
{
class ToLowerOrToUpperTask
{
public static string ToLowerOrToUpper(string word)
{
string[] words = word.Split(' ');

for (int i = 0; i < words.Length; i++)


words[i] = i % 2 == 0 ? words[i].ToUpper() : words[i].ToLower();

return String.Join(" ", words);


}

public static void Main()


{
Console.WriteLine(ToLowerOrToUpper("aaa BBB ccc DDD"));
// AAA bbb CCC ddd
Console.WriteLine(ToLowerOrToUpper("Etiam mollis lectus ac facilisis
venenatis"));
// ETIAM mollis LECTUS ac FACILISIS venenatis
Console.WriteLine(ToLowerOrToUpper("th1s 15 5amp13 53nt3nc3"));
// TH1S 15 5AMP13 53nt3nc3
}
}
}

Greater number
Given two numbers, write a method that returns greater one.
Expected Input and Output
GreaterNumber(2.1, 3) → 3
GreaterNumber(-5, 0) → 0
GreaterNumber(-111.22,111.222) → 111.222
using System;

namespace CSharpExercises.Library_functions
{
class GreaterNumberTask
47
C# Exercises
{
public static double GreaterNumber(double x, double y)
{
return Math.Max(x, y);
}

public static void Main()


{
Console.WriteLine(GreaterNumber(24.5, 127)); //127
Console.WriteLine(GreaterNumber(-1391, -9123)); //-1391
Console.WriteLine(GreaterNumber(-543, -543)); //543
}
}
}

If starts with lower case


Given a string, write a method that checks if each word in the string starts with lower
case and if so, removes this letter from the string.
Expected Input and Output
IfStartsWithLowerCase("Alfa Beta gamma") → "Alfa Beta amma"
using System;

namespace CSharpExercises.Library_functions
{
class IfStartsWithLowerCaseTask
{
public static string IfStartsWithLowerCase(string word)
{
string[] words = word.Split(' ');

for (int i = 0; i < words.Length; i++)


{
if (Char.IsLower(words[i][0]))
{
words[i] = words[i].Substring(1);
}
}

return String.Join(" ", words);


}

public static void Main()


{
Console.WriteLine(IfStartsWithLowerCase("tthis iis ffake ssentence."));
// this is fake sentence.
Console.WriteLine(IfStartsWithLowerCase("Praesent vitae convallis
purus."));
// Praesent itae onvallis urus.
Console.WriteLine(IfStartsWithLowerCase("1 2 3 7 8 9 a b c x y z"));
// 1 2 3 7 8 9
}
}
}

48
C# Exercises
TOPIC 7
LinQ
Numbers from range
Cho một mảng số nguyên, hãy viết một truy vấn trả về danh sách các số lớn hơn 30 và
nhỏ hơn 100.
Expected Input and Output
[67, 92, 153, 15] → 67, 92
using System;
using System.Collections.Generic;
using System.Linq;

namespace CSharpExercises.LINQ
{
class NumbersFromRangeTask
{
public static void Main()
{
List<int> Numbers = new List<int> { 30, 54, 3, 14, 25, 82, 1, 100, 23, 95
};

var SelectedNumbers = Numbers.Where(x => x > 30).Where(x => x < 100);

foreach (var s in SelectedNumbers)


{
Console.Write($"{s} "); // 54 82 95
}
}
}
}

Minimum length
Viết một truy vấn trả về các từ dài ít nhất 5 ký tự và biến chúng thành chữ hoa.
Expected Input and Output
"computer", "usb" → "COMPUTER"
using System;
using System.Collections.Generic;
using System.Linq;

namespace CSharpExercises.LINQ
{
class MinimumLengthTask
{
public static void Main()
{
List<string> animals = new List<string> { "zebra", "elephant", "cat",
"dog", "rhino", "bat" };

var selectedAnimals = animals.Where(s => s.Length >= 5).Select(x =>


x.ToUpper());

49
C# Exercises
foreach (var animal in selectedAnimals)
{
Console.Write($"{animal}, "); // ZEBRA, ELEPHANT, RHINO,
}
}
}
}

Select words
Viết một truy vấn trả về các từ bắt đầu bằng chữ cái 'a' và kết thúc bằng chữ cái 'm'.
Expected Input and Output
"mum", "amsterdam", "bloom" → "amsterdam"
using System;
using System.Collections.Generic;
using System.Linq;

namespace CSharpExercises.LINQ
{
class SelectWordsTask
{
public static void Main()
{
List<string> words = new List<string> { "alabam", "am", "balalam", "tara",
"", "a", "axeliam", "39yo0m", "trol" };

var selectedWords = words.Where(s => s.StartsWith("a")).Where(s =>


s.EndsWith("m"));

foreach (var word in selectedWords)


{
Console.Write($"{word}, "); // alabam, am, axeliam,
}
}
}
}

Top 5 numbers
Viết một truy vấn trả về 5 số trên cùng từ danh sách các số nguyên theo thứ tự giảm
dần.
Expected Input and Output
[78, -9, 0, 23, 54, 21, 7, 86] → 86 78 54 23 21
using System;
using System.Collections.Generic;
using System.Linq;

namespace CSharpExercises.LINQ
{
class Top5NumbersTask
{
public static void Main()
{
List<int> numbers = new List<int> { 6, 0, 999, 11, 443, 6, 1, 24, 54 };

50
C# Exercises
var top5 = numbers.OrderByDescending(x => x).Take(5);

foreach (var number in top5)


{
Console.Write($"{number} "); // 999 443 54 24 11
}
}
}
}

Square greater than 20


Viết một truy vấn trả về danh sách các số và bình phương của chúng chỉ khi bình
phương đó lớn hơn 20.
Expected Input and Output
[7, 2, 30] → 7 - 49, 30 - 900
using System;
using System.Collections.Generic;
using System.Linq;

namespace CSharpExercises.LINQ
{
class SquareGreaterThan20Task
{
public static void Main()
{
List<int> Numbers = new List<int> { 3, 9, 2, 4, 6, 5, 7 };

var SelectedNumbers = Numbers.Where(x => x * x > 20);

foreach (var s in SelectedNumbers)


{
Console.Write($"{s} - {s * s}, "); // 9 - 81, 6 - 36, 5 - 25, 7 - 49,
}
}
}
}

Replace substring
Viết một truy vấn thay thế chuỗi con 'ea' bằng astersik (*) trong danh sách các từ đã
cho.
Expected Input and Output
"learn", "current", "deal" → "l*rn", "current", "d*l"
using System;
using System.Linq;

namespace CSharpExercises.LINQ
{
class ReplaceSubstringTask
{
public static void Main()
{
var words = new[] { "near", "speak", "tonight", "weapon", "customer",
"deal", "lawyer" };
51
C# Exercises

var modifiedWords = words.Select(w => w.Contains("ea") ? w.Replace("ea",


"*") : w);

foreach (var word in modifiedWords)


{
Console.Write(word + " ");
// n*r sp*k tonight w*pon customer d*l lawyer
}
}
}
}

Last word containing letter


Given a non-empty list of words, sort it alphabetically and return a word that contains
letter 'e'.
Expected Input and Output
["plane", "ferry", "car", "bike"]→ "plane"
using System;
using System.Collections.Generic;
using System.Linq;

namespace CSharpExercises.LINQ
{
class LastWordContainingLetterTask
{
public static void Main()
{
var words = new List<string> { "cow", "dog", "elephant", "cat", "rat",
"squirrel", "snake", "stork" };

var word = words.OrderBy(x => x)


.LastOrDefault(w => w.Contains("e"));

Console.WriteLine($"{word}"); // squirrel
}
}
}

Shuffle an array
Viết một truy vấn xáo trộn mảng đã sắp xếp.
Expected Input and Output
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10] → [4, 9, 3, 5, 2, 10, 1, 6, 8, 7] [38, 24, 8, 0, -1, -17, -33, -
100] → [0, -100, -17, 38, 8, -1, 24, -33,]
using System;
using System.Linq;

namespace CSharpExercises.LINQ
{
class ShuffleAnArrayTask
{
public static void Main()
{

52
C# Exercises
var rnd = new Random();

var array = new[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };

var shuffledArray = array.OrderBy(i => rnd.Next());

foreach (var item in shuffledArray)


{
Console.Write(item + " "); // 4 10 3 6 2 8 1 9 7 5
}
}
}
}

Decrypt number
Given a non-empty string consisting only of special chars (!, @, # etc.), return a
number (as a string) where each digit corresponds to given special char on the
keyboard ( 1→ !, 2 → @, 3 → # etc.).
Expected Input and Output
"())(" → "9009" "*$(#&" → "84937" "!!!!!!!!!!" → "1111111111"
using System;
using System.Linq;

namespace CSharpExercises.LINQ
{
class DecryptNumberTask
{
public static void Main()
{
var chars = new char[] { ')', '!', '@', '#', '$', '%', '^', '&', '*', '('
};

var encryptedNumber = "#(@*%)$(&$*#&";

var decryptedNumber = string.Join("", encryptedNumber.Select(c =>


Array.IndexOf(chars, c)));

Console.WriteLine(decryptedNumber); // 3928504974837
}
}
}

Most frequent character


Viết một truy vấn trả về ký tự xuất hiện nhiều nhất trong chuỗi. Giả sử rằng chỉ có một ký tự như
thế.
Expected Input and Output
"panda" → 'a' "n093nfv034nie9"→ 'n'
using System;
using System.Linq;

namespace CSharpExercises.LINQ
{
class MostFrequentCharacterTask
{
53
C# Exercises
public static void Main()
{
string str = "49fjs492jfJs94KfoedK0iejksKdsj3";

var mostFrequentCharacter = str.GroupBy(c => c).OrderByDescending(c =>


c.Count()).First().Key;

Console.Write(mostFrequentCharacter);
}
}
}

Unique values
Given a non-empty list of strings, return a list that contains only unique (non-
duplicate) strings.
Expected Input and Output
["abc", "xyz", "klm", "xyz", "abc", "abc", "rst"] → ["klm", "rst"]
using System;
using System.Collections.Generic;
using System.Linq;

namespace CSharpExercises.LINQ
{
class UniqueValuesTask
{
public static void Main()
{
var values = new List<string> { "Hi", "Meow", "Hello", "Meow", "Hi!",
"Meow", "Hi", "Bye" };
var uniqueValues = values
.GroupBy(x => x)
.Where(x => x.Count() == 1)
.Select(x => x.Key)
.ToList();

foreach (var value in uniqueValues)


{
Console.WriteLine($"{value}"); //Hello Hi! Bye
}
}
}
}

Uppercase only
Viết một truy vấn chỉ trả về các từ viết hoa từ chuỗi.
Expected Input and Output
"DDD example CQRS Event Sourcing" → DDD, CQRS
using System;
using System.Linq;

namespace CSharpExercises.LINQ
{
class UppercaseOnlyTask
{

54
C# Exercises
public static void Main()
{
string word = "THIS is UPPERCASE string LOL";

var uppercaseOnly = word.Split(' ').Where(x => string.Equals(x,


x.ToUpper()));

foreach (var u in uppercaseOnly)


{
Console.Write($"{u}, "); // THIS, UPPERCASE, LOL,
}
}
}
}

Arrays dot product


Viết một truy vấn trả về tích vô hướng (dot product) của hai mảng.
Expected Input and Output
[1, 2, 3], [4, 5, 6] → 32 [7, -9, 3, -5], [9, 1, 0, -4] → 74
using System;
using System.Linq;

namespace CSharpExercises.LINQ
{
class ArraysDotProduct
{
public static void Main()
{
int[] array1 = new int[] { 5, 8, 2, 9 };
int[] array2 = new int[] { 1, 7, 2, 4 };

int dotProduct = array1.Zip(array2, (a, b) => a * b).Sum();

Console.WriteLine(dotProduct); // 101
}
}
}

Frequency of letters
Write a query that returns letters and their frequencies in the string.
Expected Input and Output
"gamma" → "Letter g occurs 1 time(s), Letter a occurs 2 time(s), Letter m occurs 2
time(s)"
using System;
using System.Linq;

namespace CSharpExercises.LINQ
{
class FrequencyOfLettersTask
{
public static void Main()
{
string word = "abracadabra";

55
C# Exercises

var letters = word.GroupBy(x => x);

foreach (var l in letters)


{
Console.Write($"Letter {l.Key} occurs {l.Count()} time(s), ");
// Letter a occurs 5 time(s), Letter b occurs 2 time(s), Letter r
occurs 2 time(s)
// Letter r occurs 2 time(s), Letter c occurs 1 time(s), Letter d
occurs 1 time(s)
}
}
}
}

Days names
Write a query that returns names of days.
Expected Input and Output
daysNames → "Sunday Monday Tuesday Wednesday Thursday Friday Saturday"
using System;
using System.Linq;

namespace CSharpExercises.LINQ
{
class DaysNamesTask
{
public static void Main()
{
var daysNames = Enum.GetValues(typeof(DayOfWeek)).Cast<DayOfWeek>();

foreach (var d in daysNames)


{
Console.Write($"{d} ");
// Sunday Monday Tuesday Wednesday Thursday Friday Saturday
}
}
}
}

Double letters
Write a query that returns double letters sequence in format: AA AB AC ... ZX ZY ZZ
Expected Input and Output
(no input) → "AA AB AC ... AZ BA BB ... ZX ZY ZZ"
using System;
using System.Linq;

namespace CSharpExercises.LINQ
{
class DoubleLettersTask
{
public static void Main()
{
var doubleLetters = Enumerable.Range((char)65, 26)

56
C# Exercises
.SelectMany(x => Enumerable.Range((char)65, 26).Select(y =>
(char)x + "" + (char)y));

foreach (var doubleLetter in doubleLetters)


{
Console.Write(doubleLetter + " ");
// AA AB AC ... AZ BA BB ... ZX ZY ZZ
}
}
}
}

Transpose an array
Write a query that transposes square array (switch rows with columns).
Expected Input and Output
[1,1,1,1 [1,2,3,4 2,2,2,2 1,2,3,4 3,3,3,3 → 1,2,3,4 4,4,4,4] 1,2,3,4]
using System;
using System.Linq;

namespace CSharpExercises.LINQ
{
class TransposeAnArrayTask
{
public static void Main()
{
var array = new int[][] {new int[]{ 1, 2, 3, 4, 5 },
new int[]{ 6, 7, 8, 9, 10 },
new int[]{ 11, 12, 13, 14, 15 },
new int[]{ 16, 17, 18, 19, 20 },
new int[]{ 21, 22, 23, 24, 25 }};

var transposedArray = Enumerable.Range(0, array.Length).Select(x =>


array.Select(y => y[x]));

foreach (var row in transposedArray)


{
foreach (var number in row)
{
Console.Write(number + " ");
}
Console.WriteLine();
}
//1 6 11 16 21
//2 7 12 17 22
//3 8 13 18 23
//4 9 14 19 24
//5 10 15 20 25
}
}
}

57

You might also like