Topic 1 Basics: Add Two Numbers
Topic 1 Basics: Add Two Numbers
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;
}
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;
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;
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;
}
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;
}
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;
}
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;
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;
}
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;
}
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
}
namespace CSharpExercises.Conditional_statements
{
class IfGreaterThanThirdOneTask
{
static bool IfGreaterThanThirdOne(int[] arr)
{
return arr[0] + arr[1] > arr[2] || arr[0] * arr[1] > arr[2];
}
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;
}
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];
}
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;
}
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
}
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;
}
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;
}
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();
}
}
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;
}
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;
}
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];
return theBiggest;
}
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;
}
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;
}
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;
}
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];
18
C# Exercises
return array;
}
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();
}
}
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();
}
}
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();
}
}
}
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;
return string.Empty;
}
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;
}
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;
return longest;
}
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;
return number;
}
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;
i *= 10;
j *= 10;
}
return sum;
}
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++;
}
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;
}
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();
}
}
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;
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;
}
namespace CSharpExercises.Loops
{
class ReplaceWordsTask
{
public static string ReplaceWords(string word, char ch)
{
string firstWord = string.Empty;
string secondWord = string.Empty;
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;
i *= 10;
j *= 10;
}
number = sum;
}
return (int)number;
}
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;
return check == 0;
}
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;
return separatedWord;
}
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;
}
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;
}
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;
}
namespace CSharpExercises.Strings
{
class SumDigitsInStringTask
{
static int SumDigitsInString(string str)
{
var sum = 0;
return sum;
}
34
C# Exercises
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;
35
C# Exercises
// EvEnTs AnD DeLeGaTeS
}
}
}
namespace CSharpExercises.Strings
{
class MixTwoStringsTask
{
static string MixTwoStrings(string word1, string word2)
{
string mixedWord = string.Empty;
return mixedWord;
}
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;
}
namespace CSharpExercises.Strings
{
class RevertWordsOrderTask
{
37
C# Exercises
static string RevertWordsOrder(string str)
{
string[] strArray = str.Split(' ');
int len = strArray.Length;
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;
}
}
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
return total;
}
namespace CSharpExercises.Strings
{
class SortCharactersDescendingTask
{
static char[] SortCharactersDescending(string str)
{
char[] charArray = str.ToCharArray();
char ch;
return charArray;
}
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;
return newStr;
}
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;
}
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);
}
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);
}
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;
}
namespace CSharpExercises.Recursion
{
class ToThePowerOfRecursionTask
{
static int ToThePowerOfRecursion(int b, int exp)
{
return exp == 0 ? 1 : exp > 1 ? b * ToThePowerOfRecursion(b, exp - 1) : b;
}
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;
}
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 false;
}
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];
}
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);
}
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(' ');
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(' ');
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);
}
namespace CSharpExercises.Library_functions
{
class IfStartsWithLowerCaseTask
{
public static string IfStartsWithLowerCase(string word)
{
string[] words = word.Split(' ');
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
};
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" };
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" };
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);
namespace CSharpExercises.LINQ
{
class SquareGreaterThan20Task
{
public static void Main()
{
List<int> Numbers = new List<int> { 3, 9, 2, 4, 6, 5, 7 };
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
namespace CSharpExercises.LINQ
{
class LastWordContainingLetterTask
{
public static void Main()
{
var words = new List<string> { "cow", "dog", "elephant", "cat", "rat",
"squirrel", "snake", "stork" };
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();
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[] { ')', '!', '@', '#', '$', '%', '^', '&', '*', '('
};
Console.WriteLine(decryptedNumber); // 3928504974837
}
}
}
namespace CSharpExercises.LINQ
{
class MostFrequentCharacterTask
{
53
C# Exercises
public static void Main()
{
string str = "49fjs492jfJs94KfoedK0iejksKdsj3";
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();
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";
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 };
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
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>();
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));
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 }};
57