Advertisement
wingman007

CheatSheetIntroProgrammingC#

Sep 13th, 2019 (edited)
3,032
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 35.25 KB | None | 0 0
  1. using System;
  2.  
  3. namespace IntroProgramming2019
  4. {
  5.     class Program
  6.     {
  7.         static void Main(string[] args)
  8.         {
  9.             // 1. Hello World
  10.             Console.WriteLine("Hello World!");
  11.            
  12.             // Shortcuts Ctrl+. | Ctrl+r,r | cw \t\t | Ctrl+k,d | Ctrl+k,c | Ctrl+k,u
  13.             // 2. Primitive data types, variables, literals
  14.             // variable - A variable is a named piece of memory intended to hold data
  15.             // variable type determines the type of data the variable can hold. The types that come predefined with the language are called primitive data types.
  16.             // literal is a symbol constant directly expressed in the code for setting a value of a variable
  17.  
  18.             //Let's declare and initialize a variable
  19.             byte myByte1 = 1;
  20.             byte myByte2 = 7;
  21.  
  22.             sbyte mySByte1 = -1;
  23.  
  24.             Console.WriteLine(myByte1 + myByte2);
  25.  
  26.             // I. Types have: name (e.g. int), size, default value
  27.             // 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
  28.             // built-in types:  
  29.             //2.1. integer (default = 0)
  30.             byte myByte = 23; // unsigned 8-bis (0 to 255) default = 0
  31.             sbyte mySByte = -128; // signed 8-bit (-128 to 127) default = 0
  32.  
  33.             short myShort = -1000; // signed 16-bit (-32,768 to 32,767)
  34.             ushort myUshort = 2000;  // unsigned 16-bit (0 to 65,535)
  35.  
  36.             int myVar = 4; // signed 32-bit (-2,147,483,648 to 2,147,483,647)
  37.             int myVar2 = 5; // signed 32-bit (-2,147,483,648 to 2,147,483,647)
  38.  
  39.             int sum = myVar + myVar2; // signed 32-bit (-2,147,483,648 to 2,147,483,647)
  40.  
  41.             uint myUint = 12000U; // unsigned 32-bit (0 to 4, 294, 967, 295)
  42.  
  43.             sum = 0xA8F1; // hexadecimal literal
  44.             sum = 0XA8F1; // hexadecimal literal
  45.  
  46.             long myLong = 42432L;// signed 64-bit (-9,223,372,036,854,775,808 to 9,223,372,036,854,775,807)
  47.             ulong myUlong = 23423423U; // unsigned 64-bit (0 to 18,446,744,073,709,551,615)
  48.             ulong maxIntValue = UInt64.MaxValue;
  49.             Console.WriteLine(maxIntValue); // 18446744073709551615
  50.  
  51.             // 2.2. Real (default 0.0 for F/f D/d M/m)
  52.             float myFloat = 4.566F; // signed 32-bit (±1.5e-45 to ±3.4e38) up to 7 symbols/digits
  53.             myFloat = 67.8E35f; // litteral with "E/e"
  54.  
  55.             double myDouble = 34.56d; // signed 64-bit (±5.0e-324 to ±1.7e+308) up to 15-16 symbols/digits
  56.             myDouble = -3.4e-10d;
  57.  
  58.             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
  59.  
  60.  
  61.             // Declare some variables
  62.             float floatPI = 3.141592653589793238f;
  63.             double doublePI = 3.141592653589793238;
  64.             // Print the results on the console
  65.             Console.WriteLine("Float PI is: " + floatPI); // Float PI is: 3.141593 only 7 digits
  66.             Console.WriteLine("Double PI is: " + doublePI); // Double PI is: 3.14159265358979  16 digits
  67.  
  68.             decimal decimalPI = 3.14159265358979323846m;
  69.             Console.WriteLine(decimalPI); // 3.14159265358979323846
  70.  
  71.             // 2.3. Char
  72.             char myFirstLetter = 'S';
  73.             Console.WriteLine((int)myFirstLetter);
  74.             char symbol = (char)78;
  75.             Console.WriteLine(symbol);
  76.             char myChar = '\u0065';
  77.             Console.WriteLine(myChar);
  78.             Console.WriteLine(myChar);
  79.             myChar = '\uffff';
  80.             Console.WriteLine(myChar);
  81.             myChar = '\'';
  82.  
  83.             // escaping
  84.             char myEscape = '\n'; // \n \t \r \' \\ \" \uXXXX
  85.  
  86.             // 2.4. String (default null) Reference, value in the heap. String.Compare(string1, string2) > 0 if they have to switch
  87.             string myName = "Stoyan Cheresharov";
  88.             string path = @"D:\CamtasiaVideos"; // instead of D:\\CamtasiaVideos
  89.  
  90.             Console.WriteLine($"The Path is {path}");
  91.  
  92.             //StringBuilder text = new StringBuilder();
  93.             //foreach (char symbol in list)
  94.             // {
  95.             //    text.Append(symbol);
  96.             //}
  97.  
  98.             // 2.5. Bool (default false)
  99.             bool myBool = true; // false | true
  100.  
  101.             // 2.6. Object (default null) Reference, value in the heap
  102.             Object myObject = 3;
  103.            
  104.             // 2.6.1. Nullable
  105.             Nullable<int> i1 = null;
  106.             int? i2 = i1;
  107.  
  108.             // 2.7. dynamic type the binding happens during run time not compilation time
  109.             dynamic a = 1;
  110.             dynamic b = "Hello World!";
  111.            
  112.             int i = a; // notice you don't need explicit type conversion
  113.             string c = b; // no type conversion
  114.  
  115.             // *2.8. typeof() sizeof()
  116.             // typeof()
  117.             // Console.WriteLine(typeof(i1)); // error
  118.             System.Type type = typeof(int);
  119.             int i = 0;
  120.             type = i.GetType();
  121.             Console.WriteLine(type);
  122.  
  123.             // sizeof - Used to obtain the size in bytes for an unmanaged type.
  124.             Console.WriteLine(sizeof(sbyte)); // 1
  125.  
  126.             // Unmanaged types include:
  127.             // The simple types that are listed in the following table:
  128.             // Expression Constant value
  129.             //sizeof(sbyte)   1
  130.             //sizeof(byte)    1
  131.             //sizeof(short)   2
  132.             //sizeof(ushort)  2
  133.             //sizeof(int) 4
  134.             //sizeof(uint)    4
  135.             //sizeof(long)    8
  136.             //sizeof(ulong)   8
  137.             //sizeof(char)    2(Unicode)
  138.             //sizeof(float)   4
  139.             //sizeof(double)  8
  140.             //sizeof(decimal) 16
  141.             //sizeof(bool)    1
  142.  
  143.             Console.WriteLine("Hello World! The sum is " + sum);
  144.             Console.WriteLine("-----------------------");
  145.             Console.WriteLine((char)65);
  146.             Console.WriteLine((int)'D');
  147.             Console.WriteLine('\u0065');
  148.             int? myVanya = null;
  149.             Console.WriteLine("Vanya is " + myVanya.ToString() + " years old!");
  150.             Console.WriteLine(sizeof(long));
  151.             int myDesiInt = 10;
  152.             // double myDesiDouble = 1.2;
  153.             int myDesiDouble = 3;
  154.             Console.WriteLine("Desi " + ((double)myDesiInt / myDesiDouble));
  155.             // Console.WriteLine("Desi " + ((myDesiInt / myDesiDouble));
  156.  
  157.             int nikiAge = 18;
  158.             Console.WriteLine("The age of Niki is " + nikiAge);
  159.  
  160.             int firstInt = 2; // -> 2.00
  161.             double secondDouble = 3.14;
  162.  
  163.             Console.WriteLine(firstInt + secondDouble);
  164.            
  165.             // Implicid Explicid type conversions
  166.             Console.WriteLine(3/(double)2); // Console.WriteLine(3/(double)2);
  167.  
  168.            // 3. Operators
  169.             // Ctrl+r,r - refactoring/replace a name/string
  170.             // Not possible
  171.             //int? implicitConvertInt = 0;
  172.             //if (implicitConvertInt) { // Can not implicitly convert type int to bool
  173.             //}
  174.             //Object implicitConverToObj = null;
  175.             //if (implicitConverToObj) { // Can not implicitly convert type Obj to bool
  176.             //}
  177.  
  178.            // Operators precedence:
  179.            // ++, -- (като постфикс), new, (type), typeof, sizeof
  180.            // ++, -- (като префикс), +, - (едноаргументни), !, ~
  181.            // *, /, %
  182.            // + (свързване на низове)
  183.            // +, -
  184.            // <<, >>
  185.            // <, >, <=, >=, is, as
  186.            // ==, !=
  187.            // &, ^, |
  188.            // &&
  189.            // ||
  190.            // ?: - ternary operator, ?? - null coalescing operator
  191.            // =, *=, /=, %=, +=, -=, <<=, >>=, &=, ^=, |=
  192.  
  193.            // De Morgan Low
  194.            // !(a && b) == (!a || !b) !(a || b) == (!a && !b)
  195.            // Първият закон твърди, че отрицанието на конюнкцията (логическо И) на две съждения е равна на дизюнкцията (логическо ИЛИ) на техните отри-цания.
  196.  
  197.             myDesiInt++;
  198.             Console.WriteLine(myDesiInt);
  199.             Console.WriteLine((myDesiInt > 18) ? "You are an adult" : "You are young");
  200.             byte myTest = 1;
  201.             Console.WriteLine(myTest);
  202.             Console.WriteLine(myTest << 1);
  203.             Console.WriteLine(myTest << 2);
  204.             myTest <<= 2;
  205.             Console.WriteLine(myTest);
  206.             byte myGeorgi = 8;
  207.             Console.WriteLine(myTest | myGeorgi);
  208.  
  209.             int squarePerimeter = 17;
  210.             double squareSide = squarePerimeter / 4.0;
  211.             double squareArea = squareSide * squareSide;
  212.             Console.WriteLine(squareSide); // 4.25
  213.             Console.WriteLine(squareArea); // 18.0625
  214.            
  215.  
  216.             int a = 5;
  217.             int b = 4;
  218.             Console.WriteLine(a + b); // 9
  219.             Console.WriteLine(a + b++); // 9
  220.             Console.WriteLine(a + b); // 10
  221.             Console.WriteLine(a + (++b)); // 11
  222.             Console.WriteLine(a + b); // 11
  223.             Console.WriteLine(14 / a); // 2
  224.             Console.WriteLine(14 % a); // 4
  225.  
  226.             // 3.1. Arithmetic operators
  227.             a = 11;
  228.             b = 2;
  229.             // Arithmetic operators
  230.             Console.WriteLine(a + b);
  231.             Console.WriteLine(a - b);
  232.             Console.WriteLine(a / b);
  233.             Console.WriteLine(a * b);
  234.             Console.WriteLine(a++);
  235.             Console.WriteLine(a);
  236.             Console.WriteLine(++a);
  237.             Console.WriteLine(a % b);
  238.             Console.WriteLine(--a);
  239.             Console.WriteLine(a--);
  240.  
  241.             //3.2. For comparison
  242.             Console.WriteLine(a > b);
  243.             Console.WriteLine(a < b);
  244.             Console.WriteLine(a >= b);
  245.             Console.WriteLine(a <= b);
  246.             Console.WriteLine(a == b);
  247.             Console.WriteLine(a != b);
  248.  
  249.             //3.3. Logical
  250.             bool x = true;
  251.             bool y = false;
  252.  
  253.             Console.WriteLine(x && y);
  254.             Console.WriteLine(x || y);
  255.             Console.WriteLine(x ^ y);
  256.             Console.WriteLine(!x);
  257.             Console.WriteLine(~3); // -4 w dopxlinitelen kod e chisloto
  258.  
  259.             //&&
  260.             //x   y   z
  261.             //0   0   0
  262.             //1   0   0
  263.             //0   1   0
  264.             //1   1   1
  265.  
  266.             // ||
  267.             //x   y   z
  268.             //0   0   0
  269.             //1   0   1
  270.             //0   1   1
  271.             //1   1   1
  272.  
  273.             // ^
  274.             //x   y   z
  275.             //0   0   0
  276.             //1   0   1
  277.             //0   1   1
  278.             //1   1   0
  279.  
  280.  
  281.             // !
  282.             //x z
  283.             //0 1
  284.             //1 0
  285.  
  286.  
  287.             //3.4. for asignments
  288.             a += 3; // a = a + 3;
  289.  
  290.             //3.5. Bitwise operators
  291.             Console.WriteLine(1 << 1);
  292.             Console.WriteLine(2 >> 1);
  293.             Console.WriteLine(1 | 2);
  294.             Console.WriteLine(1 & 2);
  295.             Console.WriteLine(1 ^ 3);// 2
  296.  
  297.             // 3.6. trinary
  298.             // int c = (a > b)? a : b; ternary operator
  299.             // int? a = 5;
  300.             // int? b = 6
  301.             // a = null;
  302.             // int? z = a ?? b; null coalescing operator
  303.  
  304.             // long d = 3214321342134231443;
  305.  
  306.             // int i = checked((int)d); // System.OverflowException
  307.  
  308.             int one = 1;
  309.             int zero = 0;
  310.             // Console.WriteLine(one / zero); // DivideByZeroException
  311.             double dMinusOne = -1.0;
  312.             double dZero = 0.0;
  313.             Console.WriteLine(dMinusOne / zero); // -Infinity
  314.             Console.WriteLine(one / dZero); // Infinity
  315.  
  316.            // 4. Console - Write, Read, ReadLine
  317.             Console.Clear();
  318.             Console.Write("Stoyan ");
  319.             Console.Write("Cheresharov \n\r");
  320.             Console.WriteLine("My name is Desi. I am {0} years old. my favorite number is {1}", myDesiInt, 3);
  321.             Console.WriteLine("| {0,10:######} |", 12);
  322.  
  323.             // Formatting Numbers
  324.             // Standard Formatting Symbols C, D, E, F, N, P, X
  325.             Console.WriteLine("{0:C2}", 123.456); //Output: 123,46 лв.
  326.             Console.WriteLine("{0:D6}", -1234); //Output: -001234
  327.             Console.WriteLine("{0:E2}", 123); //Output: 1,23Е+002
  328.             Console.WriteLine("{0:F2}", -123.456); //Output: -123,46
  329.             Console.WriteLine("{0:N2}", 1234567.8); //Output: 1 234 567,80
  330.             Console.WriteLine("{0:P}", 0.456); //Output: 45,60 %
  331.             Console.WriteLine("{0:X}", 254); //Output: FE
  332.  
  333.             // Custom Formatting Symbols 0000, ###, %, E0 Е+0 Е-0
  334.             Console.WriteLine("{0:0.00}", 1); //Output: 1,00
  335.             Console.WriteLine("{0:#.##}", 0.234); //Output: ,23
  336.             Console.WriteLine("{0:#####}", 12345.67); //Output: 12346
  337.             Console.WriteLine("{0:(0#) ### ## ##}", 29342525); //Output: (02) 934 25 25
  338.             Console.WriteLine("{0:%##}", 0.234);//Output: %23
  339.  
  340.             // Standard Formatting Symbols for DateTime
  341.             DateTime d = new DateTime(2018, 9, 14, 15, 30, 22);
  342.  
  343.             Console.WriteLine("{0:D}", d); // d D
  344.             Console.WriteLine("{0:t}", d); // t T
  345.             Console.WriteLine("{0:Y}", d); // y Y
  346.  
  347.             // Custom Formatting Symbols for DateTime d, dd, M, MM, yy, yyyy, hh, HH, m, mm, s, ss
  348.             Console.WriteLine("{0:dd/MM/yyyy HH:mm:ss}", d);
  349.             Console.WriteLine("{0:d.MM.yy г.}", d);
  350.             // return;
  351.             Console.Clear();
  352.             Thread.CurrentThread.CurrentCulture =
  353.             CultureInfo.GetCultureInfo("bg-Bg");
  354.  
  355.             Console.WriteLine("| {0,10:C} |", 120000.4532);
  356.             Console.Clear();
  357.  
  358.             // Reading from the console and parsing
  359.  
  360.             Console.Write("Please enter your age: ");
  361.             string inputVariable = Console.ReadLine();
  362.  
  363.             // Parsing strings to numbers
  364.             int age = int.Parse(inputVariable);
  365.             double ageInDouble;
  366.             double.TryParse(inputVariable, out ageInDouble);
  367.             Console.WriteLine(Convert.ToInt16(inputVariable));
  368.             Console.WriteLine(age + 10);
  369.  
  370.             // Read a character from the input with Read
  371.             //Console.Write("Please enter a character: ");
  372.             //int nextChar = Console.Read();
  373.             //Console.WriteLine(nextChar);
  374.             //Console.WriteLine((char)nextChar);
  375.             // return;
  376.  
  377.             // ReadKey
  378.             //Console.WriteLine("Please press ESC key to exit this endless loop");
  379.             //ConsoleKeyInfo cki;
  380.             //do {              
  381.             //    if (!Console.KeyAvailable)
  382.             //    {
  383.             //        Console.Clear();
  384.             //        Console.WriteLine("Please hit Esc");
  385.             //    }
  386.             //    cki = Console.ReadKey(true);
  387.             //    System.Threading.Thread.Sleep(50);
  388.             //} while(cki.Key != ConsoleKey.Escape);
  389.  
  390.  
  391.             Console.OutputEncoding = Encoding.UTF8;
  392.  
  393.             Console.ForegroundColor = ConsoleColor.Green;
  394.             // Console.BackgroundColor = ConsoleColor.Blue;
  395.             // To change the background color of the > console window as a whole, set the BackgroundColor property and call the Clear method.
  396.             // Console.BackgroundColor = ConsoleColor.Blue;
  397.             // Console.Clear();
  398.  
  399.             Console.SetCursorPosition(5, 10); // left top
  400.             Console.WriteLine("Това е кирилица: ☺");
  401.  
  402.             Thread.CurrentThread.CurrentCulture =
  403.             CultureInfo.GetCultureInfo("en-GB"); // UK doesn't work
  404.  
  405.             // Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture;
  406.  
  407.             Console.WriteLine("Your balance is {0, 30:C2}", 1234567.8904534);
  408.  
  409.             //for (int charCode = 0; charCode < 1000; i++)
  410.             //{
  411.             //    Console.WriteLine((char)i);
  412.             //}
  413.  
  414.            // 5. Conditional logic (Управляващи структури)
  415.             int secondNumber = 3;
  416.             int firstNumber = 2;
  417.             if (secondNumber > firstNumber)
  418.             {
  419.                 // int biggerNumber = secondNumber;
  420.                 Console.WriteLine(secondNumber);
  421.             }
  422.  
  423.             int myAge = 12;
  424.  
  425.             if (myAge < 3)
  426.             {
  427.                 Console.WriteLine("You are a baby!");
  428.             }
  429.             else if (3 <= myAge && myAge < 12) {
  430.                 Console.WriteLine("You are a kid!");
  431.             }
  432.             else if (12 <= myAge && myAge < 18)
  433.             {
  434.                 Console.WriteLine("You are a teenager!");
  435.             }
  436.             else if (18 <= myAge && myAge < 30)
  437.             {
  438.                 Console.WriteLine("You are in your golden age!");
  439.             }
  440.             else
  441.             {
  442.                 Console.WriteLine("You are an adult");
  443.             }          
  444.  
  445.             char ch = 'X';
  446.             if (ch == 'A' || ch == 'a')
  447.             {
  448.                 Console.WriteLine("Vowel [ei]");
  449.             }
  450.             else if (ch == 'E' || ch == 'e')
  451.             {
  452.                 Console.WriteLine("Vowel [i:]");
  453.             }
  454.             else if (ch == 'I' || ch == 'i')
  455.             {
  456.                 Console.WriteLine("Vowel [ai]");
  457.             }
  458.             else if (ch == 'O' || ch == 'o')
  459.             {
  460.                 Console.WriteLine("Vowel [ou]");
  461.             }
  462.             else if (ch == 'U' || ch == 'u')
  463.             {
  464.                 Console.WriteLine("Vowel [ju:]");
  465.             }
  466.             else
  467.             {
  468.                 Console.WriteLine("Consonant");
  469.             }
  470.  
  471.             //if (булев израз)
  472.             //{
  473.             //    тяло на условната конструкция;
  474.             //}
  475.             //else
  476.             //{
  477.             //    тяло на else-конструкция;
  478.             //}
  479.  
  480.             if (nikiAge > 0 && nikiAge < 12)
  481.             {
  482.                 Console.WriteLine("You are a child");
  483.             }
  484.             else if (nikiAge >= 12 && nikiAge < 20)
  485.             {
  486.                 Console.WriteLine("You are a teenager");
  487.             }
  488.             else
  489.             {
  490.                 Console.WriteLine("You are adult.");
  491.             }
  492.  
  493.             //switch (селектор)
  494.             //{
  495.             //    case целочислена - стойност - 1: конструкция; break;
  496.             //    case целочислена - стойност - 2: конструкция; break;
  497.             //    case целочислена - стойност - 3: конструкция; break;
  498.             //    case целочислена - стойност - 4: конструкция; break;
  499.             //    // …
  500.             //    default: конструкция; break;
  501.             //}
  502.             char firtsLetter = 'S';
  503.             switch (firtsLetter)
  504.             {
  505.                 case 'S':
  506.                     Console.WriteLine("Your first letter tells me you are a lucky man!");
  507.                     break;
  508.                 case 'V':
  509.                     Console.WriteLine("You are victorious!");
  510.                     break;
  511.                 default:
  512.                     Console.WriteLine("I don't know?");
  513.                     break;
  514.             }
  515.  
  516.            // 6. Loops (Цикли)
  517.             //while (условие)
  518.             //{
  519.             //    тяло на цикъла;
  520.             //}
  521.  
  522.             // Initialize the counter
  523.             int counter = 0;
  524.             // Execute the loop body while the loop condition holds
  525.             while (counter <= 9)
  526.             {
  527.                 // Print the counter value
  528.                 Console.WriteLine("Number : " + counter);
  529.                 // Increment the counter
  530.                 counter++;
  531.             }
  532.  
  533.             //  n! = (n - 1)!*n
  534.             Console.Write("Please, enter a number: ");
  535.             int n = int.Parse(Console.ReadLine());
  536.             // "decimal" is the biggest type that can hold integer values
  537.             decimal factorial = 1;
  538.             // Perform an "infinite loop"
  539.             while (true)
  540.             {
  541.                 if (n <= 1)
  542.                 {
  543.                     break;
  544.                 }
  545.                 factorial *= n;
  546.                 n--;
  547.             }
  548.             Console.WriteLine("n! = " + factorial);
  549.  
  550.             int myDoTest = 0;
  551.             do
  552.             {
  553.                 Console.Write("Please enter a number betwen 0 and 5: ");
  554.                 myDoTest = int.Parse(Console.ReadLine());
  555.             } while (myDoTest > 5 || myDoTest < 0);
  556.  
  557.             //for (инициализация; условие; обновяване)
  558.             //{
  559.             //    тяло на цикъла;
  560.             //}
  561.  
  562.             for (int j = 0; j <= 10; j++)
  563.             {
  564.                 Console.Write(j + " ");
  565.             }
  566.  
  567.             int t = 0;
  568.             while (t < 10)
  569.             {
  570.                 // i++;
  571.                 // break;
  572.                 if (t % 2 == 0)
  573.                 {
  574.                     t++;
  575.                     continue;
  576.                 }
  577.                 Console.WriteLine("t = " + t);
  578.                 t++;
  579.             }
  580.              
  581.              // break example
  582.             // Is the number prime
  583.             bool isPrime = true;
  584.             Console.Write("Please, enter a number: ");
  585.             int n = int.Parse(Console.ReadLine());
  586.             int iterator = 2;
  587.             while (iterator < n)
  588.             {
  589.                 if (n % iterator == 0)
  590.                 {
  591.                     isPrime = false;
  592.                     break;
  593.                 }
  594.                 iterator++;
  595.             }
  596.  
  597.             int[] numbers = { 2, 3, 5, 7, 11, 13, 17, 19 };
  598.             foreach (int k in numbers)
  599.             {
  600.                 Console.Write(" " + k);
  601.             }
  602.             Console.WriteLine();
  603.  
  604.             String[] towns = { "Sofia", "Plovdiv", "Varna", "Bourgas" };
  605.             foreach (String town in towns)
  606.             {
  607.                 Console.Write(" " + town);
  608.             }
  609.  
  610.             // continue
  611.             foreach (var item in numbers)
  612.             {
  613.                 if (item % 2 == 0)
  614.                 {
  615.                     continue;
  616.                 }
  617.  
  618.                 Console.WriteLine(item);
  619.             }
  620.  
  621.             // 7. Arrays (Масиви)
  622.             int special = 34;
  623.             Console.WriteLine($"This is my variable {special}");
  624.  
  625.             Console.BackgroundColor = ConsoleColor.DarkBlue;
  626.             Console.Clear();
  627.             Console.ForegroundColor = ConsoleColor.Yellow;
  628.  
  629.             string[] students = new string[100];
  630.             students[0] = "Konstantin";
  631.             students[1] = "Angel";
  632.  
  633.             Console.WriteLine(students[0]);
  634.  
  635.             int[] myArray = { 1, 2, 3, 4, 5, 6 };
  636.             int[] myArray2 = new int[3] { 23, 45, 67 };
  637.  
  638.             string[] daysOfWeek =
  639.             {
  640.                 "Monday",
  641.                 "Tuesday",
  642.                 "Wednesday",
  643.                 "Thursday",
  644.                 "Friday",
  645.                 "Saturday",
  646.                 "Sunday"
  647.             };
  648.  
  649.             int[] array = new int[] { 1, 2, 3, 4, 5 };
  650.             Console.Write("Output: ");
  651.             for (int index = 0; index < array.Length; index++)
  652.             {
  653.                 // Doubling the number
  654.                 array[index] = 2 * array[index];
  655.                 // Print the number
  656.                 Console.Write(array[index] + " ");
  657.             }
  658.             // Output: 2 4 6 8 10
  659.  
  660.             //foreach (var item in collection)
  661.             //{
  662.             //    // Process the value here
  663.             //}
  664.  
  665.             int[,] matrix =
  666.             {
  667.                 {1, 2, 3, 4}, // row 0 values
  668.                 {5, 6, 7, 8}, // row 1 values
  669.             };
  670.             // The matrix size is 2 x 4 (2 rows, 4 cols)
  671.  
  672.             Console.WriteLine();
  673.             Console.WriteLine(matrix[0,3]); // 4
  674.  
  675.             Console.WriteLine(matrix.GetLength(0));
  676.             Console.WriteLine(matrix.GetLength(1));
  677.  
  678.             int[][] myJaggedArray = {
  679.                 new int[] {5, 7, 2},
  680.                 new int[] {10, 20, 40},
  681.                 new int[] {3, 25},
  682.                 new int[] { 1,2,3,4,5,6,78,9}
  683.             };
  684.  
  685.             int[][,] jaggedOfMulti = new int[2][,];
  686.  
  687.             // another way to declare jagged array
  688.             int[][] jaggedArray;
  689.             jaggedArray = new int[2][];
  690.             jaggedArray[0] = new int[5];
  691.             jaggedArray[1] = new int[3];
  692.  
  693.             // 8. Numbering systems (Бройни системи)
  694.             // String number = "100";
  695.             // int fromBase = 16;
  696.             // int toBase = 10;
  697.  
  698.             // String result1 = Convert.ToString(Convert.ToInt32(number, fromBase), toBase);
  699.  
  700.             // e.g.
  701.             // Console.WriteLine("2093 to BIN {0}.", Convert.ToString(2093, 2));
  702.             // Console.WriteLine("2093 to OCT {0}.", Convert.ToString(2093, 8));
  703.             // Console.WriteLine("2093 to HEX {0}.", Convert.ToString(2093, 16));
  704.  
  705.             // int number = Convert.ToInt32("1111010110011110", 2); // To enter a number is arbitrary numbering system
  706.             // Console.WriteLine("{0}, to HEX {1}.",
  707.             //    number,Convert.ToString(number, 16)); // To write in a different numbering system 2, 8, 16
  708.  
  709.            // result == "256"
  710.            // Console.WriteLine(result1);
  711.            // Random randomGenerator = new Random(); https://docs.microsoft.com/en-us/dotnet/api/system.random?view=netcore-3.1
  712.            // randomGenerator.Next(); https://docs.microsoft.com/en-us/dotnet/api/system.random.next?view=netcore-3.1
  713.  
  714.  
  715.  
  716.             /* 8.1. Позиционни и непозиционни бройни системи
  717.            Iv VI - Римската бройна система - Непозиционна
  718.            8.2. Определне стойността на числото в съответната бройна система
  719.            44 - Арабската бройна система Позиционна. Позицията на цифрата в записа на числото определя стойността и.
  720.            цифрите - азбуката на числата
  721.            числата - думите записани с помощта на цифрите. Те имат стойност. Стойността се определя с помощта на основата на бройната система
  722.            Стойността на числото в една позиционна бройна система се определя като се умножи цифрата по основата на бройната система повдигната на степен позицията броена отзад напред започвайки от 0:
  723.            4*10^1 + 4*10^0 => цифрата се умножава по основата на бройната система повдигната на степен позицията на цифрата в числото броена отзад напред започвайки от 0.
  724.            1001110 (2) - трябва да знаем основата на бройната система за да определим стойността на числото  
  725.            F4(16)  - число в 16-тична бройна система
  726.            74(8) - число в осмична бройна система
  727.  
  728.             // Convert to binary system
  729.             Console.Write("Please, enter a number to convert to binary: ");
  730.             // with 340282366920938000000000000000000000000
  731.             // System.OverflowException: Value was either too large or too small for an Int32.
  732.             int number2Convert = int.Parse(Console.ReadLine());
  733.             int[] binaryNumber = new int[128]; // the default value is 0
  734.             int digitCounter = 127;
  735.             while (number2Convert > 0 && digitCounter > 0)
  736.             {
  737.                 binaryNumber[digitCounter] = number2Convert % 2;
  738.                 digitCounter--;
  739.                 number2Convert /= 2;
  740.                 Console.WriteLine(number2Convert);
  741.             }
  742.             foreach (var digit in binaryNumber)
  743.             {
  744.                 Console.Write(digit);
  745.             }
  746.             Console.WriteLine();
  747.             Console.WriteLine(Math.Pow(2, 128)); // 3.40282366920938E+38
  748.             // Console.WriteLine("{0,10:N}", Math.Pow(2, 128)); // 340,282,366,920,938,000,000,000,000,000,000,000,000.00
  749.             // Console.WriteLine("{0,10:D}", Math.Pow(2, 128)); // Exception
  750.             Console.WriteLine("{0,10:F0}", Math.Pow(2, 128)); // 340282366920938000000000000000000000000
  751.  
  752.                 // https://stackoverflow.com/questions/2954962/convert-integer-to-binary-in-c-sharp
  753.                 int value = 8;
  754.                 string binary = Convert.ToString(value, 2);
  755.  
  756.                 // Convert from any classic base to any base in C#
  757.                
  758.                 String number = "100";
  759.                 int fromBase = 16;
  760.                 int toBase = 10;
  761.  
  762.                 String result = Convert.ToString(Convert.ToInt32(number, fromBase), toBase);
  763.  
  764.                 // result == "256"
  765.                 // Supported bases are 2, 8, 10 and 16
  766.  
  767.                 var bin = Convert.ToString(n, 2);
  768.                 var oct = Convert.ToString(n, 8);
  769.                 var hex = Convert.ToString(n, 16);
  770.  
  771.             */
  772.             // 8.3. Конвертиране от една в друга бройна система
  773.             // Convert from decimal to binary system
  774.             //34 - > 100010 = 1 * 2 ^ 5 + 0 + 0 + 0 + 1 * 2 ^ 1 + 0 = 32 + 2 = 34
  775.  
  776.             //34 : 2 = 17  0
  777.             //17 : 2 = 8   1
  778.             //8 : 2 = 4    0
  779.             //4 : 2 = 2    0
  780.             //2 : 2 = 1    0
  781.             //             1
  782.  
  783.             //100010
  784.             //100010
  785.             // 8.3.2. Кконвертиране от двоична в шестнадесететична и обратно. Правилото 8421
  786.             // 8| 4 | 2 | 1
  787.             // e.g. 12 is 8 + 4 then we put 1 in positions of 8 and 4 -> 1100
  788.  
  789.             // Convert form base 16 to base 2
  790.             //0010 | 1010 | 1010 | 1010 | 1111 | 1110 | 0001 | 1111 | 1111
  791.             // 8.4. Прав обратен допълнителен код
  792.             //2AAAFD1FF
  793.            // Прав - 345
  794.            // Обратен (10^3 - 1) - 345 = 999 - 345 = 654
  795.            // Допълнителен код (10^3) - 345 или обратния код + 1 => 654 + 1 = 655
  796.            // Операцията изваждане се заменя със събиране като към умаляемото се добави допълнителния код на умалителя
  797.            // 8 - 5 = 3 - прав код
  798.            // допълнителния код на умалителя 5 е => 9 - 5 = 4 - обратен 4 + 1 = 5 - допьлнителен
  799.             // 8 + 5 = 1 | 3 - преносът се отстранява
  800.             // 4 - 7 = -3
  801.             // допълнителния код на умалителя 7 е 9 - 7 = 2 + 1 = 3
  802.             // 4 + 3 = 7 ако няма пренос значи резултата е в допьлнителен код и отрицателно число => 9 - 7 = 2 + 1 = 3 => -3
  803.  
  804.             // 9. Methods. Именован блок от кода който може да приема или не формални параметри или може да има или не върната стойност
  805.             // Method calls
  806.             string[] studentsTemp = new string[2];
  807.             InputNames(studentsTemp);
  808.             InputNames(studentsTemp, 5);
  809.             InputNames(studentsTemp, 3, 2, 3, 4, 5, 6, 2, 3, 6, 6);
  810.             InputNames(n: 6, names: studentsTemp);
  811.  
  812.             // 12.09.2019
  813.             int sum1 = Sum(100, 2000);
  814.             Console.WriteLine(sum1);
  815.  
  816.             // 13.09.2019
  817.             sum1 = Sum(34, 2500);
  818.             Console.WriteLine(sum1);
  819.  
  820.            // 10. Recursion
  821.             // Recursion
  822.             int factorial2 = 5;
  823.             Console.WriteLine("!{0} = {1}", factorial2, Factorial(factorial2));
  824.  
  825.  
  826.             // Standard Math functions
  827.             Console.WriteLine(Math.Cos(23));
  828.  
  829.             // every string can be used as array
  830.             string stoyanName = "Stoyan";
  831.             Console.WriteLine(stoyanName[0]); // S
  832.             // string functions - tyme the name of the variable and .
  833.             Console.WriteLine(stoyanName.IndexOf('t'));
  834.             // etc.
  835.  
  836.              // for concatenating a lot of strings use StringBuilder, don't concatenate directly with +
  837.              // var fb = new StringBuilder();
  838.             // for (int i = 0; i < 100000; ++i) {
  839.             //    fb.Append("Sample");
  840.             // }
  841.            // var f = fb.ToString();
  842.         }
  843.  
  844.         // Method declaration and definition, default parameters, variable number of parameters
  845.         static void InputNames(string[] names, int n = 4, params int[] myExtraParams)
  846.         {
  847.             for (var i = 0; i < names.Length; i++)
  848.             {
  849.                 Console.Write("Please enter element number {0} :", i);
  850.                 names[i] = Console.ReadLine() + " Default Mark = " + n + " Final Mark" + ((myExtraParams.Length > 0) ? myExtraParams[i].ToString() : "0"); //
  851.                 Console.WriteLine(names[i]);
  852.             }
  853.         }
  854.  
  855.         static int Sum(int firstNumber, int secondNumber = 2000)
  856.         {
  857.             int sum = 0;
  858.             sum = firstNumber + secondNumber;
  859.             return sum;
  860.         }
  861.  
  862.         // Recursion
  863.         // !n = !(n-1) * n
  864.         static int Factorial(int n)
  865.         {
  866.             if (n == 0) return 1;
  867.             return Factorial(n - 1) * n;
  868.         }
  869.  
  870.         static void GreetingUser(string name, int age = 0, int multiplier = 2)
  871.         {
  872.             // int multiplier = 2;
  873.             Console.WriteLine($"Greeting {name}! I will multiply your age by {multiplier} and the result is {age * multiplier}");
  874.         }
  875.  
  876.         static int SumCustom(int n , int m)
  877.         {
  878.             // Console.WriteLine(n + m);
  879.             int sum = n + m;
  880.             return sum;
  881.         }
  882.  
  883.         static void PrintVariableParameters(string greeting = "Hello", params string[] names)
  884.         {
  885.             for (int i = 0; i < names.Length; i++)
  886.             {
  887.                 Console.WriteLine($"{greeting} {names[i]}");
  888.             }
  889.            
  890.         }
  891.  
  892.         static int FactorialIteration(int n)
  893.         {
  894.             int factorial = 1;
  895.             for (int i = 1; i <= n; i++)
  896.             {
  897.                 factorial *= i;
  898.             }
  899.             return factorial;
  900.         }
  901.  
  902.         // 0! = 1
  903.         // n! = (n - 1)! * n
  904.         static int FactorialRecursion(int n)
  905.         {
  906.             if (n == 0) return 1;
  907.             return FactorialRecursion(n - 1) * n;
  908.         }
  909.  
  910.         static int CalcCompoundInterest(double amount, double interest, int period)
  911.         {
  912.             // double amount, double interest, int period
  913.             double finalAmount = amount * Math.Pow((1 + interest/100), period);
  914.         }
  915.     }
  916. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement