wingman007

CheatSheetIntroProgrammingC#

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