C# – Loops

Условия и решения на задачите от лекция “Loops”

Задача 1. Print N Numbers

Условие: Write a program that prints all the numbers from 1 to N.

Решение:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace _1.PrintNNumbers
{
class PrintNNumbers
{
static void Main()
{
int n;
Console.Write("Enter an integer number:");
bool isnInt = int.TryParse(Console.ReadLine(), out n);
if (isnInt)
{
for (int i = 1; i <= n; i++)
{
Console.WriteLine(i);
}
}
else
{
Console.WriteLine("Not a valid entry!");
}
}
}
}

Задача 2. Print N Number Non Divisible By 3 And 7

Условие: Write a program that prints all the numbers from 1 to N, that are not divisible by 3 and 7 at the same time.

Решение:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace _2.PrintNNumberNonDivisibleBy3And7
{
class PrintNNumberNonDivisibleBy3And7
{
static void Main()
{
int n;
Console.Write("Enter an integer number:");
bool isnInt = int.TryParse(Console.ReadLine(), out n);
if (isnInt)
{
for (int i = 1; i <= n; i++)
{
if (((i % 3) != 0) || ((i % 7) != 0))
{
Console.WriteLine(i);
}
}
}
else
{
Console.WriteLine("Not a valid entry!");
}
}
}
}

Задача 3. Find Min And Maximal Number

Условие: Write a program that reads from the console a sequence of N integer numbers and returns the minimal and maximal of them.

Решение:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace _3.FindMinAndMaximalNumber
{
class FindMinAndMaximalNumber
{
static void Main()
{
int n;
string[] numbers;
bool isInteger=true;
int minimal=int.MaxValue;
int maximal=int.MinValue;
Console.Write("Enter a sequence of numbers delimited with \",\":");
numbers = (Console.ReadLine()).Split(',');
int[] intNumbers=new int[numbers.Length];
for (int i = 0; i < (numbers.Length); i++)
{
isInteger = int.TryParse(numbers[i], out intNumbers[i]);
if (isInteger==false)
{
break;
}
}
if (isInteger)
{
for (int i = 0; i < numbers.Length; i++)
{
if (intNumbers[i] < minimal)
{
minimal = intNumbers[i];
}
if (intNumbers[i] > maximal)
{
maximal = intNumbers[i];
}
}
Console.WriteLine("minimal={0}",minimal);
Console.WriteLine("maximal={0}",maximal);
}
else
{
Console.WriteLine("Not a valid entry! Some of the entries are not integer!");
}
}
}
}

Задача 4. Devision Of Factorials

Условие: Write a program that calculates N!/K! for given N and K (1Решение:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace _4.DevisionOfFactorials
{
class DevisionOfFactorials
{
static void Main()
{
int N, K;
int divisor=1;
double result;
Console.Write("Enter the first number N:");
bool isNInt = int.TryParse(Console.ReadLine(), out N);
Console.Write("Enter the second number K:");
bool isKInt = int.TryParse(Console.ReadLine(), out K);
if (isNInt && isKInt && (N < K) && (N > 1) && (K > 1))
{
for (int i=N+1; i < K + 1; i++)
{
divisor = divisor * i;
}

result = 1.0/(double)divisor;
Console.WriteLine("result={0}",result);
}
else
{
Console.WriteLine("Not a valid entry!");
}
}
}
}

Задача 5. Factorial Calculations

Условие: Write a program that calculates N!*K! / (K-N)! for given N and K (1Решение:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Numerics;

namespace _5.FactorialCalculations
{
class FactorialCalculations
{
static void Main()
{
int N, K;
BigInteger result=1;
Console.Write("Enter the first number N:");
bool isNInt = int.TryParse(Console.ReadLine(), out N);
Console.Write("Enter the second number K:");
bool isKInt = int.TryParse(Console.ReadLine(), out K);
if (isNInt && isKInt && (N < K) && (N > 1) && (K > 1))
{
for (int i = 1; i < K + 1; i++)
{
if (N > (K - N))
{
result = result * i;
if (i < (N + 1))
{
result = result * i;
}
}
else if (N < (K - N))
{
if(i<=N)
{
result = result * i;
}
if(i>(K-N))
{
result = result * i;
}
}
else//N=K-N
{
result = result * i;
}
}
Console.WriteLine("result={0}", result);
}
else
{
Console.WriteLine("Not a valid entry!");
}
}
}
}

Задача 6. Sum Calculation

Условие: Write a program that, for a given two integer numbers N and X, calculates the sum S = 1 + 1!/X + 2!/X2 + … + N!/XN

Решение:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Numerics;

namespace _6.SumCalculation
{
class SumCalculation
{
private static BigInteger FindFactorial(int N)
{
BigInteger factorial=1;
for (int i = 1; i < N+1; i++)
{
factorial = factorial * i;
}
return factorial;
}

private static BigInteger FindPower(int X,int N)
{
BigInteger powerX=1;
for (int i = 1; i < N + 1; i++)
{
powerX = powerX *X;
}
return powerX;
}

static void Main()
{
int N, X;
double sum=1.0;
Console.Write("Enter the first number N:");
bool isNInt = int.TryParse(Console.ReadLine(), out N);
Console.Write("Enter the second number X:");
bool isXInt = int.TryParse(Console.ReadLine(), out X);
if (isNInt && isXInt)
{
for (int i = 1; i < N+1; i++)
{
sum = sum + ((double)FindFactorial(i) / (double)FindPower(X, i));

}
Console.WriteLine("sum={0}", sum);
}
else
{
Console.WriteLine("Not a valid entry!");
}
}
}
}

Задача 7. Fibonacci Sequence

Условие: Write a program that reads a number N and calculates the sum of the first N members of the sequence of Fibonacci: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, …
Each member of the Fibonacci sequence (except the first two) is a sum of the previous two members.

Решение:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Numerics;

namespace _7.FibonacciSequence
{
class FibonacciSequence
{
static void Main()
{
int N;
BigInteger sum = 1;
BigInteger newElement;
BigInteger[] sequenceMembers = { 0, 1 };
Console.Write("Enter the number N:");
bool isNInt = int.TryParse(Console.ReadLine(), out N);
if (isNInt)
{
for (int i = 0; i < N-2; i++)
{
newElement = sequenceMembers[0] + sequenceMembers[1];
sum = sum + newElement;
sequenceMembers[0] = sequenceMembers[1];
sequenceMembers[1] = newElement;
}
Console.WriteLine("sum={0}",sum);
}
}
}
}

Задача 8. Greatest Common Devider

Условие: Write a program that calculates the greatest common divisor (GCD) of given two numbers. Use the Euclidean algorithm (find it in Internet).

Решение:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace _8.GreatestCommonDevider
{
class GreatestCommonDevider
{
static void Main()
{
uint N, K, temporary, remaining;
uint greatestCommonDevider=1;
Console.Write("Enter the first number N:");
bool isNUint = uint.TryParse(Console.ReadLine(), out N);
Console.Write("Enter the second number K:");
bool isKUint = uint.TryParse(Console.ReadLine(), out K);

if (isNUint && isKUint && (N != 0 || K != 0))
{
if (N == 0)
{
greatestCommonDevider = K;
}
else if (K == 0)
{
greatestCommonDevider = N;
}
else
{
temporary = Math.Max(N, K);
K = Math.Min(N, K);
N = temporary;
do
{
remaining = N % K;
if (remaining == 0)
{
greatestCommonDevider = K;
break;
}
else
{
N = K;
K = remaining;
}
} while (true);
}
Console.WriteLine("Greatest common devider = {0}",greatestCommonDevider);
}
else
{
Console.WriteLine("Not a valid entry!");
}
}
}
}

Задача 10. Catalan Numbers

Условие: Write a program to calculate the Nth Catalan number by given N.

Решение:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Numerics;

namespace _10.CatalanNumbers
{
class CatalanNumbers
{
private static BigInteger FindPartialFactorial(uint startNumber,uint N)
{
BigInteger factorial = (BigInteger)startNumber;
for (uint i = startNumber+1; i < N+1; i++)
{
factorial = factorial * i;
}
return factorial;
}
static void Main()
{
BigInteger Nth_element;
uint N;
Console.Write("Enter the number N:");
bool isNUint = uint.TryParse(Console.ReadLine(), out N);
if (isNUint)
{
Nth_element = FindPartialFactorial((N + 1), (2 * N)) / FindPartialFactorial(1, N + 1);
Console.WriteLine("The Nth element={0}",Nth_element);
}
else
{
Console.WriteLine("Wrong entry!");
}
}
}
}

Задача 11. Print Card Names

Условие: Write a program that prints all possible cards from a standard deck of 52 cards (without jokers). The cards should be printed with their English names. Use nested for loops and switch-case.

Решение:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace _11.PrintCardNames
{
class PrintCardNames
{
static void Main()
{
for (int i = 0; i < 4; i++)
{
for (int j = 0; j < 13; j++)
{
switch (j)
{
case 0: Console.Write("Ace"); break;
case 1: Console.Write("Two"); break;
case 2: Console.Write("Three"); break;
case 3: Console.Write("Four"); break;
case 4: Console.Write("Five"); break;
case 5: Console.Write("Six"); break;
case 6: Console.Write("Seven"); break;
case 7: Console.Write("Eight"); break;
case 8: Console.Write("Nine"); break;
case 9: Console.Write("Ten"); break;
case 10: Console.Write("Jack"); break;
case 11: Console.Write("Queen"); break;
case 12: Console.Write("King"); break;
}
switch (i)
{
case 0: Console.WriteLine(" Of Clubs"); break;
case 1: Console.WriteLine(" Of Diamonds"); break;
case 2: Console.WriteLine(" Of Hearts"); break;
case 3: Console.WriteLine(" Of Spades"); break;
}

}
}
}
}
}

Задача 12. Print Matrix

Условие: Write a program that reads from the console a positive integer number N (N < 20) and outputs a matrix like the following:
N = 3
Loops_1


N = 4
Loops_2

Решение:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace _12.PrintMatrix
{
class PrintMatrix
{
static void Main()
{
int N;
Console.Write("Enter an integer number < 20:");
bool isnInt = int.TryParse(Console.ReadLine(), out N);
if (isnInt&N<20&N>0)
{
for (int i = 0; i < N; i++)
{
for (int j = 1; j < N+1; j++)
{
if (j + i > 9)
{
Console.Write("{0} ", j + i);
}
else
{
Console.Write("{0}  ", j + i);
}
}
Console.WriteLine();
}

}
else
{
Console.WriteLine("Wrong entry!");
}
}
}
}

Задача 13. Find Zeroes At The End Of The Factorial

Условие: Write a program that calculates for given N how many trailing zeros present at the end of the number N!. Examples:
N = 10 => N! = 3628800 => 2
N = 20 => N! = 2432902008176640000 => 4
Does your program work for N = 50 000?
Hint: The trailing zeros in N! are equal to the number of its prime divisors of value 5. Think why!

Решение:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Numerics;

namespace _13.FindZeroesAtTheEndOfTheFactorial
{
class FindZeroesAtTheEndOfTheFactorial
{
static void Main()
{
int N,temporary;
int numberOfZeroes=0;
BigInteger factorial = 1;
Console.Write("Enter an integer number:");
bool isnInt = int.TryParse(Console.ReadLine(), out N);
if (isnInt)
{
for (int i = 1; i < N+1; i++)
{
factorial = factorial * i;
}
Console.WriteLine("N factorial={0}",factorial);
if(N>=5)
{
do
{
temporary = N / 5;
if (temporary != 0)
{
numberOfZeroes = numberOfZeroes + temporary;
N = temporary;
}
else
{
break;
}
}
while(true);
}
Console.WriteLine("Number of zeroes =:{0}",numberOfZeroes);
}
else
{
Console.WriteLine("Wrong entry!");

}
}
}
}

Задача 14. Print Matrix In Spiral

Условие: Write a program that reads a positive integer number N (N < 20) from console and outputs in the console the numbers 1 … N numbers arranged as a spiral.
Example for N = 4
Loops_3

Решение:

using System;

namespace _14.PrintMatrixInSpiral
{
class PrintMatrixInSpiral
{
static void Main()
{
int N;
int counter = 0;
int numberOfDoubleSections; //How many Row/Column sections has the spiral
int spiralSectionLength; //Length of the spiral section ( row or column section)
byte column=0;
byte row=0;
Console.Write("Enter an integer number < 20:");
bool isnInt = int.TryParse(Console.ReadLine(), out N);
if (isnInt & N < 20 & N > 0)
{
int[,] array = new int[N, N];
for (column = 0; column < N; column++)//Fill the first row
{
counter++;
array[row, column] = counter;
}
column--;
numberOfDoubleSections = N - 1;
spiralSectionLength= N - 1;
counter++;
for (int section = 0; section < numberOfDoubleSections; section++)
{
for (int j = 0; j < 2; j++)
{
for (int i = 0; i < spiralSectionLength; i++)
{
if (j == 1)//Row printing
{
if (section % 2 == 0)// isLeftDirection
{
column--;
array[row, column] = counter;
}
else
{
column++;
array[row, column] = counter;
}
}
else //Column printing
{
if (section % 2 == 0)// isDownDirection
{
row++;
array[row, column] = counter;
}
else
{
row--;
array[row, column] = counter;
}
}
counter++;
}
}
spiralSectionLength--;
}

for (row = 0; row < N; row++)
{
for (column = 0; column < N; column++)
{
Console.Write("{0,4}",array[row,column]);
}
Console.WriteLine();
}
}
else
{
Console.WriteLine("Wrong entry!");
}
}
}
}