Advertisement
wingman007

CheatSheetIntroProgrammingC#

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