0% found this document useful (0 votes)
20 views

0149 Csharp Programming Beginner Tutorial

This document provides an introduction to programming and the C# programming language. It explains some basic concepts like variables, data types, user input, and arithmetic operations. The document is intended for absolute beginners and guides them through creating simple programs to display text, take user input, and perform calculations.

Uploaded by

Esmail
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
20 views

0149 Csharp Programming Beginner Tutorial

This document provides an introduction to programming and the C# programming language. It explains some basic concepts like variables, data types, user input, and arithmetic operations. The document is intended for absolute beginners and guides them through creating simple programs to display text, take user input, and perform calculations.

Uploaded by

Esmail
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 21

C# Programming Tutorial Davide Vitelaru

C# Programming Tutorial
Lesson 1: Introduction to Programming
About this tutorial
This tutorial will teach you the basics of programming and the basics of the C# programming language.

If you are an absolute beginner this tutorial is suited for you.

If you already know one or more programming languages, you might find it a bit boring and skip to the
next lesson.

To follow this tutorial you need to have Visual C# Express Edition 2008 or 2010 installed on your
computer. These applications are free to download and install.

The best way to learn this is by practicing. Make sure you write all the examples yourself and test them,
and that you do the tasks that I have put at the end. The tasks at the end will probably help you the
most to get used to C#.

This tutorial has been entirely created by Davide Vitelaru (http://davidevitelaru.com/).

Note: You can use the table of contents at page 20 to get around the document quickly

Software required: You must know: You will learn:


 Visual C# Express  What programming is  Some Basics
Edition 2008/2010  What a programming  Variables
language is  Variable Operations
 Decisions
 Loops
C# Programming Tutorial Davide Vitelaru

Some Basics
Throughout this tutorial I will refer to Visual C# Express 2008/2010 as the IDE (Integrated Development
Editor).

To start with, open your IDE and create a new project (File >> New >> Project or Ctrl + Shift + N). Select
the Visual C# Console Application template from the window that appears and click OK:

Once you created your project, you will see this:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Lesson_1
{
class Program
{
static void Main(string[] args)
{

}
}
C# Programming Tutorial Davide Vitelaru

I k o it looks s a , ut it’s ot that o pli ated. You o l ha e to o a out this section:

static void Main(string[] args)


{

This is the exact place where you will write your source code, to be exact, between the braces following
static void Main(string[] args).

At this poi t, ou appli atio o ’t do a thing. To start you application, press F5. You will see a black
windows appearing and closing immediately.

It loses i ediatel e ause it does e a tl hat ou told it to do: othi g. Let’s tell it to ope a d
wait for a keystroke to close.

Write the following line between the braces of static void Main(string[] args):

Console.ReadKey();

Now, press F5 to run your application. You will end up with a black window awaiting you to press any
key so it closes.

Let’s ake it e e o e fu , ake our code look like this:

static void Main(string[] args)


{
Console.WriteLine("Hello World!");
Console.ReadKey();
}

Again, press F5 to run your application. This ti e the appli atio ill displa Hello Wo ld a d the it
will wait for you to press a key. If ou get a e o , ake su e ou t ped e e thi g o e tl . Also, do ’t
forget the semicolons at the end; they are very important (and annoying for beginners that keep
forgetting them).

A statement can be used multiple times. Do the following:

static void Main(string[] args)


{
Console.WriteLine("Press a key to continue...");
Console.ReadKey();
Console.WriteLine("Now press another key...");
Console.ReadKey();
C# Programming Tutorial Davide Vitelaru

Console.WriteLine("Press again to exit...");


Console.ReadKey();
}

Just change the text between the quotation marks in the Console.WriteLine("") statement to
change the displayed message.

What’s the catch with the black window?


The la k i do that ou a e u e tl o ki g at is alled a o sole i do . Ba k i the ’s
o pute s did ’t ha e task a s a d i do s like the do o , the o l had this te t-based interface.
Your application has a text-based interface at the moment.

C eati g a appli atio ith a use i te fa e i do s, utto s, te t o es, et … is usuall ha de , ut


tha ks to Mi osoft’s .NET f a e o k e a eate o e i a fe eas steps; et, that is ot the poi t of
this lesson.

This lesson is supposed to show you the basics, and once you finish it you will be able to move on to
further lessons and create useful and good-looking applications.
C# Programming Tutorial Davide Vitelaru

Data manipulation
A program that displays messages and waits for keystrokes won’t e of use to a o e, so let’s ake it
do so ethi g useful. Let’s ake it add t o u e s.

Variables
Variables are like boxes, you can put things in them. In our case, we will use them to store values.

Variables are of different types, depending on the type it can store different values, for example and
integer variable can hold a number, while a string can hold characters e . hello a e is joh – 21
characters, spaces included).

To sta t ith, let’s use a ia les displa i fo atio :

static void Main(string[] args)


{
string name;
name = "John";
Console.WriteLine(name);
}

Press F5, run your application and see the result. If you receive an error, make sure you typed everything
correctly.

How does it work?


To use a variable, we must first create it. To eate it a ette te ould e to de la e it , you must
type the variable type, followed by the name you want the variable to have:

string variable;
int another_variable;

At this point, both of these variables are empty. To assign a value to a variable, type the name of the
variable, equal and the value you want it to hold. If it is a string, never forget to type the value between
quotation marks:

variable = "hello there";


another_variable = 22;

Make sure you assign the correct type of value to the variable, or you will receive an error; In this case
variable is a string so it can hold a string value, and is another_variable an integer so it
can hold a number. You a a e the a ia les ho e e ou like as lo g as ou do ’t use ese ed
words (like int, ou a ’t do int int e ause it ould etu a e o , a d the a e does ’t o tai
so e pa ti ula s ols, a d the a e does ’t sta t ith a number.

Let’s make the computer ask for our name, and then greet us:
C# Programming Tutorial Davide Vitelaru

static void Main(string[] args)


{
Console.WriteLine("Hello, what is your name?");
string name;
name = Console.ReadLine();
Console.WriteLine("Hello, " + name);
Console.ReadKey();
}

What this code does is to declare a variable called name a d the to assig it the alue of the use ’s
input.

Press F5 and introduce yourself to your program.

How does it work?


Console.ReadLine() represents the users input, or what you type in the console window. You can
assign that input to a variable as seen in the example above.

You can also tie together two strings using the + sign; in this case we tied together "Hello" and the
variable name which is a string too. You can also do "hello " + "there" and get “hello
there”.

Making a calculator would seem to be pretty easy, and it is, but you have to remember one thing: the
user input is a string; therefore you cannot assign it to an integer unless you convert it.

static void Main(string[] args)


{
int number1, number2;

number1 = Int32.Parse(Console.ReadLine());
number2 = Int32.Parse(Console.ReadLine());

Console.WriteLine(number1.ToString() + "+" +
number2.ToString() + "=" + (number1 + number2).ToString());

Console.ReadKey();
}

Press F5, and make sure you type a number and press enter, then type another number and press enter
then stare at the result before pressing a key to exit. If you type anything but numbers it will return you
an error so be careful.

Note that you can declare variables of the same type by separating the names with a comma (int
number1, number2).

Int32.Parse() will tu hat ou put et ee the pa e thesis i to a i tege , as lo g as it’s a st i g.


C# Programming Tutorial Davide Vitelaru

Example: int x; x = Int32.Parse("20");

In the previous example we used Int32.Parse() to convert the user input (that is a string) into an
integer and assign it to two integer variables.

Since the two variables (number1, number2 a e i tege s, ou a ’t just displa the ithout
converting them to strings. To convert them, just t pe the i tege ’s a e follo ed
“.ToString() . This will convert any integer variable, or sum of an integer variable into a string.

As you can see, we used a parenthesis to convert only the sum of the two variables:

(number1 + number2).ToString() – this will convert the sum of number1 and number2 into a
string.

Number1.ToString() + number2.ToString() – this will only convert them separately and


tie them together (Ex. "2" + "2" = "22").

Variable Operations
You al ead k o ho to eate a al ulato that a add, ut let’s also ake it su t a t, ultipl a d
divide.

Small side note: if you type // in your C# source code, all that remains of the line will be turned into a
comment. The comment has no importance for the application, but only for the programmer. I will use
comments in the source code to explain things easier. Comments are colored in green in the source
code.

static void Main(string[] args)


{
//We declare two integers
int number1, number2;

//We ask the user for values


Console.WriteLine("Please insert a number:");
number1 = Int32.Parse(Console.ReadLine());
Console.WriteLine("Please insert another number:");
number2 = Int32.Parse(Console.ReadLine());

//We create a variable to hold the results


//and use it in calculations
int result;

result = number1 + number2;


//Addition, use + to add two integers
Console.WriteLine("Sum: " + result.ToString());

result = number1 - number2;


//Subtraction, use - to subtract two integers
Console.WriteLine("Subtraction: " + result.ToString());
C# Programming Tutorial Davide Vitelaru

result = number1 * number2; //Multiplication, use *


Console.WriteLine("Multiplication: " + result.ToString());

result = number1 / number2; //Division, use /


Console.WriteLine("Division: " + result.ToString());

Console.ReadKey();
}

Press F5 and try it out.


C# Programming Tutorial Davide Vitelaru

Decisions
Sometimes, you will have to execute just a piece of code depending on the use ’s i put. Fo e a ple, if
the user has inserted a number and you want your application to display if the number is positive or
negative, you will need some extra pieces of code.

static void Main(string[] args)


{
Console.WriteLine("Insert a number: ");
//As you can see, a variable can be
//assigned while it is declared (created)
int number = Int32.Parse(Console.ReadLine());

if (number > 0) Console.WriteLine("Number is positive");


else if (number == 0) Console.WriteLine("Number is 0");
else Console.WriteLine("Number is negative");

Console.ReadKey();
}

This code is easy to understand, one of the advantages of C# being the face that it’s si ila to E glish.

If the number is greater than 0, display that the number is positive, else if the number is 0 display that it
is 0, else display that it is negative.

The equality operator is == because = is used to assign. The following statement would return an error:
if (number = 0) Console.WriteLine("Number is 0");

What do we do when we want to do multiple things under the same if clause?

if (number > 0)
Console.WriteLine("Greater than 0");
number = 0;

This would assign 0 no matter what number is, but if we insert both statements between braces
follo i g the if” clause we might get lucky:

if (number > 0)
{
Console.WriteLine("Greater than 0");
number = 0;
}

Now, if the number is greater than 0, it will be assign the value 0 after the message is displayed.

This is how braces are used to execute multiple statements.


C# Programming Tutorial Davide Vitelaru

Let’s ake a al ulato that lets the use decide what operation to perform.

Try to do it yourself, it would be good practice, then look at the code. Small tip: for strings just do if
(variable == "addition"), it’s the sa e s ta as it is fo i tege s.

static void Main(string[] args)


{ Console.WriteLine("Please insert two numbers:");
int n1 = Int32.Parse(Console.ReadLine());
int n2 = Int32.Parse(Console.ReadLine());

Console.WriteLine("Type operation to perform:");


string decision = Console.ReadLine();

if (decision == "Add")
Console.WriteLine((n1 + n2).ToString());
else if (decision == "Subtract")
{
int result;
result = n1 - n2;
Console.WriteLine(result.ToString());
}
else if (decision == "Multiply")
{
int result = n1 * n2;
Console.WriteLine(result.ToString());
}
else if (decision == "Divide")
{
string result = (n1 / n2).ToString();
Console.WriteLine(result);
}
else Console.WriteLine("Invalid choice");

Console.ReadKey();
}

Note that I used different ways to calculate the result just to show you how you how flexible the variable
operations are.

Of course, you can use an if inside another:

if (n1 > 0)
{
if (n1 > 10)
Console.WriteLine("Greater than 10");
else Console.WriteLine("Smaller than 10");

Console.WriteLine("Greater than 0");


}
C# Programming Tutorial Davide Vitelaru

What if we want to check if a variable does NOT hold a value?

//If the name is not John, display


//Hello, else display Hello John
if (name != "John")
Console.WriteLine("Hello!");
else
Console.WriteLine("Hello John!");
C# Programming Tutorial Davide Vitelaru

Loops
Where would we be without loops? Imagine that we would have to write the same statement all over
again, and it might still not work.

Just imagine asking the user for a question, if he gets it wrong, what would the application do? Exit so he
can start all over, or repeat the question?

There are several ways you can make your application repeat a statement.

While loop
This loop will repeat a statement until something happens.

static void Main(string[] args)


{
//Variable x is 5
int x = 5;

while (x > 0)
{
//While x is greater than 0,
//we display it's value and decrease it
Console.WriteLine(x.ToString());
x = x - 1;
}

Console.ReadKey();
}

As always, press F5 to test your program. It will display all numbers from 5 to 1. It will not display 0
because x will be greater than 0 at that point. What you can do is use the greater or equal operator:

while (x >= 0)
{
//While x is greater than 0,
//we display it's value and decrease it
Console.WriteLine(x.ToString());
x = x - 1;
}

This will also display 0. It also works for smaller or equal (<=).

The hile loop a e used to epeat uestio s:

static void Main(string[] args)


{
string password = "pass";
C# Programming Tutorial Davide Vitelaru

while (password != "1234")


{
Console.WriteLine("Please insert your password:");
password = Console.ReadLine();
}

Console.WriteLine("Password correct!");
Console.ReadKey();
}

This code will ask the user for the password (1234) and it will only stop when he gets it right. The last
two lines of code will be executed only if the use a ages to es ape the loop, ut he a ot do that
unless he types the correct password. Press F5 and try it yourself.

Note that e assig ed a alue to the pass o d a ia le efo e usi g it i the hile loop. If e do
not assign a value to it, it will return an error.

Also, if the condition is never accomplished, the loop will run to infinity, so you better be careful what
you condition is:

static void Main(string[] args)


{
while ((2 + 2) == 4)
{
Console.WriteLine("This will never stop");
}
}

For loop
The fo loop is diffe e t f o the hile loop the fa t that it allows you to count the times you loop.
Let’s i agi e ou a t to displa Hello! fift ti es o the s een. You could type
Console.WriteLine("Hello!") fifty times in the source code, but that would just be wrong.

I stead, use a fo loop:

static void Main(string[] args)


{
//i++ is the same thing with i = i + 1
//You can use any integer to do that
//Example: int variable = 0; variable++;

for (int i = 0; i <= 50; i++)


{
Console.WriteLine("Hello!");
}

Console.ReadKey();
C# Programming Tutorial Davide Vitelaru

I know it looks s a , ut it’s p ett eas . What the fo loop does it to de la e a a ia le a ed i


ou a a e it a a ou a t , ou assig it the alue , ou tell it that it ust ot e eed 5 ,
a d ou tell it to i ease itself i ea h loop. Once it reaches 50, it will stop.

Press F5 and test it. If you receive a y error, ake sure you did ’t forget a y se icolo i the for
statement.

Note that using ++ after an integer will increase it by 1. If you already have an integer declared, you can
use it i the fo loop i stead of de la i g a othe o e.

static void Main(string[] args)


{
int variable;

//You don't have to use { } if you only have one statement


for (variable = 0; variable < 10; variable = variable + 1)
Console.WriteLine(variable.ToString());

//As you can see, I used variable = variable + 1 instead


of variable++

//And yes, you can display the value of the counter


variable (in this case
//cleverly named "variable", but named "i" in the previous
example)

Console.ReadKey();
}

This example will display the numbers from 0 to 9.


C# Programming Tutorial Davide Vitelaru

Summary
If you are working on a project and forgot something, check this section always.

This is what you learned in this lesson, plus a few extra things so make sure you read this.

Simple statements

Console.WriteLine("Hello"); Displays on the console window the string placed


between the parentheses.
Console.ReadKey(); Prompts the user to press any key.

Variables

Declaration: variable_type variable_name;

Example: int name;

Known types (at this point): int, string.

Assigning: variable_name = value;

Variable Operations

For integers:

int x;
int y;

x = Int32.Parse(Console.ReadLine());
y = Int32.Parse("5");

x = y + 5 + 10; // x will be y + 5
x = (2 + 2) + 2 / 2 + 10; //This works too
//Use as many brakets as you need
x = x + y; // x will be x + y
x++; // x will be x + 1

x += 5; //x will be x + 5
x *= 5; //x will be x * 5
//Same for / and -
x /= 5; x -= 5;

For strings:

name = "John";
age = "17";

name = "Name is:" + name + ", and the age is:" + age;
C# Programming Tutorial Davide Vitelaru

//name will hold: "Name is: John, and the age is: 17"

Console.WriteLine(name);

int x = 15;

name += x.ToString();
//+= works here too, don't try -=, *= and /= though
//name will hold: "Name is: John, and the age is: 1715"

Decisions

if (x != 0) Console.WriteLine("Number is NOT 0");

if (x == 0) Console.WriteLine("Number is 0");

int y = 5;

//You can use && to use two conditions


if (x > 0 && y > 0)
Console.WriteLine("Both numbers are positive");
//The equivalent:
if (x > 0) if (y > 0)
Console.WriteLine("Both numbers are positive");

//This is the OR operator ||


//If any of the conditions is acomplished,
//the staments will be executed
if (x > 0 || y > 0)
Console.WriteLine("One of the numbers is positive");

//Both operators can be used more times:


if (x > 0 && y > 0 && (2 + 2 == 4))
{
Console.WriteLine("Both numbers are positive");
Console.WriteLine("The computer agrees that 2+2 equals
4");
}

//If x is greater than 0 OR 1 + 1 equals 2


if (x > 0 || (1 + 1 == 2))
{
//If this doesn't run then you computer can't
calculate
Console.WriteLine("I don't know if the number is
positive");
//This statement will run anyway because 1+1==2 is
always true
}
C# Programming Tutorial Davide Vitelaru

Loops

//WHILE LOOP
string username = "", password = "";

//While the username is NOT John


//AND &&
//The password is not 1234
while (username != "John" && password != "1234")
{
Console.WriteLine("Username and password:");
username = Console.ReadLine();
password = Console.ReadLine();
}

Console.WriteLine("Hello John!");

//FOR LOOP
for (int i = 0; i < 10; i = i + 2)
{
//i = i + 2
//This will increment i by two each loop

//You can do any operation you want there


//Multiply by 2:
//for (int i = 0; i < 10; i = i * 2)
//or
//for (int i = 0; i < 10; i *= 2)

Console.WriteLine(i.ToString());
}
C# Programming Tutorial Davide Vitelaru

Tasks
As I promised, these are the tasks. The task actually since there is a single one in this lesson, and it might
be pretty challenging for a beginner.

Make sure you try to do them yourself before looking at the source codes. After all, the whole idea is to
learn programming.

Task – Calculator
Create a simple calculator that prompts the user for 2 numbers, and then asks the user what the
operation that you want it to perform is.

The calculator must be able to do the following operations:

 Addition
 Subtraction
 Multiplication
 Division
 Exponentiatio Nu e ultiplies itself, if ou’ e ot th
g ade et do ’t do it

At the end, the calculator must ask the user if he wants it to perform another calculation, and do so if he
does.

Tips: Use a fo loop fo the e po e tiatio , a d a a ia le that holds the use ’s a s e to pe fo


a othe ope atio at the e d alo g ith a hile loop. Also, you can write the way the application will
o k o a pie e of pape , a d the t a slate hat you wrote in C#.
C# Programming Tutorial Davide Vitelaru

Code:

static void Main(string[] args)


{
//This variable holds the user's
//decision to perform another operation
string answer = "yes";

//While the answer is "yes"


while (answer == "yes")
{
//Asking the user for the numbers
Console.WriteLine("Insert a number: ");
int n1 = Int32.Parse(Console.ReadLine());
Console.WriteLine("Insert another number:");
int n2 = Int32.Parse(Console.ReadLine());

//Asking the user for the operation to perform


//Using a while loop to make sure that he gets it
right

Console.WriteLine("Operation to perform: ");


string operation = "none"; //This will hold the answer

//If the user doesn't insert a correct answer, he will


be asked to insert an answer again
while (operation != "add" && operation != "subtract"
&& operation != "multiply" && operation != "divide" && operation !=
"exponent")
{
operation = Console.ReadLine();
}

if (operation == "add")
Console.WriteLine((n1 + n2).ToString());

else if (operation == "subtract")


Console.WriteLine((n1 - n2).ToString());

else if (operation == "multiply")


Console.WriteLine((n1 * n2).ToString());

else if (operation == "divide")


Console.WriteLine((n1 / n2).ToString());

else if (operation == "exponent")


{
int result = 1;

//This will multiply n1 with itself for n2 times


for (int i = 0; i <= n2; i++)
C# Programming Tutorial Davide Vitelaru

result *= n1;

Console.WriteLine(result.ToString());
}

//Asking the user for another operation


Console.WriteLine("Would you like to perfom another
operation?");
answer = Console.ReadLine();
}
}

Watch it running:
C# Programming Tutorial Davide Vitelaru

Contents
About this tutorial ................................................................................................................................... 1
Some Basics............................................................................................................................................. 2
What’s the at h ith the la k i do ? ............................................................................................ 4
Data manipulation ................................................................................................................................... 5
Variables.............................................................................................................................................. 5
Variable Operations ............................................................................................................................. 7
Decisions ................................................................................................................................................. 9
Loops .................................................................................................................................................... 12
While loop ......................................................................................................................................... 12
For loop ............................................................................................................................................. 13
Summary ............................................................................................................................................... 15
Tasks ..................................................................................................................................................... 18
Task – Calculator ................................................................................................................................ 18

You might also like