Lecture 2 Working With Data-1
Lecture 2 Working With Data-1
• Learn how to work with data of different types in your C++ programs
• Learn how to declare and assign data to variables
• Learn how to use mathematical operators and order of precedence
DECLARING VARIABLES
• Name variables
• Variable declaration
• Constants
• A constant, like a variable, is a memory location where a value can be stored.
• The value of a constant cannot be changed while program is running
• Constants must be initialised at creation.
• C++ has two types of constants: literal and symbolic.
• Literal constants
• Value taken literally at each use
DECLARING AND USING CONSTANTS AND
VARIABLES
• Numeric constants
• A constant declared to store a numeric value
• Unnamed constants
• No identifier is associated with it
• Named constants
• Has a data type, name, and value
• Can be assigned a value only once
The keyword const is used when declaring a new symbolic constant.
C++ IDENTIFIERS
• A C++ identifier is a name used to identify a variable, function, class, module, or any other user-
defined item.
• Boolean – bool
• The wchar_t (wide character type) type comprises at least 2 bytes (16 bits)
EXAMPLES OF CHARACTER CONSTANTS
'A' Capital A 65
'a' Lowercase a 97
'' Blank 32
'.' Dot 46
'0' Digit 0 48
'\0' Terminating null character 0
EXAMPLES OF CHARACTER CONSTANTS
SAMPLE PROGRAM USING CHARACTERS
• #include <iostream>
• using namespace std;
• int main()
• {
• cout << "\nThis is\t a string\n\t\t"
• " with \"many\" escape sequences!\n";
• return 0;
• }
RANGE OF CHARACTER AND INTEGER DATA
TYPES
• Order of values:
• The short type comprises at least 2 bytes and the long type at least 4 bytes.
• The current value ranges are available in the climits header file.
• This file defines constants such as CHAR_MIN, CHAR_MAX, INT_MIN, and INT_MAX, which
represent the smallest and greatest possible values.
RANGE OF INTEGER DATA TYPE
• #include <iostream>
• #include <climits> // Definition of INT_MIN, ...
• using namespace std;
• int main()
• {
• cout << "Range of types int and unsigned int"
• << endl << endl;
• cout << "Type Minimum Maximum"
• << endl
• << "--------------------------------------------"
• << endl;
• cout << "int " << INT_MIN << " "
• << INT_MAX << endl;
• cout << "unsigned int " << " 0 "
• << UINT_MAX << endl;
• return 0;
FLOATING-POINT NUMBER DATA TYPES
Oh what
a happy day!
Oh yes,
what a happy day!
• Use the manipulator endl (end of line) or the new line character (\n) where appropriate.
• Exercise 2
• The following program contains several errors:
• */ Now you should not forget your glasses //
• #include <stream>
• int main
• {
• cout << "If this text",
• cout >> " appears on your display, ";
• cout << " endl;"
• cout << 'you can pat yourself on '
• << " the back!" << endl.
• return 0;
• )
• Rewrite the program in the correct way on paper. (10 marks)
END OF LECTURE