4Beginners Codes C# Edit
Introduction
Hey there! I'm Arvind, just diving into the coding world and having a blast learning the ropes. I'm cooking up all sorts of programs, from web stuff to fun console apps, to show my growing skills and the cool things you can do with code. Join me on this ride as I share my journey, tips, and, of course, plenty of quirky projects. Can't wait to see where this coding adventure takes us! ?
Few Basics of C# code 1. Namespace and Class: - The code starts by declaring the `using System;` directive, which imports the `System` namespace. This namespace contains essential classes and functions for input/output, data types, and other common operations. - It then defines a class named `Program`. This class acts as a container for the code that will be executed. In simple terms : The code starts by saying "Hey, I'm going to use some tools and rules from the 'System' collection." (Think of it like a toolbox for the code.) It then creates a blueprint called "Program" that outlines what the code is going to do. 2. Main Method: - Inside the `Program` class, the `Main` method is defined. This is the entry point of the program, meaning it's the first method that will be executed when the program runs. - The `Main` method takes an array of strings called `args` as its argument, which can be used to pass command-line arguments to the program. In simple terms : Inside the blueprint, there's a main set of instructions called "Main." This is where the action happens!
PROGRAM 1: TAFFY ART
using System; class DogShape { public static void PrintDog() { Console.WriteLine("Hello, Taffy!"); Console.WriteLine(""); Console.WriteLine(" __ __ "); Console.WriteLine(" //| |\\\\"); Console.WriteLine(" // |______| \\\\"); Console.WriteLine(" // | | \\\\"); Console.WriteLine(" // | | \\\\"); Console.WriteLine(" // ___| |___ \\\\"); Console.WriteLine(" //_____| |_____\\\\"); Console.WriteLine(" | 0 | | 0 |"); Console.WriteLine(" |______|______|______|"); Console.WriteLine(" \\ | ___ | / "); Console.WriteLine(" \\ |o___o_| / "); Console.WriteLine(" \\ ________ / "); Console.WriteLine(" \\ |X|xxxx|X| / "); Console.WriteLine(" \\ |X|____|X| / "); Console.WriteLine(" \\__________/ "); } } Key Takeaways: 1. Static Method for Printing Dog: - The `PrintDog()` method is defined as static, meaning it belongs to the class rather than an instance of the class. This allows you to call the method without creating an object of the `DogShape` class. 2. Console Output for ASCII Art: - The `Console.WriteLine()` statements are used to print each line of ASCII art to the console. By strategically combining characters such as slashes, pipes, underscores, and underscores, a stylized representation of a dog is created. 3. Whitespace for Formatting: - The use of empty `Console.WriteLine()` statements is for adding spacing between lines, enhancing the visual presentation of the ASCII art. 4. Stylized Dog Representation: - The ASCII art is designed to create the shape of a dog named "Taffy." 5. Code Organization: - The code is organized within a class named `DogShape`. In larger projects, organizing code into classes helps improve code structure and maintainability. 6. Creativity and Fun: - This code demonstrates a creative and fun aspect of programming, showing that code can be used for more than just functional purposes. It can also be expressive and artistic. While this code may not serve a practical function in a software application, it provides a playful example of how programming can be used for creative expression and visual representation, which can be a motivating and enjoyable aspect of coding.
PROGRAM 2: SUM OF TWO NUMBERS
using System; namespace Sum { class Sum { static void Main(string[] args) { Console.WriteLine("Enter the first number"); int a = int.Parse(Console.ReadLine()); Console.WriteLine("Enter the Seacond number"); int b = int.Parse(Console.ReadLine()); int result = a + b; Console.WriteLine("The Resut is\n " + result); } } } Key Takeaways: This C# code prompts the user to enter two numbers, reads the input, adds them together, and then displays the result. 1. Namespace: - The code is enclosed in the `Sum` namespace, which is a way to organize code and avoid naming conflicts. However, in this case, it seems the namespace doesn't serve a specific purpose as there's only one class. 2. Class: - The class is named `Sum` 3. Main Method: - The `Main` method is the entry point of the program. It prompts the user to enter the first and second numbers using `Console.WriteLine` statements. 4. Reading User Input: - It uses `Console.ReadLine` to capture user input as strings and then converts these strings to integers using `int.Parse`. This assumes that the user will input valid integer values; otherwise, an exception might occur if non-integer values are entered. 5. Calculating and Displaying Result: - The entered numbers are added together, and the result is stored in the `result` variable. The result is then displayed using `Console.WriteLine`. 6. Formatting Output: - The output includes a newline character (`\n`) to provide a cleaner separation between the user prompt and the result.
PROGRAM 3 : CALCULATOR
namespace Calculator { class Program { static void Main(string[] args) { while (true) { Console.WriteLine("ENTER THE FIRST NUMBER"); int number1 = int.Parse(Console.ReadLine()); Console.WriteLine("ENTER THE Second NUMBER"); int number2 = int.Parse(Console.ReadLine()); Console.WriteLine("Do you wana Add, Substract, Divide, Multiply or find Modulus"); String x = Console.ReadLine(); int result = 0; if (x == "+") { result = number1 + number2; } else if (x == "-") { result = number1 - number2; } else if (x == "*") { result = number1 * number2; } else if (x == "/") { if (number2 == 0) { Console.WriteLine(" Cant divide by zero "); } else { result = number1 / number2; } } else if (x == "%") { result = number1 % number2; } else { Console.WriteLine("Invalid operation"); } Console.WriteLine(" " + result); } } } } Key Takeaways : 1. Loop Structure: - The code uses a `while (true)` loop, creating an infinite loop that continues to prompt the user for input and perform calculations until manually interrupted or exited. 2. User Input and Data Type Conversion: - It continues to capture user input using `Console.ReadLine()` and converts the input to integers using `int.Parse()`. It's important to handle potential exceptions when converting user input. 3. Conditional Statements (if-else): - The code employs conditional statements (`if`, `else if`, and `else`) to determine the arithmetic operation the user wants to perform based on the entered operator (`+`, `-`, `*`, `/`, `%`). 4. Arithmetic Operations: - The code performs basic arithmetic operations such as addition, subtraction, multiplication, division, and modulus based on user input. 5. Error Handling: - There is a check for division by zero (`number2 == 0`). If the user attempts to divide by zero, a message is displayed to handle this special case. 6. String Comparison: - The code uses string comparison (`x == "+"`, `x == "-"`, etc.) to determine the user's choice of operation. It's case-sensitive, so entering "ADD" instead of "+" would result in an "Invalid operation" message. 7. Infinite Loop and Exit Condition: - The infinite loop (`while (true)`) raises concerns about the program running indefinitely. But i have just done like that because it a calculator and want the program to continue. 8. Output Formatting: - The code uses `Console.WriteLine` to display messages to the user and the result of the calculation. 9. Handling Invalid Input: - If the user enters an invalid operator, the code outputs "Invalid operation," providing feedback on the incorrect input. 10. Overall Structure: - The program structure is contained within a single class (`Program`). In larger applications, modularization and separation of concerns might be considered for better maintainability. 11. Repeating User Interaction: - The code structure allows for repeated interactions with the user, making it suitable for a simple calculator application. To enhance this code, I can consider adding a mechanism to exit the loop at a later stage
PROGRAM 4 : FIBONACCI
using System; class program { public static void Main(string[] args) { while (true) //while loop is for making the code repeat// { double a = 1, b = 1, c, i; // used double here to increase the size// String Y; Console.WriteLine("\nDo you know the spelling of fibinoki \n Y/N"); Y = Console.ReadLine(); if (Y == "Y" || Y == "y") { Console.WriteLine("Enter the number of digits"); double n = double.Parse(Console.ReadLine()); // i changed double here too// if (n == 1) { Console.Write(a); } else if (n == 2) { Console.WriteLine($"\n{a}\n{a}"); } else { Console.WriteLine($"{a}\n{b}"); for (i = 2; i < n; i++) { c = a + b; Console.WriteLine($"{c}"); a = b; b = c; } } } else { Console.WriteLine("Adiyos Amigo"); Environment.Exit(0); } } } } Key Takeaways 1. Loop Structure: - The code utilizes a `while (true)` loop to create an infinite loop, prompting the user repeatedly for input. 2. Variable Initialization: - The variables `a`, `b`, `c`, and `i` are initialized at the beginning of the loop. This is good practice to ensure variables start with a defined value. 3. String Comparison: - The user's response to whether they know the spelling of "Fibonacci" is obtained as a string (`userResponse`). The `Equals` method is used for case-insensitive string comparison. 4. User Input and Data Type Conversion: - The code captures user input for the number of digits (`n`) they want to display in the Fibonacci sequence. The input is converted from a string to a double using `double.Parse`. 5. Conditional Statements: - The code uses `if-else` statements to handle different cases based on user input. If the user knows the spelling of "Fibonacci," it proceeds to generate and display the Fibonacci sequence. Otherwise, it displays "Adios Amigo." 6. Fibonacci Sequence Generation: - The code generates and displays the Fibonacci sequence based on the user's input. It includes special cases for `n == 1` and `n == 2`. The sequence is printed using a `for` loop. 7. Variable Update in Loop: - Within the `for` loop, the variables `a`, `b`, and `c` are updated to generate the next Fibonacci numbers in the sequence. 8. String Interpolation: - The code uses string interpolation (`$"{a}\n{b}"`) to format and display the output, making the code more readable. 9. Infinite Loop: - The infinite loop might be a concern if there's no provision for the user to exit the program. It would be beneficial to include a condition for breaking out of the loop based on user input. 10. Exit: - Environment.Exit(0); Learned that this exits the terminal In summary, the code demonstrates the use of loops, conditional statements, user input, and string manipulation to generate and display a Fibonacci sequence based on user interaction.
Program 5 : ODD OR EVEN
using System; class program { static void Main(String[] args) { while (true) { double a=0; Console.WriteLine("Type a Number"); a = double.Parse(Console.ReadLine()); if (a % 2 == 0) { Console.WriteLine("Its an even number my dear friend"); } else { Console.WriteLine("Its an Odd number Amigoo"); } } } } Key Takeaways: 1. Conditional Statements: - The code uses an `if-else` statement to check whether the entered number is even or odd based on the remainder when divided by 2 (`a % 2`). 2. Even and Odd Numbers: - The code introduces the concept of checking whether a number is even or odd using the modulus operator (`a % 2`). Even numbers have no remainder when divided by 2. In summary, this code provides a simple example of a program that continuously classifies user-inputted numbers as even or odd in an infinite loop.
PROGRAM 6 : DAY OF THE WEEK
using System; using System.Transactions; class Dayoftheweek { static void Main(string[] args) { while (true) { int Day; Console.WriteLine("Enter any number of the week"); Day = int.Parse(Console.ReadLine()); switch (Day) { case 1: Console.WriteLine("Monday"); break; case 2: Console.WriteLine("Tuesday"); break; case 3: Console.WriteLine("Wednesday"); break; case 4: Console.WriteLine("Thurday"); break; case 5: Console.WriteLine("Friday"); break; case 6: Console.WriteLine("Saturday"); break; case 7: Console.WriteLine("Sunday"); break; default: Console.WriteLine("Invalid Day Sunshine"); break; } } } } Key Takeaways: 1. User Input and Data Type Conversion: - The code captures user input for the day of the week (`Day`) and converts the input from a string to an integer using `int.Parse`. Be cautious, as this can lead to an exception if the user enters non-numeric input. 2. Switch Statement: - The `switch` statement is used to check the value of `day` and execute the corresponding case. Each case corresponds to a day of the week, and there's a default case for handling invalid inputs. 3. Output Messages: - Different output messages are displayed based on the entered number, indicating the corresponding day of the week. 4. Switch Statement Breaks: - The `break` statements in the `switch` statement are essential to exit the switch block after a case is matched. Without them, the code would continue executing subsequent cases. In summary, this code provides a simple example of a program that continuously prompts the user for a number corresponding to a day of the week and displays the corresponding day using a `switch` statement.
PROGRAM 7 : SWITCH CASE CALCULATOR
using System; using System.Diagnostics; using System.Transactions; class Calculator { static void Main(string[] args) { while (true) { double num1, num2, result=0; String num3 = Test String; Char Operation; Console.WriteLine("Enter the first Number homie"); num1 = Double.Parse(Console.ReadLine()); Console.WriteLine("Enter the Second Number homie"); num2 = Double.Parse(Console.ReadLine()); Console.WriteLine("Enter the operand"); Operation=char.Parse(Console.ReadLine()); switch (Operation) { case '+': result=num1 + num2; break; case '-': result=num1 - num2; break; case '/': if (num2 == 0) { Console.WriteLine("Not possible to divide by zero"); } else { result = num1 / num2; } break; case '*' : result = num1 * num2; break; case '%' : result= num1 % num2; break; case '^' : result = Math.Pow(num1, num2); break; default: Console.WriteLine("Invaid Day Sunshine"); break; } Console.WriteLine("The result is " + result + " TADDAAAA " + num3); } } } Key Takeaways: 1. Infinite Loop: - The code uses a `while (true)` loop, creating an infinite loop that repeatedly prompts the user for input. 2. User Input and Data Type Conversion: - The code captures user input for `num1`, `num2`, and `operation`, converting the inputs from strings to double and char using `double.Parse` and `char.Parse`, respectively. 3. Switch Statement: - The `switch` statement is used to determine the operation to be performed based on the entered operand. 4. Conditional Statements: - The code includes a conditional check to prevent division by zero if the user enters '/' as the operand with `num2` being 0. 5. Math.Pow: - The code uses `Math.Pow` to calculate the power of `num1` raised to the power of `num2`. 6. Output Formatting: - Another way is (`$"The result: {result} TADDAAAA {num3}"`) to format and display the output, making it more readable by using string interpolation $ 7. Variable Initialization: - Variables (`num1`, `num2`, `result`, `num3`, `operation`) are initialized at the beginning of the loop, which is good practice to ensure variables start with defined values. New Learnings: 1. Math.Pow Method: - The code introduces the use of `Math.Pow` to calculate the power of a number. This is a useful method for raising a number to a given exponent. 2. Switch Statement with Char: - The code demonstrates using a `switch` statement with a char variable (`operation`), showing how it can be used to evaluate different cases based on characters. In summary, this code implements a simple calculator that continuously prompts the user for input, performs arithmetic operations based on the entered operands, and displays the result along with an additional constant (`num3`) to prove we can add how many ever results we want using + sign
PROGRAM 8: INTRO TO ARRAYS
using System; class Program { static void Main(string[] args) { int[] a = new int[100]; Console.WriteLine("Enter the size of the array"); int size = int.Parse(Console.ReadLine()); Console.WriteLine("Enter the set of numbers"); for (int i = 0; i < size; i++) { a[i]= int.Parse(Console.ReadLine()); } Console.WriteLine("The numbers are"); for (int i = 0;i < size; i++) { Console.WriteLine(a[i]); } } } Key Takeaways: 1. Array Declaration and Initialization: - The code declares an integer array `a` of size 100. The size is fixed during compilation, but the code allows the user to input a specific size (`size`) for the array. 2. User Input for Array Elements: - The code prompts the user to input the size of the array and then enter a set of numbers. The input numbers are stored in the array `a`. 3. For Loop for Input: - A `for` loop is used to iterate over the array and populate it with user input. 4. For Loop for Output: - Another `for` loop is used to iterate over the array and display the entered numbers. 5. Array Size Determined by User Input: - The size of the array is determined by user input (`size`), allowing flexibility in handling arrays of different lengths. 6. Dynamic Array Initialization: - The array size is not fixed during compilation and is determined at runtime based on user input. This is an example of dynamic array initialization. 7. User Interaction: - The code involves user interaction for providing the array size and entering individual elements. In summary, this code demonstrates the basic process of declaring an array, taking user input for its size, populating it with user-inputted numbers, and then displaying the contents of the array.
PROGRAM 9 : SUM OF TWO ARRAYS
using System; class Program { static void Main(string[] args) { int[] a = new int[100]; int[] b = new int[100]; int[] result= new int[100]; //did not need result in this code// Console.WriteLine("Enter the size of the array"); int size = int.Parse(Console.ReadLine()); Console.WriteLine("Enter the first set of numbers"); for (int i = 0; i < size; i++) { a[i] = int.Parse(Console.ReadLine()); } Console.WriteLine("Enter the 2nd set of numbers"); for (int i = 0; i < size; i++) { b[i] = int.Parse(Console.ReadLine()); } Console.WriteLine("The sum of the two array is"); for (int i = 0; i < size; i++) { Console.WriteLine(a[i] + b[i]); } } } Key Takeaways: 1. Array Declaration and Initialization: - The code declares two integer arrays `a` and `b` of size 100. The arrays are used to store sets of numbers. 2. User Input for Array Elements: - The code prompts the user to input the size of the arrays and then enter the first and second sets of numbers. The input numbers are stored in arrays `a` and `b`. 3. For Loop for Input: - Two `for` loops are used to iterate over the arrays and populate them with user input. 4. Array Size Determined by User Input: - The size of the arrays is determined by user input (`size`), allowing flexibility in handling arrays of different lengths. 5. Array Summation: - The code calculates the sum of corresponding elements from arrays `a` and `b` and prints the results. 6. Dynamic Array Initialization: - The array sizes are not fixed during compilation and are determined at runtime based on user input. This is an example of dynamic array initialization. 7. User Interaction: - The code involves user interaction for providing the array size and entering individual elements for two arrays. 8. Console Output: - The code displays the sum of the corresponding elements of the two arrays on the console. In summary, this code demonstrates the basic process of declaring arrays, taking user input for their size and elements, and then performing array operations (summation in this case). The result array is not necessary, as the sum can be directly printed during the summation loop.
PROGRAM 10: READ STRING AND SUBSTRING
using System; class Program { static void Main(string[] args) { string word1 = "GeForce 3060"; Console.WriteLine(word1.IndexOf("F")); Console.WriteLine(word1[4]); Console.WriteLine(word1.Substring(0,7)); } } Key Takeaways: 1. String Declaration: - The code declares a string variable named `word1` with the value "GeForce 3060". 2. IndexOf Method: - The `IndexOf` method is used to find the index of the first occurrence of the character "F" in the string `word1`. The result (index) is then printed to the console, output is 2. 3. Accessing Characters in a String: - Individual characters in a string can be accessed using indexing. The code accesses the character at index 4 in the string `word1` (zero-based indexing) and prints it to the console. 4. Substring Method: - The `Substring` method is used to extract a portion of the string. In this case, it extracts the substring from index 0 to index 6 (7 characters in total) and prints it to the console. 5. Console Output: - The code prints the results of the `IndexOf` method, accessing a specific character, and the `Substring` method to the console. 6. Zero-Based Indexing: - In C#, indexing for strings and arrays is zero-based, meaning the first element has an index of 0. In summary, this code showcases some basic string manipulation operations in C#, including finding the index of a character, accessing characters in a string by index, and extracting a substring. These methods are part of the string manipulation capabilities provided by the C# language.
PROGRAM 11 : SUM OF ELEMENTS INSIDE A SINGLE ARRAY
using System; class Program { static void Main(string[] args) { int[] a = new int[100]; int sum = 0; Console.WriteLine("Enter the size of the array"); int size = int.Parse(Console.ReadLine()); Console.WriteLine("Enter the set of numbers"); for (int i = 0; i < size; i++) { a[i] = int.Parse(Console.ReadLine()); } Console.WriteLine("The sum of the elements in the array is"); for (int i = 0; i < size; i++) { sum = sum + a[i]; } Console.WriteLine(sum); } } Explanation: 1. Array Declaration: - The code declares an integer array named `a` with a fixed size of 100. This array will be used to store a set of numbers entered by the user. 2. Variable Initialization: - The variable `sum` is initialized to zero. This variable will be used to calculate the sum of the array elements. 3. User Input for Array Size: - The program prompts the user to enter the size of the array, and the entered value is converted to an integer using `int.Parse`. This determines the number of elements the user will input into the array. 4. User Input for Array Elements: - The code prompts the user to enter a set of numbers for the array. It uses a for loop to iterate through the array, capturing user input for each element. 5. Summation of Array Elements: - The program calculates the sum of the array elements using a for loop. The current array element is added to the `sum` variable in each iteration. 6. Display the Sum: - Finally, the code prints the calculated sum of the array elements to the console. Key Takeaways 1. Array Initialization: - The code declares an integer array (`a`) and initializes it with a maximum size of 100. This array is used to store a set of numbers provided by the user. 2. User Input: - The program prompts the user to enter the size of the array (`size`) and captures the input using `Console.ReadLine()`. The entered value is then converted to an integer using `int.Parse()`. 3. User Input for Array Elements: - A loop (`for` loop) is used to iterate through the array, prompting the user to enter a set of numbers for each element. The user inputs are then stored in the array. 4. Summation of Array Elements: - Another `for` loop is employed to calculate the sum of the array elements (`sum`). The current element is added to the sum in each iteration. 5. Console Output: - The code prints the calculated sum of the array elements to the console. 6. Dynamic Array Size: - The size of the array is not fixed during compilation but is determined at runtime based on user input. This demonstrates dynamic array initialization. 7. Input Validation (Not Implemented): - The code assumes valid user inputs and does not include input validation checks (e.g., checking if the entered size is non-negative). In a production environment, additional input validation could be implemented for robustness. 8. Basic Loop Structures: - The use of `for` loops demonstrates a fundamental programming concept for iterating over arrays and performing repetitive tasks. 9. Console Interaction: - The program interacts with the user through console input and output, making it a simple console-based application. 10. Summation Logic: - The logic for calculating the sum of array elements involves iterating through the array and accumulating the values. The sum is then printed to the console. In summary, this program demonstrates the basic functionality of capturing user input to populate an array, calculating the sum of its elements, and displaying the result. The code is structured using loops and user prompts to create a simple interactive application.
PROGRAM 12 : INTERACTIVE PROGRAM SELECTOR
using System; using System.Linq; class Program { static void Main(string[] args) { while (true) { Console.WriteLine("CHOOSE THE PROGRAM \n PROGRAM 1 = DELETE TWO DECIMAL \n PROGRAM 2 = REVERSE THE NUMBERS \n PROGRAM 3 = REVERSE THE WORDS"); Console.WriteLine("ENTER THE PROGRAM NUMBER"); int Program = int.Parse(Console.ReadLine()); switch (Program) { case 1: Console.WriteLine("Enter the Number"); int a = int.Parse(Console.ReadLine()); a = a / 100; int sum; Console.WriteLine(a); break; case 2: Console.WriteLine("Enter the number"); int USERNUMBER = int.Parse(Console.ReadLine()); int reverseNUMBER = 0; while (USERNUMBER != 0) { int lastdigit = USERNUMBER % 10; reverseNUMBER = reverseNUMBER * 10 + lastdigit; USERNUMBER = USERNUMBER / 10; } Console.WriteLine(reverseNUMBER); break; case 3: Console.WriteLine("Enter a string:"); string input = Console.ReadLine(); // Use LINQ to reverse the string string reversedString = new string(input.Reverse().ToArray()); Console.WriteLine("Reversed string: " + reversedString); break; default: Console.WriteLine("INVALID CASE"); break; } } } } Explanation: This C# program serves as an interactive menu-based application where the user can choose from three different programs to execute: 1. Program 1 - Delete Two Decimal Places: - The user inputs a number, and the program divides it by 100, effectively removing the last two decimal places. The result is then displayed. 2. Program 2 - Reverse the Numbers: - The user inputs a number, and the program reverses the order of its digits. For example, inputting "123" would result in the output "321". 3. Program 3 - Reverse the Words: - The user inputs a string, and the program uses LINQ to reverse the order of characters in each word of the string. The reversed string is then displayed. Key Takeaways: 1. Interactive Menu: - The program utilizes a `while (true)` loop to create an interactive menu where the user can select different programs to execute. 2. Switch Statement: - A `switch` statement is employed to handle the different program choices. Depending on the user's input, the corresponding case is executed. 3. User Input Handling: - The program prompts the user to enter the program number and handles user input using `Console.ReadLine` and `int.Parse`. 4. Program Execution: - Different programs are executed based on the user's choice. Each program performs a specific task, such as mathematical operations or string manipulation. 5. Looping Structure: - The use of a perpetual `while (true)` loop allows the user to continue selecting and executing programs until manually interrupted. 6. != : This means not equal to condition 7. String Manipulation with LINQ: - Program 3 demonstrates the use of LINQ to reverse the characters in each word of a given string, showcasing a practical application of LINQ in string manipulation. 8. Default Case Handling: - The `default` case is included in the `switch` statement to handle scenarios where the user inputs an invalid program number. 9. Continuous Execution: - The program is designed to continuously execute, allowing the user to choose and execute multiple programs without restarting the application. This code structure provides a foundation for creating interactive console-based applications, enabling users to choose from various functionalities and demonstrating the use of control flow structures in C#.
PROGRAM 13 : REPEATING INFORMATION AND CUBE CALCUALTION
using System; class program { static void Main(string[] args) { Repeat("Arvy ", 27); Repeat("Jax ", 28); Repeat("Arjun ", 67); Repeat("Rahul ", 35); Repeat("Mohan ", 34); Repeat("Hasii ", 24); Repeat("Aish ", 20); Console.WriteLine("Enter the number you want to cube"); int userinput = int.Parse(Console.ReadLine()); Console.WriteLine("The cube of that number is " + Cube(userinput)); } static void Repeat(String name, int age) // this passes data into the method and print the command inside the method // { Console.WriteLine("Hello " + name + "your Id card number is " + age); } static int Cube(int num) // this passes data outside the method and prints the command in the Main funtion // { int Result = num * num * num; return Result; } } Key Takeaways: 1. Method Usage: - The program defines two methods (`Repeat` and `Cube`) and calls them from the `Main` method. 2. Parameter Passing: - The `Repeat` method takes two parameters (a string `name` and an integer `age`) and prints a formatted message. - The `Cube` method takes an integer parameter `num`, calculates the cube, and returns the result. 3. Method Calls: - The `Repeat` method is called multiple times from the `Main` method with different arguments, demonstrating the reuse of code. - The `Cube` method is called with the argument `user input`, and the result is printed to the console. 4. String Concatenation: - The `Repeat` method uses string concatenation to create a formatted message that includes the name and age. 5. Data Type Conversions: - The `Cube` method performs mathematical operations on an integer parameter. 6. Return Statement: - The `Cube` method uses the `return` statement to send the calculated result back to the caller. This code illustrates the use of methods for better code organization, parameter passing, and code reuse. It also demonstrates the return of values from a method.
PROGRAM 14 : CALCULATOR WITHOUT USING RESULT VARIABLE
using System; using System.ComponentModel.Design; using System.Linq; using System.Xml; class Calculator { static void Main(string[] args) { while (true) { Console.WriteLine("ENTER NUM 1:"); double Num1 = double.Parse(Console.ReadLine()); Console.WriteLine("OPERATOR:"); String Op = Console.ReadLine(); Console.WriteLine("ENTER NUM 2: "); double Num2 = double.Parse(Console.ReadLine()); if (Op == "+") { Console.WriteLine(Num1 + Num2); } else if (Op == "-") { Console.WriteLine(Num2 - Num1); } else if (Op == "*") { Console.WriteLine(Num1 * Num2); } else if (Op == "/") { if (Num2 == 0) { Console.WriteLine("Cant divide by zero"); } else { Console.WriteLine(Num1 / Num2); } } else if (Op == "%") { Console.WriteLine(Num1 % Num2); } else { Console.WriteLine("Invalid Operant"); } } } } Key Takeaway: 1. This is the same calculator as above given program 3 , but only difference is instead if using result variable i directly used Console.Writeline(); to print result directly.
PROGRAM 15 : COMPLETE THE SEQUENCE
using System; class program { static void Main(string[] args) { Console.WriteLine("Enter the first Number in the sequence"); double FirstNumber = double.Parse(Console.ReadLine()); Console.WriteLine("Enter the Last number in the sequence"); double LastNumber = double.Parse(Console.ReadLine()); for(double i = FirstNumber; i <= LastNumber; i++) // For loop for printing all the numbers inbetween the sequence // { Console.WriteLine(i); } Console.WriteLine("Do same using while loop Method YorN :"); String YESNO = Console.ReadLine(); if (YESNO == "Y" || YESNO =="") { whilemethod(FirstNumber,LastNumber); } else { Environment.Exit(0); } } static void whilemethod(double FirstNumber, double LastNumber) { double i = FirstNumber; double j = LastNumber; while (i <= j) { Console.WriteLine(i); i++; } } } Explanation: The provided C# code allows the user to enter the first and last numbers of a sequence. It then uses a `for` loop to print all the numbers in the sequence between the specified range. Additionally, the program gives the option to achieve the same result using a `while` loop by calling a separate method (`whilemethod`). The user can choose between the `for` loop and the `while` loop methods. Here's a breakdown of the code: 1. User Input: - The program prompts the user to enter the first and last numbers of the sequence using `Console.ReadLine()` and parses the input into `double` variables (`FirstNumber` and `LastNumber`). 2. For Loop: - The program uses a `for` loop to iterate through the sequence and prints each number in the range from `FirstNumber` to `LastNumber` (inclusive). 3. User Choice - For Loop or While Loop: - The program prompts the user with a message asking if they want to achieve the same result using a `while` loop (`Y` or `N`). If the user enters anything other than `Y`, the program exits. 4. While Loop Method (`whilemethod`): - If the user chooses to use a `while` loop, the program calls the `whilemethod` and passes the `FirstNumber` and `LastNumber` as parameters. - The `whilemethod` uses a `while` loop to print each number in the sequence between `FirstNumber` and `LastNumber`. 5. User Exit Option: - If the user chooses not to use the `while` loop, the program exits using `Environment.Exit(0)`. Key Takeaways: 1. Looping Structures: - Demonstrates the use of both `for` and `while` loops to achieve the same result. 2. User Input Handling: - Accepts user input for the first and last numbers in the sequence. 3. Method Usage: - Illustrates the use of a separate method (`whilemethod`) for code modularity and reusability. 4. Conditional Statements: - Uses conditional statements (`if`) to determine whether to execute the `while` loop method based on user input. 5. Program Exit: - Provides an option for the user to exit the program if they choose not to use the `while` loop.
PROGRAM 16 : PALINDROME
using System; using System.Linq; class program { static void Main(string[] args) { Console.WriteLine("Enter a string:"); string input = Console.ReadLine(); string temp = input; // Use LINQ to reverse the string string reversedString = new string(input.Reverse().ToArray()); Console.WriteLine("Reversed string: " + reversedString); if (reversedString == temp) { Console.WriteLine(" It is a palindrome"); } else { Console.WriteLine(" It is not a palindrome"); } } } Explanation: The provided C# code determines whether a given string is a palindrome or not. A palindrome is a sequence of characters that reads the same forward as backward. Here's a breakdown of the code: 1. User Input: - The program prompts the user to enter a string using `Console.ReadLine()` and stores it in the `input` variable. 2. String Reversal: - The code uses LINQ (`Reverse()` and `ToArray()`) to reverse the characters in the input string. The reversed string is stored in the `reversedString` variable. 3. Palindrome Check: - The program checks if the reversed string is equal to the original input string. If they are equal, the input string is a palindrome; otherwise, it is not. 4. Output: - The program prints the reversed string and whether the original input is a palindrome or not. Key Takeaways: 1. String Reversal: - Demonstrates the use of LINQ (`Reverse()` and `ToArray()`) to reverse the characters in a string. 2. Palindrome Check: - Compares the reversed string with the original input to determine if it is a palindrome. 3. Conditional Statements: - Uses an `if-else` statement to print whether the input string is a palindrome or not. 4. User Input Handling: - Accepts user input for a string. 5. String Comparison: - Compares two strings using the equality (`==`) operator. 6. Output Display: - Prints the reversed string and the result of the palindrome check to the console.
REVISION
using System; using System.Linq; class program { static void Main(String[] args) { Test(); string a = "Im printing a word"; // this is how we store value for variable in text format // int b = 4; // this is how we store values for integer variables // Console.WriteLine("Enter the number"); // this is how we print text // int userinput = int.Parse(Console.ReadLine()); // this how we initialise a variables and get input from user to store in it// Console.WriteLine("You Entered " + userinput); string d = "hello"; // this is how we set values for string or alphabetic variables // int[] e = { 1, 2, 4 }; // this is how we initialise an array and store numbers into it // Console.WriteLine(a); // this is how we normally print a assigned variable // Console.WriteLine(e[0]); // this is how we print an element inside an array // string[] pitbull = new string[5] { "UNO", "DUOS", "thres", "Quatro", "Five" }; // this is how we initialise an array set its size and store values into it // Console.WriteLine(pitbull[0]); // this is how we print the intances in the array on by one Console.WriteLine(pitbull[1]); Console.WriteLine(pitbull[2]); Console.WriteLine(pitbull[3]); Console.WriteLine(pitbull[4]); // Console.WriteLine(pitbull.Length); // this is alternative way to print all the elments in the array using for loop // for (int i = 0; i < pitbull.Length; i++) { Console.WriteLine(pitbull[i]); } // this is how we store values from user into an array // Console.WriteLine("Enter how many numbers u are going to type to set the size of array"); int Count = int.Parse(Console.ReadLine()); Console.WriteLine("The Count has been set as " + Count); int[] Countinarray = new int[Count]; for (int i = 0; i < Count; i++) { Console.Write($"Element {i + 1}: "); Countinarray[i] = int.Parse(Console.ReadLine()); } Console.WriteLine("Put in The numbers to store in Array"); // i dont know how to get input from user and store it array , ask doubt // reverse(); // i used method to call the reverse code which i put in the below structure // } static void reverse() // this is how u create a method and we call this method later into MAIN whenever we need // // normally when we run the program only programs in main will be executed // { Console.WriteLine("Enter the number to reverse it - this code was called into Main using method"); int num1 = int.Parse(Console.ReadLine()); int reverse = 0; int reminder; while (num1 != 0) { reminder = num1 % 10; reverse = reverse * 10 + reminder; num1 = num1 / 10; } Console.WriteLine(reverse); } static void Test() // i did this array storing code in this method to call it in Main // { Console.WriteLine("Enter the size of the array"); int size = int.Parse(Console.ReadLine()); // to get size of array from user and convert it to int & store it in size// int[] NUMS = new int[size]; // to inicialise an array called NUMS and set its size and size given by user // Console.WriteLine("Enter the numbers you want to store inside the array"); for (int i = 0; i < NUMS.Length; i++) // INSTEAD OF NUMS.LENGTH I CAN TYPE SIZE ALSO, ITS SAME CONCEPT , NUMS.LENGTH FUNCTION WILL ELIMINATE THE NEED FOR SIZE INPUT FROM USER { NUMS[i] = int.Parse(Console.ReadLine()); // This for taking user input and storing inside array nums // } Console.WriteLine("The user input was as below"); // this prints the stored user inputs that were in the array NUMS // // for (int i = 0; i < size; i++) { Console.WriteLine(NUMS[i]); } Console.WriteLine("The sum of all the numbers inside this array :"); // This takes the sum of all the numbers inside the array // int sum = 0; for (int i = 0; i < NUMS.Length; i++) { sum = sum + NUMS[i]; } Console.WriteLine(sum); } }