Presentation is loading. Please wait.

Presentation is loading. Please wait.

CS 1400. Primitive data types Variables and constants Declarations Assignment Input and output Classes and objects Style.

Similar presentations


Presentation on theme: "CS 1400. Primitive data types Variables and constants Declarations Assignment Input and output Classes and objects Style."— Presentation transcript:

1 CS 1400

2 Primitive data types Variables and constants Declarations Assignment Input and output Classes and objects Style

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

4 In order to be able to refer to a piece of data in a program, we have to give that piece of data a name. These names are called identifiers.

5 The name that you use to refer to a piece of data or a function in C++ is called an identifier. A C++ identifier must begin with either a letter or an underscore character. [a-zA-Z_] The remaining characters may be letters, digits, or the underscore character. All other characters are invalid. [a-zA-Z_0-9]* Identifiers can be of any length. Be reasonable! Identifiers are case sensitive.

6 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.

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

8 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. A complete list can be found in your book. Examples include bool break char class const do …

9 A C++ program manages two general kinds of information Primitive Data the most basic forms of data - numbers and characters int, double, char, bool Objects more complex data – usually composed of many pieces of primitive data cout, cin, string, DATA

10 Primitive data elements all have a data type The data type defines the possible set of values that a primitive data element can have, and the operations that can be performed on the data.

11 TypeStorageMax Value short16 bits-32,766 to 32,767 int32 bits- 2,147,483,646 to 2,147,483,647 long32 bits- 2,147,483,646 to 2,147,483,647 float32 bitsover 10 38 double64 bitsover 10 308 integer types real types The amount of storage allocated to various data types is not defined by the C++ language, but is dependent upon the underlying hardware. The following are examples only, and may differ on your computer. there are unsigned version of each of integer types.

12 Integers are whole numbers they have no fractional part. The most common integer data type is int Integer operations include addition subtraction multiplication division remainder assignment

13 Examples of Integers 10 -5 327 2905301 1234567890L

14 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

15 Examples of Real Numbers 10.5 -5.02 327.981 2905301.004 0.0000239897F -1.56E -4

16 Different standards exist for encoding characters The ASCII standard, finalized in 1968, uses 7 bits for each character. In the ASCII standard, 1000001 is interpreted as the character ‘A’. 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 When interpreted as a character, certain bit patterns represent printable characters and control characters.

17 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. \bbackspace \ttab \nnew-line \rcarriage return \\back slash

18 A piece of Boolean data can only have one of two values: true ( none zero ) false (0) Boolean data is defined by the keyword bool

19 A variable is a name for a memory location that holds some piece of data. The value stored in that location may change during execution of the program. A constant is a name for a memory location that holds some piece of data, where the value of the data will not change during execution of the program.

20 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.

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

22 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 without knowing its type in storage.

23 In modern digital computers, integer numbers are stored internally in a binary format. The number of bits used to store an integer depends on the type of processor in the computer, but is typically 32 or 64 bits. Example: the integer 5, when stored in a typical Intel class machine is 00000000 00000000 00000000 00000101

24 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: signexponentMantissa or Coefficient for example, the number 6,045.03 (0.604503 x 10 4 ) would have an exponent of 4 and a mantissa of.604503 The actual binary representation is beyond the scope of this course.

25 Characters are stored internally in a coded format. For example, using the standard ASCII code, the character ‘A’ would be stored as 0100 0001. Most modern computer languages support a multiple byte character code called Unicode.

26 The ASCII Code Table

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

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

29 Integersstraight binary representation Real Numberssplit into sign, exponent and coefficient Characterscoded bytes – ASCII Instructionscoded words – machine language

30 int someNumber; char firstLetter; bool theAnswer; double density = 12.45; int hoursWorked = 14; char key = ‘g’; this statement reserves space in computer memory for an integer. We can then refer to the data in this location using the name “someNumber. ” C++ does not initialize variables. 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”

31 int value1, value2, value3; //comma delimited list better int value1; int value2; int value3; This statement defines three variables, all of which are ints.

32 int value1= 12, value2= 4, value3= 21; better int value1 = 12; int value2 = 4; int value3 = 21; This statement defines three variables, all of which are ints, and initializes them.

33 const double PI = 3.1416; const int SCALE_VALUE = 14; The keyword const means that this is a constant. You cannot change the value after it is declared. We normally use all upper case letters when writing the name of a constant.

34 Consider the following declaration: const float PI = 3.14159F; the decimal signals that this is a real number the F signals that this literal value is a float data type and not a double (the default).

35 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 right hand side of the assignment statement may be a literal value, or an expression involving variables, literal values, and operators, or even function calls. 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” rvalue lvalue

36 In general, it is invalid to assign a variable of one type to a variable of another. For example, int a = 6.52; The compiler will issue the warning “conversion from 'double' to 'int', possible loss of data” This means that the code will compile, but may not produce the results expected.

37 Note that you can do this assignment. float a = 6; The compiler will force a conversion to 6.0

38 The compiler will allow you to do Widening Conversions float a = 3; because no information is lost. The compiler will warn you if you do Narrowing Conversion int pi = 3.14159; because information will be lost.

39 In C++, no initialization is done when a data element is declared. The value of that data element will be based on whatever bits happen to be in that storage location when your program starts execution. It will likely be something (bad) left over from another running program! So …… always initialize data when it is declared.

40 int numOne = 5, numTwo = 4, numThree = 17; int numOne (5), numTwo (4), numThree (17); int numOne = 5; int numTwo = 4; int numThree = 17;

41 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. const int MAX = 5;. sum = a + MAX; Exceptions are 1, -1 and 0

42 We use the term “Magic Numbers” to refer to literal data that is written into an expression in your program. double avgTemperature = sumTemperature / 10; 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.

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

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

45 size color getSize ( ) getColor( ) an object’s functions manage specific pieces of data inside the object. External Function functions outside of the object cannot see or manipulate the object’s data, which is private. However, they can call public functions inside the object to access the data. object

46 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. When we write an object oriented program, much of our time is devoted to designing and writing classes. ostream (class) cout (object) istream (class) cin (object) string (class) stg (object)

47 Languages that primarily deal with objects are called object-oriented languages. Pure object oriented languages, like C# and Java, treat everything as an object. C++ is sometimes called a hybrid language, because it has elements of a procedural language and an object-oriented language.

48 The C Language The C++ Language The C language is a pure procedural language. It was developed at AT&T’s Bell Labs in the 1970s by Brian Kernihan and Dennis Ritchie. It was first used for writing and maintaining the Unix operating system. Bjarne Stroustrup of Bell Labs developed the C++ language in the early 1980’s by adding object oriented capabilities to C (C with classes).

49 C++ has built in to it some objects that will make our programming tasks much easier. The first of these we will introduce are cin and cout

50 cin an object of the istream class (#include ). This object represents the standard input stream. The cin object is created automatically for you. keyboard buffer cin program keyboard buffer

51 cout an object of the ostream class (#include ). This object represents the standard output stream. It is also created automatically for you. output buffer cout program display buffer

52 a binary operator (it takes two operands) the left hand operand must be an output stream the right hand operand is converted into text the text data is then copied into the stream

53 display buffer int a = 5; a 0000 0000 0000 0101 the integer 5 0000 0000 0011 0101 the character 5 cout cout << a; 5

54 multiple pieces of data are output by cascading the << operator … cout << “The answer is “ << a;

55 special characters are added to the stream using the escape character \ \t//tab \n//newline etc … cout << “The answer is “ << a << ‘\n’;

56 the endl stream manipulator can be added to the output stream. It does two things: It adds a new line to the stream. It forces the buffer to be output cout << “Hello” << endl;

57 When outputting numbers with fractional parts we have to take care to make the output appear just as we would like it. This does not happen automatically.

58 To display a double or a float in standard decimal notation cout.setf(ios::fixed); setf( ) is a function in the cout object. It is responsible for setting formatting flags. We will study these in much more detail in a later section. In this case, we are setting the ios::fixed flag. This makes the output appear as a normal decimal number instead of in scientific notation. cout.setf(ios::showpoint); the ios::showpoint flag guarantees that a decimal point will be displayed in the output. cout.precision(2); the cout.precision( ) function determines how many digits will be displayed after the decimal point. The default formatting, is the “general” format. In this case precision defines the number of digits in total to be displayed

59 double price = 78.5; cout.setf(ios::fixed); cout.setf(ios::showpoint); cout.precison(2); cout << “The price is $” << price << endl;

60 Also a binary operator The left operand must be an input stream Any initial white space is skipped, then the stream is read up to the next white space character ( tab, space, new-line ) If necessary, the text just read is converted to match the type of the right operand. An error occurs if the conversion cannot be done. The data is stored in the right operand

61 keyboard buffer cin int a; cin >> a; a 0000 0000 0011 0101 the character 5 0000 0000 0000 0101 5 72 hello reading stops when white space is encountered

62 you can also cascade the stream extraction operator : cin >> a >> b;

63 You can control the size of an input field with the setw( n ) stream manipulator. cin >> setw(5) >> title;

64 The get function of the istream class works similar to the stream extraction operator. With no parameter, it gets one character from the input stream. cin.get( );

65 This function is similar to cin.get( )except that it reads an entire line of data, including spaces, and the data is stored in a string object. This is the preferred way of reading in a line of data. getline(cin, stringName);

66 This function reads in a character and ignores it. The character read in is discarded. cin.ignore( );

67 This version of the function reads in n characters and ignores them. cin.ignore(n); This version of the function reads in n characters or until it encounters the delimiter character, and ignores the characters read. cin.ignore(n, ‘\n’);

68 Why is this useful? Try the following code… int numItems; string description; cout << “\nenter the number of items and description: “; cin >> numItems; getline(cin, description); When prompted, enter the data on two lines.

69 if(cin.rdbuf()->in_avail()!=0) cin.ignore(80,'\n');

70 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 maintain the code that is being developed. In this course, you are expected to follow certain style guidelines. They are available on the course web site.

71 Use names that have meaning. Avoid single character, very short, or very long names. Examples:Meaningful NamesBaffling Names amounta isFinishedxl Constants All upper case with words separated by an underscore Example:SIZE Classes Title case (capitalization of the first letter in each word) Example:class ImpleCalc{…} Function names and Variables Lower case for the first word and title case for every word thereafter. Example:makeDeposit( )

72 Even though the C++ language does not always require braces for some statements 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 ).

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

74 void reviewCode( ) { if ( meetsGuidelines ) { cout << “Proceed to the next assignment”; } else { cout << “Rework your documentation”; } //End if/else } //End reviewCode( )

75 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.

76 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.

77 Where are variables stored? If a variable is declared inside of the curly brackets that define a function, then that variable is said to be local to the function. It is stored on the stack segment. If a variable is declared outside of the curly brackets, that define a function, then that variable is said to be global and is stored in the data segment. The code is stored in the code segement.

78 #include using namespace std; const float PI = 3.14149; int main( ) { float radius; cout <<... } Declared inside of curly braces – stack seg This is a local variable Declared outside of curly braces – global (data seg)

79 #include using namespace std; const float PI = 3.14149; int main( ) { float radius; cout <<... } Declared outside of curly braces – data segment This is a global variable

80 Name the basic C++ data types.

81 Here is some data stored in the memory of the computer. 0000 0000 0000 1001 What is it’s value?

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

83 Practice What kind of language is C++? * Object Oriented * Procedural * Hybrid

84 Practice In which part of computer storage is each of the following stored? * A global variable * A local variable

85 Name two objects that we have learned about in this lesson. To what class do they belong? Name the classes that these objects are instantied from. What is string?

86 Which operator is used to convert data into its character representation and output it to the standard output device?

87 Which operator is used to convert data from its character representation and store it to in memory in its binary representation?

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

89 Write a program that prints the message “Hello, my name is Hal”. Then the program will prompt the user for his or her name. It then Will print “Hello, user name, how are you?” Prompt the user to type in their age. Then print “ user name, you are n years old”

90 Write a program that prints the message “Hello, my name is Hal”. Then the program will prompt the user for his or her age. Then prompt the user to type in their full name. Then print “ Hello user name, you are n years old”

91 Write a program that prints the message “C++ Rocks!”. Inside a rectangle. Use |, +, and – to draw the rectangle. Your output should look like +-------------+ | C++ Rocks | +-------------+


Download ppt "CS 1400. Primitive data types Variables and constants Declarations Assignment Input and output Classes and objects Style."

Similar presentations


Ads by Google