Presentation is loading. Please wait.

Presentation is loading. Please wait.

Introduction to Computing and Programming

Similar presentations


Presentation on theme: "Introduction to Computing and Programming"— Presentation transcript:

1 Introduction to Computing and Programming
1 C# Programming: From Problem Analysis to Program Design

2 Chapter Objectives Learn about the history of computers
Explore the physical components of a computer system Examine how computers represent data Learn to differentiate between system and application software C# Programming: From Problem Analysis to Program Design

3 Chapter Objectives (continued)
Learn the steps of software development Explore different programming methodologies C# Programming: From Problem Analysis to Program Design

4 History of Computers Computing dates back 5,000 years
Currently in fourth or fifth generation of modern computing Pre-modern computing Abacus Also known as counting frame Made with a bamboo frames and beads Chinese, Egyptian, Greek, Roman, etc C# Programming: From Problem Analysis to Program Design

5 Physical Components of a Computer System
Hardware Physical devices that you can touch Central processing unit (CPU) Brain of the computer Housed inside system unit on silicon chip Most expensive component Performs arithmetic and logical comparisons on data and coordinates the operations of the system C# Programming: From Problem Analysis to Program Design

6 Physical Components of a Computer System (continued)
Figure 1-3 Major hardware components C# Programming: From Problem Analysis to Program Design

7 Physical Components of a Computer System (continued)
Figure 1-4 CPU’s instruction cycle C# Programming: From Problem Analysis to Program Design

8 Physical Components of a Computer System (continued)
Primary storage – main memory Called random-access memory (RAM) Cache Type of random access memory that can be accessed more quickly than regular RAM Acts like a buffer, or temporary storage location Each cell has a unique address C# Programming: From Problem Analysis to Program Design

9 Physical Components of a Computer System (continued)
Figure 1-5 Addressing in memory C# Programming: From Problem Analysis to Program Design

10 Physical Components of a Computer System (continued)
Auxiliary storage – secondary storage Nonvolatile, permanent memory Most common types are magnetic and optic disks (hard disk, CD, DVD, zip, and flash memory) Input/Output Devices Used to get data inside the machine Drive is the device used to store/retrieve from several types of storage media C# Programming: From Problem Analysis to Program Design

11 Data Representation Bits Bytes Bit – "Binary digIT"
Binary digit can hold 0 or 1 1 and 0 correspond to on and off, respectively Bytes Combination of 8 bits Represent one character, such as the letter A To represent data, computers use the base-2 number system, or binary number system C# Programming: From Problem Analysis to Program Design

12 Binary Number System Figure 1-6 Base–10 positional notation of 1326
C# Programming: From Problem Analysis to Program Design

13 Binary Number System (continued)
Figure 1-7 Decimal equivalent of C# Programming: From Problem Analysis to Program Design

14 Other Number Systems Decimal (base 10) Octal (base 8)
Hexadecimal (base 16) How to convert from non-base 10 to base 10? Weighted sum How to convert from base 10 to non-base 10? Division and remainder C# Programming: From Problem Analysis to Program Design

15 Data Representation (continued)
C# Programming: From Problem Analysis to Program Design

16 Data Representation (continued)
Character sets With only 8 bits, can represent 28, or 256, different decimal values ranging from 0 to 255; these are 256 different characters Unicode – Character set used by C# (pronounced C Sharp) Uses 16 bits to represent characters 216, or 65,536 unique characters, can be represented American Standard Code for Information Interchange (ASCII) – subset of Unicode First 128 characters are the same C# Programming: From Problem Analysis to Program Design

17 Data Representation (continued)
C# Programming: From Problem Analysis to Program Design

18 Software Consists of programs Two types of software
Sets of instructions telling the computer exactly what to do Two types of software System (Operating systems, etc) Application (Word processors, Java, C++, C#, etc) Power of what the computer does lies with what types of software are available C# Programming: From Problem Analysis to Program Design

19 Software (continued) Figure 1-8 A machine language instruction
C# Programming: From Problem Analysis to Program Design

20 Software Development Process
Programming is a process of problem solving How do you start? Number of different approaches, or methodologies Successful problem solvers follow a methodical approach C# Programming: From Problem Analysis to Program Design

21 Steps in the Program Development Process
1. Analyze the problem 2. Design a solution 3. Code the solution 4. Implement the code 5. Test and debug 6. Use an iterative approach C# Programming: From Problem Analysis to Program Design

22 Steps in the Program Development Process
Software development process is iterative As errors are discovered, it is often necessary to cycle back to a previous phase or step Figure Steps in the software development process C# Programming: From Problem Analysis to Program Design

23 Step 1: Analyze the Problem
Precisely what is software supposed to accomplish? Understand the problem definition Review the problem specifications C# Programming: From Problem Analysis to Program Design

24 Analyze the Problem (continued)
Figure 1-9 Program specification sheet for a car rental agency problem C# Programming: From Problem Analysis to Program Design

25 Analyze the Problem (continued)
What kind of data will be available for input? What types of values (i.e., whole numbers, alphabetic characters, and numbers with decimal points) will be in each of the identified data items? What is the domain (range of the values) for each input item? Will the user of the program be inputting values? If the problem solution is to be used with multiple data sets, are there any data items that stay the same, or remain constant, with each set? C# Programming: From Problem Analysis to Program Design

26 Analyze the Problem (continued)
May help to see sample input for each data item Figure 1-10 Data for car rental agency C# Programming: From Problem Analysis to Program Design

27 Step 2: Design a Solution
Several approaches Procedural and object-oriented methodologies Careful design always leads to better solutions Divide and Conquer Break the problem into smaller subtasks Top-down design, stepwise refinement Algorithms for the behaviors (object-oriented) or processes (procedural) should be developed C# Programming: From Problem Analysis to Program Design

28 Design a Solution (continued)
Algorithm Clear, unambiguous, step-by-step process for solving a problem Steps must be expressed so completely and so precisely that all details are included Instructions should be simple to perform Instructions should be carried out in a finite amount of time Following the steps blindly should result in the same results C# Programming: From Problem Analysis to Program Design

29 Design Object-oriented approach Class diagram
Divided into three sections Top portion identifies the name of the class Middle portion lists the data characteristics Bottom portion shows what actions are to be performed on the data C# Programming: From Problem Analysis to Program Design

30 Class Diagram Figure 1-11 Class diagram of car rental agency
C# Programming: From Problem Analysis to Program Design

31 Class Diagram (continued)
Figure 1-15 Student class diagram C# Programming: From Problem Analysis to Program Design

32 Design (continued) Structured procedural approach Tools used
Process oriented Focuses on the processes that data undergoes from input until meaningful output is produced Tools used Flowcharts Pseudocode, structured English Algorithm written in near English statements for pseudocode C# Programming: From Problem Analysis to Program Design

33 Flowchart Parallelogram – inputs and output Oval – beginning and end
Rectangular – processes Diamond – decision to be made Parallelogram – inputs and output Flow line Figure Flowchart symbols and their interpretation C# Programming: From Problem Analysis to Program Design

34 Step 3: Code the Solution
After completing the design, verify the algorithm is correct Translate the algorithm into source code Follow the rules of the language Integrated Development Environment (IDE) Visual Studio Tools for typing program statements, compiling, executing, and debugging applications C# Programming: From Problem Analysis to Program Design

35 Step 4: Implement the Code
Source code is compiled to check for rule violations C# → Source code is converted into Microsoft Intermediate Language (IL) IL is between high-level source code and native code IL code not directly executable on any computer IL code not tied to any specific CPU platform Second step, managed by .NET’s Common Language Runtime (CLR), is required C# Programming: From Problem Analysis to Program Design

36 Implement the Code (continued)
CLR loads .NET classes A second compilation, called a just-in-time (JIT) compilation is performed IL code is converted to the platform’s native code Figure 1-12 Execution steps for .NET C# Programming: From Problem Analysis to Program Design

37 Step 5: Test and Debug Test the program to ensure consistent results
Test Driven Development (TDD) Development methodologies built around testing Plan your testing Test plan should include extreme values and possible problem cases Logic errors Might cause abnormal termination or incorrect results to be produced Run-time error is one form of logic error C# Programming: From Problem Analysis to Program Design

38 Programming Methodologies
Structured Procedural Programming Emerged in the 1970s Associated with top-down design Analogy of building a house Write each of the subprograms as separate functions or methods invoked by a main controlling function or module Drawbacks During software maintenance, programs are more difficult to maintain Less opportunity to reuse code C# Programming: From Problem Analysis to Program Design

39 Programming Methodologies (continued)
Object-oriented Newer approach Construct complex systems that model real-world entities Facilitates designing components Assumption is that the world contains a number of entities that can be identified and described C# Programming: From Problem Analysis to Program Design

40 Object-Oriented Methodologies
Abstraction Through abstracting, determine attributes (data) and behaviors (processes on the data) of the entities Encapsulation Combine attributes and behaviors to form a class Polymorphism Methods of parent and subclasses can have the same name, but offer different functionality Invoke methods of the same name on objects of different classes and have the correct method executed C# Programming: From Problem Analysis to Program Design

41 The Evolution of C# and .NET
1940s: Programmers toggled switches on the front of computers 1950s: Assembly languages replaced the binary notation Late 1950s: High-level languages came into existence Today: More than 2,000 high-level languages Noteworthy high-level programming languages are C, C++, Visual Basic, Java, and C# C# Programming: From Problem Analysis to Program Design

42 C# One of the newest programming languages
Conforms closely to C and C++ Has the rapid graphical user interface (GUI) features of previous versions of Visual Basic Has the added power of C++ Has the object-oriented class libraries similar to Java C# Programming: From Problem Analysis to Program Design

43 C# (continued) Can be used to develop a number of applications
Software components Mobile applications Dynamic Web pages Database access components Windows desktop applications Web services Console-based applications C# Programming: From Problem Analysis to Program Design

44 .NET Not an operating system An environment in which programs run
Resides at a layer between operating system and other applications Offers multilanguage independence One application can be written in more than one language Includes over 2,500 reusable types (classes) Enables creation of dynamic Web pages and Web services Scalable component development C# Programming: From Problem Analysis to Program Design

45 C# Relationship to .NET Many compilers targeting the .NET platform are available C# was used most heavily for development of the .NET Framework class libraries C#, in conjunction with the .NET Framework classes, offers an exciting vehicle to incorporate and use emerging Web standards C# Programming: From Problem Analysis to Program Design

46 C# Relationship to .NET (continued)
C# is object-oriented In 2001, the European Computer Manufacturers Association (ECMA) General Assembly ratified C# and its common language infrastructure (CLI) specifications into international standards C# Programming: From Problem Analysis to Program Design

47 Chapter Summary Computing dates back some 5,000 years
Currently in 4th or 5th generation of computing Physical components of the computer System software versus application software Steps in program development process 1. Analyze the problem 2. Design a solution 3. Code the solution 4. Implement the code 5. Test and debug C# Programming: From Problem Analysis to Program Design

48 Chapter Summary (continued)
Programming methodologies Structured procedural Object-oriented C# One of the .NET managed programming languages 2001 EMCA standardized Provides rapid GUI development of Visual Basic Provides number crunching power of C++ Provides large library of classes similar to Java C# Programming: From Problem Analysis to Program Design

49 Your First C# Program 2 C# Programming: From Problem Analysis to Program Design

50 Chapter Objectives Explore a program written in C#
Examine the basic elements of a C# program Compile, run, and build an application Create an application that displays output C# Programming: From Problem Analysis to Program Design

51 Console Applications Normally send requests to the operating system
Display text on the command console Easiest to create Simplest approach to learning software development Minimal overhead for input and output of data C# Programming: From Problem Analysis to Program Design

52 Exploring the First C# Program
line // This is traditionally the first program written. line using System; //why do we need this? line namespace FirstProgram line { line class HelloWorld //can it be different from the file name? line { line static void Main( ) //can it be main? Can we omit static? line { line Console.WriteLine(“Hello World!”); //how many arguments? line } line } line } Comments in green Keywords in blue C# Programming: From Problem Analysis to Program Design

53 Output from the First C# Program
Console-based application output Figure 2-3 Output from Example 2-1 console application C# Programming: From Problem Analysis to Program Design

54 Elements of a C# Program
Comments line 1 // This is traditionally the first program written. Like making a note to yourself or readers of your program Not considered instructions to the computer Not checked for rule violations Document what the program statements are doing C# Programming: From Problem Analysis to Program Design

55 Comments Make the code more readable Three types of commenting syntax
Inline comments Multiline comments XML documentation comments C# Programming: From Problem Analysis to Program Design

56 Inline Comments Indicated by two forward slashes (//)
Considered a one-line comment Everything to the right of the slashes ignored by the compiler Carriage return (Enter) ends the comment // This is traditionally the first program written. C# Programming: From Problem Analysis to Program Design

57 Multiline Comment Forward slash followed by an asterisk (/*) marks the beginning Opposite pattern (*/) marks the end Also called block comments Does not allow you to nest multiline comments /* This is the beginning of a block multiline comment. It can go on for several lines or just be on a single line. No additional symbols are needed after the beginning two characters. Notice there is no space placed between the two characters. To end the comment, use the following symbols. */ C# Programming: From Problem Analysis to Program Design

58 using Directive Permits use of classes found in specific namespaces without having to qualify them Framework class library Over 2,000 classes included Syntax using namespaceIdentifier; C# Programming: From Problem Analysis to Program Design

59 namespace Namespaces provide scope for the names defined within the group Groups semantically related types under a single umbrella System: most important and frequently used namespace Can define your own namespace Each namespace enclosed in curly braces: { } C# Programming: From Problem Analysis to Program Design

60 namespace (continued)
Predefined namespace (System)– part of .NET FCL From Example 2-1 line // This is traditionally the first program written. line using System; line namespace FirstProgram line { line } User defined namespace Body of user defined namespace C# Programming: From Problem Analysis to Program Design

61 class Building block of object-oriented program
Everything in C# is designed around a class Every program must have at least one class Classes define a category, or type, of object Every class is named C# Programming: From Problem Analysis to Program Design

62 class (continued) line // This is traditionally the first program written. line using System; line namespace FirstProgram line { line class HelloWorld line { line } line } User defined class C# Programming: From Problem Analysis to Program Design

63 class (continued) Define class members within curly braces
Include data members Stores values associated with the state of the class Include method members Performs some behavior of the class Can call predefined classes’ methods Main( ) C# Programming: From Problem Analysis to Program Design

64 Main( ) “Entry point” for all applications
Where the program begins execution Execution ends after last statement in Main( ) Can be placed anywhere inside the class definition Applications must have one Main( ) method Begins with uppercase character C# Programming: From Problem Analysis to Program Design

65 Main( ) Method Heading line 7 static void Main( )
Begins with the keyword static Second keyword → return type void signifies no value returned Name of the method Main is the name of Main( ) method Must be Main() instead of main() (like in C++) Parentheses “( )” used for arguments No arguments for Main( ) – empty parentheses  C# Programming: From Problem Analysis to Program Design

66 Body of a Method Enclosed in curly braces Includes program statements
Example Main( ) method body line static void Main( ) line { line Console.WriteLine(“Hello World!”); line } Includes program statements Calls to other method Here Main( ) calling WriteLine( ) method C# Programming: From Problem Analysis to Program Design

67 Method Calls Program statements
line Console.WriteLine(“Hello World!”); Program statements WriteLine( ) → member of the Console class Main( ) invoking WriteLine( ) method Member of Console class Method call ends in semicolon C# Programming: From Problem Analysis to Program Design

68 Program Statements Write ( ) → Member of Console class
Argument(s) enclosed in double quotes inside ( ) “Hello World!” is the method’s argument “Hello World!” is string argument string of characters May be called with or without arguments Console.WriteLine( ); Console.WriteLine(“WriteLine( ) is a method.”); Console.Write(“Main( ) is a method.”); C# Programming: From Problem Analysis to Program Design

69 Program Statements (continued)
Read( ) accepts one character from the input device ReadLine( ) accepts string of characters from the input device Until the enter key is pressed Write( ) does not automatically advance to next line Write(“An example\n”); Same as WriteLine(“An example”); Includes special escape sequences C# Programming: From Problem Analysis to Program Design

70 Program Statements (continued)
Special characters enclosed in double quotes C# Programming: From Problem Analysis to Program Design

71 C# Elements Figure 2-4 Relationship among C# elements
C# Programming: From Problem Analysis to Program Design

72 What does Java do? import java.io.*; public class HelloWorldApp {
public static void main(String[] args) { System.out.println("Hello World!"); // Display the string. }

73 What does C++ do? // a small C++ program #include <iostream>
int main() { std::cout << “Hello, world!” << std:: endl; return 0; }

74 Create Console Application
Begin by opening Visual Studio Create new project Select New Project on the Start page OR use File → New Project option C# Programming: From Problem Analysis to Program Design

75 Create New Project Figure 2-6 Creating a console application
C# Programming: From Problem Analysis to Program Design

76 Code Automatically Generated
Figure 2-7 Code automatically generated by Visual Studio C# Programming: From Problem Analysis to Program Design

77 Typing Your Program Statements
IntelliSense feature of the IDE Change the name of the class and the source code filename Use the Solution Explorer Window to change the source code filename Select View → Solution Explorer C# Programming: From Problem Analysis to Program Design

78 Rename Source Code Name
Clicking Yes causes the class name to also be renamed Figure 2-8 Changing the source code name from Class1 C# Programming: From Problem Analysis to Program Design

79 Compile and Run Application
To Compile – click Build on the Build menu To run or execute application – click Start or Start Without Debugging on the Debug menu Shortcut – if execute code that has not been compiled, automatically compiles first Start option does not hold output screen → output flashes quickly Last statement in Main( ), add Console.Read( ); C# Programming: From Problem Analysis to Program Design

80 Build Visual Studio Project
Figure 2-9 Compilation of a project using Visual Studio C# Programming: From Problem Analysis to Program Design

81 Running an Application
Figure 2-10 Execution of an application using Visual Studio C# Programming: From Problem Analysis to Program Design

82 Debugging an Application
Types of errors (which one is harder to detect?) Syntax errors Typing error Misspelled name Forget to end a statement with a semicolon Run-time errors Failing to fully understand the problem Logical error C# Programming: From Problem Analysis to Program Design

83 Missing ending double quotation mark
Error Listing Missing ending double quotation mark Pushpin Errors reported Figure 2-12 Syntax error message listing C# Programming: From Problem Analysis to Program Design

84 Creating an Application – ProgrammingMessage Example
Figure Problem specification sheet for the ProgrammingMessage example C# Programming: From Problem Analysis to Program Design

85 ProgrammingMessage Example (continued)
Figure 2-14 Prototype for the ProgrammingMessage example C# Programming: From Problem Analysis to Program Design

86 ProgrammingMessage Example (continued)
Pseudocode would include a single line to display the message “Programming can be FUN!” on the output screen Figure Algorithm for ProgrammingMessage example C# Programming: From Problem Analysis to Program Design

87 ProgrammingMessage Example (continued)
Figure 2-16 Recommended deletions May want to remove the XML comments (lines beginning with ///) Change the name Delete [STAThread] Depending on your current settings, you may not need to make some of these changes Can replace with static void Main( ) Replace TODO: with your program statements C# Programming: From Problem Analysis to Program Design

88 ProgrammingMessage Example (continued)
/* Programmer: [supply your name] Date: [supply the current date] Purpose: This class can be used to send messages to the output screen. */ using System; namespace ProgrammingMessage { class ProgrammingDisplay static void Main( ) Console.WriteLine(“Programming can be”); Console.WriteLine(“FUN!”); Console.Read( ); } Complete program listing C# Programming: From Problem Analysis to Program Design

89 Chapter Summary Types of applications developed with C#
Web applications Windows graphical user interface (GUI) applications Console-based applications Framework class library groups by namespaces Namespaces group classes Classes have methods Methods include program statements C# Programming: From Problem Analysis to Program Design

90 Chapter Summary (continued)
Visual Studio includes .NET Framework Editor tool, compiler, debugger, and executor Compile using Build Run using Start or Start without Debugging Debugging Syntax errors Run-time errors Use five steps to program development to create applications C# Programming: From Problem Analysis to Program Design

91 Data Types and Expressions
3 C# Programming: From Problem Analysis to Program Design

92 Chapter Objectives Declare memory locations for data
Explore the relationship between classes, objects, and types Use predefined data types Use integral data types Use floating-point types Learn about the decimal data type Declare Boolean variables C# Programming: From Problem Analysis to Program Design

93 Chapter Objectives (continued)
Declare and manipulate strings Work with constants Write assignment statements using arithmetic operators Learn about the order of operations Learn special formatting rules for currency C# Programming: From Problem Analysis to Program Design

94 Memory Locations for Data
Identifier Name Rules for creating an identifier Combination of alphabetic characters (a-z and A-Z), numeric digits (0-9), and the underscore First character in the name may not be numeric No embedded spaces – concatenate (append) words together Keywords cannot be used Use the case of the character to your advantage Be descriptive with meaningful names C# Programming: From Problem Analysis to Program Design

95 Reserved Words in C# C# Programming: From Problem Analysis to Program Design

96 Naming Conventions Pascal case Camel case
First letter of each word capitalized Class, method, namespace, and properties identifiers Camel case Hungarian notation First letter of identifier lowercase; first letter of subsequent concatenated words capitalized Variables and objects C# Programming: From Problem Analysis to Program Design

97 Naming Conventions (continued)
Uppercase Every character is uppercase Constant literals and for identifiers that consist of two or fewer letters C# Programming: From Problem Analysis to Program Design

98 Examples of Valid Names (Identifiers)
C# Programming: From Problem Analysis to Program Design

99 Examples of Invalid Names (Identifiers)
C# Programming: From Problem Analysis to Program Design

100 Variables Area in computer memory where a value of a particular data type can be stored Declare a variable Allocate memory Syntax type identifier; Compile-time initialization Initialize a variable when it is declared type identifier = expression; C# Programming: From Problem Analysis to Program Design

101 Types, Classes, and Objects
C# has more than one type of number int type is a whole number floating-point types can have a fractional portion (float, double) Types are actually implemented through classes One-to-one correspondence between a class and a type Simple data type such as int, implemented as a class C# Programming: From Problem Analysis to Program Design

102 Types, Classes, and Objects
Instance of a class → object A class includes more than just data Encapsulation → packaging of data and behaviors into a single or unit→class C# Programming: From Problem Analysis to Program Design

103 Type, Class, and Object Examples
C# Programming: From Problem Analysis to Program Design

104 Predefined Data Types Common Type System (CTS)
Divided into two major categories Figure 3-1 .NET common types C# Programming: From Problem Analysis to Program Design

105 Value and Reference Types
Figure 3-2 Memory representation for value and reference types C# Programming: From Problem Analysis to Program Design

106 Value Types Fundamental or primitive data types
Figure 3-3 Value type hierarchy C# Programming: From Problem Analysis to Program Design

107 Value Types (continued)
C# Programming: From Problem Analysis to Program Design

108 Integral Data Types Primary difference How much storage is needed
Whether a negative value can be stored C# Programming: From Problem Analysis to Program Design

109 Examples of Integral Variable Declarations
int studentCount; // number of students in the class int ageOfStudent = 20; // age - originally initialized to 20 int numberOfExams; // number of exams int coursesEnrolled; // number of courses enrolled C# Programming: From Problem Analysis to Program Design

110 Floating-point Types May be in scientific notation with an exponent
n.ne±P 3.2e+5 is equivalent to 320,000 1.76e-3 is equivalent to OR in standard decimal notation Default type is double C# Programming: From Problem Analysis to Program Design

111 Examples of Floating-point Declarations
double extraPerson = 3.50; // extraPerson originally set // to 3.50 double averageScore = 70.0; // averageScore originally set // to 70.0 double priceOfTicket; // cost of a movie ticket double gradePointAverage; // grade point average float totalAmount = 23.57f; // note the f must be placed after // the value for float types C# Programming: From Problem Analysis to Program Design

112 Decimal Types Monetary data items
As with the float, must attach the suffix ‘m’ or ‘M’ onto the end of a number to indicate decimal Float attach ‘f’ or “F’ Examples decimal endowmentAmount = M; decimal deficit; C# Programming: From Problem Analysis to Program Design

113 Boolean Variables Based on true/false, on/off logic
Boolean type in C# → bool Does not accept integer values such as 0, 1, or -1 bool undergraduateStudent; bool moreData = true; C# Programming: From Problem Analysis to Program Design

114 Strings Reference type Represents a string of Unicode characters
string studentName; string courseName = “Programming I”; string twoLines = “Line1\nLine2”; C# Programming: From Problem Analysis to Program Design

115 Making Data Constant Add the keyword const to a declaration
Value cannot be changed Standard naming convention Syntax const type identifier = expression; const double TAX_RATE = ; const int SPEED = 70; const char HIGHEST_GRADE = ‘A’; C# Programming: From Problem Analysis to Program Design

116 Assignment Statements
Used to change the value of the variable Assignment operator (=) Syntax variable = expression; Expression can be: Another variable Compatible literal value Mathematical equation Call to a method that returns a compatible value Combination of one or more items in this list C# Programming: From Problem Analysis to Program Design

117 Examples of Assignment Statements
int numberOfMinutes, count, minIntValue; char firstInitial, yearInSchool, punctuation; numberOfMinutes = 45; count = 0; minIntValue = ; firstInitial = ‘B’; yearInSchool = ‘1’; enterKey = ‘\n’; // newline escape character lastChar = '\u005A'; //hexadecimal number. C# Programming: From Problem Analysis to Program Design

118 Examples of Assignment Statements (continued)
double accountBalance, weight; decimal amountOwed, deficitValue; bool isFinished; accountBalance = ; weight = 1.7E-3; //scientific notation may be used amountOwed = m; // m or M must be suffixed to // decimal deficitValue = M; C# Programming: From Problem Analysis to Program Design

119 Examples of Assignment Statements (continued)
int count = 0, newValue = 25; string aSaying, fileLocation; aSaying = “First day of the rest of your life!\n "; fileLocation isFinished = false; // declared previously as a bool count = newValue; @ placed before a string literal signals that the characters inside the double quotation marks should be interpreted verbatim C# Programming: From Problem Analysis to Program Design

120 Examples of Assignment Statements (continued)
Figure 3-5 Impact of assignment statement C# Programming: From Problem Analysis to Program Design

121 Arithmetic Operations
Simplest form of an assignment statement resultVariable = operand1 operator operand2; Readability Space before and after every operator C# Programming: From Problem Analysis to Program Design

122 Basic Arithmetic Operations
Figure 3-6 Result of 67 % 3 Modulus operator with negative values Sign of the dividend determines the result -3 % 5 = -3; % -3 = 2; % -3 = -3; C# Programming: From Problem Analysis to Program Design

123 Basic Arithmetic Operations (continued)
Plus (+) with string Identifiers Concatenates operand2 onto end of operand1 string result; string fullName; string firstName = “Rochelle”; string lastName = “Howard”; fullName = firstName + “ “ + lastName; C# Programming: From Problem Analysis to Program Design

124 Concatenation Figure 3-7 String concatenation
C# Programming: From Problem Analysis to Program Design

125 Basic Arithmetic Operations (continued)
Increment and Decrement Operations Unary operator num++; // num = num + 1; --value1; // value = value – 1; Preincrement/predecrement versus post int num = 100; System.Console.WriteLine(num++); // Displays 100 System.Console.WriteLine(num); // Display 101 System.Console.WriteLine(++num); // Displays 102 C# Programming: From Problem Analysis to Program Design

126 Basic Arithmetic Operations (continued)
int num = 100; System.Console.WriteLine(x++ + “ “ + ++x); // Displays Figure 3-9 Change in memory after count++; statement executed C# Programming: From Problem Analysis to Program Design

127 Basic Arithmetic Operations (continued)
Figure 3-10 Results after statement is executed C# Programming: From Problem Analysis to Program Design

128 Compound Operations Accumulation +=
C# Programming: From Problem Analysis to Program Design

129 Basic Arithmetic Operations (continued)
Order of operations Order in which the calculations are performed Example answer = 100; answer += 50 * 3 / 25 – 4; 50 * 3 = 150 150 / 25 = 6 6 – 4 = 2 = 102 C# Programming: From Problem Analysis to Program Design

130 Order of Operations Associativity of operators Left Right
C# Programming: From Problem Analysis to Program Design

131 Order of Operations (continued)
Figure 3-11 Order of execution of the operators C# Programming: From Problem Analysis to Program Design

132 Mixed Expressions Implicit type coercion
Changes int data type into a double No implicit conversion from double to int Figure 3-12 Syntax error generated for assigning a double to an int C# Programming: From Problem Analysis to Program Design

133 Mixed Expressions (continued)
Explicit type coercion Cast (type) expression examAverage = (exam1 + exam2 + exam3) / (double) count; int value1 = 0, anotherNumber = 75; double value2 = , anotherDouble = 100; value1 = (int) value2; // value1 = 100 value2 = (double) anotherNumber; // value2 = 75.0 can be omitted C# Programming: From Problem Analysis to Program Design

134 Formatting Output You can format data by adding dollar signs, percent symbols, and/or commas to separate digits You can suppress leading zeros You can pad a value with special characters Place characters to the left or right of the significant digits Use format specifiers C# Programming: From Problem Analysis to Program Design

135 Numeric Format Specifiers
C# Programming: From Problem Analysis to Program Design

136 Numeric Format Specifiers (continued)
C# Programming: From Problem Analysis to Program Design

137 Custom Numeric Format Specifiers
C# Programming: From Problem Analysis to Program Design

138 Custom Numeric Format Specifiers (continued)
C# Programming: From Problem Analysis to Program Design

139 Formatting Output C# Programming: From Problem Analysis to Program Design

140 Chapter Summary Memory locations for data
Relationship between classes, objects, and types Predefined data types Integral data types Floating-point types Decimal type Boolean variables Strings C# Programming: From Problem Analysis to Program Design

141 Chapter Summary (continued)
Constants Assignment statements Order of operations Formatting output C# Programming: From Problem Analysis to Program Design

142 Methods and Behaviors 4 C# Programming: From Problem Analysis to Program Design

143 Chapter Objectives Become familiar with the components of a method
Call class methods with and without parameters Use predefined methods in the Console and Math classes Write your own value and nonvalue-returning class methods (with and without parameters) Learn about the different methods and properties used for object-oriented development C# Programming: From Problem Analysis to Program Design

144 Chapter Objectives (continued)
Write your own instance methods to include constructors, mutators, and accessors Call instance methods including constructors, mutators, and accessors Distinguish between value, ref, and out parameter types C# Programming: From Problem Analysis to Program Design

145 Anatomy of a Method Methods defined inside classes
Group program statements Based on functionality Called one or more times All programs consist of at least one method Main( ) User-defined method C# Programming: From Problem Analysis to Program Design

146 Required method /* SquareExample.cs Author: Doyle */ using System;
namespace Square { public class SquareExample public static void Main( ) int aValue = 768; int result; result = aValue * aValue; Console.WriteLine(“{0} squared is {1}”, aValue, result); Console.Read( ); } Required method C# Programming: From Problem Analysis to Program Design

147 Anatomy of a Method (continued)
Figure 4-1 Method components C# Programming: From Problem Analysis to Program Design

148 Modifiers Appear in method headings
Appear in the declaration heading for classes and other class members Indicate how it can be accessed Types of modifiers Static Access C# Programming: From Problem Analysis to Program Design

149 Static Modifier Indicates member belongs to the type itself rather than to a specific object of a class Main( ) must include static in heading Members of the Math class are static public static double Pow(double, double) Methods that use the static modifier are called class methods Instance methods require an object C# Programming: From Problem Analysis to Program Design

150 Access Modifiers public protected internal protected internal private
C# Programming: From Problem Analysis to Program Design

151 Level of Accessibility
Default is private C# Programming: From Problem Analysis to Program Design

152 Return Type Indicates what type of value is returned when the method is completed Always listed immediately before method name void No value being returned return statement Required for all non-void methods Compatible value C# Programming: From Problem Analysis to Program Design

153 Return Type (continued)
public static double CalculateMilesPerGallon (int milesTraveled, double gallonsUsed) { return milesTraveled / gallonsUsed; } Compatible value (double) returned C# Programming: From Problem Analysis to Program Design

154 Method Names Follow the rules for creating an identifier Examples
Pascal case style Action verb or prepositional phrase Examples CalculateSalesTax( ) AssignSectionNumber( ) DisplayResults( ) InputAge( ) ConvertInputValue( ) C# Programming: From Problem Analysis to Program Design

155 Parameters Supply unique data to method Appear inside parentheses
Include data type and an identifier In method body, reference values using identifier name Parameter refers to items appearing in the heading Argument for items appearing in the call Formal parameters Actual arguments C# Programming: From Problem Analysis to Program Design

156 Parameters (continued)
public static double CalculateMilesPerGallon (int milesTraveled, double gallonsUsed) { return milesTraveled / gallonsUsed; } Call to method inside Main( ) method Console.WriteLine(“Miles per gallon = {0:N2}”, CalculateMilesPerGallon(289, 12.2)); Two formal parameters Actual arguments C# Programming: From Problem Analysis to Program Design

157 Parameters (continued)
Like return types, parameters are optional Keyword void not required (inside parentheses) – when there are no parameters public void DisplayMessage( ) { Console.Write(”This is “); Console.Write(”an example of a method ”); Console.WriteLine(“body. ”); return; // no value is returned } C# Programming: From Problem Analysis to Program Design

158 Method Body Enclosed in curly braces
Include statements ending in semicolons Declare variables Do arithmetic Call other methods Value-returning methods must include return statement C# Programming: From Problem Analysis to Program Design

159 Calling Class Methods Invoke a method
Call to method that returns no value [qualifier].MethodName(argumentList); Qualifier Square brackets indicate optional class or object name Call to method does not include data type Use Intellisense C# Programming: From Problem Analysis to Program Design

160 Predefined Methods Extensive class library Console class
Write( ) overloaded WriteLine( ) overloaded Read( ) ReadLine( ) C# Programming: From Problem Analysis to Program Design

161 Intellisense Figure 4-2 Console class members
After typing the dot, list of members pops up After typing the dot, list of members pops up Method signature(s) and description Method signature(s) and description 3-D fuchsia colored box —methods aqua colored box — fields (not shown) Figure 4-2 Console class members C# Programming: From Problem Analysis to Program Design

162 Intellisense Display Figure 4-3 IntelliSense display
string argument expected string parameter 18 different Write( ) methods Figure 4-3 IntelliSense display C# Programming: From Problem Analysis to Program Design

163 Intellisense Display (continued)
Figure 4-4 Console.Read ( ) signature Figure 4-5 Console.ReadLine ( ) signature C# Programming: From Problem Analysis to Program Design

164 Call Read( ) Methods int aNumber;
Console.Write(“Enter a single character: ”); aNumber = Console.Read( ); Console.WriteLine(“The value of the character entered: ” + aNumber); Enter a single character: a The value of the character entered: 97 C# Programming: From Problem Analysis to Program Design

165 Call Read( ) Methods (continued)
int aNumber; Console.WriteLine(“The value of the character entered: “ + (char) Console.Read( )); Enter a single character: a The value of the character entered: a C# Programming: From Problem Analysis to Program Design

166 Call ReadLine( ) Methods
More versatile than the Read( ) Returns all characters up to the enter key Not overloaded Always returns a string String value must be parsed C# Programming: From Problem Analysis to Program Design

167 Call Parse( ) Predefined static method
All numeric types have a Parse( ) method double.Parse(“string number”) int.Parse(“string number”) char.Parse(“string number”) bool.Parse(“string number”) Expects string argument Argument must be a number – string format Returns the number (or char or bool) C# Programming: From Problem Analysis to Program Design

168 /* AgeIncrementer.cs Author: Doyle */ using System;
namespace AgeExample { public class AgeIncrementer public static void Main( ) int age; string aValue; Console.Write(“Enter your age: “); aValue = Console.ReadLine( ); age = int.Parse(aValue); Console.WriteLine(“Your age next year” + “ will be {0}”, ++age); Console.Read( ); } } } C# Programming: From Problem Analysis to Program Design

169 /* SquareInputValue.cs Author: Doyle */ using System; namespace Square
{ class SquareInputValue static void Main( ) string inputStringValue; double aValue, result; Console.Write(“Enter a value to be squared: ”); inputStringValue = Console.ReadLine( ); aValue = double.Parse(inputStringValue); result = Math.Pow(aValue, 2); Console.WriteLine(“{0} squared is {1}”, aValue, result); } C# Programming: From Problem Analysis to Program Design

170 Call Parse( ) (continued)
string sValue = “True”; Console.WriteLine (bool.Parse(sValue)); // displays True string strValue = “q”; Console.WriteLine(char.Parse(strValue)); // displays q C# Programming: From Problem Analysis to Program Design

171 Call Parse( ) with Incompatible Value
Console.WriteLine(char.Parse(sValue)); when sValue referenced “True” Figure 4-6 System.FormatException run-time error C# Programming: From Problem Analysis to Program Design

172 Convert Class More than one way to convert from one base type to another System namespace — Convert class — static methods Convert.ToDouble( ) Convert.ToDecimal( ) Convert.ToInt32( ) Convert.ToBoolean( ) Convert.ToChar( ) int newValue = Convert.ToInt32(stringValue); C# Programming: From Problem Analysis to Program Design

173 C# Programming: From Problem Analysis to Program Design

174 C# Programming: From Problem Analysis to Program Design

175 C# Programming: From Problem Analysis to Program Design

176 Math( ) Class Each call returns a value
double aValue = ; double result1, result2; result1 = Math.Floor(aValue); // result1 = 78 result2 = Math.Sqrt(aValue); // result2 = Console.Write(“aValue rounded to 2 decimal places” + “ is {0}”, Math.Round(aValue, 2)); aValue rounded to 2 decimal places is 78.93 C# Programming: From Problem Analysis to Program Design

177 Method Calls That Return Values
In an assignment statement Line 1 int aValue = 200; Line 2 int bValue = 896; Line 3 int result; Line 4 result = Math.Max(aValue, bValue); // result = 896 Line 5 result += bValue * Line Math.Max(aValue, bValue) – aValue; // result = (896 * ) (result = ) Line 7 Console.WriteLine(“Largest value between {0} ” Line “and {1} is {2}”, aValue, bValue, Line Math.Max(aValue, bValue)); Part of arithmetic expression Argument to another method call C# Programming: From Problem Analysis to Program Design

178 Writing Your Own Class Methods
[modifier(s)] returnType  MethodName ( parameterList ) // body of method - consisting of executable statements    } void Methods Simplest to write No return statement C# Programming: From Problem Analysis to Program Design

179 Writing Your Own Class Methods – void Types
public static void DisplayInstructions( ) { Console.WriteLine(“This program will determine how ” + “much carpet to purchase.”); Console.WriteLine( ); Console.WriteLine(“You will be asked to enter the ” + “ size of the room and ”); Console.WriteLine(“the price of the carpet, ” + ”in price per square yards.”); } A call to this method looks like: DisplayInstructions( ); C# Programming: From Problem Analysis to Program Design

180 Writing Your Own Class Methods – void Types (continued)
public static void DisplayResults(double squareYards, double pricePerSquareYard) { Console.Write(“Total Square Yards needed: ”); Console.WriteLine(“{0:N2}”, squareYards); Console.Write(“Total Cost at {0:C} “, pricePerSquareYard); Console.WriteLine(“ per Square Yard: {0:C}”, (squareYards * pricePerSquareYard)); } static method called from within the class where it resides To invoke method – DisplayResults(16.5, 18.95); C# Programming: From Problem Analysis to Program Design

181 Value-Returning Method
Has a return type other than void Must have a return statement Compatible value Zero, one, or more data items may be passed as arguments Calls can be placed: In assignment statements In output statements In arithmetic expressions Or anywhere a value can be used C# Programming: From Problem Analysis to Program Design

182 Value-Returning Method (continued)
public static double GetLength( ) { string inputValue; int feet, inches; Console.Write(“Enter the Length in feet: ”); inputValue = Console.ReadLine( ); feet = int.Parse(inputValue); Console.Write(“Enter the Length in inches: “); inches = int.Parse(inputValue); return (feet + (double) inches / 12); } Return type→ double double returned C# Programming: From Problem Analysis to Program Design

183 CarpetExampleWithClassMethods (continued)
/* CarpetExampleWithClassMethods.cs */ using System; namespace CarpetExampleWithClassMethods { public class CarpetWithClassMethods C# Programming: From Problem Analysis to Program Design

184 double roomWidth, roomLength, pricePerSqYard, noOfSquareYards;
public static void Main( ) { double roomWidth, roomLength, pricePerSqYard, noOfSquareYards; DisplayInstructions( ); // Call getDimension( ) to get length roomLength = GetDimension(“Length”); roomWidth = GetDimension(“Width”); pricePerSqYard = GetPrice( ); noOfSquareYards = DetermineSquareYards(roomWidth, roomLength); DisplayResults(noOfSquareYards, pricePerSqYard); } C# Programming: From Problem Analysis to Program Design

185 public static void DisplayInstructions( ) {
Console.WriteLine(“This program will determine how much " + “carpet to purchase.”); Console.WriteLine( ); Console.WriteLine("You will be asked to enter the size of ” + “the room "); Console.WriteLine(“and the price of the carpet, in price per” + “ square yds.”); } C# Programming: From Problem Analysis to Program Design

186 public static double GetDimension(string side ) {
string inputValue; // local variables int feet, // needed only by this inches; // method Console.Write("Enter the {0} in feet: ", side); inputValue = Console.ReadLine( ); feet = int.Parse(inputValue); Console.Write("Enter the {0} in inches: ", side); inches = int.Parse(inputValue); // Note: cast required to avoid int division return (feet + (double) inches / 12); } C# Programming: From Problem Analysis to Program Design

187 string inputValue; // local variables double price;
public static double GetPrice( ) { string inputValue; // local variables double price; Console.Write(“Enter the price per Square Yard: "); inputValue = Console.ReadLine( ); price = double.Parse(inputValue); return price; } C# Programming: From Problem Analysis to Program Design

188 public static double DetermineSquareYards
(double width, double length) { const int SQ_FT_PER_SQ_YARD = 9; double noOfSquareYards; noOfSquareYards = length * width / SQ_FT_PER_SQ_YARD; return noOfSquareYards; } public static double DeterminePrice (double squareYards, double pricePerSquareYard) return (pricePerSquareYard * squareYards); C# Programming: From Problem Analysis to Program Design

189 public static void DisplayResults (double squareYards,
double pricePerSquareYard) { Console.WriteLine( ); Console.Write(“Square Yards needed: ”); Console.WriteLine("{0:N2}", squareYards); Console.Write("Total Cost at {0:C} ", pricePerSquareYard); Console.WriteLine(“ per Square Yard: {0:C}”, DeterminePrice(squareYards, pricePerSquareYard)); } } // end of class } // end of namespace C# Programming: From Problem Analysis to Program Design

190 CarpetExampleWithClassMethods (continued)
Figure 4-7 Output from CarpetExampleWithClassMethods C# Programming: From Problem Analysis to Program Design

191 The Object Concept Class Entity Abstraction
Attributes (data) Behaviors (processes on the data) Private member data (fields) Public method members C# Programming: From Problem Analysis to Program Design

192 Writing Your Own Instance Methods
Do not use static keyword Static – class method Constructor Do not return a value void is not included Same identifier as the class name Overloaded methods Default constructor No arguments C# Programming: From Problem Analysis to Program Design

193 Calling the Constructor
Default values are assigned to variables of the value types when no arguments are sent C# Programming: From Problem Analysis to Program Design

194 Writing Your Own Instance Methods (continued)
Accessor (getter) Returns the current value Standard naming convention → prefix with “get” Accessor for noOfSquareYards is GetNoOfSquareYards( ) Mutators (setters) Normally includes one parameter Method body → single assignment statement Standard naming convention → prefix with ”Set” C# Programming: From Problem Analysis to Program Design

195 Accessor and Mutator Examples
public double GetNoOfSquareYards( ) { return noOfSquareYards; } public void SetNoOfSquareYards(double squareYards) noOfSquareYards = squareYards; Accessor Mutator C# Programming: From Problem Analysis to Program Design

196 Properties Looks like a data field
More closely aligned to methods Standard naming convention in C# for properties Use the same name as the instance variable or field, but start with uppercase character C# Programming: From Problem Analysis to Program Design

197 Calling Instance Methods
Calling the Constructor ClassName objectName = new ClassName(argumentList); or ClassName objectName; objectName = new ClassName(argumentList); Keyword new used as operator to call constructor methods CarpetCalculator plush = new CarpetCalculator ( ); CarpetCalculator pile = new CarpetCalculator (37.90, 17.95); CarpetCalculator berber = new CarpetCalculator (17.95); C# Programming: From Problem Analysis to Program Design

198 Calling Accessor and Mutator Methods
Method name is preceded by the object name berber.SetNoOfSquareYards(27.83); Console.WriteLine(“{0:N2}”, berber.GetNoOfSquareYards( )); Using properties PropertyName = value; and Console.Write(“Total Cost at {0:C} ”, berber.Price); C# Programming: From Problem Analysis to Program Design

199 ToString( ) method All user-defined classes inherit four methods from the object class ToString( ) //you can override it Equals( ) GetType( ) GetHashCode( ) ToString( ) method is called automatically by several methods Write( ) WriteLine( ) methods Can also invoke or call the ToString( ) method directly C# Programming: From Problem Analysis to Program Design

200 ToString( ) method (continued)
Returns a human-readable string Can write a new definition for the ToString( ) method to include useful details public override string ToString( ) { // return string value } Keyword override added to provide new implementation details C# Programming: From Problem Analysis to Program Design

201 Types of Parameters Call by value Other types of parameters
Copy of the original value is made Other types of parameters ref out params ref and out cause a method to refer to the same variable that was passed into the method C# Programming: From Problem Analysis to Program Design

202 Types of Parameters (continued)
Figure 4-10 Call by reference versus value C# Programming: From Problem Analysis to Program Design

203 Chapter Summary Components of a method Class methods
Parameters Predefined methods Value and nonvalue-returning methods C# Programming: From Problem Analysis to Program Design

204 Chapter Summary (continued)
Properties Instance methods Constructors Mutators Accessors Types of parameters C# Programming: From Problem Analysis to Program Design


Download ppt "Introduction to Computing and Programming"

Similar presentations


Ads by Google