Presentation is loading. Please wait.

Presentation is loading. Please wait.

Programs and Data.

Similar presentations


Presentation on theme: "Programs and Data."— Presentation transcript:

1 Programs and Data

2 Topics Data Simple data types Variables and constants Declarations
Assignment Input and output Style

3 Objectives At the completion of this topic, students should be able to: Describe the way that data is stored in the computer Describe the object model of programming Create proper identifiers in a C# program Describe the difference between an object and simple data Describe the simple data types in the C# language Write C# programs that correctly use declarations use assignment statements use literal data use the Console class format simple floating point data

4 Data Central to the idea of how a program works is
the concept of data. Every program you will ever write will deal with some kind of data.

5 That data might be … An image Some music A person’s name A person’s age A table of temperatures by week A list of scores for a gymnastic event A model of a molecule A model of a character in a game etc

6 Data is stored in the computer’s memory.
We can imagine computer memory to be something like a set of post office boxes.

7 Some boxes hold small things (like integers) Some boxes hold larger things (like real numbers) and each box has an address Some boxes hold really big things (like objects)

8 When we write a program, we need to reserve space
in memory for any data that the program will use. We do this by giving the data a name and telling the computer what kind of data it is. The computer translates this name into an address.

9 In order to be able to refer to the data stored at some
X000054EA – hex address 12 In order to be able to refer to the data stored at some address in the computer, we give the data at that address a name. These names are called identifiers.

10 Identifiers The name that you use to refer to a piece of data
or a method in C# is called an identifier. A C# identifier must begin with either a letter or an underscore character i.e. [a-z A-Z _] The remaining characters may be letters, digits, or the underscore character[a-z A-Z 0-9 _]. All other characters are invalid. Identifiers can be of any length. Identifiers are case sensitive.

11 Some Valid Identifiers
x x1 _abc sum data2 oldValue It is common in C# to run words together like this. Just capitalize all words after the first.

12 Some Invalid Identifiers
123 &change 1_dollar my-data

13 Good programmers select names that are meaningful
and somehow describe the data that they name.

14 For example, we might have a piece of data
that represents the area of a circle. x would be a bad choice to name that variable areaOfCircle would be a good choice

15 Keywords C# has a set of built in keywords that are considered to
be part of the language. You cannot use any of these as identifiers in your program. In Visual C# Express Edition, By default these will show up in blue. Examples include bool break char int double class const do

16 Programs deal with all kinds of data.
This data can be put into two broad categories. Simple Data the most basic forms of data - numbers and characters Objects more complex data – made up of many pieces of simple data. For example, a person’s address is usually made up of a House number and a street name – 123 Main Street.

17 Every piece of data has a given size and shape
and is stored at an address. The values that we store in a memory location must fit the size and shape that we specified for that address.

18 A Memory Chip

19 A Memory Chip Address: Where the data resides in memory Size: How many bits make up the data Shape: How the data is coded binary digits (bits)

20 Number Systems

21 Decimal: Base 10 In all number systems, each position represents a power of the base, where the rightmost digit is the multiplied by the base0, the next digit to the left is multiplied by base1, and so on. So 352 can be expressed in powers of 10 as (3 * 102) + (5 * 101) + (2 * 100) =

22 Binary: Base 2 In binary we only have two symbols with which to count, 0 and 1. We call these binary symbols “bits”, short for “binary digits”. If we group 8 of them together we have a byte, for example: What does this represent? Who knows? Maybe an integer, maybe a character, maybe an instruction or a pixel on your monitor or a tiny bit of music.

23 Binary: Base 2 Since the base is 2, the place value represents
a power of 2. So a number like 1100 means… (1 * 23) + (1 * 22) + (0 * 21) + (0 * 20) = …which would translate to 12 in decimal

24 Hexadecimal: Base 16 Here we need 16 unique symbols to count with, so 0 – 9 aren’t enough. To fill in the remaining equivalents of 10 – 15 in decimal, we use the letters A – F. So to count in hex, we use 0, 1, 2…8, 9, A, B, C, D, E, F. That gives us 16 unique symbols, where A16 = 1010, F16 = 1510 etc. Note that in documentation, we often express the base with a subscript, as in 3D2F16 (hex) or (binary).

25 Hexadecimal: Base 16 In hex, an number like C416 means…
(C * 161) + (4 * 160) + …which could be converted to decimal with (C * 16) + (4 * 1) = (1210 * 16) + 4 = 19610 (Note that the symbols 0 -9 have the same value in decimal and hex)

26 Hexadecimal: Base 16 The convenient thing about hex (which is not true of decimal) is that the base (16) is a power of 2, specifically 24 As a result, hex is a concise shorthand for binary, because each hex digit represents four binary digits.

27 Equivalent Values Decimal Binary Hex 0000 1 0001 2 0010 3 0011 4 0100
0000 1 0001 2 0010 3 0011 4 0100 5 0101 6 0110 7 0111 Decimal Binary Hex 8 1000 9 1001 10 1010 A 11 1011 B 12 1100 C 13 1101 D 14 1110 E 15 1111 F

28 Hexadecimal: Base 16 For example, we would write the binary equivalent of decimal 12 as 11002, or C16. For large binary numbers (like memory addresses), it is more convenient to write the address in hex. So can be shortened to 4B2516, which programmers often write as 0x4B25 or just x4B25. That said, keep in mind that in memory, on your hard drive and on the Internet, binary is the only format that computers use! Decimal and hex are for humans!

29 Simple Data Simple data elements all have a data type
that defines its size and shape and an identifier that is an alias for its address in memory. The data type defines the possible set of values that a simple data element can have, and the operations that can be performed on the data.

30 Simple Numeric Data Types
The C# language defines a number of different kinds of data. In this course we will mainly use the following numeric data types: Type Storage Max Value int 32 bits - 2,147,483,647 to 2,147,483,648 double 64 bits over 10308

31 Integer Numbers Integers are whole numbers they have no
fractional part. Integer operations include addition subtraction multiplication division remainder assignment

32 Examples of Integers 10 -5 327 2,905,301

33 Real Numbers Real numbers have fractional parts
Real numbers are often written in scientific format The most common real data type is double Operations on real numbers include addition subtraction division multiplication assignment

34 Examples of Real Numbers
10.5 -5.02 2,905, -1.56 X 10-4

35 Character data is defined by the keyword char
When interpreted as a character, certain bit patterns represent printable characters and control characters. Different standards exist for encoding characters The ASCII standard, finalized in 1968, uses 7 bits for each character. In the ASCII standard, is interpreted as the character ‘A’. The 8 bit ASCII standard was added later to increase the number of possible characters that could be encoded. 7 bits only allows for the definition of 128 unique characters. Subsequent standards (ISO8859 and ISO10646) define much larger, multi-national character sets. However, both are supersets of ASCII. Character data is defined by the keyword char

36 The ASCII Code Table 1st hex digit x41 = ‘A’ 2nd hex digit

37 Character Representation
Characters are stored in the computer’s memory in ASCII format. For example, using the standard ASCII code, the character ‘A’ would be stored as C# actually uses a superset of ASCII called Unicode, that supports a multiple byte character code and The character ‘A’ is stored as

38 Characters * Characters are written in C# programs as 'A', 'B', etc. * 'A' is stored as in memory or hex 0X41 or dec 65 * 'B' is stored as in memory or hex 0X42 or dec 66 * 'a' is stored as in memory or hex 0X61 or dec 97 * 'b' is stored as in memory or hex 0X62 or dec 98

39 Control Characters Control characters are characters that do
not print, but cause some action, such as moving to a new line, to occur. In C# we write control characters as a backslash, followed by a character that denotes the action to be taken. '\b' backspace '\t' tab '\n' new-line '\r' carriage return

40 Boolean Data A piece of Boolean data can only have one of two values:
true false Boolean data is defined by the keyword bool

41 Variables and Constants
A variable is a name for a memory location (address) that holds some piece of data. The value stored in that location may change during execution of the program; however, the type may not. A constant is a name for a memory location (address) that holds some piece of data, where the value of the data cannot change during execution of the program.

42 Declarations In C#, all variables and constants must be declared
before they are used in a program. C# is what is known as a strongly typed language. This means that we must tell the compiler what the data type is for every variable. The compiler then checks all operations to make sure that they are valid for the given type of data.

43 Question . . . Assume that you are able to peek into the memory of your computer, and you see the bit pattern What does this bit pattern mean?

44 The correct answer is that you don’t know.
Unless you know what type of data you are looking at, it is impossible to interpret the bits stored in memory.

45 Integer Representation
In most modern digital computers, integer numbers are stored internally in binary. The number of bits used to store an integer in C# is 32 bits. Example: the integer 5 is This is the sign bit, and when this bit is zero, the number is positive

46 Floating Point Representation
Numbers that contain decimal points are stored internally in a very different format. The exact format depends upon the processor used in the computer, but in general it looks like: sign exponent Mantissa or Coefficient for example, the number 6, ( x 104) would have sign of 0 an exponent of 4 and a mantissa of The actual binary representation is beyond the scope of this course.

47 Computer Instructions
Locations in memory can hold both data and instructions. A special register, called the program counter points in memory to the next instruction to be executed. The computer fetches the next instruction from memory. The program counter moves to the next instruction. The computer then decodes and executes the instruction it just fetched.

48 Machine Language We call the instructions stored in computer memory
machine language instructions. They are defined by the chip manufacturer. For example, the machine instruction might mean something like take the byte stored in memory location 0024 and put it into the A register.

49 Summary Integers straight binary representation
Real Numbers split into sign, exponent and coefficient Characters coded bytes – Unicode an ASCII superset Instructions coded bytes – machine language

50 Declaring a Variable int someNumber; char firstLetter; bool theAnswer;
this statement reserves space in computer memory for an integer. We can then refer to the data in this location using the name “someNumber” which is an alias for the the address in memory where the value is stored. int someNumber; char firstLetter; bool theAnswer; double density = 12.45; int hoursWorked = 14; char key = ‘g’; this statement reserves space in computer memory for a character. The bit pattern for ‘g’ is then stored in that location. We can now refer to the data in this location using the name “key” .

51 (an alias for its address)
data type (size & shape) int idata = 500; value (value in memory) identifier (an alias for its address)

52 Declaring a Variable int value1, value2, value3;
This statement, termed a comma delimited list, declares three variables, all of which are int’s with an unknown value .

53 Declaring a Variable int value1= 12, value2= 4, value3= 21;
This statement, comma delimited list, declares three variables, all of which are int’s, and initializes them.

54 Declaring a Constant const int SCALE_VALUE = 14;
The keyword const means that this is a constant. You cannot change the value after it is declared and initialized. const int SCALE_VALUE = 14; We normally use all upper case letters when writing the name of a constant.

55 Assignment The easiest way to change the value of a variable
is to use an assignment statement. temperature = 68.4; note that all statements end with a semicolon. the expression on the right side of the operator is evaluated and the resulting value is stored in the storage location allocated to the variable “temperature” the right hand side of the assignment statement may be a literal value, or an expression involving variables, literal values, and operators, or even method calls.

56 Assignment Compatibility
In general, it is invalid to assign a variable of one type to a variable of another. For example if you write int a = 6.52; The compiler will issue the warning Cannot implicitly convert type 'double' to 'int'. … This means you are trying to put a square peg in a round hole. It won’t fit. REMEMBER variables have sizes and shapes.

57 Assignment Compatibility
Note that you can do this assignment. double a = 6; The compiler will force a conversion. Why? Sort of like being able to put a round peg in a square hole

58 The compiler will allow you to do Widening Conversions double a = 3;
because no information will be lost. The compiler will not allow you to do Narrowing Conversions int pi = ; because information is lost.

59 Un-initialized Data In C#, numbers are not always initialized to a known value. Thus they may not always be what you expect. So …… always initialize data when it is declared.

60 Initializing Data int numOne = 5, numTwo = 4, numThree = 17;
int numTwo = 4; int numThree = 17;

61 Literal Data In the statement sum = a + 5;
the value 5 is what is called literal data. It is good programming practice to use constants instead of literal data in your program. Exceptions are 1, -1 and 0 const int MAX = 5; . sum = a + MAX;

62 We use the term “Magic Numbers” to refer to
literal data that is written into an expression in your program. double avgTemperature = sumTemperature / 2; This is a magic number You do not want magic numbers in your programs. They make programs hard to maintain. You will lose points if I see magic numbers in your programs.

63 Objects and Classes Object oriented languages give programmers the
ability to model real-world objects.

64 Data Methods for example, a car has attributes * it is black
* it has a 200 hp engine * it has 2 doors * it was built in 1943 * etc Data it also has behaviors * when you turn the key it starts * when you press the brake it stops * when you push the horn it beeps * etc Methods object-oriented languages encapsulate the data and the methods that operate on that data into an object.

65 an object’s methods (behaviors) manage specific pieces
of data (attributes) inside the object. methods outside of the object cannot see or manipulate the object’s data, which is private. However, they can call public methods inside the object to access the data. size color GetSize ( ) GetColor( ) External Method

66 Classes Later on, we will spend much more time talking
about objects and classes. For now, just think of a class as a blueprint that the computer uses when creating objects of that class. When we write an object oriented program, much of our time is devoted to designing and writing classes.

67 Languages that primarily deal with objects
are called object-oriented languages.

68 Some Convenient Classes
C# has built in to it some classes that will make our programming tasks much easier. The first of these we will talk about is the String class.

69 A string is just a sequence of characters.
“hello” “George” “12 East State Road”

70 Declare a string this way:
string myName;

71 Declare a string and give it an initial value this way:
string myName = “John Dolittle”;

72 Some Convenient Classes
The other important class we need to talk about is the Console class.

73 When a Console program executes, the C# runtime
environment automatically creates these two stream objects to help manage Console input and output. display buffer output buffer Console.Out program keyboard buffer keyboard buffer program Console.In

74 Console.ReadLine( ) The Console class provides the ReadLine( ) method to read data from the standard input stream, Console.In. This method waits for the user to type in some data and press the Enter key. The ReadLine( ) method returns the data that the user typed in as a string object. keyboard buffer keyboard buffer Console.In program

75 name = Console.ReadLine( );
String name; name = Console.ReadLine( ); John Doe keyboard buffer keyboard buffer John Doe Console.In name

76 When dealing with numbers, we have to use the
Parse method to convert the string value into the appropriate numerical data type int age = 0; age = int.Parse(Console.ReadLine( ) ); 25 keyboard buffer Parse method keyboard buffer 25 the string “25” age Console.In

77 When dealing with numbers, we have to use the
Parse method to convert the string value into the appropriate numerical data type double money = 0.0; money = double.Parse(Console.ReadLine( ) ); 12.50 keyboard buffer Parse method keyboard buffer 12.50 The string “12.50” money Console.In

78 Console.WriteLine The Console class provides the WriteLine( ) method to write To the standard output stream, Console.Out. This method takes a string as it’s parameter. After writing to the display, the cursor is moved to the next line. display buffer output buffer Console.Out program

79 Console.WriteLine string name = “Joe Coder”;
Console.WriteLine( name ); display buffer Joe Coder output buffer Console.Out Joe Coder name

80 Console.WriteLine Numbers are automatically converted to
strings by the WriteLine( ) method: double money = 12.50 Console.WriteLine( money); display buffer 12.50 output buffer Console.Out 12.50 money

81 Console.WriteLine You can combine string literals and numerical data
using the placeholder { .. } to mark the place where the numerical data should be displayed. double money = 12.50 Console.WriteLine( “You owe {0} to me”, money); display buffer You owe to me output buffer Console.Out 12.50 money

82 Console.WriteLine You can use a format string to format the output
double money = 12.50 Console.WriteLine( “You owe {0:C} to me”, money); display buffer You owe $12.50 to me output buffer Console.Out 12.50 money

83 Formatting Specifiers
D or d: Display an integer value as a decimal number F or f: Display a real value - default is two digits after the decimal point C or c: Display a real value as currency

84 With an integer you can use a number to
Formatting Strings With an integer you can use a number to indicate how many digits to display int number = 23; Console.WriteLine(“The value is {0:D4}”, number) The value is 0023

85 With a double you can use a number to indicate
Formatting Strings With a double you can use a number to indicate how many decimal digits to display double number = ; Console.WriteLine(“The value is {0:F3}”, number) The value is

86 You can arrange things on the screen by using numbers
Formatting Strings You can arrange things on the screen by using numbers to specify a field width and justify the output in the field. double number = ; Console.WriteLine(“The value is {0, 6:F2}”, number) 2 3 . 9 8 The value is _23.98 6 character field

87 Data displayed on a Graphical User Interface
must first be converted to a string. That string is then assigned to the Text Property of the control where you want to see it.

88 Suppose the name of this TextBox control is “outputTxtBox”
and we have an integer named sum to show there. outputTxtBox.Text = String.Format(“{0:d}”, sum);

89 Style When writing programs, in any programming
language, it is helpful to use a consistent style. Good software development organizations will often dictate that programmers use a specific style. This makes it easier for everyone to read the code that is being developed. Program that do not conform to the style guidelines for this class will lose points.

90 Style - Identifiers Use names that have meaning. Avoid single character, very short, or very long names. Examples: Meaningful Names Baffling Names amount a isFinished xl Constants All upper case with words separated by an underscore Example: SIZE Classes and Method names Title case (capitalization of the first letter in each word) Example: SimpleCalc( ) Data Variables Lower case for the first word and title case for every word thereafter. Example: myAccount

91 Style - Braces Many C# language statements do not require braces; however, some statements such as conditionals and loops may or may not require braces and it is good programming practice to provide them. Use braces liberally to visually delimit the beginning and end of code blocks. Including braces now avoids the possibility of errors creeping into your code when you add additional statements at the last minute. Place the opening (left) brace { so that it lines up with the left side of class headers, function headers, conditional statements, or repetitive statements. Place the closing (right) brace } in the same column as the opening brace. Always enter braces in opening/closing pairs to avoid forgetting to add one or the other or both. For braces that span more than three to five lines, comment the ending brace to indicate its nature (e.g., // end if ).

92 Indentation As you moved from block to block, indent
at least three spaces. Indentation makes code much more readable.

93 Example void reviewCode( ) { if ( meetsGuidelines )
Console.WriteLine(““Proceed to the next assignment”); } else Console.WriteLine(“Rework your documentation”); } // end if/else } // end reviewCode( )

94 Your Own Code Declaration
Every source code file must contain the following declaration. Code that does not contain this declaration will not be graded! "I declare that the following source code was written solely by me. I understand that copying any source code, in whole or in part, constitutes cheating, and that I will receive a zero on this project if I am found in violation of this policy.

95 Magic Numbers A magic number is any numeric literal other than 1, 0, or –1 used in your program. However if 1, 0 and –1 are used to represent something other than the integers 1, 0, or –1 they will be considered magic numbers. Unfortunately, most code you will see in C# books or programming books in general will include magic numbers because it’s easier to code in the short run. In the long run, six months from today, you will be clueless as to what the number means. Therefore, DON’T USE MAGIC NUMBERS in your assignments.

96 Comments Keep in mind that every program that you submit should
contain comments that describe how the program works. More on this later …

97 Where are variables stored?
If a variable is declared inside of the curly brackets, that define a method, then that variable is said to be local to the method. Only the code in the method can see a local variable. It is stored on the stack. If a variable is declared outside of the curly brackets, that define a method, then that variable is said to be a class level variable. It is stored in the data segment. It is available to any method in the program.

98 This is a local variable
using System; Class Program { const double PI = ; static void Main( ) double radius; . . . } Declared inside of curly braces – stack This is a local variable

99 This is a class level variable
using System; Class Program { const double PI = ; static void Main( ) double radius; . . . } Declared outside of any method – data segment It is a global variable. It is available to any method in the class Program. This is a class level variable

100 Practice Name the simple C# data types.

101 Practice Here is some data stored in the memory of the computer. What is it’s value?

102 Practice Suppose that you needed a Student object
in a course registration program. What attributes might a Student have? What behaviors might a Student require?

103 Practice In which part of computer storage is
each of the following stored? * A class level variable * A local variable

104 Practice Name one class that we have learned about in this lesson.

105 Practice Which method is used to convert data into its
character representation and send it to the standard output device? To what class does this method belong?

106 Practice Name a method that is used to convert numerical data
from its character representation and store it to in memory in its binary representation.

107 Practice Write a program that prints the message
“Hello, my name is Hal”. Then the program will prompt the user for his or her first name. It then Will print “Hello, user name, how are you?”

108 Practice Write a program that prints the message
“Hello, my name is Hal”. Then the program will ask the user for his or her name. Get the name and save it in a String object. Then print the message “Hello, user name, how are you?” Prompt the user to type in their age. Save it in an Integer. Then print the message “user name, you are n years old”

109 Practice Write a program that does the following:
Declares an integer, a double, and a character. In turn, asks the user to enter in an appropriate piece of data for each variable and stores it in that variable. Add together the integer and the double and the character. The result is stored in a double named sum. Print out the sum. Ask the user to type their name (first and last). Store their name in a string variable. Print out “Thank you (their name). Be able to discuss the results of your program.


Download ppt "Programs and Data."

Similar presentations


Ads by Google