Chapter 8 - Notes User-Defined Simple Data Types, Namespaces, and the string Type

Similar documents
CSC 307 DATA STRUCTURES AND ALGORITHM ANALYSIS IN C++ SPRING 2011

6. User Defined Functions I

Chapter 2: Basic Elements of C++

Objectives. Chapter 2: Basic Elements of C++ Introduction. Objectives (cont d.) A C++ Program (cont d.) A C++ Program

Chapter 2: Basic Elements of C++ Objectives. Objectives (cont d.) A C++ Program. Introduction

Lab # 02. Basic Elements of C++ _ Part1

Objectives. In this chapter, you will:

Data Types. Chapter 8

CS242 COMPUTER PROGRAMMING

C++ Programming: From Problem Analysis to Program Design, Third Edition

Input And Output of C++

LECTURE 02 INTRODUCTION TO C++

Review of Important Topics in CS1600. Functions Arrays C-strings

The C++ Language. Arizona State University 1

1- Write a single C++ statement that: A. Calculates the sum of the two integrates 11 and 12 and outputs the sum to the consol.

Programming. C++ Basics

Chapter 3 - Notes Input/Output

Tokens, Expressions and Control Structures

! A program is a set of instructions that the. ! It must be translated. ! Variable: portion of memory that stores a value. char

Computer Programming : C++

Chapter 4 - Notes Control Structures I (Selection)

C++ Basic Elements of COMPUTER PROGRAMMING. Special symbols include: Word symbols. Objectives. Programming. Symbols. Symbols.

Chapter 2. C++ Syntax and Semantics, and the Program Development Process. Dale/Weems 1

Chapter 2 Basic Elements of C++

Programming Fundamentals. With C++ Variable Declaration, Evaluation and Assignment 1

Chapter 7 - Notes User-Defined Functions II

Lecture 3 The character, string data Types Files

switch case Logic Syntax Basics Functionality Rules Nested switch switch case Comp Sci 1570 Introduction to C++

Chapter 2: Overview of C++

Variables. Data Types.

CSc Introduction to Computing

! A literal represents a constant value used in a. ! Numbers: 0, 34, , -1.8e12, etc. ! Characters: 'A', 'z', '!', '5', etc.

By the end of this section you should: Understand what the variables are and why they are used. Use C++ built in data types to create program

BITG 1233: Introduction to C++

BASIC ELEMENTS OF A COMPUTER PROGRAM

COMP322 - Introduction to C++ Lecture 02 - Basics of C++

CPE 112 Spring 2015 Exam III (100 pts) April 8, True or False (12 Points)

CS2141 Software Development using C/C++ C++ Basics

Enumerated Types. Mr. Dave Clausen La Cañada High School

Introduction to C++ General Rules, Conventions and Styles CS 16: Solving Problems with Computers I Lecture #2

The University of Alabama in Huntsville Electrical and Computer Engineering CPE Example of Objective Test Questions for Test 4

UNIT- 3 Introduction to C++

Name Section: M/W or T/TH. True or False (14 Points)

C++ Basics. Lecture 2 COP 3014 Spring January 8, 2018

Chapter 2: Introduction to C++

PART I. Part II Answer to all the questions 1. What is meant by a token? Name the token available in C++.

Chapter 2: Special Characters. Parts of a C++ Program. Introduction to C++ Displays output on the computer screen

CHAPTER 1.2 INTRODUCTION TO C++ PROGRAMMING. Dr. Shady Yehia Elmashad

Overview. - General Data Types - Categories of Words. - Define Before Use. - The Three S s. - End of Statement - My First Program

Introduction to Programming EC-105. Lecture 2

CSC 126 FINAL EXAMINATION FINAL Spring 2012 B. Name (last, First) Instructor. Total Possible. Received

Basic memory model Using functions Writing functions. Basics Prototypes Parameters Return types Functions and memory Names and namespaces

CSCE 206: Structured Programming in C++

CSCE 206: Structured Programming in C++

Programming Language. Functions. Eng. Anis Nazer First Semester

Review: Exam 1. Your First C++ Program. Declaration Statements. Tells the compiler. Examples of declaration statements

Intro to Programming & C Why Program? 1.2 Computer Systems: Hardware and Software. Why Learn to Program?

Starting Out with C++: Early Objects, 9 th ed. (Gaddis, Walters & Muganda) Chapter 2 Introduction to C++ Chapter 2 Test 1 Key

COMP322 - Introduction to C++

Chapter-8 DATA TYPES. Introduction. Variable:

CSc 10200! Introduction to Computing. Lecture 2-3 Edgardo Molina Fall 2013 City College of New York

7/8/10 KEY CONCEPTS. Problem COMP 10 EXPLORING COMPUTER SCIENCE. Algorithm. Lecture 2 Variables, Types, and Programs. Program PROBLEM SOLVING

C++ Basics. Data Processing Course, I. Hrivnacova, IPN Orsay

2.1. Chapter 2: Parts of a C++ Program. Parts of a C++ Program. Introduction to C++ Parts of a C++ Program

Fundamentals of Programming CS-110. Lecture 2

2 nd Week Lecture Notes

CS101: Fundamentals of Computer Programming. Dr. Tejada www-bcf.usc.edu/~stejada Week 1 Basic Elements of C++

Introduction to C++ Professor Hugh C. Lauer CS-2303, System Programming Concepts

Introduction to C++ Systems Programming

GE U111 Engineering Problem Solving & Computation Lecture 6 February 2, 2004

Getting started with C++ (Part 2)

Computer Science II Lecture 1 Introduction and Background

CSC 126 FINAL EXAMINATION Spring Total Possible TOTAL 100

Name SECTION: 12:45 2:20. True or False (12 Points)

ME240 Computation for Mechanical Engineering. Lecture 4. C++ Data Types

C++ Programming: From Problem Analysis to Program Design, Third Edition

Exam 1 Practice CSE 232 Summer 2018 (1) DO NOT OPEN YOUR EXAM BOOKLET UNTIL YOU HAVE BEEN TOLD TO BEGIN.

A Fast Review of C Essentials Part I

Integer Data Types. Data Type. Data Types. int, short int, long int

Programming with C++ as a Second Language

CS201- Introduction to Programming Latest Solved Mcqs from Midterm Papers May 07,2011. MIDTERM EXAMINATION Spring 2010

WARM UP LESSONS BARE BASICS

conditional statements

Multiple Choice (Questions 1 13) 26 Points Select all correct answers (multiple correct answers are possible)

Programming with C++ Language

LAB 4.1 Relational Operators and the if Statement

True or False (14 Points)

Creating a C++ Program

C++ PROGRAMMING. For Industrial And Electrical Engineering Instructor: Ruba A. Salamh

CAMBRIDGE SCHOOL, NOIDA ASSIGNMENT 1, TOPIC: C++ PROGRAMMING CLASS VIII, COMPUTER SCIENCE

C++ Strings, Enums. Data Processing Course, I. Hrivnacova, IPN Orsay

Multiple Choice (Questions 1 14) 28 Points Select all correct answers (multiple correct answers are possible)

CHAPTER 4 FUNCTIONS. 4.1 Introduction

CSCI-1200 Data Structures Fall 2014 Lecture 8 Iterators

REVIEW. The C++ Programming Language. CS 151 Review #2

CSI33 Data Structures

Introduction to C++ 2. A Simple C++ Program. A C++ program consists of: a set of data & function definitions, and the main function (or driver)

STUDY NOTES UNIT 1 - INTRODUCTION TO OBJECT ORIENTED PROGRAMMING

Understanding main() function Input/Output Streams

Object-oriented Programming for Automation & Robotics Carsten Gutwenger LS 11 Algorithm Engineering

Transcription:

Chapter 8 - Notes User-Defined Simple Data Types, Namespaces, and the string Type I. Enumeration Type A. Data Type: A set of values together with a set of operations on those values. 1. C++ provides the Enumeration Type as a mechanism for users to create their own data type. 2. To define an enumeration type, you need the following items: a. A name for the data type b. A set of values for the data type c. A set of operations on the values ( C++ lets you define a and b, but not c. ) 3. The name you select for the data type and the values for the data type must be legal identifiers. 4. Syntax: enum typename value1, value2,... ; a. enum is a reserved word b. The list inside the curly braces also determines the order of the values, therefore the first value is equivalent to the value 0, the second value is equivalent to 1, etc. c. The identifiers inside the curly braces are called enumerators, they are not variables. 5. Examples: enum colors brown, blue, red, green, yellow ; a. The above line of code defines a new data type called colors consisting of the values: brown, blue, red, green, yellow enum class_standing freshman, sophomore, junior, senior ; 1

b. The above line of code defines a new data type called class_standing consisting of the values : freshman, sophomore, junior, senior. 6. Examples of Illegal Enumeration Types enum grades A, B, C, D, F ; st nd rd th enum places 1, 2, 3, 4 ; Characters not identifiers Illegal to start with number 7. If a value has already been used in one enumeration type, it cannot be used by any other in that same block. B. Declaring Variables 1. Once a data type is defined, you can now declare variables of that type. 2. Syntax: datatype identifier, identifier,... ; Example: enum trees oak, elm, maple, pine, cedar, teak ; defining data type trees woodtype, easterntrees ; declaring variables C. Assignment a. Variables of type tree have been declared as woodtype and easterntrees 1. Once a variable of the enumerated type has been declared, you can then store (assign) values to it. Example (using the above type - trees): woodtype = elm ; //stores the value elm in the variable woodtype easterntrees = woodtype ; // stores the value in woodtype into easterntrees woodtype = cherry ; //Illegal - cherry not listed as a value! 2. Notice that the only values you can legally assign to the variable(s) are those defined in the enumerated list. 2

D. Operations on Enumeration Types 1. NO Arithmetic Operations are allowed on Enumerated data types. a. The following are illegal: woodtype = elm + 2; easterntrees = oak * cedar ; woodtype++ ; easterntrees - - ; b. If you absolutely need to increment the value of an enumerated type variable, you can do so as follows: woodtype = static_cast<trees>( maple + 1 ) ; i. The above code stores the value pine into the variable woodtype because it is next in line. ii. Conversely, the code... woodtype = static_cast<trees>( maple - 1 ) ; would store the value elm int o the variable woodtype. 2. Relational Operators a. Because an enumeration is an ordered set of values, relational operators CAN be used with the enumeration type. Example ( again using the data type trees ): woodtype = cedar ; easterntrees = oak ; (woodtype > oak) given these assignments would evaluate to true (easterntrees >= woodtype ) would evaluate to false E. Enumeration Types and Loops 1. The enumeration type is an integral type, in other words the values can be counted. For this reason they can be used as control variables in loop structures. 3

2. Remember, to increment enumerated types, you must use the static_cast. Example for Loop: for ( woodtype = oak ; woodtype <= teak ; woodtype = static_cast<trees>( woodtype + 1) )...... 3. The above for Loop will go through 6 iterations because there are 6 values in the data type trees. F. Input/Output of Enumeration Types 1. Input and Output are defined only for built-in data types, therefore, enumerated type variables cannot be directly input or output to the screen or files. 2. If you try to directly output an enumerated type variable to the screen or file, YOU WILL NOT GET AN ERROR but the program will print the place number of the value in the definition list. 3. You can work around the Input/Output problem by using switch statements. Example: ( for input ) char ch ; cin >> ch ; switch ( ch ) case o : woodtype = oak ; break ; case e : woodtype = elm ; break ; case m : woodtype = maple ; break ; case p : woodtype = pine ; break ; case c : woodtype = cedar ; break ; case t : woodtype = teak ; break ; default : cout << Illegal Input. << endl ; 4

Example: ( for output ) switch ( woodtype ) case oak: cout << oak ; break ; case elm: cout << elm ; break ; case maple: cout << maple ; break ; case cedar: cout << cedar ; break ; case teak : cout << teak ; break ; G. Functions and Enumeration Types 1. You can pass the enumeration data type as a parameter in a function just like any other data type. a. Yes - you can pass the data type as either value or reference. 2. You can also pass the enumerated data type as a return type in a value returning function. Example: trees inctrees ( trees wood )...... return wood ; ; 3. Since you can pass enumerated data types as parameters and return them from functions, it would be beneficial to create functions that Input and Output your enumerated data type. H. Declaring Variables When Defining the Enumeration Type 1. C++ allows the programmer to combine the steps of defining an enumerated data type and declaring variables for the data type. Example: enum trees oak, elm, maple, pine, cedar, teak woodtypes ; or enum coins penny, nickel, dime, quarter change, uscoins ; 5

I. Anonymous Data Types 1. It is possible to declare an enumerated data type without naming it. Example: enum oak, elm, maple, pine, cedar, teak woodtypes ; 2. In the above example, woodtypes is a variable that will hold only the values specified, but it has no name for a data type. 3. Creating Anonymous Data Types Has Drawbacks i. You cannot pass an anonymous data type as a parameter to a function nor return it from a value returning function. ii. Values in one anonymous type CAN be used in another anonymous type. However, when comparing two anonymous data types with the same values, C++ will not recognize that they are equal. 4. Bottom Line : Be careful when using anonymous data types!! II. typedef Statement A. A method in C++ of creating synonyms or aliases to a previously defined data type. B. Syntax: typedef existingtypename newtypename C. NOTE: The typedef statement does NOT create a new datatype, it only creates a second name to an existing data type. D. Examples: typedef int integer ; typedef double real ; // Creates alias integer for the int data type // Creates alias real for the double data type typedef double decimal ; // Creates alias decimal for the double data type 6

III. Namespaces A. Included in the 1998, ANSI/ISO Standard C++ 1. When a header file, such as iostream, is included in a program, the global identifiers in the header file also become the global identifiers in the program. 2. Therefore, if a global identifier in a program has the same name as one of the global identifiers in the header file, the compiler generates a syntax error (such as "identifier redefined"). 3. The same problem can occur if a program uses third party libraries. a. To overcome this problem, third-party vendors begin their global identifiers with a special symbol...the underscore ( _ ). b. To avoid linking errors with included libraries, you should not use an underscore at the beginning of identifiers in your program. 4. The namespace mechanism was designed to try and solve the problem of overlapping global identifiers. B. General Syntax 1. namespace namespace_identifier members a. namespace is a reserved word. b. namespace_identifier is a unique and legal C++ identifier you give to your namespace. c. A member of a namespace can be a named constant, variable declaration, function, or even another namespace. 7

C. Example namespace globaltype const int N = 10 ; const double RATE = 7.50 ; int count = 0 ; void printresult ( ) ; *NOTE: In the above example, the four members are: named constants N and RATE, the variable count, and the function prototype printresult. D. Accessing the Namespace 1. The scope of a namespace member is local to that namespace. 2. Accessing a namespace member can be done in one of two ways: a. First Method - General Syntax: namespace_identifier : : identifier i. namespace_identifier is the name of the namespace you want to access. ii. iii. iv. identifier is the name of the member of the namespace that you want to access. The double colon ( : : ) is called a scope resolution operator. Using the example from above, access the member RATE from the namespace globaltype with the following statement: globaltype : : RATE v. To access the function member of the namespace globaltype, the following statement is required: globaltype : : printresult ( ) ; 8

vi. In summary, you can access a namespace member by using the namespace identifier, followed by the scope resolution operator, followed by the member name. b. Second Method - General Syntax: using namespace namespace_identifier ; i. Note that in the above syntax, using is a reserved word. ii. iii. This method is done in an effort to simplify the access of namespace members. Once the "using namespace" is declared, it is no longer necessary to provide the namespace identifier and scope resolution operator in front of the namespace member. So...instead of ~~~> globaltype : : RATE You now only type ~~~> RATE iv. If you want to access just a specific member using the second method, you may do so in the following manner: Syntax: using namespace_identifier : : member_name Example: using globaltype : : RATE ; v. Typically, the using statement is put after the namespace declaration. Example: namespace globaltype const int N = 10 ; const double RATE = 7.50 ; int count = 0 ; void printresult ( ) ; using namespace globaltype ; 9

IV. string Type A. Programmer Defined Data Type 1. The data type string is not part of the C++ language; the C++ standard library supplies it. 2. Before using the data type string functions, you must include the header file string : #include <string> 3. A string is a sequence of zero or more characters, and strings are enclosed in double quotation marks. 4. Example of declaring and initializing a string variable: string name = Al Pacino ; a. The variable name is declared of type string. b. The variable name is initialized to the value Al Pacino. 5. Remember that every character in a string has a position value. a. Therefore, the A in Al Pacino would be at position zero (0). REMEMBER: Strings always start at position zero (0)!!! b. The O in Al Pacino would be at position 8. ( Don t forget to count the blank space as a character.) c. The length of the string Al Pacino is 9. 6. Recall that relational operators can be used on strings ( see Chapter 4 ) and I/O operators can also be used on strings ( see Chapter 3 ). B. Two Helpful string Operators 1. String Concatenation Operator a. The binary operator + allows the programmer to concatenate two string variables or a string variable and a string defined by double quotation marks. 10

b. Example: string firstname, midname, lastname, fullname ; firstname = Alan ; midname = Jay ; lastname = Spurgeon ; fullname = firstname + + midname + + lastname ; cout << fullname << endl << endl; Alan Jay Spurgeon OUTPUT 2. Array Subscript Operator a. In C++, [ ] is called the array subscript operator. It allows the programmer to access an individual character within a string variable. b. The array subscript operator may be used on either side of the assignment operator =. c. Example of Use: string name ; char ch1, ch2 ; name = al Pacino ; name[0] = A ; cout << name << endl << endl; ch1 = name[0] ; ch2 = name[3] ; cout << Al Pacino s initials are << ch1 << << ch2 <<. ; cout << endl << endl ; 11

C. Additional string Operations ( also see pg. 1262 ) 1. length Function a. The length function returns the number of characters currently in the string variable. The value returned is an unsigned integer. b. Syntax: stringvarname.length ( ) i. Where stringvarname is the name of the string variable you want to find the length of. ii. iii. iv. The. (dot) between the variable name and the word length is essential. The function.length( ) does not take any parameters but it is still necessary to put empty parenthesis after the word length. Since this function is a value returning function, you must use it only on the right side of an assignment statement or in an output statement ( just like any other value returning function ). c. Examples: string name; int numname ; cout << Please enter your last name here -> ; cin >> name ; numname = name.length( ); cout << Your last name has << numname << letters. << endl; or what about using it in a for loop for ( int i = 0; i < name.length( ) ; i++ ) - - - - - - - - 12

2. size Function a. Exactly the same as the length function but uses the word size instead. 3. find Function a. A value returning function that searches a string variable for the first occurrence of a particular substring or character. b. The value returned is an unsigned integer indicating the position in the string where the match begins. If no match is found, my compiler returns a negative one (-1). c. Syntax: stringvarname.find( stringexpression ); stringvarname.find( stringexpression, position ); i. Where stringvarname is the string variable you are searching. ii. iii. Where stringexpression is the substring you are looking for in the string variable. Where position is the starting position of the string variable that you want to start your search. d. #include <iostream> EXAMPLE #include <string> using namespace std; int main ( ) string phrase; int num1, num2, num3; phrase = "The quick brown fox jumped over the lazy dog."; num1 = phrase.find("fox"); num2 = phrase.find("the"); num3 = phrase.find("world") ; cout << num1 << " " << num2 << " " << num3 << endl << endl; system("pause"); return 0; 13

OUTPUT 16 32-1 Press any key to continue... NOTICE that when a substring is not found, the function returns a negative one (-1). 4. substr Function a. The substring function returns a substring from a larger string, indicated by the starting position number and how many characters from the starting position you want in the substring. b. Syntax: stringvariable.substr( expr1, expr2 ) i. Where stringvariable is the string variable to be searched. ii. iii. Where expr1 is an unsigned integer indicating the starting position of the substring desired. Where expr2 is an unsigned integer indicating how many characters are to be copied from the starting position (including the starting position ). c. Example: #include <iostream> #include <string> using namespace std; int main ( ) string phrase, strword; phrase = "The quick brown fox jumped over the lazy dog."; strword = phrase.substr( 4, 5 ); cout << strword << endl << endl; system("pause"); return 0; 14

OUTPUT quick 5. swap Function Press any key to continue... a. A function to swap the string values of two string variables. b. Syntax: strvar1.swap( strvar2) ; i. Where strvar1 is one of the string variables you want swapped. ii. iii. Where strvar2 is the string variable you want swapped with strvar1. Notice that although a swap is occurring between variables, this is technically not a value returning function and can be called on its own. c. Example: #include <iostream> #include <string> using namespace std; int main ( ) string strword1, strword2; strword1 = "First" ; strword2 = "Second" ; cout << strword1 << " " << strword2 << endl << endl; strword1.swap(strword2); cout << strword1 << " " << strword2 << endl << endl; system("pause"); return 0; 15

OUTPUT First Second Second First Press any key to continue... Look for more string functions listed in the back of your textbook on pages 1262 thru 1264. 16