Jozef Goetz, 2012
1
2009 Pearson Education, Inc. All rights reserved.
2002 Prentice Hall. All rights reserved.
expanded by J. Goetz, 2012
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 roseby 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
Jozef Goetz, 2012
3OBJECTIVES
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.
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
Jozef Goetz, 2012
53.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)
Jozef Goetz, 2012
63.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
2002 Prentice Hall.All rights reserved.
Outline7
Welcome1.cs
Program Output
1 // Fig. 3.1: Welcome1.cs2 // A first program in C#.3 4 using System;5 6 class Welcome17 {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
2002 Prentice Hall.All rights reserved.
Outline8
Welcome1.cs
Program Output
1 // Fig. 3.1: Welcome1.cs2 // A first program in C#.3 4 using System;5 6 public class Welcome17 {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
Jozef Goetz, 2012
93.2 Simple Program: Printing a Line of Text
Fig. 3.3 Execution of the Welcome1 program.
Jozef Goetz, 2012
103.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
Jozef Goetz, 2012
113.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
Jozef Goetz, 2012
123.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
Jozef Goetz, 2012
133.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!" );
Jozef Goetz, 2012
143.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
Jozef Goetz, 2012
15Common 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.
Jozef Goetz, 2012
16Common 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.
Jozef Goetz, 2012
17Error-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.
Jozef Goetz, 2012
18
C# Keywords
abstract as base bool break byte case batch char checked class const continue decimal default delegate do double else enum event explicit extern false finally fixed float for foreach goto if implicit in int interface internal is lock long namespace new null object operator out override params private protected public readonly ref return sbyte sealed short sizeof stackalloc static string struct switch this throw true try typeof uint ulong unchecked unsafe ushort using virtual void volatile while
Fig. 3.2 | C# keywords.
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 { … }
Jozef Goetz, 2012
20Common 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
Jozef Goetz, 2012
21Good 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
Jozef Goetz, 2012
22Common 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.
Jozef Goetz, 2012
23Error-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.
Jozef Goetz, 2012
24Good 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
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.
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.
Jozef Goetz, 2012
273.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)
Jozef Goetz, 2012
28
Fig. 3.3 | Creating a Console Application with the New Project dialog.
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.
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
Jozef Goetz, 2012
31
Fig. 3.5 | Modifying the IDE settings.
tab setup: Tools->Options->Text Editor -> Tabs
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.
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 FileChange the File Name property to Welcome1.cs.
Jozef Goetz, 2012
343.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)
Jozef Goetz, 2012
35
Partially-typed member
Member list
Highlighted member
Tool tip describeshighlighted member
Fig. 3.7 | IntelliSense feature of Visual C# Express.
Jozef Goetz, 2012
363.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.
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.
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.
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.
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 > CommandPrompt.
Fig. 3.11 | Command Prompt window when it is initially opened.
Default prompt displays whenCommand Prompt is opened
User enters the next command here
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 aCommand Prompt window.
Updated prompt showingthe new current directory
Type this to change to theapplication’s directory
Application’s output Closes the Command PromptType this to run the Welcome1.exe application
Jozef Goetz, 2012
423.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
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.
Jozef Goetz, 2012
44Error-Prevention Tip 3.5
Exc2: Remove the 1st 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.
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
Jozef Goetz, 2012
46 1 // Fig. 3.14: Welcome2.cs
2 // Printing one line of text with multiple statements.
3 using System;
4
5 public class Welcome2
6 {
7 // Main method begins execution of C# application
8 public static void Main( string[] args )
9 {
10 Console.Write( "Welcome to " );
11 Console.WriteLine( "C# Programming!" );
12 } // end method Main
13 } // end class Welcome2 Welcome to C# Programming!
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.
Jozef Goetz, 2012
473.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!" );
Jozef Goetz, 2012
48 1 // Fig. 3.15: Welcome3.cs
2 // Printing multiple lines with a single statement.
3 using System;
4
5 public class Welcome3
6 {
7 // Main method begins execution of C# application
8 public static void Main( string[] args )
9 {
10 Console.WriteLine( "Welcome\nto\nC#\nProgramming!" );
11 } // end method Main
12 } // end class Welcome3 Welcome to C# Programming!
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.
Jozef Goetz, 2012
493.2 Simple Program: Printing a Line of Text
Escape sequence Description \n Newline. Position the screen cursor to the beginning of the
next line. \t Horizontal tab. Move the screen cursor to the next tab stop. \r Carriage return. Position the screen cursor to the beginning
of the current line; do not advance to the next line. Any characters output after the carriage return overwrite the previous characters output on that line.
\\ Backslash. Used to print a backslash character. \" Double quote. Used to print a double quote (") character. Fig. 3.16 Some common escape sequences.
Jozef Goetz, 2012
50 1 // Fig. 3.17: Welcome4.cs
2 // Printing multiple lines of text with string formatting.
3 using System;
4
5 public class Welcome4
6 {
7 // Main method begins execution of C# application
8 public static void Main( string[] args )
9 {
10 Console.WriteLine( "{0}\n{1}", "Welcome to", "C# Programming!" );
11 } // end method Main
12 } // end class Welcome4 Welcome to C# Programming!
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.
Jozef Goetz, 2012
513.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” );
2002 Prentice Hall.All rights reserved.
Outline52
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 Welcome48 {9 static void Main( string[] args )10 {§ 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
Jozef Goetz, 2012
53Simple 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
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
Jozef Goetz, 2012
553.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).
Jozef Goetz, 2012
563.5 Simple Program: Printing a Line of Text
Fig. Adding a reference to an assembly in Visual Studio .NET (part 1).
Add Reference dialogue
Jozef Goetz, 2012
573.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
Jozef Goetz, 2012
58Convention
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.
Jozef Goetz, 2012
59 1 // Fig. 3.18: Addition.cs
2 // Displaying the sum of two numbers input from the keyboard.
3 using System;
4
5 public class Addition
6 {
7 // Main method begins execution of C# application
8 public static void Main( string[] args )
9 {
10 int number1; // declare first number to add
11 int number2; // declare second number to add
12 int sum; // declare sum of number1 and number2
13
14 Console.Write( "Enter first integer: " ); // prompt user
15 // read first number from user
16 number1 = Convert.ToInt32( Console.ReadLine() );
17
18 Console.Write( "Enter second integer: " ); // prompt user
19 // read second number from user
20 number2 = Convert.ToInt32( Console.ReadLine() );
21
22 sum = number1 + number2; // add numbers
23
24 Console.WriteLine( "Sum is {0}", sum ); // display sum
25 } // end method Main
26 } // end class Addition Enter first integer: 45 Enter second integer: 72 Sum is 117
This is the well commented program with comment indented.
Outline
Addition.cs
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.
Jozef Goetz, 2012
603.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 {
Jozef Goetz, 2012
613.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 add11 int number2; // second number to add12 int sum; // second number to add
int number1, // first number to add number2, // second number to add sum; // second number to add
Jozef Goetz, 2012
62Good 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.
Jozef Goetz, 2012
633.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
Jozef Goetz, 2012
643.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 ) );
2002 Prentice Hall.All rights reserved.
Outline65
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 Addition7 {8 static void Main( string[] args )9 { // the sinle-line comments to indicate the purpose of each variable10 string firstNumber, // first string entered by user11 secondNumber; // second string entered by user12 13 int number1, // first number to add14 number2, // second number to add15 sum; // sum of number1 and number216 17 // prompt for and read first number from user as string18 Console.Write( "Please enter the first integer: " );19 firstNumber = Console.ReadLine();20 21 // read second number from user as string22 Console.Write( "\nPlease enter the second integer: " );23 secondNumber = Console.ReadLine(); // an assignment statement24 // = a binary operator 25 // convert numbers from type string to type int26 number1 = Int32.Parse( firstNumber ); // or use Convert.ToInt32()27 number2 = Int32.Parse( secondNumber );28 29 // add numbers30 sum = number1 + number2; // Read as: sum gets the value of number1 + number2
31
This is the start of class Addition
Two string variables defined over two lines
The comment after the declaration is used to briefly state the variable purpose
These are three ints 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
2002 Prentice Hall.All rights reserved.
Outline66
Addition.cs
Program Output
32 // display results33 Console.WriteLine( "\nThe sum is {0}.", sum );34 35 } // end method Main36 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
Jozef Goetz, 2012
673.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
Jozef Goetz, 2012
683.7 Memory Concepts
Fig. 3.19 Memory location showing name and value of variable number1. 45 is replaced the previous value; previous value is destroyed
number1 45
Jozef Goetz, 2012
693.7 Memory Concepts
Fig. 3.20 Memory locations number1 and number2 after values for variables number1 and number2 have been input.
number1 45
number2 72
Jozef Goetz, 2012
703.7 Memory Concepts
Fig. 3.21 Memory locations after a calculation. When a sum is read from a memory , the process is nondestructive.
number1 45
number2 72
sum 117
Jozef Goetz, 2012
713.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
Jozef Goetz, 2012
723.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
Jozef Goetz, 2012
733.8 Arithmetic
C# operation Arithmetic operator Algebraic expression C# expression
Addition + f + 7 f + 7
Subtraction – p – c p - c
Multiplication * bm b * m
Division / x / y or x / y
Modulus % r mod s r % s
Fig. 3.22 Arithmetic operators.
xy
Jozef Goetz, 2012
743.8 Arithmetic
Operator(s) Operation Order of evaluation (precedence) ( ) Parentheses Evaluated first. If the parentheses are
nested, the expression in the innermost pair is evaluated first. If there are several pairs of parentheses “on the same level” (i.e., not nested), they are evaluated left to right.
*, / or % Multiplication Division Modulus
Evaluated second. If there are several such operators, they are evaluated left to right.
+ or - Addition Subtraction
Evaluated last. If there are several such operators, they are evaluated left to right.
Fig. 3.23 Precedence of arithmetic operators.
Jozef Goetz, 2012
753.8 Arithmetic
Fig. 3.24 Order 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)
Jozef Goetz, 2012
763.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
Jozef Goetz, 2012
773.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
Jozef Goetz, 2012
783.9 Decision Making: Equality and Relational Operators
Standard algebraic equality operator or relational operator
C# equality or relational operator
Example of C# condition
Meaning of C# condition
Equality operators == x == y x is equal to y != x != y x is not equal to y Relational operators > > x > y x is greater than y < < x < y x is less than y >= x >= y x is greater than or equal to y <= x <= y x is less than or equal to y Fig. 3.25 Equality and relational operators.
Jozef Goetz, 2012
793.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
2002 Prentice Hall.All rights reserved.
Outline80
Comparison.cs
1 // Fig. 3.26: Comparison.cs ed1.2 // Using if statements, relational operators and equality3 // operators.4 5 using System;6 7 class Comparison8 {9 static void Main( string[] args )10 { // multiple declaration for same type11 int number1, // first number to compare12 number2; // second number to compare13 14 // read in first number from user15 Console.Write( "Please enter first integer: " );16 number1 = Int32.Parse( Console.ReadLine() ); // or number1 = Convert.ToInt32( Console.ReadLine() );
18 // read in second number from user19 Console.Write( "\nPlease enter second integer: " );20 number2 = Int32.Parse( Console.ReadLine() );21 22 if ( number1 == number2 )23 Console.WriteLine( number1 + " == " + number2 ); //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: 10002000 != 10002000 > 10002000 >= 1000
2002 Prentice Hall.All rights reserved.
Outline81
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 Main41 42 } // end class Comparison
Please enter first integer: 2000 Please enter second integer: 10002000 != 10002000 > 10002000 >= 1000
Please enter first integer: 1000 Please enter second integer: 20001000 != 20001000 < 20001000 <= 2000
Please enter first integer: 1000 Please enter second integer: 10001000 == 10001000 <= 10001000 >= 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
Jozef Goetz, 2012
82Common 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 );
Jozef Goetz, 2012
83Common 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.”
Jozef Goetz, 2012
84Good 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.
Jozef Goetz, 2012
85Good Programming Practice 3.12
Place one statement per line in an application. This format enhances readability.
Jozef Goetz, 2012
86Good 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" );
Jozef Goetz, 2012
873.9 Decision Making: Equality and
Relational Operators in decreasing order of precedence
Operators Associativity Type () left to right parentheses * / % left to right multiplicative + - left to right additive < <= > >= left to right relational == != left to right equality = right to left assignment Fig. 3.27 Precedence and associativity of operators discussed in this
chapter.
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 <= " );