Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Africa Learn C#

Peter Phillip
December 13, 2013
66

Africa Learn C#

This is a simple c# tutorial book. It opens up about programming in general using c# to explain.

Peter Phillip

December 13, 2013
Tweet

Transcript

  1. Content 1.1 What is a development environment 1.2 Types 1.3

    Operators 1.3.1 Assignment operators 1.3.2 Relational operators 1.3.3 Logical operators 1.3.4 Conditional operators 1.4 My first program 1.5 Explanation of Code (My first Program)
  2. About this book - Programming What will programming require of

    you? Patience, Time, Your life... yes your life... Side effects of programming? Becoming a zombie when in front of a computer, Disliking Sleep, Anti-Social behaviour, Thinking of almost everything in a technical way. What is programming? It is simply taking processes that exist in the real world and putting them into an application. Why? To make processes reachable and manageable in a systematic way, creating more time to be lazy but others may argue it's a smarter way of processing things.
  3. Chapter One 1.1 What is a development environment? This is

    where you build your applications, write code, test what you are creating etc think of it as a lab underground somewhere. This programming we are talking about has to be done somewhere... so we are going to be coding in visual studio, not much of a choice really. Well just like you use VLC or Windows Media Player to watch movies or how you use chrome to browse Facebook you will use Visual Studio to create applications such as VLC, Windows Media Player, Chrome or Facebook okay not really... but you will be able to understand how those are made. Setting up your Development environment. Just like you install VLC or games and other software on your computer you will need to install Visual Studio. You will need to download: Visual Studio 2012 Express for Windows Desktop You can download Visual Studio here: http://www.microsoft.com/visualstudio/ or http://www.microsoft.com/visualstudio/eng/downloads#d-2012-express You can also work in visual studio 2010 or other versions. Before we can jump into creating something lets go through basics about programming, starting with "Types".
  4. 1.2 Types Types: int, boolean, string, decimal In programming we

    separate numbers, letters, characters and other types that exist. We have strict names for them that are used to identify the type they are, like the following: Int - Which is an Integer which you know as a number value like 1, 2, 3, 4 or 10 or 55 Decimal - Which is a decimal, an amount value with a point or decimal like 1.0 , 45.6, 78.00 or 78.99 String - Which is a letter or word value like "A", "B", "C", "speed", "hectic" as you can see the letters and words have been enclosed in inverted commas, this is how we know and write a string value, so that means if I am to write "105" it would not be an int (Integer) but rather a string value. Boolen - Is a True or False value. Which can also be represented by 1 and 0 just like on your kettle or light switch where you have seen 1 or 0. 1 would be ON; which means true and 0 would be OFF which means false. Now that you know four types that are used in programming, I will explain how they are used. You may have noticed I used the word value for each of the descriptions of the types, this is because what a type describes is a value. For example an int type can represent the value 1 or the value 2 or the value 17 just like the type String can have the value "tree" or the letter "H". I would now like to introduce a Variable. Think of variable as a container, yes a container that carries your lunch or dessert etc... but in programming this container is known as a variable that carries types; types like int, string, boolean, decimals and so on. Enough theory, Let us get a bit more practical here using a real world example, remember when you went to a clothing store and wanted to make sure you look good in the clothes before making the purchase? So you went to the changing rooms and at the entrance you met Chuck - Whose duty was to count the amount of items you want to try on, give you a number and show you which changing to room use? Well Chuck's job was more than that, this is what his manager required from him. 1. Create a card to hold a customer details. 2. The card should have a place for following: The total amout of clothing items. The total cost of the items. The type of T-Shirt being tried. The type of Pants being tried. Identify if customer is an Adult.
  5. This is what the card looked like: Illustration 1.1 So

    we have a customer card that serves a very physical process in the real world. 1. Chuck has to write every time a client requires service. 2. Sometimes Chuck loses these cards and has to try and recall the day's events, which is sometimes not possible and ends up giving the manager bad data. 3. Chuck has to give the cards to his manager before leaving work but he does not always find the manager and ends up being late for his transport. Chuck is now fed up and decides to now become Chuck Norris. Since he is a part-time student and studying programming, he will attempt to write a program that will implement the system his manager requested and which may earn him some cash. Therefore he does not have to remember all the things, he does not have to wait anymore since everything will be on a computer. His manager will now be able to print the results of the day and so on. So Chuck whips out his c# skills and looks at the card from a programmers perspective, What do you think Chuck can see on this card? let's see what he can see on the illustration 1.2 below.
  6. Illustration 1.2 Chuck starts coding but realises he needs to

    learn about operators before he can continue, so he takes a break from coding and looks into operators and this is what he looked into:
  7. 1.3 Operators Plus (+), Minus(-), Multiplication (*), and Division (/)

    are defined in all programming languages and they do what you would expect. For example 5 * 5 = 25 and 8 - 2 = 6 We also have a few more operators that we use but not to calculate like above, they are assignment operators, logical operators, conditional operators and relational operators. Sounds like a lot to know right? Wait 'til you see and understand, you won't feel like Einstein, It is really that simple. 1.3.1. Assignment Operator The most common assignment operator is = This operator assigns the value in the right variable to the left side variable(Remember a variable as a container) For example: Items = 5 The statement above means the variable Items is being given the value 5 to hold and that's what an assignment operator does, It helps us place a value into a variable. 1.3.2. Relational Operator Relational operators checks relationship between two operands. If the relation is true, it returns value 1 and if the relation is false, it returns value 0. For example: 12 > 5 In English, the code 5 > 12 would simply state as: Is 5 greater than 12? We would say no. In code we would say false. This would return false because 5 is not greater than 12. Let's try another type of relational operator: 5 == 5 In English, the code 5 == 5 would simply state as: Is 5 equals to 5? We would say yes. In code we would say true. This would return true because 5 is equal to 5. Below is a table that explains this better and shows more types of relational operators.
  8. Operator Meaning Of Operator Example == Equal to 5==3 returns

    false (0) > Greater than 5>3 returns true (1) < Less than 5<3 returns false (0) != Not equal to 5!=3 returns true(1) >= Greater than or equal to 5>=3 returns true (1) <= Less than or equal to 5<=3 return false (0) NB: The Logical and Conditional may be a bit of a challenge for now to understand, lose no heart, you will understand it when we implement some code however if you get to understand it now that is awesome! 1.3.3. Logical Operator Logical operators are used to combine expressions containing relation operators. Operator Meaning Of Operator Example && Logial AND If c=5 and d=2 then,((c==5) && (d>5)) returns false. || Logical OR If c=5 and d=2 then, ((c==5) || (d>5)) returns true. ! Logical NOT If c=5 then, !(c==5) returns false. For expression, ((c==5) && (d>5)) to be true, both c==5 and d>5 should be true but, (d>5) is false in the given example. So, the expression is false. For expression ((c==5) || (d>5)) to be true, either the expression should be true. Since, (c==5) is true. So, the expression is true. Since, expression (c==5) is true, !(c==5) is false. 1.3.4. Conditional Operator Conditional operator takes three operands and consists of two symbols ? and : . Conditional operators are used for decision making in C. For example: c=(c>0)?10:-10 If c is greater than 0, value of c will be 10 but, if c is less than 0, value of c will be -10.
  9. 1.4 Your First Program At this stage I am assuming

    you have installed visual studio! We are going to write a simple program that will ask the user for a few details and then display the details. We are coding this program for the sake of testing and also just to ease into what you can do in your "lab". We will create a console application. It is called a console application because the user interface we will use to display questions and take in user input is called a console. It looks like this: Illustration 1. 3 Okay lets create this program! To avoid errors and for you program not to fail you, We shall go with the monkey see monkey do style. Make sure all your code is as written here. On your computer you will have to open visual studio the icon may look like one of these: Illustration 1. 4 I have used Visual Studio 2012 for this tutorial. When visual studio has loaded, you can may go ahead and follow the steps below:
  10. Step 1: We need to get to the project selection

    window. To do this you will: Click on File --> New --> Project Illustration 1. 5
  11. Step 2: We now need to select a project C#

    Console Application template. Click on: Templates --> Visual C# --> Console Application Change the name of your application to: MyFirstApp Click Ok. Illustration 1. 6
  12. Step 3: You have now created your project. Your current

    window should be looking like this: Illustration 1. 7
  13. Step 4: You will now write the code below into

    your project. As you can see, some of the things have already been written for you. This is because every type of project has it's essentials and for a console application the code already added in here is essential, you will understand this better later on. Illustration 1. 8
  14. Step 5: Now let's test it by running the code.

    To Run the code you will have to click on the start button on the toolbar. This is where you can locate the button: Illustration 1. 9 Step 6: You should now see the console application screen, This is the program you have created and should look like this: Illustration 1. 10
  15. Now go ahead and test it! When you are finshed

    entering your details. It should show you a screen like this: Illustration 1. 11 CONGRATS! YOU HAVE CREATED YOUR FIRST PROGRAM!
  16. 1.5 Explanation of Code (My first Program) You can get

    this program from: www.peterphillip.co.za/africalearn/resources/chapter1program.zip Lets look into the code. Line by line to see what is going on. Every program runs from Top to Bottom. Illustration 1. 12 In a program. You can have "comments" the comments appear green. They are used to teach other s about what your code does. You can also use comments as notes on what you are doing or still have to do etc... I have added comments to the code to explain what each line does. In the version that you have/could download will have comments and so will the other programs to come. Have a look at the code and learn what each line does.
  17. /*************************************************************************** * Authour: Peter Phillip * Date: 18 July 2013

    * * Description: * This program gets user input and details and then displays the input. * * ***************************************************************************/ //These are libraries that are used by the applicaion. using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace MyFirstApp { class Program { //When you start the progam, it begins here line by //line all the way to the bottom where there is no more code to run through. static void Main(string[] args) { //DECLARING******************************************************************** //Here you are declaring a variable called name of type string. string name; //Here you are declaring a variable called suranme of type string. string surname; //Here you are declaring a variable called age of type int. int age; //GET USER NPUT***************************************************************** //Here you are telling the console to write a line with the sentence // which says: "Note: Please press enter after you answer a question." Console.WriteLine("Note: Please press enter after you answer a quesiton."); //Here you are starting a new line by using the code "\n" in you string. Console.WriteLine("\n"); //Here you are telling the console to write "Please enter your name: " on //the console. Console.WriteLine("Please enter your name: "); //Here you are getting user input from the user through the console //and assigning it to the variable name. After this line the variable name //will //hold what ever was written by the user e.g "Peter" . name = Console.ReadLine();
  18. //Here you are telling the console to write "Please enter

    your surname: " //on the console. Console.WriteLine("Please enter your surname: "); //Here you are getting user input from the user through the console //and assigning it to the variable surname. After this line the variable //surname will //hold what ever was written by the user e.g "Phillip" surname = Console.ReadLine(); //Here you are telling the console to write "Please enter your surname: " on the console. Console.WriteLine("Please enter your age: "); //Here you are getting the number from the console but converting it to an //int because the //value that is given from the console is a string value. a string value //can not be stored in //an int variable. So basically int value to int and string value to string value is the rule. age = Convert.ToInt32(Console.ReadLine()); //Here you are clearing the console screen, All the questions and answers //showing will //be removed and the screen will be blank. Console.Clear(); //DISPLAY RESULTS FROM USER INPUT //At this point we want to display all the input that was given onto the cleared screen. Console.WriteLine("You entered the following details:"); Console.WriteLine("\n"); //Here you are writing your sentence and filling in the name variable to //show what is inside it. //Therefore if the variable name has the value "peter" // on the screen it will display "Name: Peter" Console.WriteLine("Name: " + name); Console.WriteLine("\n"); //Just like name the surname sentence will be displayed here like //"Surname: Phillip" //that is if the variable surname is holding the value "Phillip" Console.WriteLine("Surname: " + surname); Console.WriteLine("\n"); Console.WriteLine("Age: " + age); Console.WriteLine("\n"); Console.WriteLine("Press Enter to Exit."); Console.ReadLine(); } } } END OF CHAPTER ONE
  19. Chapter Two In the practical of chapter one, We created

    a program that collects data and displays it. In the actual world this means we are only servicing a client then the program closes. Chuck's manager is not happy with this and would like him to make it more useable, what chuck has to do is make sure the program captures more than one person during the course of the day. In order for chuck to do this he will have to work with Lists, Classes and Loops. Let us go through these three; do remember that all things we do in programming are actions and recreation or imitations of objects in the real world. 2. 1 Class My explanation of a class will be very basic, people view this from a different perspectives but at the end we all agree on the same main point and purpose of a class. A class is a representation of an object in the real world - Think of any object... that can be a class. Now hold on to that object you thought about. We used a customer card earlier, that card is an object. Therefore it can be a class and we can call the class "CustomerCard". So when we think of it we see it like this:
  20. Illustration 2.1.1 Classes have properties also known as a members.

    The properties that exist on the card are as follows: So we have a physical card and the card has a space for each of the following fields to be filled in top, pants, total cost, adult and total items. The code below is what creates properties in your customer card class. Declarations of properties: public string Top { get; set; } public string Pants { get; set; } public decimal TotalCost { get; set; } public bool Adult { get; set; } public int TotalItems { get; set; } In this declaration you see "{get; set;}" these are what we will use later when we want to assign something to a property, for example top = "blue jeans"; this is setting using the keyword "set". Then later when we use the top variable, for example Console.Writeline(top); This means we will get the variable stored in top and display it, this is getting using the keyword "get".
  21. So back to your thought! What did you think of?

    can you write out the properties of your object? I thought of a minion. My properties would be skin colour, number of eyes, number of legs etc. So our card class in full would be coded like: class CustomerCard { public string Top { get; set; } public string Pants { get; set; } public decimal TotalCost { get; set; } public bool Adult { get; set; } public int TotalItems { get; set; } } 2.1. 1Methods Classes don't only have properties. They also have other members. One other member I would like to introduce to you is the method member. A method is something that holds functionality that is executable for class. It also uses the properties of the class to give back a certain result. In this case for the customer card we need to write values onto the card. In the physical world we would need to use a pen, gather the right information to write down then write it onto the card. So we are going to do the same! No... we won't write on your screen with a pen. Instead we will create a method that will capture incoming data and write it to our class. So what should our method do? 1. Get information given to it through the parameters. 2. Write the information to the specific class properties. NB: This method is called a constructor, constructor methods are used to initialise a class by giving the properties in the class values this specific one also has the keyword void which means nothing it being returned after the method runs or is called to execute. So in our Customer Class the constructor method would look like this: class CustomerCard { public void customerCard(string top, string pants,Decimal totalCost, Boolean adult, int totalItems) { this.Top = top; this.Pants = pants; this.TotalCost = totalCost; this.Adult = adult; } }
  22. A normal method would be something like this, as you

    can see I have added the keyword decimal which means this method will return a decimal value. What does this method do in the Custormer class? 1. The method receives value through the variable extraAmount. 2. The method checks if the person being serviced is an adult, If it is an adult the the if statement will be true and the amount will be added to the totalCost of this Customer Card. 3. The method then returns the total cost using this line of code: return TotalCost; public decimal CalculateTotalCost(decimal extraAmount) { if (this.Adult == true) { this.TotalCost = TotalCost + extraAmount; } return TotalCost; } Let's put all Four parts together! Here is the customer class. Illustration 2.1.2
  23. 2.2 Loops Okay, What is a loop in programming? A

    loop is what it is. It's a loop. Simply going on and on and on and on like I just did before I decided to stop writing that. We make a process run, then we dictate exactly how many times it should run before stopping or until a certain condition is met then we stop the process. It sure does make you feel like a villain or some dictator right? In the illustration below it shows what a loop is about in programming. Illustration 2.2.1 There are many types of ways to execute a loop, here are a few examples! 2.2.1 For loop The syntax of a for loop in C# is: for ( init; condition; increment ) { statement(s); } Here is the flow of control in a for loop:
  24. 1. The init step is executed first, and only once.

    This step allows you to declare and initialize any loop control variables. You are not required to put a statement here, as long as a semicolon appears. 2. Next, the condition is evaluated. If it is true, the body of the loop is executed. If it is false, the body of the loop does not execute and flow of control jumps to the next statement just after the for loop. 3. After the body of the for loop executes, the flow of control jumps back up to the incrementstatement. This statement allows you to update any loop control variables. This statement can be left blank, as long as a semicolon appears after the condition. 4. The condition is now evaluated again. If it is true, the loop executes and the process repeats itself (body of loop, then increment step, and then again condition). After the condition becomes false, the for loop terminates. 2.2.3 Loop explanations Loop Type Description and code example while loop Repeats a statement or group of statements while a given condition is true. It tests the condition before executing the loop body. Code Example: while (condition) { statement(s); } for loop and foreach Execute a sequence of statements multiple times and abbreviates the code that manages the loop variable. Code Examples: For loop: for (init; condition; increment) { statement(s); } Foreach loop: foreach (var item in collection) { statement(s); } do...while loop Like a while statement, except that it tests the condition at the end of the loop body Code Example: do { statement(s); } while (condition);
  25. nested loops You can use one or more loop inside

    any another while, for or do..while loop. Code Example: for ( init; condition; increment ) { for ( init; condition; increment ) { statement(s); } statement(s); } 2.2.4 Practical Examples on Loops We are not going to create a small console application that will loop and displays a number that has been incremented through each loop. 1. Create a new console app as we did in chapter 1. 2. Name the Console app: smallLoopingConsoleApp 2. Write the code as below and run your program.
  26. 3. This is the result you will get: Lets create

    a tiny virus! There is something called an infinite loop. This is a loop that remains true and continues to run until a program is manually stops, we could perhaps just call it a virus of some sort? Try it out, put the following code in your console application (This code would be lethal if the process happening uses lots of CPU and RAM on a computer, therefore making it slow down or even shutting down your computer from overheating.) class Program { static void Main(string[] args) { for ( ; ; ) { Console.WriteLine("Hey! I am Trapped"); } } }
  27. 2.2 Lists Okay... So we have been dealing with the

    Customer card for a while now. We also know that more than one card is required for use. Therefore we would end up having a stack of cards at the end of the day. So how do we manage these cards in the virtual world? (Your programs). It is pretty simple. We use something called lists. Lists will be able to store all the different cards that are entered. Let's look at this scene. 1. Customer 1 comes in, a card is filled in for them. 2. Customer 2 comes in, a card is filled in for them. Yes, this list is as a normal list. And it holds one type at a time. So a list of customer cards will only have customer cards in it and customer card is a class therefore it is a type. List is a class of its own, It has methods that allow us to do stuff like add to the list, remove from the list, search in the list etc functions that you would be able to do in the real world if you had a pack of customer cards. Here are a few things you can do with a list. In this case your customer card list which we named "ListofCustomerCards" Illustration 2.1
  28. Lets declare the card. List<CustomerCard> listOfCustomerCard = new List<CustomerCard>(); 1.

    Add a customer card to the list. First we need a card so let us declare one. CustomerCard custCard = new CustomerCard(); custCard.Top = "T-shirt"; custCard.Pants = "Black Jeans"; custCard.TotalCost = 750; custCard.Adult = true; custCard.TotalItems = 2; We now have the customer card called "custCard". Now let's add it to the list "listOfCustomersCard" that we declared. listOfCustomerCard.Add(custCard); 2. Making the list empty. listOfCustomerCard.Clear(); 3. Finding out how many items are in the list. (Specifically, how many cards.) listOfCustomerCard.Count();
  29. 2.3 Customer Card Program Now that we know how to

    create a class and we know how to work with loops and we also know how to create lists we may go ahead and create the program chuck's manager requested! We need to capture each client's details then display a list of all clients that were captured, so because we have more than one customer we will need to perform capturing in a loop and saving it into a list. Then we will need to display the list. To display the list we will be required to loop through the list and display each item. You can have a look at this code with comments on the uploaded project. Find the link in the downloads section. We start off by creating a new console app. So like our first project "MyFirstApp" you will create the app by following these steps: Step 1: Click on File -> New -> Project. Step2: Click Visual C# -> Console Application Step3: Name it "CustomerCardApp" Step 4: Click Okay. You will be looking at a window like this:
  30. We now need to add a new class called "CustomerCards"

    to this console application. Step5: On the right you will notice the picture below Right click on "CustomerCardApp" -> Add -> New Item You will now see: Step 6: Select "Class"
  31. Step 7: name it "CustomerCard" then Click Add. You now

    have a customer card class in your console app. Step 8: Write the code below into your class. Code for the CustomerCard.cs Class for customer card: using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace CustomerCardApp { public class CustomerCard { public string Top { get; set; } public string Pants { get; set; } public decimal TotalCost { get; set; } public bool Adult { get; set; } public int TotalItems { get; set; } public void customerCard(string top, string pants, Decimal totalCost, Boolean adult, int totalItems) { this.Top = top; this.Pants = pants; this.TotalCost = totalCost; this.Adult = adult; } public decimal CalculateTotalCost(decimal extraAmount) { if (this.Adult == true) { this.TotalCost = TotalCost + extraAmount; } return TotalCost; } } }
  32. Step 9: Double click the program.cs class to open it.

    You will now see: Step 10: Write the code below and run it. The Program.cs class (main class) This class uses the customer card class. using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace CustomerCardApp { class Program { public static List<CustomerCard> listOfCustomerCard = new List<CustomerCard>(); static void Main(string[] args) { showMainMenu(); }
  33. public static void showMainMenu() { int mainMenuOption; Console.WriteLine("Welcome to Customer

    Card Managing.\n"); Console.WriteLine("Please select a number then press enter.\n"); Console.WriteLine("Menu: \n"); Console.WriteLine("1. Enter new card.\n"); Console.WriteLine("2. View all cards.\n"); Console.WriteLine("3. Exit. \n"); Console.WriteLine("Your option: "); mainMenuOption = Convert.ToInt32(Console.ReadLine()); if(mainMenuOption == 1) { EnterNewCard(); } if(mainMenuOption == 2) { ShowAllCards(); } if(mainMenuOption == 3) { Environment.Exit(0); } } public static void EnterNewCard() { bool flag = true; int menuOption; do { Console.Clear(); CustomerCard newCustomerCard = new CustomerCard(); Console.WriteLine("Create a new card.\n"); Console.WriteLine("\n Please enter the type of top: "); newCustomerCard.Top = Console.ReadLine(); Console.WriteLine("\n Please enter the type of pants: "); newCustomerCard.Pants = Console.ReadLine(); Console.WriteLine("\n Please enter the total cost of items: "); newCustomerCard.TotalCost = Convert.ToDecimal(Console.ReadLine()); Console.WriteLine("\n Is the customer an adult? Yes/No : "); string ans = Console.ReadLine(); if (ans.ToLower() == "yes") { newCustomerCard.Adult = true; } else { newCustomerCard.Adult = false;
  34. } newCustomerCard.CalculateTotalCost(5); Console.WriteLine("\n Please enter the total number of items:

    "); newCustomerCard.TotalItems = Convert.ToInt32(Console.ReadLine()); listOfCustomerCard.Add(newCustomerCard); Console.Clear(); Console.WriteLine("\n Customer information has been Captured.\n"); Console.WriteLine("Select option.\n"); Console.WriteLine("1. Capture another.\n"); Console.WriteLine("2. Go to main menu.\n"); menuOption = Convert.ToInt32(Console.ReadLine()); if (menuOption == 1) { flag = true; } if (menuOption == 2) { flag = false; } } while (flag); Console.Clear(); showMainMenu(); } public static void ShowAllCards() { Console.Clear(); int counter = 1; Console.WriteLine("\n\nPress enter to return to main menu."); Console.WriteLine("\n\n**********************************All Cards**********************************\n\n"); foreach (var card in listOfCustomerCard) { Console.WriteLine("\n**********************************Card "+counter+"**********************************\n\n"); Console.WriteLine("Top: " + card.Top + " \n"); Console.WriteLine("Pants: " + card.Pants + " \n"); Console.WriteLine("Cost of Items: " + card.TotalItems + " \n"); Console.WriteLine("Adult? : " + card.Adult.ToString() + " \n"); Console.WriteLine("Number of items: "+ card.TotalItems+" \n"); counter++;
  35. } Console.WriteLine("\n\nPress enter to return to main menu."); Console.ReadLine(); Console.Clear();

    showMainMenu(); } } } Step 11: Run your code. Using the start button. You should be able to see your main screen: