LECTEURE # 5 : STRUCTURED PROGRAMMING Variables , input , memory Tr.Hadeel 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 Tr.Hadeel@hotmail.com Variable 3 Location on computer’s memory to store data then use and change its value in a program Each variable has 1. 2. Name (identifier) Series of letters, digits, underscores Not a keyword Start with a letter Case sensitive Meaningful Type Programmer-defined Tr.Hadeel@hotmail.com Determine which of the following variables name is valid or invalid : 4 _under_bar_ z2 h22 2h 67h2 his_account_total t5 87 m928134 her_sales 3g j7 a b c Tr.Hadeel@hotmail.com C++ Built-in Data Types 5 Called fundamental types or primitives types: numeric, character, logical bool Data Type 6 Has two values, true and false Manipulate logical (Boolean) expressions true and false are called logical values bool, true, and false are reserved words Tr.Hadeel@hotmail.com char Data Type 7 Used for characters Each character is enclosed in single quotes letters, digits, and special symbols Examples: 'A', 'a', '0', '*', '+', '$', '&' A blank space is a character and is written ' ' with a space left between the single quotes Tr.Hadeel@hotmail.com Declaring Variables 8 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 dataType varName; Variables of the same type can be declared in Multiple lines One line separated by commas int num1; int num2; int num3; int num1, num2, num3; Tr.Hadeel@hotmail.com Initializing Variable 9 Variables can be initialized once declared int first=13, second=10; char ch=' '; double x=12.6, y=123.456; first and second are int variables with the values 13 and 10, respectively ch is a char variable whose value is empty x and y are double variables with 12.6 and 123.456, respectively Tr.Hadeel@hotmail.com Using cin 10 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> Tr.Hadeel@hotmail.com Using cin (cont.) 11 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 Tr.Hadeel@hotmail.com 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 // Fig. 2.5: fig02_05.cpp // Addition program that display the sum of two numbers. #include <iostream> // allow program to perform input and output // function main begins program execution int main() { Declare integer variables. // variable declaration int number1; // first integer to add int number2; // second integer to add Use and stream extraction int sum; // sum of number1 number2 std::cout << "Enter std::cin >> number1; operator with standard input to obtain input. user first stream integer: \n"; user // prompt for data // read first integer from user to number1 Calculations can be performed in output statements: alternative for std::cout << "Enter second integer: \n"; // prompt user for data lines 19 and 21: std::cin >> number2; // read second integer from user to number2 Stream manipulator std::cout << "Sum is " << number1 + number2outputs << std::endl; std::endl a sum = number1 + number2; // add the numbers; stor result in sum newline, then “flushes output std::cout << "Sum is " << sum << std::endl; // display buffer.” sum; end line return 0; // indicate that program ended successfully } // end function main Enter first integer 45 Enter second integer 72 Concatenating, chaining or cascading stream insertion operations. Sum is 117 Tr.Hadeel@hotmail.com 12 Variable Scope 13 Portion of the program where the variable can be used Scope can be Local Global Tr.Hadeel@hotmail.com Local Variables 14 Defined within a module Can be seen and used only by module itself Store temporally in memory Erased when the module terminates int main() { int i; char a; return 0; } Tr.Hadeel@hotmail.com Global Variables 15 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 (::) int i; int main() { char a; return 0; } Tr.Hadeel@hotmail.com Unary Scope Resolution Operator 16 Denoted as ( :: ) Used to declare local and global variables have a same name To avoid conflicts Syntax rule ::variable y = ::x + 3 Not needed if names are different Tr.Hadeel@hotmail.com 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 // Fig. 6.23: fig06_23.cpp // using the unary scope resolution operator. #include <iostream> using std::cout; using std::endl; int number = 7; // global variable named number int main() { double number = 10.5; // local variable named number // display values of local and global variables cout <<“local double value of number = “ << number << “\nGlobal int value of number = “ << ::number << endl; return 0; // indicate successful termination } // end main Local double value of number = 10.5 Global int value of number = 7 Tr.Hadeel@hotmail.com 17 Variables and Memory 18 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 Tr.Hadeel@hotmail.com Variables and Memory (cont.) 19 std::cin >> number1; Assume user entered 45 std::cin >> number2; Assume user entered 72 sum = number1 + number2; number1 45 number1 45 number2 72 number1 45 number2 72 sum Tr.Hadeel@hotmail.com 117 Constants 20 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 const char Gender = ‘F’; With #define keyword #define studentsPerClass 15 Tr.Hadeel@hotmail.com Compatible C++ Data Types 21 Data types Highest long double double float unsigned long int (synonymous with unsigned long) long int (synonymous with long) unsigned int int (synonymous with unsigned) unsigned short int (synonymous with unsigned short) short int unsigned char char bool (synonymous with short) Lowest Tr.Hadeel@hotmail.com Converting Data Types 22 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 Tr.Hadeel@hotmail.com Implicit Conversion 23 Promote to double Mixed Type Expressions double double avg = total int / cnt ; Assignment statement int x int = 7.5 ; double Demote to int fraction part is truncated warning : conversion from 'double' to 'int', possible loss of data Tr.Hadeel@hotmail.com Explicit Conversion - Typecasting 24 C-like notation int a double b = = 2000; b; (double) a; Functional notation b = double (a); Using keyword static_cast b = static_cast<double>(a); Tr.Hadeel@hotmail.com Enumerated Data Types 25 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 }; Tr.Hadeel@hotmail.com Enumerated Data Types (cont.) 26 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; Tr.Hadeel@hotmail.com Enumerated Data Types (cont.) 27 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 Tr.Hadeel@hotmail.com Enumerated Data Types (cont.) 28 You can NOT 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? Tr.Hadeel@hotmail.com Exercise - 1 29 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 Tr.Hadeel@hotmail.com 30 End Tr.Hadeel@hotmail.com