wingman007 icon

CheatSheetIntroProgrammingC#

wingman007 | PRO | 10/23/25 01:17:38 PM UTC (Edited) | 0 ⭐ | 4911 👁️ | Never ⏰ | []
C# |

38.76 KB

|

None

|

0 👍

/

0 👎

using System;
 
namespace IntroProgramming2019
{
    class Program
    {
        static void Main(string[] args)
        {
            // 1. Hello World
            Console.WriteLine("Hello World!");
            
            // Shortcuts Ctrl+. | Ctrl+r,r | cw \t\t | Ctrl+k,d | Ctrl+k,c | Ctrl+k,u
            // 2. Primitive data types, variables, literals
            // variable - A variable is a named piece of memory intended to hold data
            // variable type determines the type of data the variable can hold. The types that come predefined with the language are called primitive data types.
            // literal is a symbol constant directly expressed in the code for setting a value of a variable
 
            //Let's declare and initialize a variable
            byte myByte1 = 1; 
            byte myByte2 = 7;
 
            sbyte mySByte1 = -1;
 
            Console.WriteLine(myByte1 + myByte2);
 
            // I. Types have: name (e.g. int), size, default value
            // II. Variables have: name (A-Za-z_0-9 all utf-8, can't start with 0-9, can't be a keyword), type, value
            // built-in types:  
            //2.1. integer (default = 0)
            byte myByte = 23; // unsigned 8-bis (0 to 255) default = 0
            sbyte mySByte = -128; // signed 8-bit (-128 to 127) default = 0
 
            short myShort = -1000; // signed 16-bit (-32,768 to 32,767)
            ushort myUshort = 2000;  // unsigned 16-bit (0 to 65,535)
 
            int myVar = 4; // signed 32-bit (-2,147,483,648 to 2,147,483,647)
            int myVar2 = 5; // signed 32-bit (-2,147,483,648 to 2,147,483,647)
 
            int sum = myVar + myVar2; // signed 32-bit (-2,147,483,648 to 2,147,483,647)
 
            uint myUint = 12000U; // unsigned 32-bit (0 to 4, 294, 967, 295)
 
            sum = 0xA8F1; // hexadecimal literal
            sum = 0XA8F1; // hexadecimal literal
 
            long myLong = 42432L;// signed 64-bit (-9,223,372,036,854,775,808 to 9,223,372,036,854,775,807)
            ulong myUlong = 23423423U; // unsigned 64-bit (0 to 18,446,744,073,709,551,615)
            ulong maxIntValue = UInt64.MaxValue;
            Console.WriteLine(maxIntValue); // 18446744073709551615
 
            // 2.2. Real (default 0.0 for F/f D/d M/m)
            float myFloat = 4.566F; // signed 32-bit (±1.5e-45 to ±3.4e38) up to 7 symbols/digits
            myFloat = 67.8E35f; // litteral with "E/e"
 
            double myDouble = 34.56d; // signed 64-bit (±5.0e-324 to ±1.7e+308) up to 15-16 symbols/digits
            myDouble = -3.4e-10d;
 
            decimal myDecimal = 23.45M; // signed 128-bit (±1.0e-28 to ±7.9e28) precission 28-29 symbols/digits, closest to 0 ±1.0e-28, decimal floating-point arithmetic
 
 
            // Declare some variables
            float floatPI = 3.141592653589793238f;
            double doublePI = 3.141592653589793238;
            // Print the results on the console
            Console.WriteLine("Float PI is: " + floatPI); // Float PI is: 3.141593 only 7 digits
            Console.WriteLine("Double PI is: " + doublePI); // Double PI is: 3.14159265358979  16 digits
 
            decimal decimalPI = 3.14159265358979323846m;
            Console.WriteLine(decimalPI); // 3.14159265358979323846
 
            // 2.3. Char
            char myFirstLetter = 'S';
            Console.WriteLine((int)myFirstLetter);
            char symbol = (char)78;
            Console.WriteLine(symbol);
            char myChar = '\u0065';
            Console.WriteLine(myChar);
            Console.WriteLine(myChar);
            myChar = '\uffff';
            Console.WriteLine(myChar);
            myChar = '\'';
 
            // escaping
            char myEscape = '\n'; // \n \t \r \' \\ \" \uXXXX
 
            // 2.4. String (default null) Reference, value in the heap. String.Compare(string1, string2) > 0 if they have to switch
            string myName = "Stoyan Cheresharov";
            string path = @"D:\CamtasiaVideos"; // instead of D:\\CamtasiaVideos
 
            Console.WriteLine($"The Path is {path}");
 
            //StringBuilder text = new StringBuilder();
            //foreach (char symbol in list)
            // {
            //    text.Append(symbol);
            //}
 
            // 2.5. Bool (default false)
            bool myBool = true; // false | true
 
            // 2.6. Object (default null) Reference, value in the heap (e.g. Structs are Value Types - Stored on the stack, Classes are Reference Types - Stored on the heap)
            Object myObject = 3;
            
            // 2.6.1. Nullable
            Nullable<int> i1 = null;
            int? i2 = i1;
 
            // 2.7. dynamic type the binding happens during run time not compilation time
            dynamic a = 1;
            dynamic b = "Hello World!";
           
            int i = a; // notice you don't need explicit type conversion
            string c = b; // no type conversion
 
            // *2.8. typeof() sizeof()
            // typeof()
            // Console.WriteLine(typeof(i1)); // error
            System.Type type = typeof(int);
            int i = 0;
            type = i.GetType();
            Console.WriteLine(type);
 
            // sizeof - Used to obtain the size in bytes for an unmanaged type.
            Console.WriteLine(sizeof(sbyte)); // 1
 
            // Unmanaged types include:
            // The simple types that are listed in the following table:
            // Expression Constant value
            //sizeof(sbyte)   1
            //sizeof(byte)    1
            //sizeof(short)   2
            //sizeof(ushort)  2
            //sizeof(int) 4
            //sizeof(uint)    4
            //sizeof(long)    8
            //sizeof(ulong)   8
            //sizeof(char)    2(Unicode)
            //sizeof(float)   4
            //sizeof(double)  8
            //sizeof(decimal) 16
            //sizeof(bool)    1
 
            Console.WriteLine("Hello World! The sum is " + sum);
            Console.WriteLine("-----------------------");
            Console.WriteLine((char)65);
            Console.WriteLine((int)'D');
            Console.WriteLine('\u0065');
            int? myVanya = null;
            Console.WriteLine("Vanya is " + myVanya.ToString() + " years old!");
            Console.WriteLine(sizeof(long));
            int myDesiInt = 10;
            // double myDesiDouble = 1.2;
            int myDesiDouble = 3;
            Console.WriteLine("Desi " + ((double)myDesiInt / myDesiDouble));
            // Console.WriteLine("Desi " + ((myDesiInt / myDesiDouble));
 
            int nikiAge = 18;
            Console.WriteLine("The age of Niki is " + nikiAge);
 
            int firstInt = 2; // -> 2.00
            double secondDouble = 3.14;
 
            Console.WriteLine(firstInt + secondDouble);
           
            // Implicid Explicid type conversions
            Console.WriteLine(3/(double)2); // Console.WriteLine(3/(double)2);
 
            // 1. Value Type vs. Reference Type
            // Structs are Value Types:
            //  Stored on the stack.
            //  When you assign one struct variable to another, a copy of the data is made.
            //  Modifying one variable does not affect the other.
 
            // Classes are Reference Types:
            //  Stored on the heap.
            //  When you assign one class instance to another, both variables reference the same object.
            //  Modifying the object through one variable affects all references to that object.
 
            struct PointStruct
            {
                public int X;
                public int Y;
            }
 
            class PointClass
            {
                public int X;
                public int Y;
            }
 
            // Using struct
            PointStruct ps1 = new PointStruct { X = 1, Y = 2 };
            PointStruct ps2 = ps1;
            ps2.X = 3;
            // ps1.X remains 1
 
            // Using class
            PointClass pc1 = new PointClass { X = 1, Y = 2 };
            PointClass pc2 = pc1;
            pc2.X = 3;
            // pc1.X is now 3
 
           // 3. Operators
            // Ctrl+r,r - refactoring/replace a name/string
            // Not possible
            //int? implicitConvertInt = 0;
            //if (implicitConvertInt) { // Can not implicitly convert type int to bool
            //}
            //Object implicitConverToObj = null;
            //if (implicitConverToObj) { // Can not implicitly convert type Obj to bool
            //}
 
           // Operators precedence:
           // ++, -- (като постфикс), new, (type), typeof, sizeof
           // ++, -- (като префикс), +, - (едноаргументни), !, ~
           // *, /, %
           // + (свързване на низове)
           // +, -
           // <<, >>
           // <, >, <=, >=, is, as
           // ==, !=
           // &, ^, |
           // &&
           // ||
           // ?: - ternary operator, ?? - null coalescing operator
           // =, *=, /=, %=, +=, -=, <<=, >>=, &=, ^=, |=
 
           // De Morgan Low
           // !(a && b) == (!a || !b) !(a || b) == (!a && !b)
           // Първият закон твърди, че отрицанието на конюнкцията (логическо И) на две съждения е равна на дизюнкцията (логическо ИЛИ) на техните отри-цания.
 
            myDesiInt++;
            Console.WriteLine(myDesiInt);
            Console.WriteLine((myDesiInt > 18) ? "You are an adult" : "You are young");
            byte myTest = 1;
            Console.WriteLine(myTest);
            Console.WriteLine(myTest << 1);
            Console.WriteLine(myTest << 2);
            myTest <<= 2;
            Console.WriteLine(myTest);
            byte myGeorgi = 8;
            Console.WriteLine(myTest | myGeorgi);
 
            int squarePerimeter = 17;
            double squareSide = squarePerimeter / 4.0;
            double squareArea = squareSide * squareSide;
            Console.WriteLine(squareSide); // 4.25
            Console.WriteLine(squareArea); // 18.0625
            
 
            int a = 5;
            int b = 4;
            Console.WriteLine(a + b); // 9
            Console.WriteLine(a + b++); // 9
            Console.WriteLine(a + b); // 10
            Console.WriteLine(a + (++b)); // 11
            Console.WriteLine(a + b); // 11
            Console.WriteLine(14 / a); // 2
            Console.WriteLine(14 % a); // 4
 
            // 3.1. Arithmetic operators 
            a = 11;
            b = 2;
            // Arithmetic operators
            Console.WriteLine(a + b);
            Console.WriteLine(a - b);
            Console.WriteLine(a / b);
            Console.WriteLine(a * b);
            Console.WriteLine(a++);
            Console.WriteLine(a);
            Console.WriteLine(++a);
            Console.WriteLine(a % b);
            Console.WriteLine(--a);
            Console.WriteLine(a--);
 
            //3.2. For comparison
            Console.WriteLine(a > b);
            Console.WriteLine(a < b);
            Console.WriteLine(a >= b);
            Console.WriteLine(a <= b);
            Console.WriteLine(a == b);
            Console.WriteLine(a != b);
 
            //3.3. Logical
            bool x = true;
            bool y = false;
 
            Console.WriteLine(x && y);
            Console.WriteLine(x || y);
            Console.WriteLine(x ^ y);
            Console.WriteLine(!x);
            Console.WriteLine(~3); // -4 w dopxlinitelen kod e chisloto
 
            //&&
            //x   y   z
            //0   0   0
            //1   0   0
            //0   1   0
            //1   1   1
 
            // ||
            //x   y   z
            //0   0   0
            //1   0   1
            //0   1   1
            //1   1   1
 
            // ^
            //x   y   z
            //0   0   0
            //1   0   1
            //0   1   1
            //1   1   0
 
 
            // !
            //x z
            //0 1
            //1 0 
 
 
            //3.4. for asignments
            a += 3; // a = a + 3;
 
            //3.5. Bitwise operators
            Console.WriteLine(1 << 1);
            Console.WriteLine(2 >> 1);
            Console.WriteLine(1 | 2);
            Console.WriteLine(1 & 2);
            Console.WriteLine(1 ^ 3);// 2
 
            // 3.6. trinary
            // int c = (a > b)? a : b; ternary operator
            // int? a = 5;
            // int? b = 6
            // a = null;
            // int? z = a ?? b; null coalescing operator
 
            // long d = 3214321342134231443;
 
            // int i = checked((int)d); // System.OverflowException
 
            int one = 1;
            int zero = 0;
            // Console.WriteLine(one / zero); // DivideByZeroException
            double dMinusOne = -1.0;
            double dZero = 0.0;
            Console.WriteLine(dMinusOne / zero); // -Infinity
            Console.WriteLine(one / dZero); // Infinity
 
           // 4. Console - Write, Read, ReadLine
            Console.Clear();
            Console.Write("Stoyan ");
            Console.Write("Cheresharov \n\r");
            Console.WriteLine("My name is Desi. I am {0} years old. my favorite number is {1}", myDesiInt, 3);
            Console.WriteLine("| {0,10:######} |", 12);
 
            // Formatting Numbers
            // Standard Formatting Symbols C, D, E, F, N, P, X
            Console.WriteLine("{0:C2}", 123.456); //Output: 123,46 лв.
            Console.WriteLine("{0:D6}", -1234); //Output: -001234
            Console.WriteLine("{0:E2}", 123); //Output: 1,23Е+002
            Console.WriteLine("{0:F2}", -123.456); //Output: -123,46
            Console.WriteLine("{0:N2}", 1234567.8); //Output: 1 234 567,80
            Console.WriteLine("{0:P}", 0.456); //Output: 45,60 %
            Console.WriteLine("{0:X}", 254); //Output: FE
 
            // Custom Formatting Symbols 0000, ###, %, E0 Е+0 Е-0
            Console.WriteLine("{0:0.00}", 1); //Output: 1,00
            Console.WriteLine("{0:#.##}", 0.234); //Output: ,23
            Console.WriteLine("{0:#####}", 12345.67); //Output: 12346
            Console.WriteLine("{0:(0#) ### ## ##}", 29342525); //Output: (02) 934 25 25
            Console.WriteLine("{0:%##}", 0.234);//Output: %23
 
            // Standard Formatting Symbols for DateTime
            DateTime d = new DateTime(2018, 9, 14, 15, 30, 22);
 
            Console.WriteLine("{0:D}", d); // d D
            Console.WriteLine("{0:t}", d); // t T
            Console.WriteLine("{0:Y}", d); // y Y
 
            // Custom Formatting Symbols for DateTime d, dd, M, MM, yy, yyyy, hh, HH, m, mm, s, ss
            Console.WriteLine("{0:dd/MM/yyyy HH:mm:ss}", d);
            Console.WriteLine("{0:d.MM.yy г.}", d);
            // return;
            Console.Clear();
            Thread.CurrentThread.CurrentCulture =
            CultureInfo.GetCultureInfo("bg-Bg");
 
            Console.WriteLine("| {0,10:C} |", 120000.4532);
            Console.Clear();
 
            // Reading from the console and parsing
 
            Console.Write("Please enter your age: ");
            string inputVariable = Console.ReadLine();
 
            // Parsing strings to numbers
            int age = int.Parse(inputVariable);
            double ageInDouble;
            double.TryParse(inputVariable, out ageInDouble);
            Console.WriteLine(Convert.ToInt16(inputVariable));
            Console.WriteLine(age + 10);
 
            // Read a character from the input with Read
            //Console.Write("Please enter a character: ");
            //int nextChar = Console.Read();
            //Console.WriteLine(nextChar);
            //Console.WriteLine((char)nextChar);
            // return;
 
            // ReadKey
            //Console.WriteLine("Please press ESC key to exit this endless loop");
            //ConsoleKeyInfo cki;
            //do {              
            //    if (!Console.KeyAvailable)
            //    {
            //        Console.Clear();
            //        Console.WriteLine("Please hit Esc");
            //    }
            //    cki = Console.ReadKey(true);
            //    System.Threading.Thread.Sleep(50);
            //} while(cki.Key != ConsoleKey.Escape);
 
 
            Console.OutputEncoding = Encoding.UTF8;
 
            Console.ForegroundColor = ConsoleColor.Green;
            // Console.BackgroundColor = ConsoleColor.Blue;
            // To change the background color of the > console window as a whole, set the BackgroundColor property and call the Clear method.
            // Console.BackgroundColor = ConsoleColor.Blue;
            // Console.Clear();
 
            Console.SetCursorPosition(5, 10); // left top
            Console.WriteLine("Това е кирилица: ☺");
 
            Thread.CurrentThread.CurrentCulture =
            CultureInfo.GetCultureInfo("en-GB"); // UK doesn't work
 
            // Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture;
 
            Console.WriteLine("Your balance is {0, 30:C2}", 1234567.8904534);
 
            //for (int charCode = 0; charCode < 1000; i++)
            //{
            //    Console.WriteLine((char)i);
            //}
 
           // 5. Conditional logic (Управляващи структури)
            int secondNumber = 3;
            int firstNumber = 2;
            if (secondNumber > firstNumber)
            {
                // int biggerNumber = secondNumber;
                Console.WriteLine(secondNumber);
            }
 
            int myAge = 12;
 
            if (myAge < 3)
            {
                Console.WriteLine("You are a baby!");
            }
            else if (3 <= myAge && myAge < 12) {
                Console.WriteLine("You are a kid!");
            }
            else if (12 <= myAge && myAge < 18)
            {
                Console.WriteLine("You are a teenager!");
            }
            else if (18 <= myAge && myAge < 30)
            {
                Console.WriteLine("You are in your golden age!");
            }
            else
            {
                Console.WriteLine("You are an adult");
            }           
 
            char ch = 'X';
            if (ch == 'A' || ch == 'a')
            {
                Console.WriteLine("Vowel [ei]");
            }
            else if (ch == 'E' || ch == 'e')
            {
                Console.WriteLine("Vowel [i:]");
            }
            else if (ch == 'I' || ch == 'i')
            {
                Console.WriteLine("Vowel [ai]");
            }
            else if (ch == 'O' || ch == 'o')
            {
                Console.WriteLine("Vowel [ou]");
            }
            else if (ch == 'U' || ch == 'u')
            {
                Console.WriteLine("Vowel [ju:]");
            }
            else
            {
                Console.WriteLine("Consonant");
            }
 
            //if (булев израз)
            //{
            //    тяло на условната конструкция;
            //}
            //else
            //{
            //    тяло на else-конструкция;
            //}
 
            if (nikiAge > 0 && nikiAge < 12)
            {
                Console.WriteLine("You are a child");
            }
            else if (nikiAge >= 12 && nikiAge < 20)
            {
                Console.WriteLine("You are a teenager");
            }
            else
            {
                Console.WriteLine("You are adult.");
            }
 
            //switch (селектор)
            //{
            //    case целочислена - стойност - 1: конструкция; break;
            //    case целочислена - стойност - 2: конструкция; break;
            //    case целочислена - стойност - 3: конструкция; break;
            //    case целочислена - стойност - 4: конструкция; break;
            //    // …
            //    default: конструкция; break;
            //}
            char firtsLetter = 'S';
            switch (firtsLetter)
            {
                case 'S':
                    Console.WriteLine("Your first letter tells me you are a lucky man!");
                    break;
                case 'V':
                    Console.WriteLine("You are victorious!");
                    break;
                default:
                    Console.WriteLine("I don't know?");
                    break;
            }
 
           // 6. Loops (Цикли)
            //while (условие)
            //{
            //    тяло на цикъла;
            //}
 
            // Initialize the counter
            int counter = 0;
            // Execute the loop body while the loop condition holds
            while (counter <= 9)
            {
                // Print the counter value
                Console.WriteLine("Number : " + counter);
                // Increment the counter
                counter++;
            }
 
            //  n! = (n - 1)!*n
            Console.Write("Please, enter a number: ");
            int n = int.Parse(Console.ReadLine());
            // "decimal" is the biggest type that can hold integer values
            decimal factorial = 1;
            // Perform an "infinite loop"
            while (true)
            {
                if (n <= 1)
                {
                    break;
                }
                factorial *= n;
                n--;
            }
            Console.WriteLine("n! = " + factorial);
 
            int myDoTest = 0;
            do
            {
                Console.Write("Please enter a number betwen 0 and 5: ");
                myDoTest = int.Parse(Console.ReadLine());
            } while (myDoTest > 5 || myDoTest < 0);
 
            //for (инициализация; условие; обновяване)
            //{
            //    тяло на цикъла;
            //}
 
            for (int j = 0; j <= 10; j++)
            {
                Console.Write(j + " ");
            }
 
            int t = 0;
            while (t < 10)
            {
                // i++;
                // break;
                if (t % 2 == 0)
                {
                    t++;
                    continue;
                }
                Console.WriteLine("t = " + t);
                t++;
            }
             
             // break example
            // Is the number prime
            bool isPrime = true;
            Console.Write("Please, enter a number: ");
            int n = int.Parse(Console.ReadLine());
            int iterator = 2;
            while (iterator < n)
            {
                if (n % iterator == 0)
                {
                    isPrime = false;
                    break;
                }
                iterator++;
            }
 
            int[] numbers = { 2, 3, 5, 7, 11, 13, 17, 19 };
            foreach (int k in numbers)
            {
                Console.Write(" " + k);
            }
            Console.WriteLine();
 
            String[] towns = { "Sofia", "Plovdiv", "Varna", "Bourgas" };
            foreach (String town in towns)
            {
                Console.Write(" " + town);
            }
 
            // continue
            foreach (var item in numbers)
            {
                if (item % 2 == 0)
                {
                    continue;
                }
 
                Console.WriteLine(item);
            }
 
            // 7. Arrays (Масиви)
            int special = 34;
            Console.WriteLine($"This is my variable {special}");
 
            Console.BackgroundColor = ConsoleColor.DarkBlue;
            Console.Clear();
            Console.ForegroundColor = ConsoleColor.Yellow;
 
            string[] students = new string[100];
            students[0] = "Konstantin";
            students[1] = "Angel";
 
            Console.WriteLine(students[0]);
 
            int[] myArray = { 1, 2, 3, 4, 5, 6 };
            int[] myArray2 = new int[3] { 23, 45, 67 };
 
            string[] daysOfWeek =
            {
                "Monday",
                "Tuesday",
                "Wednesday",
                "Thursday",
                "Friday",
                "Saturday",
                "Sunday"
            };
 
            int[] array = new int[] { 1, 2, 3, 4, 5 };
            Console.Write("Output: ");
            for (int index = 0; index < array.Length; index++)
            {
                // Doubling the number
                array[index] = 2 * array[index];
                // Print the number
                Console.Write(array[index] + " ");
            }
            // Output: 2 4 6 8 10
 
            //foreach (var item in collection)
            //{
            //    // Process the value here
            //}
 
            int[,] matrix =
            {
                {1, 2, 3, 4}, // row 0 values
                {5, 6, 7, 8}, // row 1 values
            };
            // The matrix size is 2 x 4 (2 rows, 4 cols)
 
            Console.WriteLine();
            Console.WriteLine(matrix[0,3]); // 4
 
            Console.WriteLine(matrix.GetLength(0));
            Console.WriteLine(matrix.GetLength(1));
 
            int[][] myJaggedArray = {
                new int[] {5, 7, 2},
                new int[] {10, 20, 40},
                new int[] {3, 25},
                new int[] { 1,2,3,4,5,6,78,9}
            };
 
            int[][,] jaggedOfMulti = new int[2][,];
 
            // another way to declare jagged array
            int[][] jaggedArray;
            jaggedArray = new int[2][];
            jaggedArray[0] = new int[5];
            jaggedArray[1] = new int[3];
 
            // 8. Numbering systems (Бройни системи) Бройната система е правилата и символите които използваме за запис стойността на числата
            // String number = "100";
            // int fromBase = 16;
            // int toBase = 10;
 
            // String result1 = Convert.ToString(Convert.ToInt32(number, fromBase), toBase);
 
            // e.g.
            // Console.WriteLine("2093 to BIN {0}.", Convert.ToString(2093, 2));
            // Console.WriteLine("2093 to OCT {0}.", Convert.ToString(2093, 8));
            // Console.WriteLine("2093 to HEX {0}.", Convert.ToString(2093, 16));
 
            // int number = Convert.ToInt32("1111010110011110", 2); // To enter a number is arbitrary numbering system
            // Console.WriteLine("{0}, to HEX {1}.",
            //    number,Convert.ToString(number, 16)); // To write in a different numbering system 2, 8, 16
 
           // result == "256"
           // Console.WriteLine(result1);
           // Random randomGenerator = new Random(); https://docs.microsoft.com/en-us/dotnet/api/system.random?view=netcore-3.1
           // randomGenerator.Next(); https://docs.microsoft.com/en-us/dotnet/api/system.random.next?view=netcore-3.1
 
 
 
            /* 8.1. Позиционни и непозиционни бройни системи
           Iv VI - Римската бройна система - Непозиционна
           8.2. Определне стойността на числото в съответната бройна система
           44 - Арабската бройна система Позиционна. Позицията на цифрата в записа на числото определя стойността и.
           цифрите - азбуката на числата
           числата - думите записани с помощта на цифрите. Те имат стойност. Стойността се определя с помощта на основата на бройната система
           Стойността на числото в една позиционна бройна система се определя като се умножи цифрата по основата на бройната система повдигната на степен позицията броена отзад напред започвайки от 0:
           4*10^1 + 4*10^0 => цифрата се умножава по основата на бройната система повдигната на степен позицията на цифрата в числото броена отзад напред започвайки от 0.
           1001110 (2) - трябва да знаем основата на бройната система за да определим стойността на числото  
           F4(16)  - число в 16-тична бройна система
           74(8) - число в осмична бройна система
 
            // Convert to binary system
            Console.Write("Please, enter a number to convert to binary: ");
            // with 340282366920938000000000000000000000000
            // System.OverflowException: Value was either too large or too small for an Int32.
            int number2Convert = int.Parse(Console.ReadLine());
            int[] binaryNumber = new int[128]; // the default value is 0
            int digitCounter = 127;
            while (number2Convert > 0 && digitCounter > 0)
            {
                binaryNumber[digitCounter] = number2Convert % 2;
                digitCounter--;
                number2Convert /= 2;
                Console.WriteLine(number2Convert);
            }
            foreach (var digit in binaryNumber)
            {
                Console.Write(digit);
            }
            Console.WriteLine();
            Console.WriteLine(Math.Pow(2, 128)); // 3.40282366920938E+38
            // Console.WriteLine("{0,10:N}", Math.Pow(2, 128)); // 340,282,366,920,938,000,000,000,000,000,000,000,000.00
            // Console.WriteLine("{0,10:D}", Math.Pow(2, 128)); // Exception
            Console.WriteLine("{0,10:F0}", Math.Pow(2, 128)); // 340282366920938000000000000000000000000
 
                // https://stackoverflow.com/questions/2954962/convert-integer-to-binary-in-c-sharp
                int value = 8;
                string binary = Convert.ToString(value, 2);
 
                // Convert from any classic base to any base in C#
               
                String number = "100";
                int fromBase = 16;
                int toBase = 10;
 
                String result = Convert.ToString(Convert.ToInt32(number, fromBase), toBase);
 
                // result == "256"
                // Supported bases are 2, 8, 10 and 16
 
                var bin = Convert.ToString(n, 2);
                var oct = Convert.ToString(n, 8);
                var hex = Convert.ToString(n, 16);
 
            */
            // 8.3. Конвертиране от една в друга бройна система
            // Convert from decimal to binary system
            //34 - > 100010 = 1 * 2 ^ 5 + 0 + 0 + 0 + 1 * 2 ^ 1 + 0 = 32 + 2 = 34
 
            //34 : 2 = 17  0
            //17 : 2 = 8   1
            //8 : 2 = 4    0
            //4 : 2 = 2    0
            //2 : 2 = 1    0
            //             1
 
            //100010
            //100010
            // 8.3.2. Кконвертиране от двоична в шестнадесететична и обратно. Правилото 8421
            // 8| 4 | 2 | 1
            // e.g. 12 is 8 + 4 then we put 1 in positions of 8 and 4 -> 1100
 
            // Convert form base 16 to base 2
            //0010 | 1010 | 1010 | 1010 | 1111 | 1110 | 0001 | 1111 | 1111
            // 8.4. Прав обратен допълнителен код
            //2AAAFD1FF
           // Прав - 345
           // Обратен (10^3 - 1) - 345 = 999 - 345 = 654
           // Допълнителен код (10^3) - 345 или обратния код + 1 => 654 + 1 = 655 
           // Операцията изваждане се заменя със събиране като към умаляемото се добави допълнителния код на умалителя
           // 8 - 5 = 3 - прав код
           // допълнителния код на умалителя 5 е => 9 - 5 = 4 - обратен 4 + 1 = 5 - допьлнителен
            // 8 + 5 = 1 | 3 - преносът се отстранява
            // 4 - 7 = -3
            // допълнителния код на умалителя 7 е 9 - 7 = 2 + 1 = 3
            // 4 + 3 = 7 ако няма пренос значи резултата е в допьлнителен код и отрицателно число => 9 - 7 = 2 + 1 = 3 => -3
8.5 Floating point Числа с плаваща запетая
23.41 => 
 
23 : 2 = 11 | 1
11 : 2 = 5 | 1
5 : 2 = 2 | 1
2 : 2 = 1 | 0
           1
 
10111.0110 => 1.01110110 *2^4
 
0.41 * 2 = 0.82 | 0
0.82 * 2 = 0.64 | 1
0.64 * 2 = 0.28 | 1
0.28 * 2 = 0.56 | 0
...
 
2345.45=> 2.34545 * 10^3
 
            // 9. Methods. Именован блок от кода който може да приема или не формални параметри или може да има или не върната стойност
            // Method calls
            string[] studentsTemp = new string[2];
            InputNames(studentsTemp);
            InputNames(studentsTemp, 5);
            InputNames(studentsTemp, 3, 2, 3, 4, 5, 6, 2, 3, 6, 6);
            InputNames(n: 6, names: studentsTemp);
 
            // 12.09.2019
            int sum1 = Sum(100, 2000);
            Console.WriteLine(sum1);
 
            // 13.09.2019 
            sum1 = Sum(34, 2500);
            Console.WriteLine(sum1);
 
           // 10. Recursion
            // Recursion
            int factorial2 = 5;
            Console.WriteLine("!{0} = {1}", factorial2, Factorial(factorial2));
 
 
            // Standard Math functions
            Console.WriteLine(Math.Cos(23));
 
            // every string can be used as array
            string stoyanName = "Stoyan";
            Console.WriteLine(stoyanName[0]); // S
            // string functions - tyme the name of the variable and .
            Console.WriteLine(stoyanName.IndexOf('t'));
            // etc.
 
             // for concatenating a lot of strings use StringBuilder, don't concatenate directly with +
             // var fb = new StringBuilder();
            // for (int i = 0; i < 100000; ++i) {
            //    fb.Append("Sample");
            // }
           // var f = fb.ToString();
        }
 
        static string Greet(string name= "Default")
        {
            return $"Hello {name}!";
        }
 
        // Method declaration and definition, default parameters, variable number of parameters
        static void InputNames(string[] names, int n = 4, params int[] myExtraParams)
        {
            for (var i = 0; i < names.Length; i++)
            {
                Console.Write("Please enter element number {0} :", i);
                names[i] = Console.ReadLine() + " Default Mark = " + n + " Final Mark" + ((myExtraParams.Length > 0) ? myExtraParams[i].ToString() : "0"); //
                Console.WriteLine(names[i]);
            }
        }
 
        static int Sum(int firstNumber, int secondNumber = 2000)
        {
            int sum = 0;
            sum = firstNumber + secondNumber;
            return sum;
        }
 
        // Recursion
        // !n = !(n-1) * n
        static int Factorial(int n)
        {
            if (n == 0) return 1;
            return Factorial(n - 1) * n;
        }
 
        static void GreetingUser(string name, int age = 0, int multiplier = 2)
        {
            // int multiplier = 2;
            Console.WriteLine($"Greeting {name}! I will multiply your age by {multiplier} and the result is {age * multiplier}");
        }
 
        static int SumCustom(int n , int m) 
        {
            // Console.WriteLine(n + m);
            int sum = n + m;
            return sum;
        }
 
        static void PrintVariableParameters(string greeting = "Hello", params string[] names)
        {
            for (int i = 0; i < names.Length; i++)
            {
                Console.WriteLine($"{greeting} {names[i]}");
            }
            
        }
 
        static int FactorialIteration(int n)
        {
            int factorial = 1;
            for (int i = 1; i <= n; i++)
            {
                factorial *= i;
            }
            return factorial;
        }
 
        // 0! = 1
        // n! = (n - 1)! * n
        static int FactorialRecursion(int n)
        {
            if (n == 0) return 1;
            return FactorialRecursion(n - 1) * n;
        }
 
        static int CalcCompoundInterest(double amount, double interest, int period)
        {
            // double amount, double interest, int period
            double finalAmount = amount * Math.Pow((1 + interest/100), period);
        }
 
        static void PrintFibonacci(int n)
        {
            ulong previos1 = 0;
            ulong previos2 = 1;
            ulong temp;
            Console.WriteLine(previos1);
            Console.WriteLine(previos2);
            for (int i = 0; i < n; i++)
            {
                Console.WriteLine(previos1 + previos2);
                temp = previos1;
                previos1 = previos2;
                previos2 = temp + previos2;
            }
        }
 
 
        static int GetFibonacciNumber (int n )
        {
            if (n <= 1) return n;
            int fibonacci1 = 0;
            int fibonacci2 = 1;
            int fibonacci = 0; 
 
            for (int i = 1; i < n; i++)
            {
 
                fibonacci = fibonacci1 + fibonacci2;
                fibonacci1 = fibonacci2;
                fibonacci2 = fibonacci;
 
            }
            return fibonacci;
        }
 
 
        static int GetFibonacciNumberR (int n)
        {
             if (n <= 1) return n;
            return GetFibonacciNumberR(n - 1) + GetFibonacciNumberR(n - 2);
        }
 
        static void SortBubble(int[] array)
        {
            int temp;
            for (int i = 0; i < array.Length; i++)
            {
                for (int j = i + 1; j < array.Length; j++)
                {
                  if (array[i] > array[j])  
                  {
                        temp= array[i];
                        array[i] = array[j];
                        array[j] = temp;
                  }  
                }
            }
        }
 
 
        static int[] FilterOdd(int[] array)
        {
            int[] result = new int[array.Length];
            for (int i = 0; i < array.Length; i++)
            {
                if (array[i] % 2 == 1)
                {
                    result[i] = array[i];
                }
            }
            return result;
        }
 
    }
}

Comments