Hi and welcome to this C# tutorial! Hope this helps you out!
Important notes:
- C# uses
//
for single line comments.- Ex:
//computer doesn't read this
- Ex:
- C# places a semicolon
;
at the end of each statement.- Ex:
int a = 5;
- Ex:
Variables:
These are the main variables which will be dicussed here. There are more but here are the basics.
- Strings:
- They are made up of multiple characters.
- They are surrounded by double quotes
- Ex:
string name = "Bob";
- Integers:
- Are integers. Are whole numbers.
- Ex:
int b = 6;
- Doubles:
- Have a decimal point and are more precise than integers.
- Ex:
double num = 5.01;
- Booleans:
- Are either true or false.
- Ex:
bool fun = true;
Converting
In the repl.it that is included with this tutorial there are some conversions..toString();
-> Converts to a stringConvert.toDouble();
-> Converts to a doubleConvert.toInt32();
-> Converts to an int
Output and Input
- Output:
Console.WriteLine();
is used to write something on a new line.
Console.Write();
writes something on the same line- Ex:
Console.WriteLine("Hello World");
- Ex:
- Input:
Console.ReadLine();
returns the input as a string.
If/Else Statements (Conditionals)
An if statement is executed when something results to true. An if statement has a condition and body. If the condition is true then the body will run.
An example of a condition is a == 5
. Note that the ==
is used because it is comparing two things. A !=
is the comparison operator for not true.
Example of an if statement:
int choice = Convert.ToInt32(Console.ReadLine());
if(choice == 1) //addition
{
double addition_output = first_num + second_num;
Console.WriteLine("You have choosen addition!");
Console.WriteLine("Output: " + addition_output);
}
An else statement is only executed if the rest are false. If you use 3 if statements and then an else statement then the code will try each if statement but if you use an if- else if- else setup then the code will only try 1 if statement.
While Loop
A while loop can be used to continue to do something while a condition results to true.
In the calculator program included in this tutorial there is a variable declared at the very beginning like this: bool try_again = true;
. Then at the end, once the person has finised, if they input something other than yes for continuing the game the else statement body contains code which is try_again = false
which terminates the while loop. Every while loop needs a terminating condition or it will become an infinite loop!
nice i love it