introduction and basics in · 2/4/2014 · content 2 variables c++ built in data types c++...
TRANSCRIPT
STRUCTURED
PROGRAMMING
Variables
Content 2
Variables
C++ Built in data types
C++ variable declaration syntax
cin statement
Local and global variables
Scope resolution operator (::)
Variables and RAM
Defining constants
Typecasting
Enumerated data types
Objectives 3
By the end you should be able to:
Understand what a variable is and why they are used
Declare, naming, and initialize variables and constants
Use C++ Built in data types to create program variables
Differentiate between constants, and variables
Recognize the ways that can be used to change the data stored in variables
Apply C++ syntax rules in reading user input using cin stream and iostream library
Explain what is meant by the scope of a variable
Differentiate between local and global variables
Recognize the ways how can we convert from one type to another
Declare, initialize, and manipulate enumerated data types
Create, trace, and debug programs containing input and output
Variable
Location on computer’s memory to store data then use and change
its value in a program
Each variable has
1. Name (identifier)
Series of letters, digits, underscores
Not a keyword
Start with a letter
Case sensitive
Meaningful
2. Type
Programmer-defined
Built-in
4
C++ Built-in Data Types
Called fundamental types or primitives types: numeric, character,
logical
5
bool Data Type
Has two values, true and false
Manipulate logical (Boolean) expressions
true and false are called logical values
bool, true, and false are reserved words
6
char Data Type
Used for characters
letters, digits, and special symbols
Each character is enclosed in single quotes
Examples: 'A', 'a', '0', '*', '+', '$', '&'
A blank space is a character and is written ' ' with a space left
between the single quotes
7
Declaring Variables
All variables must be declared anywhere in program with a name
and data type before they used
Syntax rule: begin with a data type then variable name
Variables of the same type can be declared in
Multiple lines
One line separated by commas
8
int num1;
int num2;
int num3;
int num1, num2, num3;
dataType varName;
string Data Type
Used to store data as a text ( a sequence of characters)
Ex: “This is some text”
String should be enclosed within double quotation “ ”
To declare a variable of type string should refer to the header file
named string
9
#include <string>
using namespace std;
int main()
{
string studentName;
return 0;
}
Initializing Variable
Variables can be initialized once declared
first and second are int variables with the values 13 and 10,
respectively
ch is a char variable whose value is empty
st is a string variable whose value is Amal
x and y are double variables with 12.6 and 123.456, respectively
10
int first=13, second=10;
char ch=' ';
string st=“Amal”;
double x=12.6, y=123.456;
Using cin
Namespace
std::
Specifies using a name that belongs to “namespace” std
Can be removed through use of using statements
Standard output stream object
std::cin
“Connected” to keyboard
Defined in input/output stream header file <iostream>
11
Using cin (cont.)
Stream extraction operator >>
Value to left (left operand) inserted into right operand
Waits for user to input value then press Enter key
Example
std::cin >> num1;
Inserts the standard input from keyboard into variable num1
Prints message before cin statement to direct the user to take a
specification called prompt
cin and cout facilitate interaction between user and program
12
13
Enter first integer
45
Enter second integer
72
Sum is 117
1 // Fig. 2.5: fig02_05.cpp
2 // Addition program that display the sum of two numbers.
3 #include <iostream> // allow program to perform input and output
4
5 // function main begins program execution
6 int main()
7 {
8 // variable declaration
9 int number1; // first integer to add
10 int number2; // second integer to add
11 int sum; // sum of number1 and number2
12
13 std::cout << "Enter first integer: \n"; // prompt user for data
14 std::cin >> number1; // read first integer from user to number1
15
16 std::cout << "Enter second integer: \n"; // prompt user for data
17 std::cin >> number2; // read second integer from user to number2
18
19 sum = number1 + number2; // add the numbers; stor result in sum
20
21 std::cout << "Sum is " << sum << std::endl; // display sum; end line
22
23 return 0; // indicate that program ended successfully
24 } // end function main
Declare integer variables.
Use stream extraction
operator with standard input
stream to obtain user input.
Stream manipulator std::endl outputs a
newline, then “flushes output
buffer.”
Concatenating, chaining or
cascading stream insertion
operations.
Calculations can be performed in output statements: alternative for
lines 18 and 20:
std::cout << "Sum is " << number1 + number2 << std::endl;
Variable Scope
Portion of the program where the variable can be used
Scope can be
Local
Global
14
Local Variables
Defined within a module
Can be seen and used only by module itself
Store temporally in memory
Erased when the module terminates
15
int main()
{
int i;
char a;
return 0;
}
Global Variables
Defined outside any module
Used and seen by all modules
Variable name can be duplicated within and outside a modules
Differentiate between them by using unary scope resolution operator (::)
16
int i;
int main()
{
char a;
return 0;
}
Unary Scope Resolution Operator
Denoted as ( :: )
Used to declare local and global variables have a same name
To avoid conflicts
Syntax rule
Not needed if names are different
17
y = ::x + 3
::variable
18
1 // Fig. 6.23: fig06_23.cpp
2 // using the unary scope resolution operator.
3 #include <iostream>
4 using std::cout;
5 using std::endl;
6
7 int number = 7; // global variable named number
8
9 int main()
10 {
11 double number = 10.5; // local variable named number
12
13 // display values of local and global variables
14 cout << “local double value of number = “ << number
15 << “\nGlobal int value of number = “ << ::number << endl;
16 return 0; // indicate successful termination
17 } // end main
Local double value of number = 10.5
Global int value of number = 7
Variables and Memory
Variables names correspond to location in the computer’s memory
(RAM)
Every variable has name, type, size and value
Placing new value into variable (memory location), overwrites old
value – called destructive
Reading value of variable in memory – called nondestructive
19
Variables and Memory (cont.)
std::cin >> number1;
Assume user entered 45
std::cin >> number2;
Assume user entered 72
sum = number1 + number2;
20
number1 45
number1 45
number2 72
number1 45
number2 72
sum 117
Constants
Like variables
data storage locations
Unlike variables
Values never changed during program execution
Any attempt to change a const creates a compilation error
Declared in two ways and follow identifier naming rules
With const keyword
With #define keyword
21
const char Gender = ‘F’;
#define studentsPerClass 15
Compatible C++ Data Types 22
Data types
long double
double
float
unsigned long int (synonymous with unsigned long)
long int (synonymous with long)
unsigned int (synonymous with unsigned)
int
unsigned short int (synonymous with unsigned short)
short int (synonymous with short)
unsigned char
char
bool
Highest
Lowest
Converting Data Types
Convert variables or expression of a given type into another type
Two kinds of conversion
Implicit conversion
Explicit conversion
May include
Promotion: converting from low to high data type
Demotion: converting from high to low data type
23
Implicit Conversion
Mixed Type Expressions
double avg = total / cnt ;
Assignment statement
int x = 7.5 ;
24
double int
Promote to double
double int
Demote to int fraction part is truncated
warning : conversion from 'double' to 'int',
possible loss of data
Explicit Conversion - Typecasting
C-like notation
int a = 2000;
double b;
b = (double) a;
Functional notation
b = double (a);
Using keyword static_cast
b = static_cast<double>(a);
25
Enumerated Data Types
Enable to create new types and then define variables of these types
Syntax rule
Write the keyword enum followed by new type name
List legal values separated by a comma within braces
enum COLOR { RED, BLUE, GREEN, WHITE, BLACK };
26
Enumerated Data Types (cont.)
Every enumerated constant has an integer value
enum COLOR { RED=100, BLUE, GREEN=500, WHITE, BLACK=700 };
If you don’t specify integer values, the first constant has the value 0, and the
rest count up from there
Variable declaration and manipulation
Color dress;
dress = RED;
27
Enumerated Data Types (cont.)
Every enumerated constant has an integer value
enum Day { MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY };
In memory...
MONDAY = 0 TUESDAY = 1 WEDNESDAY = 2 ..etc
Using the Day declaration, the following code...
Day d = FRIDAY ;
cout << MONDAY << " " << WEDNESDAY << " " << d << endl;
..will produce this output: 0 2 4
28
Enumerated Data Types (cont.)
You canNOT directly assign an integer value to an enum variable
Day workDay ;
workDay = 3; // Error!
Instead, you must cast the integer:
workDay = static_cast<Day>(3);
You CAN assign an enumerator to an int variable
int x; x = THURSDAY; x = workDay ;
.. What is the value of x in each statements above?
29
Exercise - 1 30
1. Write a program that declares two constant A and B
2. Initialize A =1 and B=2.2
3. Declare an int named C and float named D
4. Initialize C =A and D=B
5. Write statements to print C and D to screen
Included Sections 31
Chapter 2: from section 4 and 5