1 / 37

COP 2360 – C# Programming

COP 2360 – C# Programming. Chapter 3 – Sept 9, 2015. Before Class Starts. Stick in your thumb drive Start-Up VS2012 Create a new Solution/Project named Lecture3. Updated Course Outline. Aug 26 – Introduction – Chapter 1 Sept 2 – Variables & Arithmetic – Chapter 2

wcunniff
Download Presentation

COP 2360 – C# Programming

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. COP 2360 – C# Programming Chapter 3 – Sept 9, 2015

  2. Before Class Starts • Stick in your thumb drive • Start-Up VS2012 • Create a new Solution/Project named Lecture3

  3. Updated Course Outline • Aug 26 – Introduction – Chapter 1 • Sept 2 – Variables & Arithmetic – Chapter 2 • Sept 9 – Methods – Input/Output – Chapter 3 • Sept 16 – Logic – File I/O – Chapters 5 & 13 • Sept 23 – Iteration – Chapter 6 • Sept 30 – Exam 1 • Oct 7 – Arrays – Chapter 7 • Oct 14 – Collections/Classes – Chapters 4 & 8

  4. Course Outline • Oct 21 – Windows Programming – Chapter 9 • Oct 28 – Windows Forms – Chapter 10 • Nov 4 – Exam 2 • Nov 11- Veterans Days • Nov 18 – Exception Handling – Chapter 12 • Nov 25 – Database Access – Chapter 14 • Dec 2 – Web Development – Chapter 15 • Dec 9 – Web Development • Dec 16 – Comprehensive Final Exam

  5. Assignment 1 • A clarification • Tons and pounds and ounces – I want to have the program say something like this: • 1100 kilograms is • 1 Ton(s) • 425 pound(s) and • 1 ounce(s) • To do this, you need to change kilograms to ounces (ounces would be an int), then divide by the number of ounces in a ton to get tons. Then use the remainder (modulus) to get the number of ounces left. Repeat for pounds. • Review the instructions!! • Deadline Changed to September 11 at 11:59 PM

  6. A Word About Pseudo-Code • If you can’t do something by hand or manually, you can’t code that something into a computer. • It is more important to be able to understand a problem and write the procedure for solving it, than it is to write a program that solves it. The program is a dictionary/translation task.

  7. A Quick Review of Chapter 2 • A variable is a location in memory that has been given a “name” for the convenience of a programmer. • Defining a variable in C# is done with a variable declaration: • VariableType VariableName ( = InitialValue); • int myWeight = 165; • double myBMI; • C# has two Variable Types • Value – The location in memory holds the value of the variable. • Reference – The location in memory is a pointer to another memory location which holds the value of the variable. • Why would there need to be a difference?

  8. More Stuff on Value vs. Reference • C# uses two memory data structures to hold variables. • The Stack is used to hold Value variables and the start address and length of Reference variables. • Bottom to Top • Like those trays in the cafeteria • The Heap is used to stored the values of Reference variables. • Like my dirty clothes pile • Stuff is placed in the next available memory location(s) of sufficient size. • If you are interested, see: • http://www.codeproject.com/Articles/76153/Six-important-NET-concepts-Stack-heap-value-types

  9. A Quick Review of Chapter 2 • A Constant is the use of a specific value that will not change in a program • A Named Constant gives a “name” to the constant, again for the convenience of the programmer. • The same rules for definition are used for Named Constants, but they start with the literal “const” • const int INCHESPERFOOT = 12; • const char STOP = ‘Y’;

  10. A Quick Review of Chapter 2 • With assignment statements, the expression on the right side of the equal signs is completely computed, and the result is then stored in the variable on the left hand side. • The equal sign does NOT mean that the two sides are equal. It is telling the compiler to do the computation, take the final value and place it in the variable. • number = number + 1

  11. A Quick Review of Chapter 2 • There are two main “Value” variables that we have used so far • Integral/Decimal/Char – Exact representation of a number or a single character • Float/Double – Approximate representation of a number using an exponent and a mantissa? (What the heck is a mantissa? Is it going to be on the test?) • If Anything on the right side of a assignment statement includes a float, the result will be a float. • Only if ALL of the variables on the right side are integral will the result be integral. • Even with that said, pieces of the expression may be one or the other depending upon variable types • BUT – regardless of what happens on the right side of an assignment statement, the final variable type is dependant on the variable type on the left of the assignment statement: • int stuff = 3.0 * 4.3 * 2.0 / 1.1; will give an error since the left side is whole number and the right is not • C# MAY require you to cast an int to a double/decimal or a double/decimal to an int to show that you understand you may be loosing precision or decimals

  12. A couple of other comments • Remember, numeric and character literal constants (3, ‘G’, “Stuff”, 3.1413) are usually not a good idea. • They hide what is being done • They are hard to understand by others • Whenever possible, use named constants where the name means what the constant is/does

  13. Quick In-Class Assignment • Write a program that computes the average of three exam scores. Each score should be requested and retrieved from the console. The program should then compute the average, then display each score and that average to the console.

  14. Moving on • Tonight we go into more detail with input into and output from the computer. • Console.WriteLine and Console.Write • Console.ReadLine, Console.Read and Console.ReadKey • These methods allow us to get and store character data from/to the console (that big ole black box). • These methods are included in a C# library called System. (What does that mean to any program that uses Console.Write or Console.Read?)

  15. Programming Language Basics • A way to store and retrieve information to and from memory. • A way to compute basic mathematics and store results • A way to communicate with the “outside world” • A way to compare information and take action based on the comparison • A way to iterate a process multiple times • A way to reuse components.

  16. But First…Let’s better understand Methods • A method is a group of code that (may or may not) accept parameters and (may or may not) produce a result • We have been writing a Method static void Main(string[] args)method which • Accepts a parameter named args that is a string array • Returns nothing • Is a Static Method (more on that a little later) • Is the starting place for our programs • Another name for “Method” could be: • Function (what a method is called in C and C++) • SubProgram (what a method with nothing to return is called in VB.Net)

  17. More On Methods • Methods can be programmed within our main program, in another program or class files, or can be stored in libraries • When stored in libraries, to access the Method, that library must be included at the beginning of the program. • What is really happening is the “using” is referencing that library of functions to “show” the compiler the different ways that the method can be called.

  18. The Concept of Methods • Methods are usually blocks of code that are accessed multiple times in a program. • So they allow for code to be reused • They accept parameters so that their results are flexible. • Methods with the same name can have different sets of parameters and can return different types. This feature is called overloading. • Methods are members of Classes. • Methods that return a value can be used as a variable on the right side of an expression (like a constant)

  19. The Concept of Methods • The normal Method format is: • Visibility [static] ReturnType Name (Parameters) Visibility includes public – Anyone can call the method protected – will discuss later internal – Only methods in the same project (namespace) can call the method protected internal – will discuss later private – Only methods in the same class can call the method [static] indicates that this method is a “utility” method and is not dependant on the Class being first initialized to work. More on this when we talk about classes. ReturnType is any of the normal types of variables that we have learned (int, double, string, etc.) or void. void indicates that nothing is returned. If there is a return type other than void, then the Method MUST have a return clause in the code.

  20. More on Methods • Visibility [static] ReturnType Name (Parameters) • The Name is usually a verb that describes what the method does. It is usually in proper case. (This means that normally named constants are all upper case, variables are camel case and methods are proper case) • The Parameters are optional and include the type of variable that will be passed in to the Method.

  21. Let’s Play Around • Add a new Project called Lesson3 and put it in your Lesson3 Solution. • Get the Lesson3.txt from the Web Site, cut and paste it into your Program file. • Follow Along • Let’s Look at the structure of what we did.

  22. Some More words about Methods • Some stuff to note • If you have no parameters, you still need to pass the parenthesis into the function call • There is a chance that two libraries (or that your own code) would have the same function name. If that is the case, the library from which you want the function to be pulled from needs to be identified. • answer = math.pow (4.0, 5.0) If by chance there is more than one pow function. • Let’s look at a quick example of a string function called length. Notice that the length is associated with the “name” of the string. A lot more on this later in the clas, but that string variable is an instance of a class, and all methods associated with that class are available to the variable. • The book goes through the various methods available in the Math library. So, if you need to do some math, check out the methods available and what they do.

  23. Some Rules of Thumb • When writing a program, the second time you code the same thing for whatever reason, you need to determine if the code should be “refactored” to a its own method. • Whenever you are writing a new program and find you are doing the same thing you already did in another program, consider the use of a Utility Class Library that you create to hold the repetitive code.

  24. Let’s review the Write and WriteLine Methods • Simple format for a single variable: • Console.WriteLine (Variable Name) • Also • Console.WriteLine (Format String, Variable List) • The two different formats means that the WriteLine method is Overloaded!! • Write and WriteLine do the same thing • The only difference is that the WriteLine method includes a CRLF (Carriage Return/Line Feed) at the end of the variables. • The Format String is any text (or other string variables) you want to print out along with format codes • {#,W:F} • # = variable number, W = width (optional) F = Format

  25. Format String Syntax • The Format String is the first parameter to the Write/WriteLine Method • It is a single string. Each set of curly brackets represents the format of one variable (left most variable is {0}, then {1}, etc.) • The string can also have regular text embedded within in for context (similar to the C fprint command • const int INCHES_PER_FOOT = 12; • int nFeet = 3; • int nInches = nFeet * INCHES_PER_FOOT; • Console.WriteLine ("{0} Feet = {1} Inches",nFeet,nInches);

  26. Console Write Statement Examples

  27. Formatting Output

  28. Formatting Output (continued)

  29. Formatting Output (continued) • FYI. I never remember all of these codes. So, they won’t be on the test, but the concept will be!! • There is also the ability to make up your own. • There is also a “width” indicate that goes after the variable number • Console.WriteLine(“{0,5:F0}{1,-8:C}”,9,14 • The 9 will be right justified and five characters long, the 14 will be left justified, 8 characters long with dollar sign.

  30. Escape Sequences • There are certain “things” that we need to send to the console that “can’t” be directly entered into a string. To “fix” this • \n = newline • \t = tab • \b = backspace • \r = return (no line feed) • \\ = just the backslash • \’ = print a single quote (otherwise thinks it is a char) • \" = print a double quote (otherwise thinks it is a string) • These are active on string assignment statements unless the literal is preceded by an @: • String sString1 = “This \t is \t a \t String”; • String sString2 = @” This \t is \t a \t String”;

  31. Using WriteLine to Debug a Program • Although you can do a better job with Visual Studio, before there was a VS, we used to use output commands to help debug a program • We stuck in a bunch or output commands with intermediary variable values so we could see what was going on. • Sometimes we stuck stuff like • Console.WriteLine(“We Are Here – Line 11”); If we were trying to track our what through a program • Most of that type of debugging can now just be done with the breakpoint and the command window in VS, but sometimes it still comes in handy.

  32. WriteLine Format String • Is really a string • Which means you can programmatically create it • Probably not all that useful now, but when we get into arrays and other structures, it makes the format ability a lot more versatile. • Let’s Look at these format abilities in action • Add another Project to your Lecture3 Solution called Lesson3a and add the code from the Lesson3a.txt file from our web page. • Make it the start up project!!

  33. There are Three Methods in System.Console for Reading • Console.Read() – Returns an integer with the Unicode value of the next character entered on the keyboard • Console.ReadKey() – Returns a char with the next character entered • Console.ReadLine() – Returns whatever a user enters up to a CR/LF into a String • None of these Methods are Overloaded.

  34. Once you get it in to ReadLineParse It • Predefined static method (Utility. Doesn’t rely on any other information from the class!) • All numeric types have a Parse( ) method • double.Parse("string number") • int.Parse("string number") • bool.Parse("string number") • Expects string argument • Argument must be a number inside a string • Returns the number (or bool) • Will discuss what happens if the input format is bad a little more down the line. • Right now it goes kaboom!!

  35. In-Class Assignment 2 • Modify your Average Grade Score program so that the Average is computed using a method instead of directly within the main routine. • The method should accept three parameters with the grade for each test. • The method should return a decimal number.

  36. Attendance for Today • Open a Microsoft Word Document. (You can use any other word processer as long as the output is in Word DOC or DOCx format.) • Put your Full Name, and the text “Lecture 3 code” at the top of each page. • Copy and Paste your Average Grade Program that includes your newly created Method to the Word Document. • Mail this to me at bradleyl@palmbeachstate.edu

  37. Lab Time • Time to work on your Assignment 1 (or to play around and ask questions)

More Related