Difference between revisions of "C"
(→Advanced skills) |
(→Advanced skills) |
||
(12 intermediate revisions by the same user not shown) | |||
Line 1: | Line 1: | ||
=General Skills= | =General Skills= | ||
==Helloworld== | ==Helloworld== | ||
+ | To write output to the screen in C# you need to use 'Console.WriteLine': | ||
− | ==Constants - Variables - Data Types== | + | <syntaxhighlight lang="csharp">Console.WriteLine("HelloWorld");</syntaxhighlight> |
+ | |||
+ | it is important to note that a semi colon is used at the end of each statement. | ||
+ | |||
+ | When you run this, your computer can cope will hundreds of thousands of instructions per second, so the window may only flash up for a fraction of a second. to pause a program you can 'Console.ReadLine()': | ||
+ | |||
+ | <syntaxhighlight lang="csharp"> | ||
+ | Console.WriteLine("HelloWorld"); | ||
+ | Console.ReadLine(); | ||
+ | </syntaxhighlight> | ||
+ | |||
+ | ==Constants - Variables - Data Types - User Input== | ||
There are 9 types of data types. These include: | There are 9 types of data types. These include: | ||
*boolean | *boolean | ||
Line 67: | Line 79: | ||
<syntaxhighlight lang="csharp">long example = 7846354759340276482;</syntaxhighlight> | <syntaxhighlight lang="csharp">long example = 7846354759340276482;</syntaxhighlight> | ||
+ | |||
+ | ===User Input=== | ||
+ | You have so far used 'Console.ReadLine()' to pause a program, it is waiting for the user to press enter. This is used to get input from the keyboard, so when the user presses enter the value will be available to the programmer: | ||
+ | |||
+ | <syntaxhighlight lang="csharp"> | ||
+ | Console.WriteLine("HelloWorld"); | ||
+ | string Name = Console.ReadLine(); | ||
+ | Console.WriteLine("Hola Mundo, " + Name); | ||
+ | </syntaxhighlight> | ||
+ | |||
+ | This works well for strings, because 'Console.ReadLine()' returns a string. If you wanted to use this value as an integer, or other data type it must be converted: | ||
+ | |||
+ | <syntaxhighlight lang="csharp"> | ||
+ | Console.WriteLine("HelloWorld"); | ||
+ | int Age = Convert.ToInt32(Console.ReadLine()); | ||
+ | Console.WriteLine("Hola Mundo, you are" + Age); | ||
+ | Console.WriteLine("You will be "+ (Age+1) + " at your next birthday"); | ||
+ | </syntaxhighlight> | ||
+ | |||
+ | 'Convert' provides methods to convert each of the main data types. | ||
===Local vs Global=== | ===Local vs Global=== | ||
Line 266: | Line 298: | ||
==Subroutines - Functions== | ==Subroutines - Functions== | ||
+ | A set of instructions designed to perform a frequently used operation within a program. This makes it easy to repeat code. | ||
+ | |||
+ | A subroutine must be contained within a class, the standard C# template will include a class of Program: | ||
+ | |||
+ | <syntaxhighlight lang="csharp" line> | ||
+ | class Program | ||
+ | { | ||
+ | static void Main(string[] args) | ||
+ | { | ||
+ | greeting(); | ||
+ | greeting(); | ||
+ | } | ||
+ | |||
+ | public static void greeting() | ||
+ | { | ||
+ | Console.WriteLine("Hello"); | ||
+ | Console.WriteLine("Pleased to meet you"); | ||
+ | } | ||
+ | } | ||
+ | </syntaxhighlight> | ||
+ | |||
+ | This will produce the following output: | ||
+ | Hello | ||
+ | Pleased to meet you | ||
+ | Hello | ||
+ | Pleased to meet you | ||
+ | |||
+ | Every time <tt>greeting()</tt> is written, the program runs the ''greeting'' function. The term 'void' means the subroutine doesn't return a value. The terms 'public' and 'static' are not important at this stage. | ||
+ | |||
+ | Subroutines can also accept parameters, these are variables which can be passed into the subroutine when the subroutine is called: | ||
+ | |||
+ | <syntaxhighlight lang="csharp" line> | ||
+ | namespace Project | ||
+ | { | ||
+ | class Program | ||
+ | { | ||
+ | static void Main(string[] args) | ||
+ | { | ||
+ | greeting("Geoff"); | ||
+ | greeting("Bob"); | ||
+ | } | ||
+ | |||
+ | static void greeting(string name) | ||
+ | { | ||
+ | Console.WriteLine("Hello, " + name); | ||
+ | } | ||
+ | } | ||
+ | } | ||
+ | </syntaxhighlight> | ||
+ | |||
+ | This will produce the output: | ||
+ | |||
+ | Hello, Geoff | ||
+ | Hello, Bob | ||
+ | |||
+ | Functions are subroutines, but they can return a single value. The value returned can be done using any data type, but the data type must be specified when you create the function: | ||
+ | |||
+ | <syntaxhighlight lang="csharp" line> | ||
+ | namespace Project | ||
+ | { | ||
+ | class Program | ||
+ | { | ||
+ | static void Main(string[] args) | ||
+ | { | ||
+ | int x = Divide(16, 3); | ||
+ | Console.WriteLine(x); | ||
+ | } | ||
+ | |||
+ | static int Divide(int a, int b) | ||
+ | { | ||
+ | return a / b; | ||
+ | } | ||
+ | } | ||
+ | } | ||
+ | </syntaxhighlight> | ||
+ | |||
+ | Here the function is called 'Divide', notice the word 'void' is replaced by the data type ie 'int'. A function can also be used to assign a value to a variable, the value returned by the function is essentially stored with the variable name. | ||
+ | |||
+ | ==Parameters== | ||
+ | ===Value Parameters=== | ||
+ | Parameters passed to a function are passed as copies of their actual values and hence values sent and used as arguments by method are from a memory point of view different to the values actually passed. | ||
+ | |||
+ | Because of this any changes made within the subroutine have no affect on the value of the actual variable they're passed from, for example: | ||
+ | |||
+ | <syntaxhighlight lang="csharp" line> | ||
+ | |||
+ | class Program { | ||
+ | public static void DoSomething(int intTest) { | ||
+ | intTest++; | ||
+ | } | ||
+ | |||
+ | public static void Main(String[] Args) { | ||
+ | int test = 1; | ||
+ | Console.WriteLine(test); // Outputs 1; | ||
+ | |||
+ | DoSomething(test); | ||
+ | Console.WriteLine(test); // Outputs 1; | ||
+ | |||
+ | test++; | ||
+ | Console.WriteLine(test); // Outputs 2; | ||
+ | } | ||
+ | } | ||
+ | |||
+ | </syntaxhighlight> | ||
+ | |||
+ | |||
+ | In the code above, the first two 'Console.WriteLine()' statements will produce the same output. The subroutine 'DoSomething()' increments its own copy of 'value', but this value is not passed back. | ||
+ | |||
+ | ===Reference Parameters=== | ||
+ | Another option would be to use the 'ref' keyword before the parameter, allowing the value being passed as an argument to be passed as a reference to the memory location of the actual variable instead of as a copy of the value stored at said memory location. Now any changes within 'DoSomething()' will be retained: | ||
− | == | + | <syntaxhighlight lang="csharp" line> |
+ | |||
+ | class Program { | ||
+ | public static void DoSomething(ref int intTestRef) { | ||
+ | intTestRef++; | ||
+ | } | ||
+ | |||
+ | public static void Main(String[] Args) { | ||
+ | int test = 1; | ||
+ | Console.WriteLine(test); // Outputs 1; | ||
+ | |||
+ | DoSomething(ref test); // passed as reference | ||
+ | Console.WriteLine(test); // Outputs 2; | ||
+ | |||
+ | test++; | ||
+ | Console.WriteLine(test); // Outputs 3; | ||
+ | } | ||
+ | } | ||
+ | |||
+ | </syntaxhighlight> | ||
=Advanced skills= | =Advanced skills= | ||
Line 280: | Line 441: | ||
[[Handling Exceptions]] | [[Handling Exceptions]] | ||
+ | |||
+ | [[MySql Database]] |
Latest revision as of 14:09, 3 December 2023
Contents
General Skills
Helloworld
To write output to the screen in C# you need to use 'Console.WriteLine':
Console.WriteLine("HelloWorld");
it is important to note that a semi colon is used at the end of each statement.
When you run this, your computer can cope will hundreds of thousands of instructions per second, so the window may only flash up for a fraction of a second. to pause a program you can 'Console.ReadLine()':
Console.WriteLine("HelloWorld");
Console.ReadLine();
Constants - Variables - Data Types - User Input
There are 9 types of data types. These include:
- boolean
- string
- integer
- double
- decimal
- character
- byte
- float
- long
To declare a variable you state the data type followed by the name of the variable:
DataType VariableName;
You can declare and assign a variable at the same time:
DataType VariableName = Value;
Examples
Boolean is a binary value, being either true or false.
bool example = true;
String is used for storing characters in word form (note the double quotes "").
string example = "hello world";
Integer is used to store whole numbers (32 bit values).
int example = 457568368;
Double is used to store numbers where there are numbers before and after the decimal point, using 64 bits of memory.
double example = 3.3;
Decimal is used to store larger numbers with information before and after the decimal point, using 128 bits of memory.
decimal example = 12.593;
Character is used to store single letters (note the single quotes ).
char example = 'A';
Byte is used to store a byte (eight bits). In C#, it is specifically an 8 bit integer (0-255).
byte example = 255;
Float is used to store a 32 bit decimal number, which must be defined as being a float using "F" or "f" to distinguish it from a double, or it may cause compilation errors.
float example = 9.4F;
Long integer is also used to store whole numbers (However these are 64 bit values).
long example = 7846354759340276482;
User Input
You have so far used 'Console.ReadLine()' to pause a program, it is waiting for the user to press enter. This is used to get input from the keyboard, so when the user presses enter the value will be available to the programmer:
Console.WriteLine("HelloWorld");
string Name = Console.ReadLine();
Console.WriteLine("Hola Mundo, " + Name);
This works well for strings, because 'Console.ReadLine()' returns a string. If you wanted to use this value as an integer, or other data type it must be converted:
Console.WriteLine("HelloWorld");
int Age = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Hola Mundo, you are" + Age);
Console.WriteLine("You will be "+ (Age+1) + " at your next birthday");
'Convert' provides methods to convert each of the main data types.
Local vs Global
It is important to know that a variable declared within a block is only available within that block, it doesn't exist outside of the block. These would therefore be local variables, because they are local to where they are declared.
You can therefore declare variables within your program and declare them outside of any block, these variables will be available anywhere within your program. These are called global variables, because they can be used throughout the program.
Constants
Constants are used to create a variable of a specified data type that can never be changed after declaration.
During runtime, once the constant is set the value cannot change during the execution of the program.
The only way to change it is to edit the code and re-compile.
const int example = 32
Selection
Selection uses if statements and switch statements. These allow your programs to make decisions or change the course of your program based on an input or a variable.
If / If Else
if statements work by performing an action only if a condition is reached. After the if command, the condition should be within round brackets, the contents of which should equate to true or false.
1 if (a > b)
2 {
3 Console.WriteLine("A is greater than B");
4 }
This can also be paired with else, which will perform an action if the "if" condition is not met.
1 if (a > b)
2 {
3 Console.WriteLine("A is greater than B");
4 }
5 else
6 {
7 Console.WriteLine("A is not Greater Than B");
8 }
Else If
1 if (a > b)
2 {
3 Console.WriteLine("A is greater than B");
4 }
5 else if (a > c)
6 {
7 Console.WriteLine("A is greater than C");
8 }
9 else
10 {
11 Console.WriteLine("A is not Greater Than B or C");
12 }
Switch / Case
Switch is basically a combined if and if else statement, and is used for a lot of different options.
1 switch(x)
2 {
3 case 1:
4 x++;
5 break;
6 case 2:
7 x--;
8 break;
9 }
Default is an optional part of the switch method, which is used in case none of the other conditions are met.
1 switch(x)
2 {
3 case 1:
4 x++;
5 break;
6 case 2:
7 x--;
8 break;
9 default:
10 x*= x;
11 break;
12 }
Nesting Statements
Both if and switch statements can be nested, meaning that one statement can be contained within another.
1 if (a > b)
2 {
3 if (b > 50)
4 {
5 Console.WriteLine("b is a very large number!");
6 }
7 }
Repetition - Iteration
Repetition is the use of a for loop to execute one piece of code over and over. There are multiple ways to create a for loop though. These are:
While uses one condition that which if met, will repeat the code.
1 while (true)
2 {
3 x ++;
4 }
For loops intialise a variable, check a condition and perform an action. This is done before each iteration.
1 for (int i = 0; i <= 1000000; i++)
2 {
3 console.WriteLine(i);
4 }
Do while is the same as a while, however it doesn't check until it has done one iteration.
1 do
2 {
3 x ++;
4 }
5 while (true)
Foreach loops can also be used to access array variables [1]
1 foreach (int x in Arr)
2 {
3 Console.WriteLine(x);
4 }
An iteration is the piece of code performed each time a loop runs.
Iterations can be skipped by calling the continue function.
1 for (int i = 0; i <= 10; i++)
2 {
3 if(i==5)
4 {
5 continue;
6 }
7 console.WriteLine(i);
8 }
Iteration can be terminated with the break function.
1 for (int i = 0; i <= 10; i++)
2 {
3 if(i==5)
4 {
5 break;
6 }
7 console.WriteLine(i);
8 }
Operators
Mathematical operators
Operation | Character used | Description | Example |
---|---|---|---|
Addition | Performed using the "+" operator | Adds values together. | A + B = 12 |
Subtraction | Performed using the "-" operator | Subtracts values. | A - B = 8 |
Multiplication | Performed using the "*" operator | Multiplies values together. | A * B = 20 |
Division | Performed using the "/" operator | Divides values. | S / B = 5 |
Increment | Performed using the "++" operator | Adds 1 to a variable and saves the variable. | A++ = 11 |
Decrement | Performed using the "--" operator | Subtracts 1 from a variable and saves the variable. | B-- = 9 |
Modulus | Performed using the "%" operator | Finds the remainder of a division between values. | 10 % 3 = 1 |
Note: there are variations on the increment and decrement operators. These can be performed in both prefix and postfix forms. In prefix form, (syntax "++x;") the variable will be incremented or decremented, and then the value will be used by the function calling it. In postfix form, however, (syntax "x++;") the variable will be used by the function calling it, and be incremented or decremented afterwards.
Comparison Operators
Operation | Character used | Description | Example |
---|---|---|---|
Equal | Performed using == | Returns true if both inputs are the same. | value == "test" |
Not Equal | performed using != | returns true if both inputs are not the same | value != "test" |
Less Than | Performed using < | Returns true if value 1 is less than or equal to value 2. | value < 0 |
Greater Than | performed using > | Returns true if value 1 is greater than value 2. | value > 1 |
Less Than or Equal | Performed using <= | Returns true if value 1 is less than or equal to value 2. | value <= 0 |
Greater Than or Equal | performed using >= | Returns true if value 1 is greater than or equal to value 2. | value >= 1 |
Bitwise operators
Operation | Character used | Description | Example |
---|---|---|---|
AND | Performed using "&" or "&&" | Returns true if both inputs are true. | true && false = false |
OR | performed using "|" or "||" | returns true if one or both inputs are true. | true || false = true |
XOR | Performed using "^" | Returns true if both inputs are different. | true ^ false = true |
NOT | performed using "!" | Returns false if true, or true if false. | !true = false |
Subroutines - Functions
A set of instructions designed to perform a frequently used operation within a program. This makes it easy to repeat code.
A subroutine must be contained within a class, the standard C# template will include a class of Program:
1 class Program
2 {
3 static void Main(string[] args)
4 {
5 greeting();
6 greeting();
7 }
8
9 public static void greeting()
10 {
11 Console.WriteLine("Hello");
12 Console.WriteLine("Pleased to meet you");
13 }
14 }
This will produce the following output:
Hello Pleased to meet you Hello Pleased to meet you
Every time greeting() is written, the program runs the greeting function. The term 'void' means the subroutine doesn't return a value. The terms 'public' and 'static' are not important at this stage.
Subroutines can also accept parameters, these are variables which can be passed into the subroutine when the subroutine is called:
1 namespace Project
2 {
3 class Program
4 {
5 static void Main(string[] args)
6 {
7 greeting("Geoff");
8 greeting("Bob");
9 }
10
11 static void greeting(string name)
12 {
13 Console.WriteLine("Hello, " + name);
14 }
15 }
16 }
This will produce the output:
Hello, Geoff Hello, Bob
Functions are subroutines, but they can return a single value. The value returned can be done using any data type, but the data type must be specified when you create the function:
1 namespace Project
2 {
3 class Program
4 {
5 static void Main(string[] args)
6 {
7 int x = Divide(16, 3);
8 Console.WriteLine(x);
9 }
10
11 static int Divide(int a, int b)
12 {
13 return a / b;
14 }
15 }
16 }
Here the function is called 'Divide', notice the word 'void' is replaced by the data type ie 'int'. A function can also be used to assign a value to a variable, the value returned by the function is essentially stored with the variable name.
Parameters
Value Parameters
Parameters passed to a function are passed as copies of their actual values and hence values sent and used as arguments by method are from a memory point of view different to the values actually passed.
Because of this any changes made within the subroutine have no affect on the value of the actual variable they're passed from, for example:
1 class Program {
2 public static void DoSomething(int intTest) {
3 intTest++;
4 }
5
6 public static void Main(String[] Args) {
7 int test = 1;
8 Console.WriteLine(test); // Outputs 1;
9
10 DoSomething(test);
11 Console.WriteLine(test); // Outputs 1;
12
13 test++;
14 Console.WriteLine(test); // Outputs 2;
15 }
16 }
In the code above, the first two 'Console.WriteLine()' statements will produce the same output. The subroutine 'DoSomething()' increments its own copy of 'value', but this value is not passed back.
Reference Parameters
Another option would be to use the 'ref' keyword before the parameter, allowing the value being passed as an argument to be passed as a reference to the memory location of the actual variable instead of as a copy of the value stored at said memory location. Now any changes within 'DoSomething()' will be retained:
1 class Program {
2 public static void DoSomething(ref int intTestRef) {
3 intTestRef++;
4 }
5
6 public static void Main(String[] Args) {
7 int test = 1;
8 Console.WriteLine(test); // Outputs 1;
9
10 DoSomething(ref test); // passed as reference
11 Console.WriteLine(test); // Outputs 2;
12
13 test++;
14 Console.WriteLine(test); // Outputs 3;
15 }
16 }