Chapter Three
Constants, Variables, data Types and Operators
C++ tokens
:
Identifiers Names given to different entries such as variables, structures, and functions
Keywords: Reserved words which have fixed meaning and its meaning cannot be changed
Operators: A symbol that is used to perform mathematical or logical manipulations
Constants: Are like a variable, except that their value never changes during execution once
defined
Identifiers
Programmer given names
Identify classes, variables, functions, etc.
Consist of letters, digits, and the underscore character (_)
Must begin with a letter or underscore
Not be a reserved word, they are reserved for special purpose
C++ is case sensitive
Some predefined identifiers are cout and cin
Unlike reserved words, predefined identifiers may be
redefined, but it is not a good idea
Rules for naming C++ identifiers
Identifiers must begin with a letter or underscore( _ ).
No special characters are allowed in identifier naming,
only letters, digits or underscores can be used.
A keyword can’t be an identifier.
White space is not allowed within identifier
It should only be up to 31 characters long
Legal and Illegal Identifiers
The following are legal identifiers in C++:
first
conversion
payRate
Keywords (reserved words)
Words with special meaning to the compiler
Have a predefined meaning that can’t be changed
All reserved words are in lower-case letters
Must not be used for any other purposes
Example
and , auto, bool, break, char, const, default, delete ,do,
double, else, for, friend, new, void, if
Variables
A variable is a memory address where data can be stored and
changed.
Declaring a variable means specifying both its name and its
data type.
All variables have two important attributes
A type - Once defined, the type of a C++ variable cannot be
changed
A value - can be changed by assigning a new value
E.g. int a = 5;
Type integer
Value 5
Variable Declaration
All variables must declared before use.
At the top of the program
Just before use.
Commas are used to separate identifiers of the same type.
int count, age;
Variables can be initialized to a starting value when they
are declared
int count = 0;
int age, count = 0;
Variable Declaration
defining (creating) a variable
Two parts
Variable name - unique name of the memory location
Data type (or type) - defines what kind of values the variable
can hold
Syntax
<type> <Var-idf>;
E.g.
double varTime;
int myAge;
Can declare several variables of same type in one
declaration
Comma-separated list
int integer1, integer2, sum;
Variables must be declared before used
Variable names
Valid identifier
Series of characters (letters, digits, underscores)
Cannot begin with digit
Case sensitive
Assignment operator =
Assigns value on left to variable on right
Binary operator (two operands)
Example:
sum = variable1 + variable2;
Add the values of variable1 and variable2
Store result in sum
1 // Fig. 2.5: fig02_05.cpp
Outline
2
3
4
// Addition program that displays the sum of two numbers.
#include <iostream.h> // allows program to perform input and output
5 // function main begins program execution
6 int main()
7 {
8 // variable declarations
9 int number1; // first integer to add
10 int number2; // second integer to add
11 int sum; // sum of number1 and number2
12
13 cout << "Enter first integer: "; // prompt user for data
14 std::cin >> number1; // read first integer from user into number1
15
16 cout << "Enter second integer: "; // prompt user for data
17 cin >> number2; // read second integer from user into number2
18
19 sum = number1 + number2; // add the numbers; store result in sum
20
21 cout << "Sum is " << sum << std::endl; // display sum; end line
22
23 return 0; // indicate that program ended successfully
24
25 } // end function main
Enter first integer: 45
Enter second integer: 72
Sum is 117
Variables and Memory Concept
Variable names
Correspond to actual locations in computer's memory
Every variable has name, type, size and value
When new value placed into variable, overwrites old value
Writing to memory is destructive
Reading variables from memory nondestructive
Example
int number1= 45;
int number2= 72;
int sum = 0;
sum = number1 + number2;
Value of sum is overwritten
Values of number1 and number2 remain intact
CONSTANTS
Constants are treated just like regular variables except
that their values cannot be modified after their
definition
There are two simple ways in C++ to define constants
Using #define preprocessor.
Using const keyword
The #define Preprocessor
Following is the form to use #define preprocessor to
define a constant
#define identifier value
Eg,
RESULT
The const Keyword
Following is the form
const type variable = value;
Eg,
RESULT
Note that it is a good programming practice to define constants in CAPITALS.
Data Types
When you define a variable in C++, you must tell the
compiler what kind of variable it is
Tell the data type
Data Type: set of values together with a set of operations
C++ data can be classified into three categories:
Simple data type
Structured data type
Pointers
Simple Data Types
Three categories of simple data Type
Integral: integers (numbers without a decimal)
Floating-point: decimal numbers
Enumeration type: user-defined data type
Type Size Values
unsigned short int 2 bytes 0 to 65,535
short int(signed short 2 bytes -32,768 to 32,767
int)
unsigned long int 4 bytes 0 to 4,294,967,295
long int(signed long 4 bytes - 2,147,483,648 to 2, 147,483,647
int)
int 2 bytes -32,768 to 32,767
unsigned int 2 bytes 0 to 65,535
signed int 2 bytes -32,768 to 32,767
char 1 byte 256 character values
float 4 bytes 3.4e-38 to 3.4e38
double 8 bytes 1.7e-308 to 1.7e308
long double 10 1.2e-4932 to 1.2e4932
bytes
Simple Data Types
Type int
represent integers or whole numbers
Some rules to follow:
Plus signs do not need to be written before the number
Minus signs must be written when using negative
Decimal points cannot be used
Commas cannot be used
Leading zeros should be avoided
Signed - negative or positive
Unsigned - positive
Short
Long
Simple Data Types
Type double, float
used to represent real numbers
many programmers use type float
avoid leading zeros, trailing zeros are ignored
long double
Simple Data Types
Type char
used to represent character data
a single character which includes a space
1 byte, enough to hold 256 values
must be enclosed in single quotes eg. ‘d’
Escape sequences treated as single char
‘\n’ newline
‘\’’ apostrophe
‘\”’ double quote
‘\t’ tab
(0-255) or as a member of the ASCII set
E.g. the lowercase letter "a" is assigned the value 97
Simple Data Types
Strings
used to represent textual information
string constants must be enclosed in double quotation marks
eg. “Hello world!”
empty string “”
new line char or string “\n”
“the word \”hello\”” (puts quotes around “hello” )
[Link]
#include <iostream.h>
int main() {
float Length;
float Width;
// Extract length and width
cout << enter width and length: ";
cin >> Length >> Width;
// Compute and insert the area
float Area = Length * Width;
cout << "Area = " << Area << " =
Length "
<< Length << " * Width " << Width
<< endl;
return 0;}
Write a program that accepts a character from the user
and echo it to the screen.
Operator
A symbol that tells the compiler to perform specific
mathematical or logical manipulations
5 Operators
Arithmetic operators
Assignment operator
Increment/Decrement operators
Relational operators
Logical operators
Arithmetic Operators
Common
Addition +
Subtraction -
Multiplication *
Division /
Mod %
Integer Division
Integer division produces an integer result
Truncates the result
Examples
3 / 2 evaluates to 1
4 / 6 evaluates to 0
10 / 3 evaluates to 3
Mod
Produces the remainder of the division
Examples
5 % 2 evaluates to 1
12 % 4 evaluates to 0
4 % 5 evaluates to 4
Arithmetic Operators and Precedence
Consider m*x + b which of the following is it equivalent to
(m * x) + b
m * (x + b)
Operator precedence tells how to evaluate expressions
Standard precedence order
() Evaluate first, if nested innermost
done first
*/% Evaluate second. If there are several,
then evaluate from left-to-right
+- Evaluate third. If there are several,
then evaluate from left-to-right
Arithmetic Operator Precedence
Examples
20 - 4 / 5 * 2 + 3 * 5 % 4
(4 / 5)
((4 / 5) * 2)
((4 / 5) * 2) (3 * 5)
((4 / 5) * 2) ((3 * 5) % 4)
(20 -((4 / 5) * 2)) ((3 * 5) % 4)
(20 -((4 / 5) * 2)) + ((3 * 5) % 4)
Increment & Decrement Operators
Increment operator: increment variable by 1
Decrement operator: decrement variable by 1
Pre-increment:++variable
Post-increment: variable++
Pre-decrement: --variable
Post-decrement: variable--
Increment & Decrement Operators (continued)
++count; or count++; increments the value of count by
1
--count; or count--; decrements the value of count by 1
If x = 5; and y = ++x;
After the second statement both x and y are 6
If x = 5; and y = x++;
After the second statement y is 5 and x is 6
Assignment Operator
Assignment operator =
Assigns value on left to variable on right
Example:
int a= 5;
float b= 9.66;
char ch=‘d’;
int m, n, p;
m = n = p = 100;
Assignment Operator
Compound assignment Operator
+=, -=, *=, /=, %=
Compound assignment Operator
Relational Operators
Operator
Name Example
== Equality 5 == 5 // gives 1
!= Inequality 5 != 5 // gives 0
< Less Than 5 < 5.5 // gives 1
<= Less Than or Equal 5 <= 5 // gives
1
> Greater Than 5 > 5.5 // gives 0
>= Greater Than or Equal 6.3 >= 5 // gives 1
Relational operators
Logical Operators
Like the relational operators, logical
operators evaluate to 1 or 0.
Operator Name Example
! Logical Negation !(5 == 5) // gives 0
&& Logical And 5 < 6 && 6 < 6 // gives 0
|| Logical Or 5 < 6 || 6 < 5 // gives 1
Logical operators
Type conversion
A value in any of the built-in types can be converted
Called type cast
Syntax
(<data – type> )value; or <data – type> (value);
E.g
(int) 3.14 // converts 3.14 to an int to give 3
(long) 3.14 // converts 3.14 to a long to give 3L
(double) 2 // converts 2 to a double to give 2.0
(char) 122 // converts 122 to a char whose code is
122
(unsigned short) 3.14 // gives 3 as an unsigned short
Some times the compiler does the type casting – implicit
type cast
E.g
double d = 1; // d receives 1.0
int i = 10.5; // i receives 10
i = i + d;
End of 3rd chapter
43