-
[Basic C#]
Programming language: A language that Humans use to communicate with machines. Without computer programs, we wouldn't have smartphones, websites, or even exploration in outer space.
- Summary
- C# is a powerful OOP language developed by Micorsoft.
- General Purpose: We can create mobile, web,desktop and game application.
- we can built application on the Microsoft .NET platform.
- Cross Platform Independent: Micorsoft .NET Core made sure C# is not more only for windows but for linux and MacOS well.
- typed safe / statically typed language
C# (pronounced "C sharp") is a modern, object-oriented programming language developed by Microsoft. It is designed for building a variety of applications on the Microsoft .NET platform. C# is widely used for developing desktop applications, web applications, mobile apps, cloud-based services, and game development.
Key features and aspects of C# include:
-
Object-Oriented: C# is an object-oriented programming (OOP) language, supporting concepts such as classes, objects, encapsulation, inheritance, and polymorphism.
-
Managed Code: C# code is typically compiled into an intermediate language called Common Intermediate Language (CIL), and it runs on the Common Language Runtime (CLR), which provides features like memory management (garbage collection), exception handling, and security.
-
Type-Safe: C# is statically typed, which means that the type of a variable must be declared before it can be used. This helps catch type-related errors at compile time.
-
Syntax: C# syntax is influenced by languages like C, C++, and Java. If you are familiar with these languages, you'll find many similarities in C# syntax.
-
Rich Standard Library: C# comes with a comprehensive standard library, part of the .NET Framework or .NET Core, which provides functionality for tasks such as file I/O, networking, database access, and more.
-
Integrated Development Environment (IDE): Microsoft provides Visual Studio, a powerful IDE for C# development. Visual Studio offers features like code completion, debugging tools, and project management, making it a popular choice among C# developers.
-
Cross-Platform Development: With the introduction of .NET Core, C# is no longer limited to Windows development. .NET Core is a cross-platform, open-source framework that allows C# developers to build applications for Windows, Linux, and macOS.
-
Language Features: C# includes modern language features such as LINQ (Language-Integrated Query), async/await for asynchronous programming, properties, events, delegates, and more.
-
Web Development: C# is commonly used for web development, particularly in combination with ASP.NET, a framework for building web applications.
-
Game Development: C# is a primary language for game development using the Unity game engine. Unity enables developers to create games for various platforms, including desktop, mobile, and consoles.
C# continues to evolve with new features and improvements, and it remains a popular choice for developers building a wide range of applications in different domains.
- mac: install .NET Core using homebrew.
brew install --cask dotnet-sdk
and check the versiondotnet --version
- install VSCode editior
- install c# extension
-
output: a message on screen/terminal.
Console.WriteLine("Welcome to C#!");
using System; public class Program { public static void Main(string[] args) { Console.Write("Welcome to the Code Playground"); Console.WriteLine("Welcome to the Code Playground"); } }
-
Namespaces / Class: helps to separate code.
using System;
allows you to use Console.WriteLine method and other methods. Namespaces are optional. Instead of System.Console.WriteLine use Console.WriteLine method by use System. Use . operator to access the class or namespace members. -
In C#, creating a class is mandatory for the program’s execution. Main method is the entry point or starting point of the program.
To run the first C# program in Visual Studio Code (VSCode), follow these steps:
-
Install Visual Studio Code: If you don't have Visual Studio Code installed, you can download and install it from the official website: Visual Studio Code.
-
Install .NET SDK: Ensure you have the .NET SDK installed on your machine. You can follow the previous instructions to install it using Homebrew on macOS.
-
Create a Folder: Open your terminal and create a new folder for your C# project:
mkdir HelloWorld cd HelloWorld
-
Initialize a C# Project: Run the following command to initialize a new C# console application:
dotnet new console
This command creates a simple "Hello World" C# console application.
-
Open VSCode: Open Visual Studio Code and navigate to the folder you created for your C# project:
code .
This command opens the current folder in VSCode.
-
Open Terminal in VSCode: In VSCode, open a new terminal by clicking on "View" in the top menu and selecting "Terminal."
-
Build and Run: In the terminal, run the following commands to build and run your C# program:
dotnet build dotnet run
This will build and execute your C# program. You should see the "Hello World" output in the terminal.
Congratulations! You've successfully run your first C# program in Visual Studio Code. You can now start exploring and writing C# code in your VSCode environment.
- A statement (a line of code) performs a specific task. Each Statement ends with a semicolon.
- In case of multiple statements top to bottom is the apporach of executing statements.
public class Program{
public static void Main(string[] args)
{
Console.WriteLine("My name is Anisul Islam.");
Console.WriteLine(143);
}
}
class Test
{
public static void Main(string[] args)
{
Console.WriteLine("Name: Anisul Islam");
Console.WriteLine("Age: 32");
Console.WriteLine("Profession: Software developer");
}
}
- what is comment and why do you need comment? - to explain your code - to avoid running some part of your code for debugging
- single line comment ->
// this is a single line comment
- multi-line comments ->
/* */
- escape sequences: \n, \t, \r, \, ", '
string fullName = "Aniul\nIslam\nRubel";
Console.WriteLine(fullName);
- verbatim string: it allows linebreaks in strings. use @ symbol before double quotes.
Console.WriteLine(@"Hello!
Welcome to the verbatim string");
-
variable declaration and initialization
-
data type - string; example of string: "this is a string" -
string name; name="Anisul Islam";
- char; char bloodGroup = 'A' - int; int age = 32 - double; double age = 95.4 - float height = 1.82f; - decimal weight = 92.8m; - bool isRegistered = true; -
we can change the value of variable anywhere in the program
- descriptive
- meaningful
- camelCase
- avoid single letter naming (exception for loops)
- constant variables: const string universityName = "Leading University";
- string concatenation: "anisul" + "islam"
- multiple variables: int x,y,z; x=y=z=50;
- Implicit (automatically - converting a smaller type to a larger type size): char -> int -> long -> float -> double
- Explicit (manually - converting a larger type to a smaller size type): double -> float -> long -> int -> char
- Type Conversion Methods: It is also possible to convert data types explicitly by using built-in methods, such as Convert.ToBoolean, Convert.ToDouble, Convert.ToString, Convert.ToInt32 (int) and Convert.ToInt64 (long)
System.Console.WriteLine($"{number2.GetType()}");
- Console.ReadLine(), Convert.ToString(), Convert.ToBoolean(), Convert.ToInt16(),Convert.ToInt32(), Convert.ToInt64() and Convert.ToChar(), Convert.ToDouble()
- Error: not possible to convert a textual string like "welcome" to an int.
using System;
class Test
{
public static void Main(string[] args)
{
string? studentName;
int studentAge;
double salary;
Console.Write("Enter your name: ");
studentName = Console.ReadLine();
Console.Write("Enter your age: ");
studentAge = Convert.ToInt32(Console.ReadLine());
Console.Write("Enter your monthly salary: ");
salary = Convert.ToDouble(Console.ReadLine());
Console.WriteLine("Name: " + studentName);
Console.WriteLine("Age: " + studentAge + " years old");
Console.WriteLine($"Welcome {name}. You are {age}. Your salary is ${salary:F2}");
}
}
- we can use variable inside a string by using string interpolation!
int number1 = 10;
int number2 = 3;
int result;
double pi = 3.1416;
result = number1 + number2;
// Console.WriteLine($"{number1} + {number2} = {result}");
Console.WriteLine("{0} + {1} = {2}", number1, number2, result);
Console.WriteLine($"pi = {pi}");
Console.WriteLine($"pi = {pi:F2}");
C# supports various operators that allow you to perform operations on variables and values. Here's a list of some common operators in C#:
-
Addition (
+
):int result = a + b;
-
Subtraction (
-
):int result = a - b;
-
Multiplication (
*
):int result = a * b;
-
Division (
/
):int result = a / b;
-
Modulus (
%
):int result = a % b;
- some arithmetic operators programs
// basic calculator
using System;
class Test
{
public static void Main(string[] args)
{
int number1 = 10;
int number2 = 3;
int result;
result = number1 + number2;
// Console.WriteLine($"{number1} + {number2} = {result}");
Console.WriteLine("{0} + {1} = {2}", number1, number2, result);
result = number1 - number2;
Console.WriteLine($"{number1} - {number2} = {result}");
result = number1 * number2;
Console.WriteLine($"{number1} * {number2} = {result}");
double div = (double)number1 / number2;
Console.WriteLine($"{number1} / {number2} = {div.ToString("F2")}");
Console.WriteLine($"{number1} / {number2} = {div:F2}");
result = number1 % number2;
Console.WriteLine($"{number1} % {number2} = {result}");
}
}
// area of triagle
using System;
class Test
{
public static void Main(string[] args)
{
// triangle area = 0.5 * base * height
double baseLength, height, triangleArea;
Console.WriteLine("Triangle Area Calculator");
Console.Write("Base = ");
baseLength = Convert.ToDouble(Console.ReadLine());
Console.Write("Height = ");
height = Convert.ToDouble(Console.ReadLine());
triangleArea = 0.5 * baseLength * height;
Console.WriteLine($"Triangle Area = {triangleArea.ToString("F2")}");
}
}
// temperature conversion (celsius to fahrenheit conversion)
using System;
class Test
{
public static void Main(string[] args)
{
double fahrenheit, celsius;
Console.Write("fahrenheit = ");
fahrenheit = Convert.ToDouble(Console.ReadLine());
celsius = (fahrenheit - 32) / 1.8;
Console.WriteLine($"celsius = {celsius:F2} degrees");
}
}
using System;
class Test
{
public static void Main(string[] args)
{
int number1, number2, number3, sum;
double average;
Console.Write("number1 = ");
number1 = Convert.ToInt32(Console.ReadLine());
Console.Write("number2 = ");
number2 = Convert.ToInt32(Console.ReadLine());
Console.Write("number3 = ");
number3 = Convert.ToInt32(Console.ReadLine());
sum = number1 + number2 + number3;
Console.WriteLine($"sum = {sum}");
average = (double)sum / 3;
Console.WriteLine($"average = {average.ToString("F2")}");
}
}
using System;
class Test
{
public static void Main(string[] args)
{
// circle area = 3.1416 * radius * radius
double radius, circleArea;
Console.WriteLine("Circle Area Calculator");
Console.Write("radius = ");
radius = Convert.ToDouble(Console.ReadLine());
circleArea = Math.PI * radius * radius;
Console.WriteLine($"Circle Area = {circleArea.ToString("F2")}");
}
}
using System;
class Test
{
public static void Main(string[] args)
{
double fahrenheit, celsius;
Console.Write("celsius = ");
celsius = Convert.ToDouble(Console.ReadLine());
fahrenheit = (1.8 * celsius) + 32;
Console.WriteLine($"fahrenheit = {fahrenheit:F2} degrees");
}
}
-
Assignment (
=
):int a = 10;
-
Add and assign (
+=
):a += 5; // equivalent to a = a + 5;
-
Subtract and assign (
-=
):a -= 5; // equivalent to a = a - 5;
-
Multiply and assign (
*=
):a *= 2; // equivalent to a = a * 2;
-
Divide and assign (
/=
):a /= 2; // equivalent to a = a / 2;
-
Modulus and assign (
%=
):a %= 3; // equivalent to a = a % 3;
using System;
class Test
{
public static void Main(string[] args)
{
int number = 20;
number += 5; // number = number + 5
Console.WriteLine($"{number}");
number -= 5; // number = number - 5
Console.WriteLine($"{number}");
number *= 5; // number = number * 5
Console.WriteLine($"{number}");
number /= 5; // number = number / 5
Console.WriteLine($"{number}");
number %= 5; // number = number % 5
Console.WriteLine($"{number}");
}
}
-
Equal to (
==
):if (a == b)
-
Not equal to (
!=
):if (a != b)
-
Greater than (
>
):if (a > b)
-
Less than (
<
):if (a < b)
-
Greater than or equal to (
>=
):if (a >= b)
-
Less than or equal to (
<=
):if (a <= b)
-
Logical AND (
&&
):if (condition1 && condition2)
-
Logical OR (
||
):if (condition1 || condition2)
-
Logical NOT (
!
):if (!condition)
In C#, bitwise operators perform operations at the bit level. These operators work with individual bits of integer types (int
, long
, short
, byte
, etc.). Here are the bitwise operators in C#:
-
Bitwise AND (
&
):-
Description: Sets each bit to 1 if both bits are 1.
-
Example:
int result = 5 & 3; // Binary: 101 & 011 = 001 Console.WriteLine(result); // Output: 1
-
-
Bitwise OR (
|
):-
Description: Sets each bit to 1 if at least one of the corresponding bits is 1.
-
Example:
int result = 5 | 3; // Binary: 101 | 011 = 111 Console.WriteLine(result); // Output: 7
-
-
Bitwise XOR (
^
):-
Description: Sets each bit to 1 if only one of the corresponding bits is 1.
-
Example:
int result = 5 ^ 3; // Binary: 101 ^ 011 = 110 Console.WriteLine(result); // Output: 6
-
-
Bitwise NOT (
~
):-
Description: Inverts each bit.
-
Example:
int result = ~5; // Binary: ~0101 = 1010 Console.WriteLine(result); // Output: -6
-
-
Left Shift (
<<
):-
Description: Shifts the bits of a number to the left by a specified number of positions.
-
Example:
int result = 5 << 2; // Binary: 101 << 2 = 10100 Console.WriteLine(result); // Output: 20
-
-
Right Shift (
>>
):-
Description: Shifts the bits of a number to the right by a specified number of positions.
-
Example:
int result = 5 >> 1; // Binary: 101 >> 1 = 10 Console.WriteLine(result); // Output: 2
-
Bitwise operators are commonly used in scenarios where individual bits represent flags or options, and you need to perform operations at a lower level than regular arithmetic operators.
-
Increment (
++
):a++;
-
Decrement (
--
):a--;
int result = (a > b) ? a : b;
// even/odd program
class Test
{
public static void Main(string[] args)
{
Console.Write("Enter a number: ");
int number = Convert.ToInt32(Console.ReadLine());
string result = number % 2 == 0 ? "Even" : "Odd";
Console.WriteLine($"{number} is an {result} number");
Console.Read();
}
}
This is a concise way to express an if-else
statement.
These are some of the basic operators in C#. Understanding how to use these operators is fundamental to writing effective C# code.
Control statements in C# are used to control the flow of execution in a program. They allow you to make decisions, loop through code, and execute different blocks of code based on certain conditions. Here are some of the main control statements in C#:
-
if Statement:
-
The
if
statement is used for conditional branching. It executes a block of code if a specified condition is true.if (condition) { // Code to be executed if the condition is true }
-
nested if
-
-
else Statement:
-
The
else
statement is used withif
to execute a block of code if theif
condition is false.if (condition) { // Code to be executed if the condition is true } else { // Code to be executed if the condition is false }
-
-
else if Statement:
-
The
else if
statement is used to specify a new condition to test if the previousif
orelse if
conditions are false.if (condition1) { // Code to be executed if condition1 is true } else if (condition2) { // Code to be executed if condition2 is true } else { // Code to be executed if all conditions are false }
-
-
switch Statement:
-
4 keywords to remember: switch, case, break and default. The
switch
statement is used to select one of many code blocks to be executed.switch (variable) { case value1: // Code to be executed if variable equals value1 break; case value2: // Code to be executed if variable equals value2 break; // ... other cases ... default: // Code to be executed if none of the cases match break; }
-
// program 1. positive, negative or zero
using System;
class Test
{
public static void Main(string[] args)
{
int number = 0;
if (number > 0)
{
Console.WriteLine("Positive Number");
}
else if (number < 0)
{
Console.WriteLine("Negative Number");
}
else
{
Console.WriteLine("Zero");
}
}
}
// program 2: digit spelling program
using System;
class Test
{
public static void Main(string[] args)
{
// digit - 0-9
// digit spelling program
Console.Write("Enter any digit between 0 and 9: ");
int digit = Convert.ToInt32(Console.ReadLine());
if (digit == 0)
{
Console.WriteLine("Zero");
}
else if (digit == 1)
{
Console.WriteLine("One");
}
else if (digit == 2)
{
Console.WriteLine("Two");
}
else if (digit == 3)
{
Console.WriteLine("Three");
}
else if (digit == 4)
{
Console.WriteLine("Four");
}
else if (digit == 5)
{
Console.WriteLine("Five");
}
else if (digit == 6)
{
Console.WriteLine("Six");
}
else if (digit == 7)
{
Console.WriteLine("Seven");
}
else if (digit == 8)
{
Console.WriteLine("Eight");
}
else if (digit == 9)
{
Console.WriteLine("Nine");
}
else
{
Console.WriteLine("Not a valid digit.");
}
}
}
using System;
class Test
{
public static void Main(string[] args)
{
int number;
Console.Write("Enter a number: ");
number = Convert.ToInt32(Console.ReadLine());
if (number % 2 == 0)
{
Console.WriteLine($"{number} is Even");
}
else
{
Console.WriteLine($"{number} is Odd");
}
}
}
using System;
class Test
{
public static void Main(string[] args)
{
int number1, number2;
Console.Write("number1: ");
number1 = Convert.ToInt32(Console.ReadLine());
Console.Write("number2: ");
number2 = Convert.ToInt32(Console.ReadLine());
if (number1 > number2)
{
Console.WriteLine($"{number1} is large number");
}
else if (number2 > number1)
{
Console.WriteLine($"{number2} is large number");
}
else
{
Console.WriteLine($"numbers are equal");
}
}
}
using System;
class Program {
static void Main() {
Console.Write("Enter three numbers separated by spaces: ");
string[] input = Console.ReadLine().Split(' ');
int num1 = int.Parse(input[0]);
int num2 = int.Parse(input[1]);
int num3 = int.Parse(input[2]);
if (num1 >= num2 && num1 >= num3) {
Console.WriteLine($"{num1} is the largest.");
} else if (num2 >= num1 && num2 >= num3) {
Console.WriteLine($"{num2} is the largest.");
} else {
Console.WriteLine($"{num3} is the largest.");
}
}
}
using System;
class Program {
static void Main() {
Console.Write("Enter a year: ");
int year = int.Parse(Console.ReadLine());
if ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)) {
Console.WriteLine($"{year} is a leap year.");
} else {
Console.WriteLine($"{year} is not a leap year.");
}
}
}
using System;
class Test
{
public static void Main(string[] args)
{
char letter;
Console.Write("Enter any letter: ");
letter = Convert.ToChar(Console.ReadLine());
if (letter >= 'A' && letter <= 'Z')
{
Console.WriteLine($"{letter} is a capital letter");
}
else
{
Console.WriteLine($"{letter} is a small letter");
}
}
}
using System;
class Test
{
public static void Main(string[] args)
{
char letter;
Console.Write("Enter any letter: ");
letter = Convert.ToChar(Console.ReadLine()); // A
letter = char.ToLower(letter);
if (letter == 'a' || letter == 'e' || letter == 'i' || letter == 'o' || letter == 'u')
{
Console.WriteLine($"{letter} is a Vowel");
}
else
{
Console.WriteLine($"{letter} is a consonant");
}
}
}
**Objective:** Create a simple program that calculates and displays the letter grade based on the percentage score entered by the user.
**Instructions:**
1. **Input:**
- Prompt the user to enter their percentage score.
- Validate the input to ensure it is a number between 0 and 100.
2. **Grade Calculation:**
- Use if-else statements to determine the letter grade based on the following grading scale:
- A: 90-100
- B: 80-89
- C: 70-79
- D: 60-69
- F: 0-59
3. **Output:**
- Display the calculated letter grade to the user.
**Example Output:**
Enter your percentage score: 85
Your grade is: B
**Grading:**
- Correct calculation of letter grade: 70%
- Input validation: 20%
- Code structure, comments, and readability: 10%
**Additional Challenges:**
1. Allow the user to input their scores for multiple subjects and calculate the overall GPA.
2. Implement a switch statement instead of if-else for grade calculation.
3. Handle edge cases, such as negative scores or scores above 100, gracefully.
This assignment allows students to practice if-else statements, input validation, and basic program structure. They can also extend the functionality to make it more complex based on their skill level.
// assignment solution
using System;
class Program
{
static void Main()
{
Console.Write("Enter your percentage score: ");
double percentage;
if (double.TryParse(Console.ReadLine(), out percentage) && percentage >= 0 && percentage <= 100)
{
char grade;
if (percentage >= 90)
{
grade = 'A';
}
else if (percentage >= 80)
{
grade = 'B';
}
else if (percentage >= 70)
{
grade = 'C';
}
else if (percentage >= 60)
{
grade = 'D';
}
else
{
grade = 'F';
}
Console.WriteLine($"Your grade is: {grade}");
}
else
{
Console.WriteLine("Invalid input. Please enter a valid percentage between 0 and 100.");
}
}
}
// solution with switch
using System;
class Program
{
static void Main()
{
Console.Write("Enter your percentage score: ");
double percentage;
if (double.TryParse(Console.ReadLine(), out percentage) && percentage >= 0 && percentage <= 100)
{
char grade;
switch ((int)percentage / 10)
{
case 10:
case 9:
grade = 'A';
break;
case 8:
grade = 'B';
break;
case 7:
grade = 'C';
break;
case 6:
grade = 'D';
break;
default:
grade = 'F';
break;
}
Console.WriteLine($"Your grade is: {grade}");
}
else
{
Console.WriteLine("Invalid input. Please enter a valid percentage between 0 and 100.");
}
}
}
using System;
class Test
{
public static void Main(string[] args)
{
// switch, break, case, default
int digit;
Console.Write("Enter a digit: ");
digit = Convert.ToInt32(Console.ReadLine());
switch (digit)
{
case 0:
Console.WriteLine("Zero");
break;
case 1:
Console.WriteLine("One");
break;
case 2:
Console.WriteLine("Two");
break;
case 3:
Console.WriteLine("Three");
break;
case 4:
Console.WriteLine("Four");
break;
case 5:
Console.WriteLine("Five");
break;
case 6:
Console.WriteLine("Six");
break;
case 7:
Console.WriteLine("Seven");
break;
case 8:
Console.WriteLine("Eight");
break;
case 9:
Console.WriteLine("Nine");
break;
default:
Console.WriteLine("Not a digit");
break;
}
}
}
using System;
class Test
{
public static void Main(string[] args)
{
char input;
Console.Write("Enter a single character: ");
input = Convert.ToChar(Console.ReadLine());
switch (Char.ToLower(input))
{
case 'a':
case 'e':
case 'i':
case 'o':
case 'u':
Console.WriteLine($"{input} is a Vowel");
break;
default:
if (Char.IsLetter(input))
{
Console.WriteLine($"{input} is a Consonant");
}
else
{
Console.WriteLine($"{input} is not a letter");
}
break;
}
}
}
using System;
class Test
{
public static void Main(string[] args)
{
Console.Write("Enter a day of the week : ");
string day = Console.ReadLine();
switch (day.ToLower())
{
case "monday":
case "tuesday":
case "wednesday":
case "thursday":
case "friday":
Console.WriteLine("Weekday");
break;
case "saturday":
case "sunday":
Console.WriteLine("Weekend");
break;
default:
Console.WriteLine("Invalid day entered");
break;
}
}
}
// switch: temperature converter
using System;
class Test
{
public static void Main(string[] args)
{
Console.WriteLine("Temperature Converter Started");
Console.WriteLine("Choose 1. Fahrenheit to Celsisus");
Console.WriteLine("Choose 2. Celsisus to Fahrenheit");
int choice = Convert.ToInt32(Console.ReadLine());
switch (choice)
{
case 1:
Console.Write("Enter Fahrenheit temperature: ");
double fahrenheit = Convert.ToDouble(Console.ReadLine());
double celsisus = (fahrenheit - 32) / 1.8;
Console.Write($"Temperature in Celsisus : {celsisus:F2} ");
break;
case 2:
Console.Write("Enter Celsisus temperature: ");
double cels = Convert.ToDouble(Console.ReadLine());
double fahr = cels * 1.8 + 32;
Console.Write($"Temperature in Fahrenheit : {fahr:F2} ");
break;
default:
Console.WriteLine("Invalid Choice");
break;
}
}
}
// switch: basic calculator
using System;
class Test
{
public static void Main(string[] args)
{
int number1, number2;
char operation;
Console.Write("Enter an operation (+,-,*,/) : ");
operation = Convert.ToChar(Console.ReadLine());
Console.Write("Enter number1: ");
number1 = Convert.ToInt32(Console.ReadLine());
Console.Write("Enter number2: ");
number2 = Convert.ToInt32(Console.ReadLine());
switch (operation)
{
case '+':
Console.WriteLine($"{number1} + {number2} = {number1 + number2}");
break;
case '-':
Console.WriteLine($"{number1} - {number2} = {number1 - number2}");
break;
case '*':
Console.WriteLine($"{number1} * {number2} = {number1 * number2}");
break;
case '/':
if (number2 != 0)
{
Console.WriteLine($"{number1} / {number2} = {number1 / number2}");
}
else
{
Console.WriteLine("Can not divide by zero");
}
break;
default:
Console.WriteLine("Invalid operation");
break;
}
}
}
-
while Loop:
-
The
while
loop is used to repeatedly execute a block of code as long as the specified condition is true.while (condition) { // Code to be executed while the condition is true }
-
-
do-while Loop:
-
The
do-while
loop is similar to thewhile
loop, but it ensures that the block of code is executed at least once.do { // Code to be executed } while (condition);
-
-
for Loop:
-
The
for
loop is used to repeatedly execute a block of code a specific number of times.for (initialization; condition; update) { // Code to be executed in each iteration }
-
-
foreach Loop:
-
The
foreach
loop is used to iterate over elements in a collection (e.g., arrays, lists).foreach (var item in collection) { // Code to be executed for each item in the collection }
-
These control statements provide flexibility and help in creating more dynamic and responsive programs in C#.
using System;
class Test
{
public static void Main(string[] args)
{
Console.Write("Enter the start number: ");
int start = Convert.ToInt32(Console.ReadLine());
Console.Write("Enter the last number: ");
int end = Convert.ToInt32(Console.ReadLine());
Console.Write("Enter the difference number: ");
int diff = Convert.ToInt32(Console.ReadLine());
for (int count = start; count <= end; count = count + diff)
{
Console.Write($"{count} ");
}
}
}
// 1 2 3 4 ... 100
// 1 3 5 7 ... 99
// 2 4 6 8 ... 100
// 2 5 8 11 ...
using System;
class Test
{
public static void Main(string[] args)
{
int sum = 0;
for (int i = 1; i <= 10; i++)
{
if (i % 2 != 0)
{
sum = sum + i;
}
}
Console.WriteLine($"Sum of odd numbers = {sum}");
}
}
// 2+4+6+8+10=30
using System;
class Test
{
public static void Main(string[] args)
{
Console.Write("Enter a number : ");
int number = Convert.ToInt32(Console.ReadLine());
int fact = 1;
for (int i = number; i >= 1; i--)
{
fact = fact * i;
}
Console.WriteLine($"Factorial({number}) = {fact}");
}
}
// 5 = 5*4*3*2*1 = 120
// 4 = 4*3*2*1= 24
// 3 = 3*2*1 = 6
// 2 = 2*1 = 2
using System;
class Test
{
public static void Main(string[] args)
{
for (int i = 1; i <= 3; i++)
{
for (int j = 1; j <= 5; j++)
{
Console.WriteLine($"i={i}, j={j} : Bangladesh");
}
}
}
}
// outer loop i=1 1<=3
// inner loop j=1 1<=5 Bangladesh
// inner loop j=2 2<=5 Bangladesh
// inner loop j=3 3<=5 Bangladesh
// inner loop j=4 4<=5 Bangladesh
// inner loop j=5 5<=5 Bangladesh
// inner loop j=6 6<=5
// outer loop i=2 2<=3
// inner loop j=1 1<=5 Bangladesh
// inner loop j=2 2<=5 Bangladesh
// inner loop j=3 3<=5 Bangladesh
// inner loop j=4 4<=5 Bangladesh
// inner loop j=5 5<=5 Bangladesh
// inner loop j=6 6<=5
// outer loop i=3 3<=3
// inner loop j=1 1<=5 Bangladesh
// inner loop j=2 2<=5 Bangladesh
// inner loop j=3 3<=5 Bangladesh
// inner loop j=4 4<=5 Bangladesh
// inner loop j=5 5<=5 Bangladesh
// inner loop j=6 6<=5
// outer loop i=4 4<=3
using System;
class Test
{
public static void Main(string[] args)
{
Console.Write("Enter start number: ");
int startNumber = Convert.ToInt32(Console.ReadLine());
Console.Write("Enter end number: ");
int endNumber = Convert.ToInt32(Console.ReadLine());
for (int i = startNumber; i <= endNumber; i++)
{
for (int j = 1; j <= 10; j++)
{
Console.WriteLine($"{i} X {j} = {i * j}");
}
Console.WriteLine("--------------------");
}
}
}
// start number = 2
// end number = 8
// number = 5
// number X i = number*i
// 5 X 1 = 5
// 5 X 2 = 10
// ....
// 5 X 10 = 50
-
use capital letter for Method Name
-
what to learn? - how to define a function - how to call a function - how to pass parameters to a function - how to return from a function
-
Method: A method is a block of code created inside a class that performs a specific task or operation. It is a fundamental building block in any programming language and is defined within a class or a struct. Methods are used to encapsulate logic, promote code reusability, and organize code into manageable units.
// AccessModifier ReturnType MethodName(ParameterType parameter1, ParameterType parameter2, ...)
// {
// // Method body
// // Code to perform the task
// // Optionally, return a value of ReturnType
// }
public class MyClass
{
// Example method without parameters and return type
public void SimpleMethod()
{
// Method body
Console.WriteLine("Hello from SimpleMethod!");
}
// Example method with parameters and return type
public int Add(int a, int b)
{
// Method body
int sum = a + b;
return sum;
}
}
Certainly! Here's a simple project idea for practicing methods in C#: a basic calculator application.
Calculator Project:
Requirements:
- Create a C# console application.
- Define a
Calculator
class that contains methods for basic arithmetic operations (addition, subtraction, multiplication, division). - Implement a menu-driven interface that allows the user to choose an operation and input operands.
- Perform the selected operation and display the result.
Code Example:
using System;
class Calculator
{
public int Add(int a, int b)
{
return a + b;
}
public int Subtract(int a, int b)
{
return a - b;
}
public int Multiply(int a, int b)
{
return a * b;
}
public double Divide(int a, int b)
{
if (b != 0)
{
return (double)a / b;
}
else
{
Console.WriteLine("Error: Cannot divide by zero.");
return double.NaN;
}
}
}
class Program
{
static void Main()
{
Calculator calculator = new Calculator();
while (true)
{
Console.WriteLine("Simple Calculator");
Console.WriteLine("1. Add");
Console.WriteLine("2. Subtract");
Console.WriteLine("3. Multiply");
Console.WriteLine("4. Divide");
Console.WriteLine("5. Exit");
Console.Write("Choose an operation (1-5): ");
string choice = Console.ReadLine();
if (int.TryParse(choice, out int operation) && operation >= 1 && operation <= 5)
{
if (operation == 5)
{
Console.WriteLine("Exiting the calculator. Goodbye!");
break;
}
Console.Write("Enter the first operand: ");
int operand1 = int.Parse(Console.ReadLine());
Console.Write("Enter the second operand: ");
int operand2 = int.Parse(Console.ReadLine());
int result = 0;
switch (operation)
{
case 1:
result = calculator.Add(operand1, operand2);
break;
case 2:
result = calculator.Subtract(operand1, operand2);
break;
case 3:
result = calculator.Multiply(operand1, operand2);
break;
case 4:
double divisionResult = calculator.Divide(operand1, operand2);
if (!double.IsNaN(divisionResult))
{
Console.WriteLine($"Result: {divisionResult}");
}
continue; // Skip displaying the result for division until the end
}
Console.WriteLine($"Result: {result}");
}
else
{
Console.WriteLine("Invalid choice. Please enter a number between 1 and 5.");
}
Console.WriteLine();
}
}
}
This simple calculator project allows students to practice creating a class with methods to perform different operations, handle user input, and implement a menu-driven interface.
Certainly! Here's a simple C# console application for a converter that converts between units. In this example, let's create a basic length converter:
using System;
class Program
{
static void Main()
{
while (true)
{
Console.WriteLine("Unit Converter");
Console.WriteLine("1. Convert Inches to Centimeters");
Console.WriteLine("2. Convert Centimeters to Inches");
Console.WriteLine("3. Exit");
Console.Write("Choose an operation (1-3): ");
string choice = Console.ReadLine();
if (int.TryParse(choice, out int operation) && operation >= 1 && operation <= 3)
{
if (operation == 3)
{
Console.WriteLine("Exiting the unit converter. Goodbye!");
break;
}
switch (operation)
{
case 1:
Console.Write("Enter length in inches: ");
if (double.TryParse(Console.ReadLine(), out double inches))
{
double centimeters = InchesToCentimeters(inches);
Console.WriteLine($"{inches} inches is equal to {centimeters} centimeters.");
}
else
{
Console.WriteLine("Invalid input for inches.");
}
break;
case 2:
Console.Write("Enter length in centimeters: ");
if (double.TryParse(Console.ReadLine(), out double centimeters))
{
double inches = CentimetersToInches(centimeters);
Console.WriteLine($"{centimeters} centimeters is equal to {inches} inches.");
}
else
{
Console.WriteLine("Invalid input for centimeters.");
}
break;
}
}
else
{
Console.WriteLine("Invalid choice. Please enter a number between 1 and 3.");
}
Console.WriteLine();
}
}
private static double InchesToCentimeters(double inches)
{
return inches * 2.54;
}
private static double CentimetersToInches(double centimeters)
{
return centimeters / 2.54;
}
}
This simple converter allows users to convert lengths between inches and centimeters. Users can choose the desired conversion, enter the length, and get the converted result. Feel free to expand and modify the converter to include other units or functionalities based on your needs.
-
class: A template from individual object is created. A class is a custom data type or blueprint. It defines the data and behavior for a type. We can have variables and methods in a class.
-
object: An object is a instance of a class.
-
by default all class member is private. we can use dot operator to assign value to a class member.
class Student{
public string name;
public int age;
public static DisplayInfo(){
Console.WriteLine();
}
}
class Test{
public static void Main(string[] args){
Student s1 = new Student();
s1.name="Anisul";
}
}
- encapsulation is the idea of "surrounding" an entity, not just to keep what's inside together, but also to protect it. hiding from outside using private.
- benefits of encapsulation
- You can control access or modification of the data.
- You can make the code more flexible and easy to change with new requirements.
- Change one part of code without affecting other parts of code.
- Access modifiers: public, private, protected, internal, protected internal. The public access modifier makes the member accessible from the outside of the class. The private access modifier makes members accessible only from within the class and hides them from the outside.
class Student
{
private string fullName;
private int age;
public void SetFullName(string fName)
{
fullName = fName;
}
public string GetFullName()
{
return fullName;
}
public void SetAge(int age)
{
this.age = age;
}
public int GetAge()
{
return age;
}
}
class Test
{
public static void Main(string[] args)
{
Student s1 = new Student();
s1.SetFullName("Anisul Islam");
s1.SetAge(33);
Console.WriteLine(s1.GetFullName());
Console.WriteLine(s1.GetAge());
}
}
- a special public method that has no return type and called automatically when the object is created.
- encapsulate members and give access them with Property a public member that will have accessor (get and set accessors)
class Student
{
private string name; // field
public string Name // property
{
set { name = value; }
get { return name; }
}
}
class Test
{
public static void Main(string[] args)
{
Student s1 = new Student();
s1.Name = "Anisul Islam";
Console.WriteLine(s1.Name);
}
}