Presentation is loading. Please wait.

Presentation is loading. Please wait.

Jozef Goetz, 2012 1  2009 Pearson Education, Inc. All rights reserved.  2002 Prentice Hall. All rights reserved. expanded by J. Goetz, 2012.

Similar presentations


Presentation on theme: "Jozef Goetz, 2012 1  2009 Pearson Education, Inc. All rights reserved.  2002 Prentice Hall. All rights reserved. expanded by J. Goetz, 2012."— Presentation transcript:

1

2 Jozef Goetz, 2012 1  2009 Pearson Education, Inc. All rights reserved.  2002 Prentice Hall. All rights reserved. expanded by J. Goetz, 2012

3 Jozef Goetz, 2012 2  When faced with a decision, I always ask, “What would be the most fun?” Peggy Walker  What’s in a name? That which we call a rose by any other name would smell as sweet. William Shakespeare “ Take some more tea,” the March Hare said to Alice, very earnestly. “I’ve had nothing yet.” Alice replied in an offended tone, “So I can’t take more.” “You mean you can’t take less,” said the Hatter, “it’s very easy to take more than nothing.” Lewis Carroll

4 Jozef Goetz, 2012 3 OBJECTIVES In this chapter you will learn:  To write simple C# applications using code rather than visual programming.  To write statements that input and output data to the screen.  To declare and use data of various types.  To store and retrieve data from memory.  To use arithmetic operators. To determine the order in which operators are applied.  To write decision-making statements.  To use relational and equality operators.  To use message dialogs to display messages.

5 Jozef Goetz, 2012 4 Chapter 3 – Introduction to C# Programming Outline 3.1 Introduction 3.2 A Simple C# Application: Displaying a Line of Text 3.3 Creating Your Simple Application in Visual C# Express 3.4 Modifying Your Simple C# Application 3.5 Formatting Text with Console.Write and Console.Writeline 3.6 Another C# Application: Adding Integers 3.7 Memory Concepts 3.8 Arithmetic 3.9 Decision Making: Equality and Relational Operators

6 Jozef Goetz, 2012 5 3.1 Introduction  Console applications No visual components Only text output Text output in a console application is displayed in a console window.  Two types of console window – Command Line Interfaces (CLI) –MS-DOS prompt called in Windows 95/98/ME –Command prompt called in windows 2000/NT/XP/Vista/Windows 7  Windows applications  Forms with several output types (windows, dialogs, and so forth)  Contain Graphical User Interfaces (GUIs)

7 Jozef Goetz, 2012 6 3.2 Simple Program: Printing a line of text  Comments Comments can be created using //… Multi-lines comments use /* … */ /* This is a multiple line comment. It can be split over many lines */ Comments are ignored by the compiler Used only for human readers  Namespaces Groups related fundamental classes and base classes into categories Allows the easy reuse of code Many namespaces are found in the Framework Class Library (FCL) Must be referenced in order to be used  White Space Includes spaces, newline characters and tabs

8  2002 Prentice Hall. All rights reserved. Outline 7 Welcome1.cs Program Output 1 // Fig. 3.1: Welcome1.cs 2 // A first program in C#. 3 4 using System; 5 6 class Welcome1 7 { 8 static void Main( string[] args ) 9 { 10 Console.WriteLine( "Welcome to C# Programming!" ); 11 } 12 } Welcome to C# Programming! This is the using directive. It lets the compiler know that it should include the System namespace. This is the start of the Main method. In this case it instructs the program to do everything

9  2002 Prentice Hall. All rights reserved. Outline 8 Welcome1.cs Program Output 1 // Fig. 3.1: Welcome1.cs 2 // A first program in C#. 3 4 using System; 5 6 public class Welcome1 7 { 8 static void Main( string[] args ) 9 { 10 Console.WriteLine( "Welcome to C# Programming!" ); 11 } 12 } Welcome to C# Programming! Line 1, 2: These are two single line comments. They are ignored by the compiler and are only used to aid other programmers. They use the double slash (//) This is the using directive. It lets the compiler know that it should include the System namespace. Line3: This is a blank line. It means nothing to the compiler and is only used to add clarity to the program. Line 6: This is the beginning of the Welcome1 class definition. It starts with the class keyword and then the name of the class followed by class bodies This is the start of the Main method. In this case it instructs the program to do everything This is a string of characters that Console.WriteLine instructs the compiler to output

10 Jozef Goetz, 2012 9 3.2 Simple Program: Printing a Line of Text Fig. 3.3Execution of the Welcome1 program.

11 Jozef Goetz, 2012 10 3.2 Simple Program: Printing a line of text  C# identifier Series of characters consisting of letters, digits and underscores ( _ ) Does not begin with a digit, has no spaces Examples: Welcome1, identifier, _value, button7  7button is invalid C# is case sensitive (capitalization matters)  a1 and A1 are different  Blank line Makes program more readable Blank lines, spaces, and tabs are white-space characters Ignored by compiler 6 class Welcome1

12 Jozef Goetz, 2012 11 3.2 Simple Program: Printing a line of text  Keywords words reserved for use by C# e.g. public class Words that cannot be used as variable or class names or any other capacity Have a specific unchangeable function within the language –Example: class All keywords are lowercase  Classes Every C# program has at least one user-defined class Class names can only be one word long (i.e. no white space in class name ) Class names are capitalized, capitalize every word –SampleClassName Each class name is an identifier 6 class Welcome1

13 Jozef Goetz, 2012 12 3.2 Simple Program: Printing a line of text Class bodies start with a left brace ({)  class Welcome1 { Class bodies end with a right brace (})  Methods Building blocks of programs –C# applications contain one or more methods Methods can perform tasks and return information  void means Main returns no information The Main method  Each console or windows application must have exactly one  All programs start by executing the Main method (in Java main() ) – only a lower case difference) –static void Main( string[] args ) Braces are used to start ({) and end (}) a method body

14 Jozef Goetz, 2012 13 3.2 Simple Program: Printing a line of text  Statements Instructs computer to perform an action Anything in quotes (“) is considered a string including white spaces Every statement must end in a semicolon (;)  Prints string of characters –String: series characters inside double quotes  White-spaces in strings are not ignored by compiler Method Console.WriteLine  Standard output  Print to command window (i.e., MS-DOS prompt)  Displays line of text 10 Console.WriteLine( "Welcome to C# Programming!" );

15 Jozef Goetz, 2012 14 3.2 Simple Program: Printing a line of text  Graphical User Interface GUIs are used to make it easier to get data from the user as well as display data to the user Message boxes  Within the System.Windows.Forms namespace  Used to prompt or display information to the user

16 Jozef Goetz, 2012 15 Common Programming Error 3.1  Forgetting one of the delimiters of a delimited comment is a syntax error.  The syntax of a programming language specifies the rules for creating a proper application in that language.  A syntax error occurs when the compiler encounters code that violates C#’s language rules. In this case, the compiler does not produce an executable file. Instead, the compiler issues one or more error messages to help you identify and fix the incorrect code.  Syntax errors are also called compiler errors, compile-time errors or compilation errors, because the compiler detects them during the compilation phase. You will be unable to execute your application until you correct all the syntax errors in it.

17 Jozef Goetz, 2012 16 Common Programming Error 3.2  Keyword: using  A using directive tells the compiler where to look for a predefined class that is used in an application.  Predefined classes are organized under namespaces—named collections of related classes. Collectively,.NET’s namespaces are referred to as the.NET Framework Class Library.  The System namespace contains the predefined Console class and many other useful classes.  All using directives must appear before any other code (except comments) in a C# source code file; otherwise a compilation error occurs.

18 Jozef Goetz, 2012 17 Error-Prevention Tip 3.1  Forgetting to include a using directive for a class used in your application typically results in a compilation error containing a message such as " The name ' Console ' does not exist in the current context."  When this occurs, check that you provided the proper using directives and that the names in the using directives are spelled correctly, including proper use of uppercase and lowercase letters.

19 Jozef Goetz, 2012 18 Fig. 3.2 | C# keywords.

20 Jozef Goetz, 2012 19 Good Programming Practice 3.1  By convention, always begin a class name’s identifier with a capital letter and start each subsequent word in the identifier with a capital letter.  public class MyClass { … }

21 Jozef Goetz, 2012 20 Common Programming Error 3.2  C# is case sensitive. Not using the proper uppercase and lowercase letters for an identifier normally causes a compilation error. Identifiers may also be preceded by the @ character. This indicates that a word should be interpreted as an identifier, even if it is a keyword (e.g. @int ).  By convention, a file that contains a single public class should have a name that is identical to the class name (plus the.cs extension) Naming your files in this way makes it easier for other programmers (and you) to determine where the classes of an application are located. Good Programming Practice 3.2

22 Jozef Goetz, 2012 21 Good Programming Practice 3.5  We recommend using 3 spaces to form each level of indentation.  As with class declarations, indent the entire body of each method declaration one “level” of indentation between the left and right braces that define the method body. This format makes the structure of the method stand out and makes the method declaration easier to read. You can let the IDE format your code by selecting Edit > Advanced > Format Document

23 Jozef Goetz, 2012 22 Common Programming Error  Omitting the semicolon at the end of a statement is a syntax error.  Exc.1: Try removing a semicolon or brace from the code of Fig. 3.1, then recompiling the application to see the error messages generated by the omission.

24 Jozef Goetz, 2012 23 Error-Prevention Tip  When the compiler reports a syntax error, the error may not be in the line indicated by the error message.  First, check the line for which the error was reported.   If that line does not contain syntax errors, check several preceding lines.

25 Jozef Goetz, 2012 24 Good Programming Practice  Following the closing right brace of a method body or class declaration with a comment indicating the method or class declaration to which the brace belongs improves application readability. } // end method Main

26 Jozef Goetz, 2012 25 3.2 A Simple C# Application: Displaying a Line of Text (Cont.). Error-Prevention Tip 3.2 Whenever you  type an opening left brace, {, in your application,  immediately type the closing right brace, },  then reposition the cursor between the braces and  indent to begin typing the body.  This practice helps prevent errors due to missing braces.

27 Jozef Goetz, 2012 26 3.2 A Simple C# Application: Displaying a Line of Text (Cont.)  Parentheses after an identifier indicate that it is an application building block called a method. Class declarations normally contain one or more methods.  Console.WriteLine( "Welcome to C# Programming!" )  Method names usually follow the same casing capitalization conventions used for class names.  For each application, one of the methods in a class must be called Main ; otherwise, the application will not execute.  Methods are able to perform tasks and return information when they complete their tasks. Keyword void indicates that this method will not return any information after it completes its task.

28 Jozef Goetz, 2012 27 3.3 Creating Your Simple Application in Visual C# Express 1.Creating the Console Application Select File > New Project … to display the New Project dialog (Fig. 3.3). Select the Console Application template. In the dialog’s Name field, type Welcome1, and click OK to create the project. 2.Modifying the Editor Settings Visual C# Express provides many ways to personalize your coding experience (Fig. 3.5) e.g. tab setup: Tools->Options->Text Editor -> Tabs 3.Changing the Name of the Application File Change the File Name property to Welcome1.cs. (Fig. 3.6)

29 Jozef Goetz, 2012 28 Fig. 3.3 | Creating a Console Application with the New Project dialog.

30 Jozef Goetz, 2012 29 3.3 Creating a Simple Application in Visual C# Express (Cont.)  The IDE now contains the open console application.  The code coloring scheme used by the IDE is called syntax-color shading and helps you visually differentiate application elements.

31 Jozef Goetz, 2012 30 3.3 Creating a Simple Application in Visual C# Express (Cont.) Fig. 3.4 | IDE with an open console application. Editor window

32 Jozef Goetz, 2012 31 Fig. 3.5 | Modifying the IDE settings. tab setup: Tools->Options->Text Editor -> Tabs

33 Jozef Goetz, 2012 32 Fig. 3.5 | Modifying the IDE settings.  To have the IDE display line numbers, select Tools > Options…. In the dialog that appears (Fig. 3.5), click the Show all settings checkbox on the lower left of the dialog. Expand the Text Editor node in the left pane and select All Languages. On the right, check the Line numbers checkbox.

34 Jozef Goetz, 2012 33 Solution Explorer Properties window File Name Property Click Program.cs to display its properties Type Welcome1.cs here to rename the file Fig. 3.6 | Renaming the program file in the Properties window. 1.Changing the Name of the Application File Change the File Name property to Welcome1.cs.

35 Jozef Goetz, 2012 34 3.3 Creating Your Simple Application in Visual C# Express (Cont.) 4.Writing Code IntelliSense: Lists a class’s members after a dot (Fig. 3.7-3.8) 5.Saving the Application Specify the directory where you want to save this project (Fig. 3.9) 6.Compiling and Running the Application Compiler compiles code into files (Fig. 3.10)  Ex:.exe (executable),.dll (dynamic link library), and more! 7.Running the Application from the Command Prompt Alternate way to go run a program without using the IDE (Fig. 3.11-3.12)

36 Jozef Goetz, 2012 35 Partially-typed member Member list Highlighted member Tool tip describes highlighted member Fig. 3.7 | IntelliSense feature of Visual C# Express.

37 Jozef Goetz, 2012 36 3.3 Creating a Simple Application in Visual C# Express (Cont.)  IntelliSense lists a class’s members, which include method names.  As you type characters, Visual C# Express highlights the first member that matches all the characters typed, then displays a tool tip containing a description of that member.  You can either type the complete member name, double click the member name in the member list or press the Tab key to complete the name.  While the IntelliSense window is displayed pressing the Ctrl key makes the window transparent so you can see the code behind the window.

38 Jozef Goetz, 2012 37 3.3 Creating a Simple Application in Visual C# Express (Cont.)  When you type the open parenthesis character, (, after a method name, the Parameter Info window is displayed (Fig. 3.8).  This window contains information about the method’s parameters. Down arrow Parameter Info window Up arrow Fig. 3.8 | Parameter Info window. Up and down arrows allow you to scroll through overloaded versions of the method.

39 Jozef Goetz, 2012 38 3.3 Creating a Simple Application in Visual C# Express (Cont.)  To save an application, select File > Save All to display the Save Project dialog (Fig. 3.9).  In the Location textbox, specify the directory where you want to save this project.  Select the Create directory for solution checkbox and click Save. Fig. 3.9 | Save Project dialog.

40 Jozef Goetz, 2012 39 Console window Fig. 3.10 | Executing the application shown in Fig. 3.11  To compile an application, select Build > Build Solution.  To execute it, select Debug > Start Without Debugging (or type Ctrl + F5 ). This invokes the Main method.

41 Jozef Goetz, 2012 40 3.3 Creating a Simple Application in Visual C# Express (Cont.) Running (outside the IDE) the Application from the Command Prompt  To open the Command Prompt, select Start > All Programs > Accessories > Command Prompt. Fig. 3.11 | Command Prompt window when it is initially opened. Default prompt displays when Command Prompt is opened User enters the next command here

42 Jozef Goetz, 2012 41 3.3 Creating a Simple Application in Visual C# Express (Cont.)  To Enter the command cd (which stands for “change directory”), followed by the directory where the application’s.exe file is located  Run the compiled application by entering the name of the.exe file. Fig. 3.12 | Executing the application shown in Fig. 3.1 from a Command Prompt window. Updated prompt showing the new current directory Type this to change to the application’s directory Application’s output Closes the Command Prompt Type this to run the Welcome1.exe application

43 Jozef Goetz, 2012 42 3.3 Creating Your Simple Application in Visual C# Express (Cont.)  Syntax Errors, Error Messages and the Error List Window Syntax Error  A violation of Visual C# rules for creating correct application Error List Window (Fig. 3.13)  Window where the descriptions of the errors are located Note: Red underline indicts a syntax error

44 Jozef Goetz, 2012 43 Intentionally omitted parenthesis character (syntax error) Red underline indicates a syntax errorError List window Error description(s) Fig. 3.13 | Syntax errors indicated by the IDE.

45 Jozef Goetz, 2012 44 Error-Prevention Tip 3.5 Exc2: Remove the 1 st parenthesis in line 10. What happens?  The compiler thinks there are 2 statements.  One syntax error can lead to multiple entries in the Error List window.  Each error that you address could eliminate several subsequent error messages when you recompile your application.  So when you see an error you know how to fix, correct it and recompile — this may make several other errors disappear.

46 Jozef Goetz, 2012 45 Class Welcome2, shown in Fig. 3.14, uses two statements to produce the same output as that shown in the previous example. Unlike WriteLine, the Console class’s Write method does not position the screen cursor at the beginning of the next line in the console window. 3.4 Modifying Your Simple C# Application

47 Jozef Goetz, 2012 46 Outline  Welcome2. cs Cursor stays on same line after outputting Cursor moves to next line after outputting Console.WriteLine will pick up where the line ends. This will cause the output to be on one line even though it is on two in the code.

48 Jozef Goetz, 2012 47 3.4 Modifying Your Simple C# Application (Cont.)  Escape characters Backslash ( \ ) Indicates special characters be output  Newline characters ( \n ) Interpreted as “special characters” by methods Console.Write and Console.WriteLine Indicates cursor should be at the beginning of the next line Welcome3.cs (Fig. 3.15) Line breaks at \n 10 Console.WriteLine( “ Welcome\nto\nC#\nProgramming!" );

49 Jozef Goetz, 2012 48  Welcome3. cs Notice how a new line is output for each \n escape sequence. The \n escape sequence is used to put output on the next line. This causes the output to be on several lines even though it is only on one in the code.

50 Jozef Goetz, 2012 49 3.2 Simple Program: Printing a Line of Text

51 Jozef Goetz, 2012 50 Outline  Welcome4.cs Formatting Text  Place a space after each comma (,) in an argument list to make applications more readable.  Splitting a statement in the middle of an identifier or a string is a syntax error. Method WriteLine ’s first argument is a format string that may consist of fixed text and format items.

52 Jozef Goetz, 2012 51 3.5 Formatting Text with Console.Write and Console.WriteLine  Formatted Data Arguments are separated with commas WriteLine’s first argument is format string  Format items: Placeholder for a value – {0} is a placeholder for the first additional argument. – {1} is a placeholder for the second, and so on. Fixed text: Regular text that is outputted 10 Console.WriteLine( “ {0}\n{1} ”, “ Welcome to ”, “ C# Programming ” );

53  2002 Prentice Hall. All rights reserved. Outline 52 Welcome4.cs Program Output 1 // Fig. : Welcome5.cs ed1. 2 // Printing multiple lines in a dialog Box. 3 4 using System; 5 using System.Windows.Forms; 6 7 class Welcome4 8 { 9 static void Main( string[] args ) 10 { 11 MessageBox.Show( "Welcome\nto\nC#\nprogramming!" ); // static method of class MessageBox // static methods called using class name, dot (.) then method name 12 } 13 } The System.Windows.Forms namespace allows the programmer to use the MessageBox class. This will display the contents in a message box as opposed to in the console window. Create the GUI output

54 Jozef Goetz, 2012 53 Simple Program: Printing a Line of Text Fig. Dialog displayed by calling MessageBox.Show. OK button allows the user to dismiss the dialog. Dialog is automatically sized to accommodate its contents. Mouse cursor Close box

55 Jozef Goetz, 2012 54  Namespaces Groups related C# fundamental classes and base classes into a categories  The assembly is package containing the Microsoft intermediate Language (MSIL) code that a project has been compiled into, plus other info that is needed for these classes Assemblies can be comprised of many files of several different types  MessageBox is located in assembly System.Windows.Forms.dll  Developer for the appl. needs to include: namespaces with the using directive (package in Java) and references  click the References folder in the solution Explorer and select Add References and select component from the dialog box by double clicking, then click OK –VS adds a few common references when a project is created Class Console is located in mscorlib.dll Class MessageBox is located System.Windows.Forms.dll  (see C:\WINDOWS\Microsoft.Net\Framework\v4.0.30319 for above.dlls or select another version number) but a reference to mscorlib.dll assembly is not required to use it

56 Jozef Goetz, 2012 55 3.5 Simple Program: Printing a Line of Text References folder Solution Explorer System.Windows.Forms reference Fig. Adding a reference to an assembly in Visual Studio.NET (part 2).

57 Jozef Goetz, 2012 56 3.5 Simple Program: Printing a Line of Text Fig. Adding a reference to an assembly in Visual Studio.NET (part 1). Add Reference dialogue

58 Jozef Goetz, 2012 57 3.6 Another Simple Program: Adding Integers  Primitive data types Data types that are built into C#  String, Int, Double, Char, Long  15 primitive data types (chapter 4) Each data type name is a C# keyword Same type variables can be declared on separate lines or on one line  Console.ReadLine() Used to get a value from the user input  Int32.Parse() or Convert.ToInt32() Used to convert a string argument to an integer Allows math to be preformed once the string is converted

59 Jozef Goetz, 2012 58 Convention  Begin with a lowercase letter and capitalize each successive English letter for identifiers representing variables. middleInitial, myName.  This naming convention is known as camel casing.

60 Jozef Goetz, 2012 59 Outline  Addition.c s using declaration imports necessary components from the System namespace. Declare variables number1, number2 and sum. Convert user’s input into an int, and assign it to number1. Convert user’s next input into an int, and assign it to number2. Calculate the sum of the variables number1 and number2, assign result to sum. Display the sum using formatted output.

61 Jozef Goetz, 2012 60 3.6 Another C# Application: Adding Integers Begins public class Addition  Recall that file name must be Addition.cs Lines 8-9: begins Main Variables  Location in memory that stores a value –Declare with name and type before use  Variable name: any valid identifier Declarations end with semicolons ; Initialize variable in its declaration  Equal sign 5 public class Addition 6 { 8 public static void Main( string[] args) 9 {

62 Jozef Goetz, 2012 61 3.6 Another C# Application: Adding Integers (Cont.) Declare variable number1, number2 and sum of type int  int holds integer values (whole numbers): i.e., 0, -4, 97  Types float, double and decimal can hold decimal numbers  Type char can hold a single character: i.e., x, $, \n, 7  int, float, double, decimal and char are simple types Can add comments to describe purpose of variables Can declare multiple variables of the same type in one declaration  Use comma-separated list 10 int number1; // first number to add 11 int number2; // second number to add 12 int sum; // second number to add int number1, // first number to add number2, // second number to add sum; // second number to add

63 Jozef Goetz, 2012 62 Good Programming Practice 3.8  Choosing meaningful variable names helps code to be self-documenting i.e., one can understand the code simply by reading it rather than by reading documentation manuals or viewing an excessive number of comments.

64 Jozef Goetz, 2012 63 3.6 Another C# Application: Adding Integers (Cont.) Similar to previous statement  Prompts the user to input the second integer Similar to previous statement  Assign variable number2 to second integer input Assignment statement  Calculates sum of number1 and number2 (right hand side)  Uses assignment operator = to assign result to variable sum  Read as: sum gets the value of number1 + number2  number1 and number2 are operands 18 Console.Write( "Enter second integer: " ); // prompt user 20 number2 = Convert.ToInt32( (Console.ReadLine() ); 22 sum = number1 + number2; // add numbers

65 Jozef Goetz, 2012 64 3.6 Another C# Application: Adding Integers (Cont.) Use Console.WriteLine to display results {0} is placeholder for sum Calculations can also be performed inside WriteLine Parentheses around the expression number1 + number2 are not required 24 Console.WriteLine( "Sum is {0}: ", sum ); // display sum Console.WriteLine( "Sum is {0} ", ( number1 + number2 ) );

66  2002 Prentice Hall. All rights reserved. Outline 65 Addition.cs 1 // Fig. 3.11: ed2. Addition.cs. Well commented program with comment indented. 2 // An addition program. 3 4 using System; 5 6 class Addition 7 { 8 static void Main( string[] args ) 9 { // the sinle-line comments to indicate the purpose of each variable 10 string firstNumber, // first string entered by user 11 secondNumber; // second string entered by user 12 13 int number1, // first number to add 14 number2, // second number to add 15 sum; // sum of number1 and number2 16 17 // prompt for and read first number from user as string 18 Console.Write( "Please enter the first integer: " ); 19 firstNumber = Console.ReadLine(); 20 21 // read second number from user as string 22 Console.Write( "\nPlease enter the second integer: " ); 23 secondNumber = Console.ReadLine(); // an assignment statement 24 // = a binary operator 25 // convert numbers from type string to type int 26 number1 = Int32.Parse( firstNumber ); // or use Convert.ToInt32() 27 number2 = Int32.Parse( secondNumber ); 28 29 // add numbers 30 sum = number1 + number2; // Read as: sum gets the value of number1 + number2 31 This is the start of class AdditionTwo string variables defined over two lines The comment after the declaration is used to briefly state the variable purpose These are three int s that are declared over several lines and only use one semicolon. Each is separated by a coma. Console.ReadLine is used to take the users input and place it into a variable. This line is considered a prompt because it asks the user to input data. Int32.Parse() or Convert.ToInt32() is used to convert the given string into an integer. It is then stored in a variable. // Place spaces on either side of a binary operator to make it stand out and make the code more readable – see line 30

67  2002 Prentice Hall. All rights reserved. Outline 66 Addition.cs Program Output 32 // display results 33 Console.WriteLine( "\nThe sum is {0}.", sum ); 34 35 } // end method Main 36 37 } // end class Addition Please enter the first integer: 45 Please enter the second integer: 72 The sum is 117. Putting a variable out through Console.WriteLine is done by placing the variable after the text while using a placeholder { a number in curly braces} to show where the variable should be placed. Declare each variable on a separate line. This format allows a comment to be easily inserted next to each declaration. See line 13-15

68 Jozef Goetz, 2012 67 3.7 Memory Concepts  Memory locations  Variables Every variable has 1.a name, 2.a type, 3.a size and 4.a value Name corresponds to location in memory When new value is placed into a variable, replaces (and destroys) previous value Reading variables from memory does not change them

69 Jozef Goetz, 2012 68 3.7 Memory Concepts Fig. 3.19Memory location showing name and value of variable number1. 45 is replaced the previous value; previous value is destroyed number145

70 Jozef Goetz, 2012 69 3.7 Memory Concepts Fig. 3.20Memory locations number1 and number2 after values for variables number1 and number2 have been input. number145 number272

71 Jozef Goetz, 2012 70 3.7 Memory Concepts Fig. 3.21Memory locations after a calculation. When a sum is read from a memory, the process is nondestructive. number145 number272 sum117

72 Jozef Goetz, 2012 71 3.8 Arithmetic  Arithmetic operations Not all operations use the same symbol  Asterisk (*) is multiplication  Slash (/) is division  Percent sign (%) is the modulus operator: 7 % 5 evaluates to 2  Plus (+) and minus (-) are the same Must be written in a straight line There are no exponents  Division Division can vary depending on the variables used  When dividing two integers the result is always rounded down to an integer 7 / 5 evaluates to 1 Tip: To be more exact use a variable that supports decimals

73 Jozef Goetz, 2012 72 3.8 Arithmetic  Order (Operator precedence): 1.Parenthesis are done first 2.Division, multiplication and modulus are done second  Left to right 3.Addition and subtraction are done last  Left to right  Use parenthesis when needed or for clarity Example: Find the average of three variables a, b and c  Do not use: a + b + c / 3  Use: ( a + b + c ) / 3

74 Jozef Goetz, 2012 73 3.8 Arithmetic x y

75 Jozef Goetz, 2012 74 3.8 Arithmetic

76 Jozef Goetz, 2012 75 3.8 Arithmetic Fig. 3.24Order in which a second-degree polynomial is evaluated. Exc: Show the order for z = p*r % w/x - y Step 1. Step 2. Step 5. Step 3. Step 4. Step 6. y = 2 * 5 * 5 + 3 * 5 + 7; 2 * 5 is 10 (Leftmost multiplication) y = 10 * 5 + 3 * 5 + 7; 10 * 5 is 50 (Leftmost multiplication) y = 50 + 3 * 5 + 7; 3 * 5 is 15 (Multiplication before addition) y = 50 + 15 + 7; 50 + 15 is 65 (Leftmost addition) y = 65 + 7; 65 + 7 is 72 (Last addition) y = 72; (Last operation—place 72 into y )

77 Jozef Goetz, 2012 76 3.9 Decision Making: Equality and Relational Operators  The if structure Used to make a decision based on the truth of the condition  True: a statement is performed  False: the statement is skipped over

78 Jozef Goetz, 2012 77 3.9 Decision Making: Equality and Relational Operators  if control structure Simple version in this section, more detail later If a condition is true, then the body of the if statement executed  0 interpreted as false, non-zero is true Control always resumes after the if structure Conditions for if structures can be formed using equality or relational operators (next slide) ************************************************** if ( condition ) statement //executed if condition true *****************************************  No semicolon needed after condition –Else conditional task not performed

79 Jozef Goetz, 2012 78 3.9 Decision Making: Equality and Relational Operators

80 Jozef Goetz, 2012 79 3.9 Decision Making: Equality and Relational Operators if structure to test for equality using ( == )  If variables equal (condition true) –number1 concatenated using + operator if ( number1 == number2 ) Console.WriteLine( number1 + " == " + number2 ); string = number1 + other strings –Right side evaluated first, new string assigned to string

81  2002 Prentice Hall. All rights reserved. Outline 80 Comparison.cs 1 // Fig. 3.26: Comparison.cs ed1. 2 // Using if statements, relational operators and equality 3 // operators. 4 5 using System; 6 7 class Comparison 8 { 9 static void Main( string[] args ) 10 { // multiple declaration for same type 11 int number1, // first number to compare 12 number2; // second number to compare 13 14 // read in first number from user 15 Console.Write( "Please enter first integer: " ); 16 number1 = Int32.Parse( Console.ReadLine() ); 17 // or number1 = Convert.ToInt32( Console.ReadLine() ); 18 // read in second number from user 19 Console.Write( "\nPlease enter second integer: " ); 20 number2 = Int32.Parse( Console.ReadLine() ); 21 22 if ( number1 == number2 ) 23 Console.WriteLine( number1 + " == " + number2 ); 24 //or Console.WriteLine( "{0} == {1}", number1, number2 ); 25 if ( number1 != number2 ) 26 Console.WriteLine( number1 + " != " + number2 ); 27 28 if ( number1 < number2 ) 29 Console.WriteLine( number1 + " < " + number2 ); 30 31 if ( number1 > number2 ) 32 Console.WriteLine( number1 + " > " + number2 ); 33 Combining these two methods eliminates the need for a temporary string variable. Please enter first integer: 2000 Please enter second integer: 1000 2000 != 1000 2000 > 1000 2000 >= 1000

82  2002 Prentice Hall. All rights reserved. Outline 81 Comparison.cs Program Output 34 if ( number1 <= number2 ) 35 Console.WriteLine( number1 + " <= " + number2 ); 36 37 if ( number1 >= number2 ) 38 Console.WriteLine( number1 + " >= " + number2 ); 39 40 } // end method Main 41 42 } // end class Comparison Please enter first integer: 2000 Please enter second integer: 1000 2000 != 1000 2000 > 1000 2000 >= 1000 Please enter first integer: 1000 Please enter second integer: 2000 1000 != 2000 1000 < 2000 1000 <= 2000 Please enter first integer: 1000 Please enter second integer: 1000 1000 == 1000 1000 <= 1000 1000 >= 1000 If number1 is less than or equal to number2 then this code will be used Lastly if number1 is greater than or equal to number2 then this code will be executed

83 Jozef Goetz, 2012 82 Common Programming Error 3.6  Omitting the left and/or right parentheses for the condition in an if statement is a syntax error — the parentheses are required. if ( number1 > number2 ) Console.WriteLine( number1 + " > " + number2 );

84 Jozef Goetz, 2012 83 Common Programming Error  Confusing the equality operator, ==, with the assignment operator, =, can cause a logic error or a syntax error.  The equality operator should be read as “is equal to,” and the assignment operator should be read as “gets” or “gets the value of.”  To avoid confusion, some people read the equality operator as “double equals” or “equals equals.”

85 Jozef Goetz, 2012 84 Good Programming Practice 3.9  Indent an if statement’s body to make it stand out and to enhance application readability. if ( number1 > number2 ) Console.WriteLine( number1 + " > " + number2 );  Placing a semicolon immediately after the right parenthesis of the condition in an if statement is normally a logic error.

86 Jozef Goetz, 2012 85 Good Programming Practice 3.12  Place one statement per line in an application. This format enhances readability.

87 Jozef Goetz, 2012 86 Good Programming Practice 3.13  A lengthy statement can be spread over several lines.   If a single statement must be split across lines, choose breaking points that make sense,  such as after a comma in a comma-separated list, or  after an operator in a lengthy expression.  If a statement is split across two or more lines, indent all subsequent lines until the end of the statement. if ( studentGrade >= 90 ) Console.WriteLine( "A" ); else if ( studentGrade >= 80 ) Console.WriteLine( "B" );

88 Jozef Goetz, 2012 87 3.9 Decision Making: Equality and Relational Operators in decreasing order of precedence Example: x = y = 0 is evaluated as if were written x = (y = 0) and later the result of (y = 0) is 0 assigned to x If you are uncertain about the order of evaluation in a complex expression, use parentheses to force the order, as you would do in algebraic expressions. Observe that some operators, such as assignment, =, associate from right to left rather than from left to right. if ( x > 5 ) { if ( y > 5 ) Console.WriteLine("x and y are > 5" ); } else Console.WriteLine( "x is <= " );


Download ppt "Jozef Goetz, 2012 1  2009 Pearson Education, Inc. All rights reserved.  2002 Prentice Hall. All rights reserved. expanded by J. Goetz, 2012."

Similar presentations


Ads by Google