Advertisement
Lyuben_Andreev

CrashCourse

Feb 16th, 2025
109
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 14.13 KB | Source Code | 0 0
  1. using System;
  2. using c_sharp_crash;
  3.  
  4. /**
  5.  * HELLO WORLD APPLICASTION
  6.  */
  7. class Program
  8. {
  9.     static void Main()
  10.     {
  11.         PrintToConsole();
  12.         VariablesAndDataTypes();
  13.         MathOperators();
  14.         ComparisonOperators();
  15.         LogicalOperators();
  16.         ConditionalStatements();
  17.         Loops();
  18.         Arrays();
  19.         Collections();
  20.         Methods();
  21.         Classes();
  22.         ExceptionHandling();
  23.     }
  24.  
  25.     private static void PrintToConsole()
  26.     {
  27.         Console.WriteLine("Hello, World!");
  28.     }
  29.  
  30.     private static void VariablesAndDataTypes()
  31.     {
  32.         // Integer (whole number)
  33.         int age = 30;
  34.         Console.WriteLine(age);
  35.  
  36.         // Floating point number with single-digit precision
  37.         // Use 'f' to specify a float literal
  38.         float price = 19.99f;
  39.         Console.WriteLine(price);
  40.  
  41.         // Floating point number with Double-digit precision floating point number
  42.         double interest = 5.52;
  43.         Console.WriteLine(interest);
  44.  
  45.         // for the most accurate rounding, use decimal instead of double (best used for money values)
  46.         decimal accountBalance = 3424.45M;
  47.         Console.WriteLine($"Your account balance is {accountBalance}");
  48.  
  49.         // Character
  50.         char grade = 'A';
  51.         Console.WriteLine($"Your overall grade this semester: {grade}");
  52.  
  53.         // Strings are text values that usually contain one or more characters. THey are immutable objects,
  54.         // which means that we cannot change them. Every "change" will create a new string object in memory.
  55.         string name = "Ron";
  56.         Console.WriteLine($"Hi, my name is {name}");
  57.  
  58.         // Booleans are true or false values
  59.         bool isStudent = true;
  60.         Console.WriteLine(isStudent);
  61.  
  62.         // Variables can also be declared without initialization
  63.         int quantity;
  64.         string product;
  65.  
  66.         // Assigning values to previously declared variables
  67.         quantity = 4;
  68.         product = "apples";
  69.         Console.WriteLine($"There are {quantity} {product} on sale.");
  70.  
  71.         // Constants are read-only values that cannot be changed
  72.         const double Pi = 3.14159265359;
  73.         Console.WriteLine($"Value of PI: {Pi}");
  74.  
  75.         // If we try to change Pi, we'll get an error message
  76.         //Pi = 0;
  77.     }
  78.  
  79.  
  80.     private static void MathOperators()
  81.     {
  82.         int num1 = 10;
  83.         int num2 = 5;
  84.  
  85.         int addition = num1 + num2;    // Addition: 10 + 5 = 15
  86.         Console.WriteLine("Addition: " + addition);
  87.  
  88.         int subtraction = num1 - num2; // Subtraction: 10 - 5 = 5
  89.         Console.WriteLine("Subtraction: " + subtraction);
  90.  
  91.         int multiplication = num1 * num2; // Multiplication: 10 * 5 = 50
  92.         Console.WriteLine("Multiplication: " + multiplication);
  93.  
  94.         int division = num1 / num2;      // Division: 10 / 5 = 2
  95.         Console.WriteLine("Division: " + division);
  96.  
  97.  
  98.         // The following will cause a Divide by Zero exception. Use a try/catch block to handle these (see exception handling below)
  99.         int num3 = 5;
  100.         int num4 = 0;
  101.  
  102.         try
  103.         {
  104.             division = num3 / num4;
  105.             Console.WriteLine(division);
  106.         } catch (DivideByZeroException ex)
  107.         {
  108.             Console.WriteLine("An error occurred: " + ex.ToString());
  109.         }
  110.  
  111.         int modulus = num1 % num2;       // Modulus (remainder of 0): 10 % 5 = 0
  112.         Console.WriteLine("Modulus: " + modulus);
  113.  
  114.         modulus = 11 % 2;       // Modulus (remainder of 1): 11 % 5 = 1
  115.         Console.WriteLine("Modulus: " + modulus);
  116.     }
  117.  
  118.     private static void ComparisonOperators()
  119.     {
  120.         int a = 10;
  121.         int b = 5;
  122.  
  123.         bool isEqual = (a == b);    // Equal to: false
  124.         Console.WriteLine("Numbers equal? " + isEqual);
  125.  
  126.         bool isNotEqual = (a != b); // Not equal to: true
  127.         Console.WriteLine("Numbers not equal? " + isNotEqual);
  128.  
  129.         bool isGreater = (a > b);   // Greater than: true
  130.         Console.WriteLine("Is A greater than B? " + isGreater);
  131.  
  132.         bool isLess = (a < b);      // Less than: false
  133.         Console.WriteLine("Is A less than B? " + isLess);
  134.  
  135.         bool isGreaterOrEqual = (a >= b); // Greater than or equal to: true
  136.         Console.WriteLine("Is A greater than or equal to B? " + isGreaterOrEqual);
  137.  
  138.         bool isLessOrEqual = (a <= b);    // Less than or equal to: false
  139.         Console.WriteLine("Is A less than or equal to B? " + isLessOrEqual);
  140.     }
  141.  
  142.     private static void LogicalOperators()
  143.     {
  144.         bool x = true;
  145.         bool y = false;
  146.  
  147.         bool andResult = x && y; // Logical AND: false
  148.         Console.WriteLine("X and Y: " + andResult);
  149.  
  150.         bool orResult = x || y;  // Logical OR: true
  151.         Console.WriteLine("X or Y: " + orResult);
  152.  
  153.         bool notResult = !x;     // Logical NOT (inverts boolean values): false
  154.         Console.WriteLine("Inverse of x: " + notResult);
  155.     }
  156.  
  157.     private static void ConditionalStatements()
  158.     {
  159.         /**
  160.          * IF-ELSE STATEMENTS
  161.          */
  162.         int age = 25;
  163.  
  164.         if (age < 18)
  165.         {
  166.             Console.WriteLine("You are a minor.");
  167.         }
  168.         else if (age >= 18 && age < 65)
  169.         {
  170.             Console.WriteLine("You are an adult.");
  171.         }
  172.         else
  173.         {
  174.             Console.WriteLine("You are a senior citizen.");
  175.         }
  176.  
  177.         /**
  178.          * SWITCH STATEMENTS
  179.          */
  180.         int day = 3;
  181.         string dayName;
  182.  
  183.         switch (day)
  184.         {
  185.             case 1:
  186.                 dayName = "Monday";
  187.                 break;
  188.             case 2:
  189.                 dayName = "Tuesday";
  190.                 break;
  191.             case 3:
  192.                 dayName = "Wednesday";
  193.                 break;
  194.             case 4:
  195.                 dayName = "Thursday";
  196.                 break;
  197.             case 5:
  198.                 dayName = "Friday";
  199.                 break;
  200.             default:
  201.                 dayName = "Weekend";
  202.                 break;
  203.         }
  204.  
  205.         Console.WriteLine("Today is " + dayName);
  206.     }
  207.  
  208.     private static void Arrays()
  209.     {
  210.         // Declare an array with pre-determined number of indexes
  211.         int[] numbers = new int[5];
  212.  
  213.         // Initialize elements of the array
  214.         numbers[0] = 1;
  215.         numbers[1] = 2;
  216.         numbers[2] = 3;
  217.         numbers[3] = 4;
  218.         numbers[4] = 5;
  219.  
  220.         Console.WriteLine("The first number in the array is " + numbers[0]);
  221.         Console.WriteLine("The fourth number in the array is " + numbers[3]);
  222.  
  223.         // Get number of items in array
  224.         Console.WriteLine("Amount of numbers in array: " + numbers.Length);
  225.  
  226.         // Declare an array with shorthand and no pre-determined number of indexes
  227.         string[] names =
  228.         {
  229.             "Bobby", "Katie", "Joseph", "Barbara", "Jimmy"
  230.         };
  231.  
  232.         Console.WriteLine("The last name in the array is: " + names[names.Length - 1]);
  233.     }
  234.  
  235.     private static void Collections()
  236.     {
  237.         // Lists are like dynamic arrays that can store elements of a specified type (T)
  238.         // Lists can contain duplicate values
  239.         List<string> cities = new List<string>();
  240.  
  241.         // add items to List
  242.         cities.Add("New York");
  243.         cities.Add("Tokyo");
  244.         Console.WriteLine("First city: " + cities[0]);
  245.         Console.WriteLine("Secondy city: " + cities[1]);
  246.         Console.WriteLine("Number of cities in list: " + cities.Count);
  247.  
  248.         // Looping through a List with a foreach loop
  249.         foreach (string city in cities)
  250.         {
  251.             Console.WriteLine("City: " + city);
  252.         }
  253.        
  254.  
  255.         // Dictionaries contain key-value pairs. The keys are used to index a particular entry and they are unique.
  256.         // Values can be duplicated between entries.
  257.  
  258.         Dictionary<string, int> ageDict = new Dictionary<string, int>();
  259.         string dictKey = "Alice";
  260.         ageDict[dictKey] = 30;
  261.  
  262.         // Now get the dictionary entry
  263.         if (ageDict.ContainsKey(dictKey))
  264.         {
  265.             Console.WriteLine($"{dictKey}'s age: {ageDict[dictKey]}");
  266.         }
  267.  
  268.         // Loop through dictionary entries
  269.         foreach (var entry in ageDict)
  270.         {
  271.             // get key
  272.             Console.WriteLine("Key: " + entry.Key);
  273.             Console.WriteLine("Value: " + entry.Value);
  274.         }
  275.  
  276.         // Hashsets store only unique values (no duplicates)
  277.         HashSet<string> names = new HashSet<string>();
  278.         names.Add("Ron");
  279.         names.Add("Tommy");
  280.         names.Add("Tommy"); // Duplicate, won't be added
  281.  
  282.         // Loop through HashSet
  283.         foreach (string name in names)
  284.         {
  285.             Console.WriteLine("Name in hashset: " + name);
  286.         }
  287.  
  288.         // Queues are First-In / Frst-Out collections (FIFO). The first entry to be added to a Queue will
  289.         // be the first one to be removed.
  290.         Queue<string> queue = new Queue<string>();
  291.         queue.Enqueue("First");
  292.         queue.Enqueue("Second");
  293.         queue.Enqueue("Third");
  294.  
  295.         while (queue.Count > 0)
  296.         {
  297.             string item = queue.Dequeue();
  298.             Console.WriteLine("Queue: " + item);
  299.         }
  300.  
  301.         // Stacks are Last-In / First-Out (LIFO) collections
  302.         Stack<string> stack = new Stack<string>();
  303.         stack.Push("First");
  304.         stack.Push("Second");
  305.         stack.Push("Third");
  306.  
  307.         while (stack.Count > 0)
  308.         {
  309.             string item = stack.Pop();
  310.             Console.WriteLine("Stack: " + item);
  311.         }
  312.     }
  313.  
  314.     private static void Loops()
  315.     {
  316.         // For-loop continues to iterate until the condition is met
  317.         for (int i = 1; i <= 5; i++)
  318.         {
  319.             Console.WriteLine("For-loop count " + i);
  320.         }
  321.  
  322.         // While-loop is used when you don't want to specify a condition beforehand. The loop will continue to iterate
  323.         // unless a condition (which is specified within the loop block) is met.
  324.         int count = 0;
  325.  
  326.         while (count < 3)
  327.         {
  328.             Console.WriteLine("While-loop count: " + count);
  329.             count++; // VERY IMPORTANT: make sure to increment or decrement a counter to prevent infinite loops
  330.         }
  331.  
  332.         // Do-while-loops (unlike while-loops) are guaranteed to run at least once. Use this loop if you don't want to specify
  333.         // the condition beforehand, but want the loop to execute the code block AT LEAST ONCE.
  334.         int num = 1;
  335.  
  336.         do
  337.         {
  338.             Console.WriteLine("Do-while-loop count: " + num);
  339.             num++;
  340.         } while (num <= 3);
  341.  
  342.         // FOR-EACH LOOPS
  343.         // For-each loops are generally used with collection types, and they continue to iterate until the loop reaches the end of
  344.         // the collection.
  345.  
  346.         // Foreach loop with array
  347.         int[] numbers = { 1, 2, 3, 4, 5 };
  348.  
  349.         foreach (int number in numbers)
  350.         {
  351.             Console.WriteLine("Number: " + number);
  352.         }
  353.     }
  354.  
  355.     private static void Methods()
  356.     {
  357.         SayHello();
  358.  
  359.         int a = 10;
  360.         int b = 20;
  361.         int sum = Add(a, b);
  362.         Console.WriteLine($"Sum of {a} and {b}: " + sum);
  363.  
  364.         // Method overloading
  365.         Console.WriteLine($"Overload 1 (double): {Add(10.5, 20.39)}");
  366.         Console.WriteLine($"Overload 2 (int): {Add(1, 3, 5)}");
  367.     }
  368.  
  369.     // Function without parameters and return value (void)
  370.     private static void SayHello()
  371.     {
  372.         Console.WriteLine("Hello, World!");
  373.     }
  374.  
  375.     // Function with parameters and return value
  376.     private static int Add(int a, int b)
  377.     {
  378.         int sum = a + b;
  379.         return sum;
  380.     }
  381.  
  382.     /**
  383.      * METHOD OVERLOADING
  384.      */
  385.     // We can also overload methods. Method overrloading occurs when you define multiple methods of the same name with
  386.     // different return types and/or parameter data types.
  387.  
  388.     // Method for adding two doubles
  389.     private static double Add(double a, double b)
  390.     {
  391.         return a + b;
  392.     }
  393.  
  394.     // Method for adding three integers
  395.     private static int Add(int a, int b, int c)
  396.     {
  397.         return a + b + c;
  398.     }
  399.  
  400.     private static void Classes()
  401.     {
  402.         // Create an object of the "Person" class using a constructor
  403.         Person person1 = new Person("Chad", 30);
  404.  
  405.         // Access and modify properties
  406.         person1.Age = 31;
  407.         Console.WriteLine("Updated Age: " + person1.Age);
  408.  
  409.         // Call a method to display information
  410.         person1.Greet();
  411.     }
  412.  
  413.     private static void ExceptionHandling()
  414.     {
  415.         // In C#, a DivideByZero exception is thrown when an dividing any number by zero.
  416.         // We need to handle this exception gracefully to continue program execution
  417.         int a = 10;
  418.         int b = 0;
  419.  
  420.         try
  421.         {
  422.             int result = a / b;
  423.         } catch (DivideByZeroException ex)
  424.         {
  425.             Console.WriteLine("Oops, an error occurred: " + ex.Message);
  426.        }
  427.  
  428.         // Sometimes, we won't know what type of exception to catch. We can use the base .NET exception class
  429.         // to catch miscellaneous exceptions
  430.         List<string> shapes = new List<string>{ "square", "rectangle", "circle" };
  431.  
  432.         try
  433.         {
  434.             // Let's intntionally throw an exception by grabbing the 4th item in the list (which doesn't exist)
  435.             // Shouuld throw an "index out of range" exception
  436.             Console.WriteLine(shapes[3]);
  437.         } catch (Exception ex)
  438.         {
  439.             Console.WriteLine(ex.Message);
  440.         } finally
  441.         {
  442.             // Finally always executes, even if no exception is thrown
  443.             Console.WriteLine("This code always runs!");
  444.         }
  445.  
  446.         // We can also create custom exception classes
  447.         bool isStudent = false;
  448.  
  449.         try
  450.         {
  451.             if (isStudent)
  452.             {
  453.                 Console.WriteLine("This is a student");
  454.             }
  455.             else
  456.             {
  457.                 throw new CustomException("You cannot enroll for this course because you are not a student.");
  458.             }
  459.         } catch (CustomException ex)
  460.         {
  461.             Console.WriteLine(ex.Message);
  462.         }
  463.     }
  464. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement