0% found this document useful (0 votes)
1 views

C++ Programming

Uploaded by

varun_new87
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1 views

C++ Programming

Uploaded by

varun_new87
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 461

C++

Programming By Ray Yao For Beginners (With


100 Tests & Answers)
Copyright © 2015 by Ray Yao All Rights Reserved Neither part of this book
nor whole of this book may be reproduced or transmitted in any form or by any
means electronic, photographic or mechanical, including photocopying,
recording, or by any information storage or retrieval system, without prior
written permission from the author.
Ray Yao

About the Author


Ray Yao: Certified PHP engineer by Zend, USA Certified JAVA programmer
by Sun, USA Certified SCWCD developer by Oracle, USA Certified A+
professional by CompTIA, USA Certified ASP. NET expert by Microsoft, USA
Certified MCP professional by Microsoft, USA Certified TECHNOLOGY
specialist by Microsoft, USA Certified NETWORK+ professional by CompTIA,
USA
Highly Recommend Computer Books on Amazon:
Linux Command Line
JAVA Programming
PHP Programming
JavaScript Programming
C++ Programming
AngularJS Programming
JQuery Programming
Python Programming
HTML CSS Programming
C# Programming
Visual Basic Programming
JavaScript 50 Useful Programs
Advanced Java Programming
Advanced C++ Programming
Preface
“C++ Programming” covers all essential C++ knowledge. You can learn complete primary skills of C++
fast and easily.
This book includes many practical Hands-On Projects. You can study C++ coding with Hands-On Projects.

Source Code for Download


This book provides source code for download; you can download the source
code for better study, or copy the source code to your favorite editor to test the
programs.
Download Link: C++ Source Code for Download
Table of Contents
Hour 1 Start C++
Install C++
What is C + +?
C++ Comments
Run First Programming
Output Commands
Escaping Characters
C++ Keywords
Data Types
Create a Variable
Arithmetical Operators
Logical Operators
Assignment Operators
Comparison Operators
Hands-On Project: Calculation

Hour 2 Statements
If Statement
If-else Statement
Switch Statement
For Loop
While Loop
Do-While Loop
Break Statement
Continue Statement
Boolean-Expression
Conditional Operator
Hands-On Project: The Sum

Hour 3 Use Array


Create an Array (1)
Create an Array (2)
Array Size
Element Value
Function
Function & Arguments
Return Value
Call Another Function
Constants
Data Type Conversion
Hands-On Project: Max Value

Hour 4 String
A String Variable
Input String Data
Input String Sentence
Test Whether Inputted
String Length
Find a Character
Connect Strings
Exchange Strings
Find a Word’s Position
Insert a Substring
Hands-On Project: Show Inputted

Hour 5 Class & Object


Class Definition
Object Declaration
Class & Object
Constructor
Destructors
Inheritance
Using Derived class
Public Permission
Private Permission
Private Example
Protected Permission
Class Method
Access Private Member
Hands-On Project: My House

Hour 6 Pointer & Reference


Pointer
Pointer Initialize
Using Pointer
Exchange Pointers
Pointer and Array
Pointer Array
Pointer & String
Reference a Variable
Reference an Object
Reference Arguments
Hands-On Project: Address

Hour 7 File Operation


Output One Character
Output String
Input One Character
Input String
Input String Sentence
Write a File
Open a File
Read a File
End of File
Hands-On Project: Process File

Hour 8 Static Exception Vector


this -> member
Static Variable
Static Function
A++ or ++A
Call My Own Function
Local & Global Variable
Exceptions
Try-Catch
Return Exception Message
Throw Exception
Vector
Vector.method( )
Vector.method( )
Hands-On Project: Error Occurs!

Appendix C++ 100 Tests & Answers


100 Tests
100 Answers

Source Code for Download


Hour 1
Start C++
Install C++

Many free downloaded C++ compilers and editors are available on the internet;
you can choose one of them to write, edit, compile and execute your C++ codes.
Dev-C++ is an excellent C++ Compiler & Editor
Maybe you want to install free “Dev-C++” to your local computer, please
download it from the following website.
http://www.bloodshed.net/dev/devcpp.html.
If you don’t want “Dev-C++”, please download and install “Visual Studio”.

Or
Download Visual Studio
Visual Studio provides free tools to develop applications for a specific platform,
such as Visual C++, Visual C#, Visual Basic, Asp.net and Windows
applications.
Visual C++ contains all C++ libraries, C++ tools building and running C++
programs. Visual C++ is an IDE that can create a C++ development
environment.
To download a free edition of Visual Studio, go to
https://www.visualstudio.com
Install Visual Studio
In Visual Studio, Visual C++ is not installed by default. When installing, be sure
to choose Custom installation and then choose the Visual C++ components you
require.

Or
Online C++ Compiler & Editor
An online C++ compiler & editor are available at:
http://www.tutorialspoint.com/codingground.htm
When running the online C++ compiler & editor, you can type C++ codes into
the editor, click “Compile”, then click “Execute”, the result will appear.
What is C + +?
C++ is a general-purpose programming language, which is an extension of the C
language. C++ is an object-oriented programming language that is used
extensively.
Example 1.1
#include <iostream> using namespace std; int main() {
cout << "Hello World!" << endl; return 0;
} (Output: Hello World!)
Explanation:
“#include <iostream>” means including an input/output library named iostream
that helps input or output operation.
“using namespace std” means that “std” is a standard namespace , which can
solve the name conflict problems.
“int” is a return type, it specifies the return type of a function.
“main( )” is an obligatory function that runs main code of C++.
“cout <<” displays or show the contents.
“return 0” indicates the program run successfully.
C++ Comments
//

/* …… */

C++ comments are used to explain the current code, describe what this code is
doing. C++ compiler will ignore comments.
// is used in the single line comment.
/*…*/ is used in the multi line comments
Example 1.3
cout << “Hello World” ; // show “Hello World”
/* cout << is a C++ output command, meaning display or print.

*/
Explanation:
// show “Hello World” is a single line comment.
/* cout << is a C++ output command, meaning display or print. */ is a multi
line comment.
Note: Each C++ command ends with semicolon”;”.
Run First Programming
Hello World!
Write C++ codes to your favorite editor.

#include <iostream> // including an input/output library


using namespace std; // “std” is a standard namespace int main() { // the start
point to run the program cout << "Hello World!" << endl; // output return 0;
// “return 0” means successful }
Save, Compile, and Run the Program.
Output:
Hello World!
Explanation:
“ int main( )” is a required main function in C++ programs.
“cout << "Hello World!" << endl;” displays “Hello World!”.
Output Commands
cout << “ ”; // print the result at the same line.

cout << “ ” << endl; // print the result at the


different line.
Example 1.4
cout << " 1 "; // output in the same line cout << " 2 "; cout << " 3 ”; (
Output: 1 2 3 ) cout << " 1 " << endl ; // output in the different line cout << "
2 " << endl ; cout << " 3 " << endl ; ( Output: )1
2
3
Explanation:
cout << “ ”; // print the result at the same line.
cout << “ ” << endl; // print the result at the different line.
Escaping Characters
The “ \ ” backslash character can be used to escape characters.
\n outputs content to the next new line.
\r makes a return
\t makes a tab
\’ outputs a single quotation mark.
\” outputs a double quotation mark .
Example 1.5
#include <iostream> using namespace std; int main( ) {
cout << " \" Hello World! \" "; // \” a double quotation mark return 0;

(Output: “Hello World!”)


Explanation:
\” outputs a double quotation mark. Note that “Hello World” has a double quote
with it. Another sample: cout << “Hello \t\t\t World” ; // Note it has three taps.
( Output: Hello World )
C++ Keywords
Some words are only used by C++ language itself. They may not be used when
choosing identifier names for variable, function, and labels. The following words
are C++ keywords:
asm auto break
delete case catch
char class const
continue default do
double else enum
float friend for
goto if inline
extern short int
long new operator
register private protected
public return signed
static struct switch
this throw(s) typedef
union unsigned virtual
try void while
Example 1.6
const // const is a keyword of C++
continue // continue is a keyword of C++
Explanation:
Above words, “const” and “continue” is C++ reserved words, which may be not
used as variable name, function name, and label name.
Data Types
C++ five basic data types are listed in the following:
Data Types Explanation
char a character
string several characters

int an integer number

float a floating point number with 6 decimals

double a floating point number with 10 decimals


bool a value with true or false
Example 1.7
“hello” // string 168 // int 0.123456 // float 0.0123456789 //
double true // bool
Explanation:
The data type of “hello” is a string.
The data type of 168 is an int The data type of 0.123456 is a float The data type
of true is a bool.
Create a Variable
A variable is a symbolic name associated with a value.
Using following syntax can create a variable and value.
dataType variableName = value;
Example 1.8
void main ( ) {
char mychar = ‘m’; // define a variable “mychar”
int myinteger = 168168; // define a variable “myinteger”
float myflt = 28.98; // define a variable “myflt”
double mydbl = 0.0123456789 // define a variable “mydbl”
boolean mybool = true; // define a variable “mymybool”

}
Explanation:
mychar is a name of variable, its value is “m”.
myinteger is a name of variable, its value is 168168.
mybool is a name of variable, its value is true.
“main ( ) { }” declares a main method.
Arithmetical Operators

Operators Running

+ add, connect strings

- subtract

* multiply

/ divide

% get modulus

++ increase 1

-- decrease 1

% modulus operator divides the first number by the second number and returns
the remainder. e.g. 9%2=1.
Example 1.9
#include <iostream>
using namespace std;
int main( ) {
int a = 200, b = 100;
int sum = a + b; cout<< sum<<endl;
int divi = a / b; cout<< divi<<endl;
int modu = a % b; cout<< modu<<endl; // get remainder
cout << ++a << endl; // increase 1
return 0;
}
Output:
300
2
0
201
Explanation:
“int sum = a + b” means 100 plus 200.
“int divi = a / b” means 200 divide 100.
“int modu = a % b” means 200 modulus 100.
“++a” increases its value by 1.
Logical Operators
Operators Equivalent
&& and

|| or

! not
After using logical operators, the result will be true or false.
“1” represents true, “0” represents false.
Example 1.10
bool x=true; bool y=false; bool a= x && y; cout << a << endl; // output: 0
bool b=x || y; cout << b << endl; // output: 1
bool c=! x; cout << c << endl; // output: 0
Explanation:
“1” represents true, “0” represents false.
true && true && false
true; returns false; returns &&false;
true; false; returns false;
true II true; true II false; false II false;
returns true; returns true; return false;
! false; ! true; returns
returns true; false;
Assignment Operators
Operator Example Explanation

+= x += y x=x+y

-= x -= y x=x-y

*= x *= y x=x*y

/= x /= y x=x/y

%= x %= y x=x%y
Example 1.11
#include <iostream>
using namespace std;
int main( ) {
int x=200; int y=100;
cout <<"200+=100 equals " << (x+=y)<< endl;
cout <<"300-=100 equals " << (x-=y)<< endl;
cout <<"200*=100 equals " << (x*=y)<< endl;
cout <<"20000%=100 equals "<< (x%=y)<< endl;
return 0;
}
Explanation:
x+=y; // x=x+y, x=200+100, output 300.
x-=y; // x=x-y, x=300-100, output 200.
x*=y; // x=x*y, x=200*100, output 20000.
x%y; // x=%y, x=2000000%100, output 0.
Comparison Operators

Operators Running
> greater than
< less than
>= greater than or equal
<= less than or equal

== equal

!= not equal
After using comparison operators, the result will be true or false.
Example 1.12
#include <iostream> using namespace std; int main( ) {
int x=200; int y=100; bool result1 = (x>y); cout << result1<< endl; bool result2
= (x<=y); cout << result2<< endl; bool result3 = (x!=y ); cout << result3 <<
endl; return 0;

};
Output:
1
0
1
Explanation:
“1” represents true.
“0” represents false.

x>y // test 200>100, output true.


x<=y // test 200<=100, output false.
x!=y // test 200!=100, output true.
Hands-On Project: Calculation
Calculation
Write C++ codes to your favorite editor.

#include <iostream>
using namespace std; int main(){
int a=10, b=20, c=30; // define three variables int sum; // define a variable
sum = a + b * c; // calculation cout << "a+b*c = "<< sum << endl; //
output return 0; // run successfully }
Save, and run the program.
Output:
a+b*c = 610
Explanation:
“#include <iostream>” includes an input/output library named iostream that
helps input or output operation.
“using namespace std” means that “std” is a standard namespace, which can
solve the name conflict problems.
“int” is a return type, it specifies the return type of a function.
“main( )” is an obligatory function that runs main code of C++.
“int a=10, b=20, c=30;” initialize three variables a, b, c.
“sum = a + b * c;” is an expression that assigns the result value to “sum”.
“cout <<” displays or show the contents.
“return 0” indicates the program run successfully.
Hour 2
Statements
If Statement
if ( test-expression ) { // if true do this; }
“if statement” executes codes inside { … } only if a specified condition is true,
does not execute any codes inside {…} if the condition is false.
Example 2.1
#include <iostream> using namespace std; int main( ) {
int a=200;
int b=100;
if (a>b){ // if true do this;
cout << "a is greater than b."; }
return 0;
} (Output: a is greater than b.)
Explanation:
( a>b ) is a test expression, namely (200>100), if returns true, it will execute the
codes inside the { }, if returns false, it will not execute the codes inside the { }.
If-else Statement
if ( test-expression) { // if true do this; }
else { // if false do this; }
“if...else statement” runs some code if a condition is true and another code if the
condition is false
Example 2.2
#include <iostream> using namespace std; int main( ) {
int a=100; int b=200; if (a>b) { // if true do this;
cout << "a is greater than b."; }
else { // if false do this;
cout << "a is less than b"; }
return 0;
} (Output: a is less than b.)
Explanation:
( a>b ) is a test expression, namely (100>200), if returns true, it will output ”a is
greater than b.” if returns false, it will output “a is less than b”.
Switch Statement

switch ( variable ) { case 1: if equals this case, do


this; break; case 2: if equals this case, do this; break;
case 3: if equals this case, do this; break; default : if
not equals any case, run default code; break; }

The value of the variable will compare each case first, if equals one of the “case”
value; it will execute that “case” code. “break;” terminates the code running.
Example 2.3
#include <iostream>
using namespace std; int main( ) {
int number=20; switch ( number ) { // “number” compares each case case 10 :
cout << "Running case 10 \n" ; break; case 20 : cout << "Running case 20 \n" ;
break; case 30 : cout << "Running case 30 \n" ; break; default : cout <<
"Running default code \n" ; break; }
return 0;

}
Output:
Running case 20
Explanation:
The number value is 20; it will match case 20, so it will run the code in case 20.
For Loop
for( init, test-expression, increment) { // some code; }
“for loop” runs a block of code by the specified number of times.
Example 2.4
#include <iostream> using namespace std; int main( ) {
int x;
for (x = 0; x <= 5; x++){ // repeat 5 times cout << x; }
return 0;
} (Output: 012345 )
Explanation:
x = 0 is an initializer,
x <= 5 is a test-expression, the code will run at most 5 times.
x++ means that x will increase 1each loop.
After 5 times loop, the code will output 012345.
While Loop
while ( test-expression ) { // some C++ code in here;
}
“while loop” loops through a block of code if the specified condition is true.
Example 2.5
#include <iostream> using namespace std; int main( ) {
int counter=0; while (counter < 8){ // run 8 times cout << "&"; counter++;

return 0;
} ( Output: &&&&&&&& )
Explanation:
“counter< 8” is a test expression, if the condition is true, the code will loop less
than 8 times, until the counter is 8, then the condition is false, the code will stop
running.
Do-While Loop
do{ // some c++ code in here } while ( test-
expression);
“do...while” loops through a block of code once, and then repeats the loop if the
specified condition is true.
Example 2.6
#include <iostream> using namespace std; int main( ) {
int counter=0; do {
cout << "@"; counter++;
} while (counter<8); // run 8 times return 0;
} ( Output: @@@@@@@@ )
Explanation:
“counter< 8” is a test expression, if the condition is true, the code will loop less
than 8 times, until the counter is 8, then the condition is false, the code will stop
running.
Break Statement
Break;
“break” keyword is used to stop the running of a loop according to the condition.
Example 2.7
#include <iostream> using namespace std; int main( ) {
int num=0;
while ( num<10 ){
if ( num==5 ) break; // leave the current while loop num++;

cout << num ; return 0;


} ( Output: 5)
Explanation:
“if (num==5) break;” is a break statement. If num is 5, the program will run the
“break” command, the break statement will exit the loop, then run “cout << num
”.
Continue Statement
continue;
“continue” keyword is used to stop the current iteration, ignoring the following
code, and then continue the next loop.
Example 2.8
#include <iostream> using namespace std; int main( ) {
int num=0;
while ( num<10 ){
num++;
if ( num==5 ) continue; // go to the next while loop cout << num ; }
return 0;
} ( Output: 1234678910)
Explanation:
Note that the output has no 5.
“if (num==5) continue;” includes “continue” command. When the num is 5, the
program will run “continue”, skipping the next command “cout << num ”, and
then continue the next loop.
Boolean-Expression
If ( bool-expression ) { statements }

while ( boolean-expression ) { statement }


The boolean-expression can be only a variable. For example: if (var) { }, if
(!flag) { }.
Example 2.9
#include <iostream>
using namespace std;
int main( ) {
int num=10;
if ( num ) { // just like "if (num == 10)"
cout << "num = 10" << endl;
}
while ( !num ){ // just like "while(num!=10)"
cout << "num !=10" <<endl;
}
return 0;
} (Output: num = 10 )
Explanation:
“if( num )” and “while ( !num )” are correct codes, because they can have a
variable inside the ( ).
In Java, it should be “if (num==10)” or “while (num!=10)”.
Conditional Operator
(test-expression) ? (if-true-do-this) : (if-false-do-
this);
( test-expression) looks like this: a<b, x!= y, m==n. etc.
Example 2.10
#include <iostream>
using namespace std; int main( ) {
int a=100; int b=200; string result = (a<b) ? "apple" : "banana"; // (test-
expression) ? (if-true-do-this) : (if-false-do-this); cout << result << endl; return
0;
} (Output: apple)
Explanation:
The conditional operator use (a<b) to test the “a” and “b”, because “a” is less
than “b”, it is true. Therefore, the output is “apple”.
“return 0;” indicates the program run successfully.
Hands-On Project: The Sum
For Loop Program
Write C++ codes to your favorite editor.

#include <iostream> using namespace std; int main(){


int sum = 0; for (int n=1; n<=100; n++) // run 100 times sum += n ; // sum =
sum + n cout << "Sum = " << sum << endl; return 0; }

Save, and run the program.


Output:
Sum = 5050
Explanation:
“for (int n=1; n<=100; n++)” runs a block of code by specified number of times.
n = 1 is initialize.
n <= 100 is a test-expression, the code will run at most 100 times.
n++ means that n will increase 1each loop.
“sum += n” is equivalent to “sum = sum + n”.
“cout << "Sum = " << sum << endl;” displays the value of sum.
Returning a zero indicates that the program runs successfully.
After 100 times loop, the code will output 5050.
Hour 3
Use Array
Create an Array (1)
An array is a variable, which can contain multiple values.
The first method to create an array as following:
int array-name[ number] = {“value0”, “value1”,
“value2”,…};
“number” means the number of array elements.
Example 3.1
int myarray[4] = { 10,20,30,40 }; // create an array
Explanation:
The above code creates an array named “myarray”, which has four elements:
“myarray[4]” means that “myarray” has 4 elements The 1st element is
myarray[0] with value 10. Key is 0.
The 2nd element is myarray[1] with value 20. Key is 1.
The 3th element is myarray[2] with value 30. Key is 2.
The 4th element is myarray[3] with value 40. Key is 3.
In array, Key’s alias is “index”. Index’s alias is “key”.
Note that index begins from 0.
Create an Array (2)

An array is a variable, which can contain multiple values.


The second method to create an array as following:

int myarray [ number of elements ]; int array-


name[index0] = “value1”; int array-name[index1] =
“value1”; int array-name[index2] = “value2”;
Example 3.2
#include <iostream>
using namespace std;
int main( ) {
string color[3]; // declare an array
color [0] = "Red "; // assign the value to the array
color [1] = "Yellow ";
color [2] = "Green ";
cout<< color[0]<<color[1]<<color[2];
return 0;
}
Output:
Red Yellow Green
Explanation:
Above code creates an array, array name is “color”, and it has three elements:
color [0], color [1], color [2]. Its indexes are 0, 1, and 2. Its values are Red,
Yellow and Green.
Note that index begins from 0.
Array Size
sizeof (array-name);
“sizeof (array-name);” can return the total number of bytes of an array.
Example 3.3
#include <iostream> using namespace std; int main( ) {
int arr[50]; // declare an array “arr”
int num = sizeof ( arr ); // get the size of “arr”
cout << num << " bytes"; return 0;
} ( Output: 200 bytes )
Explanation:
“sizeof ( arr );” is used to get the length of the array “arr”, which means the total
number of bytes.
Note that sizeof ( datatype ) can return the number of bytes of that data type. e.g.
sizeof ( int ) returns 4 bytes.
Element Value
int value = array[index]; // Get a value from an
element.

int array[index] = value; // Set a value to an element.


Example 3.4
int arr[5] = {10, 20, 30, 40, 50}; int value = arr[2]; // get a value from an
element.
cout << value <<endl; ( Output: 30)
Example 3.5
int num[ 5 ]; num[3] = 800; // set a value to an element.
cout << num[3] <<endl; ( Output: 800)
Explanation:
“int value = arr[2];” gets a value 30 from “arr[2]”, and assigns to the “value”
variable.
“num[3] = 800;” sets a value 800 to the element “num[3]” .
Function

The function is a code block that can be repeated using.


Before using a function, you need to declare a function first.

type function-name( ); // declare a function function-


name( ); // calls a function.
type function-name( ) {…..}; // define a function
Example 3.6
#include <iostream> using namespace std; void myFunction( ); // declare a
function
int main( ) {
myFunction( ); // call the function return 0;

void myFunction ( ) { // define a function cout << "This is a function demo."


<<endl; }
Output:
This is a function demo.
Explanation:
“void myFunction();” declares a function.
“myFunction( );” calls a function.
“void myFunction( ) {……}” defines a function.
“return 0” indicates the program run successfully.
“void” is a return type, meaning without return value. Namely without “return”
command in function body.
Function & Arguments

A function sometimes has an argument.


Before using a function, you need to declare a function.

type function-name( arg ); // declare a function


function-name ( argument ); // call the function
type function-name ( arg ) {……}; // define a
function
Example 3.7
#include <iostream> using namespace std; void myFunction(string arg ); //
declare a function int main( ) {
myFunction ( "with arguments." ); // call the function return 0;

void myFunction ( string arg ) { // define a function cout << "This is a


function " + arg << endl; }
Output:
This is a function with arguments
Explanation:
“void myFunction(string arg );” declares a function.
“myFunction( “with arguments” );” calls a function.
“void myFunction ( string arg) {…}” defines a function with argument.
“myFunction( “with arguments” );” calls function “void myFunction(String
argument) {…}”, and pass the argument “with arguments” to it. After receiving
the argument “with arguments”, it outputs “This is a function with arguments”.
Return Value

“return value” can return a value to the caller.

type function-name ( argument ) { return value };


function-name ( arg );
Example 3.8
#include <iostream> using namespace std; int myFunction(int arg ); // declare a
function int main( ) {
cout << "The number is " << myFunction(10)<<endl; // caller return 0;

int myFunction ( int arg ) {


return ++arg; // return a value to caller }
Output:
The number is 11.
Explanation:
“myFunction( “10” )” calls a function. Therefore “myFunction( “10” )” is a
caller.
“int myFunction ( int arg ) {…}” defines a function.
“int” is a return type, it means the function returns int type.
“return ++arg; ” can return the value “11” to the caller.
The output is “The number is 11”.
Call Another Function

function1 ( );
type function1 ( ) { function2( ); }; type function2 (
) { };

In function1, the function2( ) calls another function.


Example 3.9
#include <iostream> using namespace std; void firstFunction(int num); //
declare a function int secondFunction(int arg ); // declare a function int main( )
{
int num = 2;
firstFunction ( num ); // call the function return 0;

void firstFunction ( int num ){


cout << "The result is "<< secondFunction (num) <<endl; } // call anther
function int secondFunction( int num) {
return ( num * 50); }
Output:
The result is 100.
Explanation:
In “firstFunction”, the “secondFunction (num)” calls a function named “int
secondFunction( int num) { }”, and gets a return value 100.
Constants

Data that cannot change while running of the program is called constants.

#define CONSTANT-NAME “value”


“#define” defines a constant.
“CONSTANT-NAME” is a constant name, using capital.
NOTE: Using #define, the sentence cannot have a semicolon at the end.
Example 3.10
#include <iostream> using namespace std; #define SYMBOL "$" // define a
constant
#define PRICE 80 // define a constant #define MONEY " dollars." //
define a constant int main( ) {
int num = 10; cout << SYMBOL << num * PRICE << MONEY; return 0;

}
Output:
$800 dollars.
Explanation:
#define SYMBOL “$” defines a constant named “SYMBOL”, its value is “$”.
The PRICE value is “80”, the MONEY value “dollars”.
Data Type Conversion

variable 1= ( datatype) variable 2;


(datatype) can convert a data type to another data type.
Example 3.11
#include <iostream> #define PI 3.1415926 // macro definition using
namespace std; int main( ){
int number1, number2; float decimalNumber = 28.699; bool boolValue = false;
number1 = (int) decimalNumber; // convert to int number2 = (int)
boolValue; // convert to int cout << "number1: " << number1 <<endl; cout<<
"number2: " << number2 <<endl; return 0;

}
Output:
Number 1: 28
Number 2: 0
Explanation:
(int) can change the data type to integer.
(float) can change the data type to float pointing number.
(string) can change the data type to string.
And so on…..
Hands-On Project: Max Value
Array Operation Program
Write C++ codes to your favorite editor.
#include <iostream>
using namespace std; int main(){
int arr[5]= {20, -6, 0, 100, 78}; // create an array int max = arr[0]; // assume
the first element is the max for(int n=1; n<5; n++) // run 5 times
if(arr[n]>max) // compare the max with the current element max=arr[n]; //
the new max replaces the old max cout << "Max Value = "<< max << endl;
return 0;

Save, and run the program.


Output:
Max Value = 100
Explanation:
“int arr[5]= {20, -6, 0, 100, 78};” creates an array including five elements.
“int max = arr[0];” assigns the value 20 to variable “max”. The value of arr[0] is
20.
“arr[n]>max” compares the value of arr[n] and the value of “max”.
“max=arr[n];” gets the maximum value and assigns to “max” .
Hour 4
String
A String Variable
Before using string data type, <string> class should be included in the document
first, which help using string.
#include <string>
To declare and initialized a string variable:
string mystring = “some characters”
Example 4.1
#include <string>
#include <iostream> using namespace std; int main( ) {
string mystring = "We Love C++"; // a string variable cout << mystring <<
endl; return 0;
} ( Output: We Love C++ )
Explanation:
“#include <string>” includes <string> class from C++ library.
“string mystring = “We Love C++” declares and initialize a string variable.
Input String Data
cin >> string variable;
“cin >> string variable;” can input a single word.
Example 4.2
#include <string> #include <iostream> using namespace std; int main( ) {
string mystring; // declare a string variable cout << "Please enter a word: "<<
endl; cin >> mystring; // assume entering GOOD
cout << mystring <<endl; return 0;
} ( Output: Please enter a word: GOOD )
Explanation:
“#include <string>” include “string” class.
“cin >> mystring;” can accept a word input from the user.
Note that “cin >> mystring;” cannot input a whole line of sentence.
Input String Sentence
getline ( cin, mystring);
“getline ( cin, mystring);” can let user input a string sentence.
Example 4.3
#include <string> #include <iostream> using namespace std; int main( ) {
string mystring; cout << "Please enter a sentence: " << endl; getline ( cin,
mystring); // input “C++ is Very Good!”
cout << mystring << endl; return 0;
} ( Output: Please enter a sentence: C++ is Very Good!)
Explanation:
“getline ( cin, mystring);” accepts the user input by sentence. When a user enters
“C++ is Very Good!”, the value of “mystring” is “C++ is Very Good!”.
Test Whether Inputted

mystring.empty( );
“mystring.empty( );” can test whether a user has inputted a word or sentence
before submitting data. If mystring is empty, it returns true. Otherwise, it returns
false.
Example 4.4
#include <string>
#include <iostream> using namespace std; int main( ) {
string mystring; if ( mystring.empty( )) {
cout << "Please enter your name: "; getline ( cin , mystring); // input Smith
John cout << mystring << endl; }
else {
cout << "You have entered your name, thank you! "; }
return 0;

}
Output:
Please enter your name:
Smith John
Explanation:
“if ( mystring.empty( ))” can check the user whether has entered data or not. If
true, it indicates the user has not entered any data.
String Length
mystring.size( );
“mystring.size( )” can check the length of a string, returns the total number of
characters and space in this string.
Example 4.5
#include<string> #include <iostream> using namespace std; int main( ) {
string mystring = "operating system"; int stringSize = mystring.size( ); // get
the size of string cout << "String length is: " << stringSize << endl; return 0;
}; ( Output: String length is: 16 )
Explanation:
“mystring.size( )” returns the size of “operating system”, the result is 16.
“return 0” indicates the program run correctly.
Note that a single space equals the string size of 1 character.
Find a Character
mystring. at(index);
“mystring.at (index)” gets a character from a string by index. The index of a
string begins with 0.
Example 4.6
#include<string> #include <iostream> using namespace std; int main( ) {
string mystring = "operating system"; char aCharacter = mystring.at(2); // get
one character cout << "The character is: " << aCharacter << endl; return 0;
}; ( Output: The character is: e )
Explanation:
“mystring.at(2)” gets a character at index 2 from the string “operating system”.
Note that the index of a string begins with 0.
Connect Strings
originalString.append ( newString ); originalString +
newString;

“append( )”can connect a new string to an existing string.


“+” can connect two strings together.
Example 4.7
#include<string>
#include <iostream>
using namespace std;
int main( ) {
string a= "Java", b= "Script", newWord, allWord;
newWord = a + b;
cout << newWord <<endl; //Output: JavaScript
allWord = a.append(b);
cout << allWord << endl; //Output: JavaScript
return 0;
}; (Output: JavaScript JavaScript)
Explanation:
“a + b” and “a.ppend (b)” concatenate “Java” and “Script” to a new String
“JavaScript”.
Exchange Strings

string1.swap(string2);
“swap( )” can exchange two strings’ values.
Example 4.8
#include<string>
#include <iostream>
using namespace std;
int main( ) {
string s1 = "Number One.";
string s2 = "Number Two.";
cout << "string1: " << s1<< endl;
cout << "string2: " << s2 << endl;
s1.swap(s2); // exchange two string values
cout << "string1: " << s1<< endl;
cout << "string2: " << s2 << endl;
return 0;
};
Output:
string1: Number One.
string2: Number Two.
string1: Number Two.
string2: Number One.
Explanation:
“s1.swap(s2);” swaps two string’s value.
Find a Word’s Position
mystring.find ( substring, start )
“find( )” can locate a substring’s place.
“Substring” means a substring that needs to search.
“start” means a start index to find a substring.
Example 4.9
#include<string>
#include <iostream>
using namespace std;
int main( ) {
string mystring = "An operating system.";
string substring = "system";
int position = mystring.find ( substring, 0 ); // get index
cout << "The position of substring is at: " << position << endl;
return 0;
}; (Output: The position of substring is at: 13 )
Explanation:
“system” locates index 13 in string “An operating System”. Note that string
index begins with 0. One space in string equals one character size.
Insert a Substring
originalString = insert ( index, substring );
“originalString = insert ( index, substring );” can insert a substring into an
original string.
“index” means a position where inserting a substring.
Example 4.10
#include<string> #include <iostream> using namespace std; int main( ) {
string originalString = "Flower is beautiful!"; string substring = "very ";
originalString.insert ( 10, substring); // insert a string cout << originalString
<< endl; return 0;
}; ( Output: Flower is very beautiful! )
Explanation:
“originalString.insert ( 10, substring);” inserts a substring “very” into an original
string “Flower is beautiful” at the index 10.
Hands-On Project: Show Inputted
String Operation Program
Write C++ codes to your favorite editor.

#include <string> #include <iostream> using namespace std; int main(){


string myString; // declare a string variable cout << "Please enter a sentence,"
<< endl; cout << "then Enter!" << endl; getline(cin, myString); // input “Java
in 8 Hours”
cout << "You have inputed: " << myString << endl; return 0; }

Save, and run the program.


Input “Java in 8 Hours”, and “Enter”, you can see the output:
Output:
You have inputted: Java in 8 Hours
Explanation:
“#include <string>” imports string method to manipulate string of text.
“string myString;” defines a string variable.
“getline(cin, myString);” is used to input a string of text including spaces.
“cout << "You have inputed: " << myString << endl;” displays the data you
have input.
Hour 5
Class & Object
Class Definition
A class is a template for an object, and can create an object. The class represents
one kind of something. An object represents a concrete thing.

class ClassName { // define a class public:


// specify the access permission type variable; //
define a variable type function-name( ) { }; // define
a method };
Example 5.1
class Color { // create a class named Color public: // specify a access
permission string c1, c2; // declare two variable members void brightness ( ) {
cout << "blue" <<endl; }; // a method };
Explanation:
Above codes define a class named “Color”, access permission “public”, two
variables named “c1”, “c2” and a method named “brightness”.
Variables and method in a class are called as “members”.
Object Declaration
Object is an instance of a class.

ClassName ObjectName; // create an object


Object.variable; // an object references a variable
Object.method-name( ); // an object references a
method
Example 5.2
Color Tint; // create an object named "Tint".
Tint.c1= "yellow"; // an object references a variable
Tint.c2="purple"; // an object references a variable Tint.brightness ( ); // an
object references a method
Explanation:
“Color Tint;” creates an object named “Tint”, then Tint references variable “c1”
and “c2”.
“Tint.brightness ( );” means that an object “Tint” references a method
“brightness ( );”
Class & Object

class ClassName{ }; // define a class ClassName


ObjectName; // create an object
Example 5.3
#include<string> #include <iostream> using namespace std; class Color { //
create a class named Color public: // specify a access permission string c1, c2;
void brightness ( ) { cout << "Green" <<endl; }; };

int main( ) {
Color Tint; // create an object named "Tint".
Tint.c1= "Red "; Tint.c2="Yellow "; cout << Tint.c1 << endl; cout << Tint.c2
<< endl; Tint.brightness ( ); return 0;

}
Output:
Red
Yellow
Green
Explanation:
“class Color” defines a class “Color”.
“Color Tint;” creates an object “Tint”.
“Tint.c1” means an object “Tint” references a variable “c1”.
“Tint.brightness ( );” means an object “Tint” calls a method “brightness( ).”
Constructor
Constructor is used to initialize variables. Constructor name is the same as class
name.

class ClassName{

ClassName( ) { …} ; // this is a constructor };

class ClassName{ …} defines a class.


ClassName( ) { …} declares a constructor.
Example 5.4
#include<string> #include <iostream> using namespace std; class Color { //
create a class named Color public: // specify an access permission string c1,
c2; void brightness ( ) { cout << "Green" <<endl; }; Color ( ) { c1="Red";
c2="Yellow"; }; // constructor };

int main( ) {
Color Tint; // create an object named "Tint".
cout << Tint.c1 << endl; cout << Tint.c2 << endl; Tint.brightness ( ); return 0;

}
Output:
Red
Yellow
Green
Explanation:
“Color ( ) { c1=”yellow”; c2=”purple”; }” is a constructor. It initializes
variable c1 as “yellow” and c2 as “purple”.
Destructors
A destructor is used to release the memory occupation, clean up the constructor
data.
~ destructor( );
Destructor name is the same as class name, but it is preceded by a ~ symbol.
Destructor has no any arguments, and has no return value.
Example 5.5
class Color { // define a class public:
string c1, c2; Color ( ) { c1=”yellow”; c2=”purple”; } ; // constructor ~ Color (
); // This is a destructor.

};
Explanation:
“~ Color ( );” is a destructor.
The declaration of destructor must follow the constructor.
Inheritance
A class can be inherited by its derived class. The object in derived class can be
treated as the object in base class.
The derived class inherits base class as following:

derived class: public base class


Example 5.6
class Computer // base class

// base class member…

};

class Laptop: public Computer // derived class {


// derived class member…

};
Explanation:
“Laptop” is a derived class, “Computer” is a base class.
“Laptop” class inherits “Computer” class.
Derived class inherits public member in base class.
Using Derived class

An object of a derived class can access the public member of a base class.
Example 5.7
#include<string>
#include <iostream> using namespace std; class Computer { // base class
public:
void display( ){
cout << "Computer OK!" << endl; }

};

class Laptop: public Computer { // derived class // derived class’s


member……

};

int main ( ){
Laptop Lt; // derived class creates an object Lt Lt. display( ); // Lt calls base
class’s method return 0;

}
Output:
Computer OK!
Explanation:
“Lt. display( );” means a derived class’s object “Lt” calls base class’s method
display( ).
Public Permission

“public” is one of the “Member Access Specifier”,.

public class members can be accessed by the object


in the current class or another class
Example 5.8
#include<string> #include <iostream> using namespace std; class Computer {
public: // define public permission void display( ){
cout << "Computer OK!" << endl; }

};

int main( ){
Computer obj; // create an object obj.display( ); // object references method
return 0;

}
Output:
Computer OK!
Explanation:
“obj.display( );” indicates an object “obj” calls “display( ){ }”.
Note that “obj” is outside the class “Computer”, but “obj” can access the public
member “display( ){ }”.
Private Permission
“private” is one of the “Member Access Specifier”,.
private class member can be accessed by the object in
the current class, but not in a derived class, not in
another class
Example 5.9
#include<string>
#include <iostream> using namespace std; class Computer {
private: // define private permission
void display( ){
cout << "Computer OK!" << endl; }} ;
int main( ){
Computer obj; // create an object obj.display( ); // error! References a
private method return 0;
} ( Output: Error Messages )
Explanation:
“ obj.display( );” indicates an object “obj” calls “display( ){ }”.
Note that “obj” is outside the class “Computer”, so “obj” cannot access the
private member “display( ){ }”.
Private Example
Example:
#include <string> #include <iostream> using namespace std; class Flower {
private: // define private permission string color = "The flower is red"; //
“color” is a private member public: void show(){
cout<< color; // access the private member }}; int main( ){
Flower obj; // create an object obj.show(); // ok! References a public method
return 0; }
Output:
The flower is red
Explanation:
Private variables can be accessed by the codes only in the same class.
Protected Permission
“protected” is one of the “Member Access Specifier”,.
protected class member can be accessed by the object
in the current class and derived class, but not in
another class.
Example 5.10
#include <iostream> using namespace std; class A {
protected: // define protected permission int prot; // declare a protected
member };

class B:A { // inheritance public:


void myfunction(){
prot = 100; // access protected member, ok!
cout << prot; }

};

int main(){
B obj;
obj.myfunction(); return 0;

}
Output:
100
Explanation:
“protected: int prot;” declares a protected member.
“prot = 100;” access protected member of the base class, because the protected
member in base class can be accessed by derived class.
Class Method

Sometimes a method needs to be defined outside a class.


ClassName:: method( ) { }
:: is used to specify the method belonging to a class.
Example 5.11
#include<string>
#include <iostream>
using namespace std;
class Time { // define a class
public:
void setHour( int);
int hour;
};
void Time::setHour(int h){ // class method
int hour = h;
cout << "The hour is : " << hour << endl;
}
int main( ){
Time obj; // create an object
obj.setHour(10);
return 0;
}
Output:
The hour is: 10
Explanation:
“void Time::setHour(int h){ }” defines a method outside the class. It means that
“Time” class has a method “setHour(int h ){ }”.
“int hour = h;” means a variable “h” access a public member “hour”.
Access Private Member

Private Member is only accessed in the same class.


Example 5.12
#include<string>
#include <iostream> using namespace std; class Time { // define a class public:
void setHour(int); private: int hour; // hour is a private member };
void Time::setHour(int h){
int hour = h; //“h” accesses private member “hour”, ok!
cout<< hour; }

int main( ){
Time obj; // create an object obj.setHour(10); return 0;

}
Output:
10
Explanation:
“void Time::setHour(int h){ }” defines a method outside the class. It means
“setHour( ){ }” belongs to the class “Time”.
“int hour = h;” means a variable “h” access a private member “hour” in the same
class. It’s valid!
Hands-On Project: My House
Class & Object
Write C++ codes to your favorite editor.

#include<string> #include <iostream> using namespace std;

class House{ // define an object “House”


public: // set access permission int height;
int width;
string color;
string size;

};

int main( ) {
House myHouse; // create an object “myHourse”
myHouse.height = 100; // object references variable myHouse.width = 200;
// object references variable myHouse.color = "white"; // object references
variable myHouse.size = "big"; // object references variable cout << "Height:
"<< myHouse.height <<endl; cout << "Width: "<< myHouse.width <<endl; cout
<< "Color: "<< myHouse.color <<endl; cout << "Size: "<< myHouse.size
<<endl; return 0;

Save, and run the program.


Output:
Height: 100
Width: 200
Color: white
Size: big
Explanation:
“class House” creates a class named “House”.
“House myHouse” creates an object named “myHourse”.
“myHouse.height = 100;” sets the value of 100 to variable “height”.
“cout << "Height: "<< myHouse.height <<endl;” gets and shows the value of the
“height.
Hour 6
Pointer & Reference
Pointer
A pointer is a variable that stores the memory address of the variable. Pointer
name is preceded by a “ * ”.

dataType *PointerName;
pointerName = &variable;

“dataType *PointerName ” defines a pointer.


“pointerName = &variable;” stores address of the variable into pointer. “&”
means memory address.
Example 6.1
#include <string> #include <iostream> using namespace std; int main( ) {
int num = 10; int *numPointer ; // defines a pointer numPointer =
&num; // stores address of num to pointer cout << "Address of num is: " <<
numPointer << endl; cout << "Value of num is: " << *numPointer <<endl; return
0;

}
Output:
Address of num is: 0x22ff58
Value of num is: 10
Explanation:
“numPointer” represents the address of “num”.
“*numPointer” represents the variable of “num”.
Pointer Initialize

dataType *PointerName = &variable;


“dataType PointerName = &variable” declares and initializes a pointer, stores
the memory address of the variable into PointerName”. “&” means memory
address.
Example 6.2
#include <string> #include <iostream> using namespace std; int main( ) {
int digit = 20; int *digitPointer = &digit; // initializes a pointer cout <<
"Address of digit is: " << digitPointer << endl; cout << "Value of digit is: " <<
*digitPointer << endl; return 0;

}
Output:
Address of digit is: 0x22ff58
Value of digit is: 20
Explanation:
“int *digitPointer = &digit;” declares and initializes a pointer. “digitPointer”,
stores the memory address of “digit”
“digitPointer” represents the address of “digit”.
“*digitPointer” represents the variable of “digit”.
Using Pointer

“int pointer1 = &x” means that pointer1 is x


variable.
“int pointer2 = &y” means that pointer2 is y
variable.
Example 6.3
#include <string> #include <iostream> using namespace std; int main( ) {
int x =10, y; int pt1 = &x, pt2 = &y; // declare & initialize two pointers pt2 =
pt1; // namely y = x; *pt1= 20; // namely x = 20; cout << x << " " << y
<<endl; cout << pt1 << " " << pt2 << endl; return 0;

}
Output:
20 10
20 10
Explanation:
“*pointer” represents a variable when running program.
“int pt1 = &x” means that pt1 is “x” variable.
“int pt2 = &y” means that pt2 is “y” variable.
“pt2 = pt1;” namely “y=x”.
“*pt1= 20;” namely “x=20”.
Exchange Pointers

pt=pt1; pt1=pt2; pt2=pt;


“pt1” exchanges “pt2” in the above codes.
Example 6.4
#include <string> #include <iostream> using namespace std; int main( ) {
int *pt, x, y; int *pt1 = &x; // *pt1 is x variable int *pt2 = &y; // *pt2 is y
variable x= 100, y = 200; cout << x << " " << y << endl; pt=pt1; pt1=pt2;
pt2=pt; // exchange pointers cout << pt1 << " " << pt2 << endl; return 0;

}
Output:
100 200
200 100
Explanation:
“*pt” represents a variable when running program.
Before exchanging pts, *pt1 represents x, *pt2 represents y.
After exchanging pts, *pt1 represents y, *pt2 represents x.
Pointer and Array

*pointer = array;
“*pointer = array;” means that the pointer points to the first element of the array
Example 6.5
#include <string> #include <iostream> using namespace std; int main( ) {
int myarray[ 3 ] = { 10, 20, 30 }; int *pt = myarray; // pointer points to the first
element myarray[0]
cout << "The first value is: " << *pt << endl; pt++; // move pointer to next
element myarray[1]
cout << "The second value is: " << *pt << endl; pt++; // move pointer to next
element myarray[2]
cout << "The third value is: " << *pt << endl; return 0;

}
Output:
The first value is: 10
The second value is: 20
The third value is: 30
Explanation:
“int *pt = myarray;” means that the pointer points to the first element of
“myarray”. Namely myarrray[0].
“pt++” moves the pointer to next element.
“*pt” represents the array element.
Pointer Array

int a, b, c;
int *pointer[n] = { &a, &b, &c };
“int *pointer[n] = { &a, &b, &c };” declares a pointer array.
Example 6.6
#include <string> #include <iostream> using namespace std; int main( ) {
int a, b, c;
a = 10, b = 20, c = 30; int *myarray[3] = { &a, &b, &c }; // declare a pointer
array cout << myarray[0] + myarray[1] << endl; // a + b cout << myarray[2]
- myarray[1] << endl; // c - b return 0;

}
Output:
30
10
Explanation:
“int *myarray[3] = { &a, &b, &c };” declares a pointer array.
*myarray[0] represents “a” variable.
*myarray[1] represents “b” variable.
*myarray[2] represents “c” variable.
Pointer & String

char *pointer = “mystring”;


“char *pointer = “mystring”;” defines a pointer which points to the first
character of the “mystring”.
Example 6.7
#include <string>
#include <iostream> using namespace std; int main( ) {
char *pt = "mystring"; int counter = 0; // define a counter while ( *pt!=0 ) {
// pointer points to a character counter++; // counts how many characters
pt++; // pointer moves to the next character }
cout << counter; // output the number of characters.
return 0;

}
Output:
8
Explanation:
“char *pt = “mystring”;” make the pointer points to the first character of
“mystring”.
*pt!=0 means that the pointer does not point to nothing.
“pt++” moves the pointer points to the next character in “mystring”.
Reference a Variable

The reference is an alias for a variable or an object. A reference name is


preceded by a symbol “&”.

dataType &reference = variable;


“&reference” is an alias for the variable.
Example 6.8
#include <string> #include <iostream> using namespace std; int main( ) {
int num;
int &r = num; // “r” is an alias of “num”
r = 100;
cout << num << endl; // num equals r num = 200;
cout << r << endl; // r equals num return 0;

}
Output:
100
200
Explanation:
“int &r = num” defines that the alia of “num” is “r”.
“r = 100;” indicates “num = 100”.
“num = 200;” indicates “r = 200”.
Reference an Object

ClassName &reference = object


“&reference” is an alias for the object.
Example 6.9
#include <string> #include <iostream> using namespace std; class Color{
public:
void display(); };
void Color:: display( ){
cout <<"The color is blue." << endl; }

int main( ) {
Color Tint; // create an object "Tint"
Color &r = Tint; //"r" is an alias of "Tint"
r.display( ); // namely Tint.dispaly(); return 0;

}
Output:
The color is blue.
Explanation:
“Color &r = Tint;” references an object “Tint”, whose alias is “r”.
“r.display( );” means that a referenced object can call a method “display( ){ }”.
Reference Arguments

dataType functionName ( &a, &b ) { }


“functionName ( &a, &b )” means that function arguments can be referenced.
Example 6.10
#include <string> #include <iostream> using namespace std; void swap ( int
&a, int &b) { // reference arguments int temp;
temp = a, a = b, b = temp; // reference exchange }

int main( ) {
int x = 10, y = 20; cout << x << " " << y << endl; swap ( x, y ); cout << x << " "
<< y << endl; return 0;

}
Output:
10 20
20 10
Explanation:
“void swap ( int &a, int &b)” uses the reference in the argument.
Before swap, “a” is an alias of “x”, “b” is an alias of “y”.
After swap, “a” is an alias of “y”, “b” is an alias of “x”.
Hands-On Project: Address
Pointer Sample Program
Write C++ codes to your favorite editor.

#include<iostream> using namespace std; int main( ){


int x=100, y=200; int *xPointer = &x; // declare and initializes a pointer int
*yPointer; // declare a pointer yPointer=&y; // store address of “y” to
pointer cout<<"X value: "<<*xPointer<<endl; // show value cout<<"X
address: "<<xPointer<<endl; // show address cout<<"Y value: "
<<*yPointer<<endl; // show value cout<<"Y address: "<<yPointer<<endl;
// show address return 0;

}
Save, and run the program.
Output:
X value: 100
X address: 0x22ff54
Y value: 200
Y address: 0x22ff50
Explanation:
“int *xPointer = &x;” declares and initializes a pointer.
“xPointer” represents the address of “x”.
“*xPointer” represents the variable of “x”.
“int *yPointer;” declares a pointer.
“yPointer=&y;” stores address of “y” to pointer.
“cout<<"X value: "<<*xPointer<<endl;” shows the value of “*xPointer”.
“cout<<"X address: "<<xPointer<<endl;” shows the address of “xPointer”.
Hour 7
File Operation
Output One Character
cout.put (char C)
“cout.put (char C)” outputs one character.
Example 7.1
#include <string> #include <iostream> using namespace std; int main( ) {
char ch = 'C'; // Note: use single quote.
cout.put (ch) << endl; // output one character return 0;

( Output: C )
Explanation:
“#include <iostream>” includes iostream class that helps to input or output.
“cout.put ( ch )” display one character “C”.
Output String
cout.write (stringArray, stringLength);
“cout.write( )” can output a string.
“stringArray” defines the string as an array.
“stringLength” defines the string size.
Example 7.2
#include <iostream> #include <string.h> using namespace std; int main(){
char ch[ ]="This is a test"; // define a string array cout.write(ch, strlen(ch))
<<endl; // output a string return 0;
} ( Output: This is a test )
Explanation:
“ch[ ] = “This is a test” defines a string array.
“strlen ( ch )” gets the size of “ch” as the output length.
cout.write ( ) is used to output a string.
Input One Character
cin.get (char c );

“cin.get (char c );” is used to input one character by keyboard.


Example 7.3
#include <iostream> #include <string.h> using namespace std; int main(){
char c;
cout << "Input one character: "<< endl; cin.get ( c ); // input one character
cout << c <<endl; return 0;
} ( Output Input one character: )
Explanation:
“cin.get ( c );” inputs one character “A” by keyboard.
“cout << c <<endl;” displays what have inputted.
Input String
cin.read ( stringArray, stringLength);
“cin.read ( )” is used to input strings.
“stringArray” defines the string as an array.
“stringLength” defines the string size.
Example 7.4
#include <iostream> #include <string.h> using namespace std; int main(){
cout<< "Please input a sentence:"<< endl; char mystring[ 80]; // max length is
80
cin.read ( mystring , 10 ); // input 10 characters cout << "What you inputed
is: " << mystring << endl; return 0;
} ( Output: Please input a sentence: __ )
Explanation:
“char mystring[ 80 ];” defines a string array, whose maximum size is 80
characters.
“cin.read ( mystring, 10 )” inputs a sentence with 10 characters.
Input String Sentence
getline ( cin, mystring);
“getline ( cin, mystring);” can let user input a string sentence.
Example 7.5
#include <iostream>
#include <string.h> using namespace std; int main(){
string mystring; cout << "Please enter a sentence:" << endl; getline ( cin,
mystring ); // enter "C++ is very good"
cout << mystring << endl; return 0;
} ( Output: Please enter a sentence: C++ is very good )
Explanation:
“getline ( cin, mystring);” accepts the user input by sentence. When a user enters
“C++ is very good”, the value of “mystring” is “C++ is very good”.
Write a File

For operating file, you need to use #include <fstream>.

ofstream fileObject (“myFile.txt”); fileObject <<


mystring << endl;
“ofstream fileObject (“myFile.txt”);” creates an output file object “fileObject”.
“ofstream” class is used to write data to a file.
“fileObject” is an output file object.
“fileObject << mystring << endl;” writes mystring to file.
Example 7.6
// Please create an empty file “myFile.txt” in the Project Folder first.
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main(){
ofstream fileObject ( "myFile.txt" ); // create an object
string mystring = "C++ is a very good language.";
fileObject << mystring << endl; // write mystring to file
fileObject.close ( );
return 0;
}
Explanation:
“ofstream” class is used to write data to a file.
“ofstream fileObject ( “myFile.txt” );” creates an output file object “fileObject”.
“fileObject << mystring << endl;” writes mystring to the file “myFile.txt”.
In myFile.txt, you will find some texts as follow: C++ is a very good language.
Open a File
When opening a file, you can specify the “File Mode”.
Mode Usage
ios :: in open a file to read input
ios :: out open a file to write output
ios :: app open a file to append output
ios :: trunc open a file or truncate old file
ios :: ate open a file without truncating an old file
ios ::
open a file as binary file
binary
Example 7.7
ofstream fileObject ( “myfile.txt”, ios :: app ); //line1
ofstream fileObject ( “myfile.txt”, ios :: trunk ); //line2
ofstream fileObject ( “myfile.txt”, ios :: binary ); //line3
Explanation:
Line1: Open “myfile.txt”, append the output at the end of existing content.
Line2: Open “myfile.txt”, or truncate the existing file, and clear up all data.
Line3: Open “myfile.txt”, treat the file as binary format instead of text format.
Read a File

For operating file, you need to use #include <fstream>.

ifstream fileObject ( “myFile.txt” ); getline (


fileObject, mystring);

“ifstream fileObject ( “myFile.txt” );” creates an input file object “fileObject”.


“ifstream” class is used to read data from a file.
“fileObject” is an input file object.
“getline ( fileObject, mystring);” reads the file to mystring.
Example 7.8
// Please create a file “myFile.txt” in the Project Folder first.
// “myFile.txt” has content: “C++ is a very good language.”

#include <iostream> #include <fstream> #include <string> using namespace std;


int main(){
string mystring; ifstream fileObject ( "myFile.txt" ); // create an object
getline ( fileObject, mystring ); // reads file to mystring cout << mystring
<<endl; fileObject.close ( ); return 0;

}
Output:
C++ is a very good language.
Explanation:
“ifstream” class is used to read data from a file.
“ifstream fileObject ( “myFile.txt” );” creates an input file object “fileObject”.
“getline ( fileObject, mystring);” reads the file to mystring.
End of File

fileObject.eof ( );
“fileObject.eof( );” means that while reading data, eof( ) returns true at the end
of file, otherwise eof( ) returns false at somewhere on file.
Example 7.9
// “myFile.txt” has content: “C++ is a very good language.”

#include <iostream>
#include <fstream> #include <string> using namespace std; int main(){
char ch;
ifstream fileObject ( "myFile.txt"); while ( ! fileObject.eof( ) ) { // not at the end
of file fileObject.get (ch); // read characters from “myfile.txt”
cout << ch; // show all characters }
fileObject.close ( ); return 0;

}
Output:
C++ is a very good language.
Explanation:
“!fileObject.eof( )” indicates that “not at the end of file while reading data.”
“fileObject.get (ch);” keeps reading characters from “myfile.txt”
“fileObject.close( )” closes the file.
Hands-On Project: Process File
Read a File

(1) Please prepare myFile.txt as following: (myFile.txt)


PHP in 8 Hours!
JAVA in 8 Hours!
JQUERY in 8 Hours!
JAVASCRIPT in 8 Hours!
Save myFile.txt in the same project folder with the following C++ file.

(2) Write C++ codes to your favorite editor.

#include<fstream> #include<iostream> using namespace std; int main(){


char word;
ifstream fileObject("myFile.txt"); // create an object if(!fileObject){ // if file
is not existing cout<<"File is not existing" << endl; return -1; // -1 means
failure }
else{
while(!fileObject.eof()){ // if not the end of file fileObject.get(word); //
read the text to variable word cout<<word; // show the text }
fileObject.close(); return 0;

}
Save, and run the program.
Output:
PHP in 8 Hours!
JAVA in 8 Hours!
JQUERY in 8 Hours!
JAVASCRIPT in 8 Hours!
Explanation:
Note that myFile.txt and the current C++ file should be in the same folder.
“ifstream fileObject("myFile.txt");” creates an input file object “fileObject”.
“if(!fileObject)” checks the existence of “myFile.txt”.
“return -1;” means the program runs unsuccessfully.
“if(!fileObject.eof())” checks the “end of the file”.
“fileObject.get(word)” reads characters from “myFile.txt”.
“cout<<word;” shows all characters in “myFile.txt”.
Hour 8
Static Exception Vector
this -> member

this -> member


“this” represents a current object.
“this -> member” means that the “current object” references a member variable
or member method.
Example 8.1
#include <iostream> using namespace std; class Time{
public:
int num;
void setHour(int num ); };
void Time::setHour( int num ){ // class method this->num = num; //"this"
represents current object cout << "The hour is: " << num << endl; }

int main() {
Time t; // creates an object "t"
t.setHour(10); return 0;

}
Output:
The hour is: 10
Explanation:
“this” represents object “t”.
Static Variable

Static variable can be referenced by a class or any objects. Non-static variable is


referenced only by the object, not by class.

static dataType variable; className :: variable;


“static” declaration means that the variable belongs to a class. “className ::
variable;” means that a class can references this static variable directly.
Example 8.2
#include <iostream>
using namespace std; class Account {
public:
static int num; // static declaration };
int Account :: num = 100; // class references a variable int main() {
cout << Account :: num << endl; return 0;

}
Output:
100
Explanation:
“static int num” means a static variable “num” can be referenced by a class or an
object.
“Account :: num” means a class “Account” can reference a static variable
“num”.
Non-static variable is referenced only by the object, not by class.
Static Function

Static function can be referenced by a class or any objects. Non-static function is


referenced only by the object, not by class.

static dataType function( ); className :: function( );

“static” declaration means that function belongs to a class. “className ::


function( );” means that a class can references this static function directly.
Example 8.3
#include <iostream> using namespace std; class Account {
public:
static int myfunction( int n ); // static declaration };
int Account :: myfunction(int n){ // class method return n;

int main() {
cout << Account :: myfunction( 200 ) << endl; /* a class references a method
directly */
return 0;

}
Output:
200
Explanation:
“static int myfunction(int n)” means a static function “myfunction(int n)” can be
referenced by a class or an object.
“Account :: myfunction ( 200)” means a class “Account” can references a static
function “myfunction( 200 )”.
Non-static function is referenced only by the object, not by class.
A++ or ++A
++A A plus 1 first, then run expression
A++ Run expression first, then A plus 1
--B B minus 1 first, then run expression
B-- Run expression first, then B minus 1.
Example 8.4
int A = 10, num; num = ++A - 2; /* A plus 1equals 11, 11 minus 2 equals 9, then
the result “9” assigns to num.*/
cout << num << endl; // ( output: 9 )
Example 8.5
int A = 10, num; num = A++ - 2; /* A minus 2 equals 8, the result “8” assigns to
num, then A plus 1.*/
cout << num << endl; // ( output: 8 )
Explanation:
“++A” increases 1 first, and then runs the expression.
“A++” runs the expression first, and then increases 1.
Call My Own Function

A function body includes its own function with the same function name, which
is known as a recursive function.
Example 8.6
#include <iostream> using namespace std; void myself(int n); int main() {
myself ( 1 ); return 0;

void myself ( int n){ // define a function cout << "Number " << n << endl;
++n;
if ( n == 4) return; // return means stop running else myself ( n ); // the
embedded function calls myself() }
Output:
Number 1
Number 2
Number 3
Explanation:
“void myself ( int n){ }” body contains an embedded function “myself(n);”
and “void myself ( int n)” is called by “myself(n);”, which is known as recursive
function.
“else myself ( n );” calls “void mysef (int n){… }” just like the loop statement,
until n equals 4, then leaves the loop statement.
Local & Global Variable

Local variable is defined inside the function.


Global variable is defined outside the function.
The local variable is only visible in the current function.
The global variable is visible in any function.
Example 8.7
#include <iostream> using namespace std; void test1(); void test2(); int main(){
test1();
test2();
return 0;

int a = 100, b = 200; // global variable void test1 ( ) { // define a


function int x =30, y =40; // local variable cout << a << "," << b << endl;
cout << x << "," << y << endl; }
void test2 ( ) { // define a function int x =50, y =60; // local
variable cout << a << "," << b << endl; cout << x << "," << y << endl; }
Output:
100, 200
30, 40
100, 200
50, 60
Explanation:
“a” and “b” are global variables, which are visible in any function.
“x” and “y” are local variables, which are visible only in the current function.
Exceptions
C++ program may have some bugs, which calls “Exceptions”.
The main exceptions as following:
Exceptions Situations
domain_error out of precondition
invalid_argument invalid argument in function
length_error size too long or short
out_of_range invalid range
overflow_error data overflow
Example 8.8
int main( ) {
int a, b=0;
a=100/b; // exception occurs!
cout << a << endl;return 0; return 0;

( Output: Exception: ArithmeticException: / by zero)


Explanation:
“100/b” causes an Exception, because “b” is zero.
Try-Catch

For “try-catch”, you need to use #include<stdexcept>.

try

{ …}

catch(exception) {……}
“try {… …}” throws the exception out to the catch( ) { } block when an
exceptional error occurs.
“catch( ){ }” catches any exception from the try block, and handles it.
Example 8.9
#include <iostream>
#include <stdexcept>
using namespace std;
int main(){
string str1="JavaScript";
string str2="and";
try{ // exception may occur
str1.insert(100, str2); // “100” causes error
}
catch(logic_error){ // process the exception
cout << "Catch an exception." << endl;
cout << "Out of range!" << endl;
}
return 0;
}
Output:
Catch an exception.
Out of range!
Explanation:
In try{ } block, “str1.insert(100, str2);” causes an exception.
“catch(logic_error){ }” catches the exception.
Return Exception Message

try

{…}

catch(exception& e) { cout << e.what( ) <<endl; }


“e.what( )” can return exception message.
Example 8.10
#include <stdexcept> #include <iostream> using namespace std; int main ()

string str = "JavaScript"; try{


str.at(100);

catch(exception& e) { // e is an exception object cout<<"Catch an exception: "


<< e.what( ) << endl; // “e.what( )” shows exception message.

return 0;

}
Output:
Catch an exception: basic_string:: at
Explanation:
“catch(exception& e)” can catch an exception. Note that its parameters are
“exception &e”, “e” is an exception object.
“e.what( )” returns exception message.
Throw Exception

try
{… throw…}
catch

{……}

“throw” can throw out an exception catch block that can handle the exception.
Example 8.11
#include <stdexcept> #include <iostream> using namespace std; int main (){
try{
int a=100, b=0; if(b==0){
throw b; // throw out an exception a=a/b;

catch (int e){ // handle the exception cout << "An exception occurred." <<
endl; cout << "The exception integer division by " << e ; }
return 0;

}
Output:
An exception occurred.
The exception integer division by 0
Explanation:
“throw b;” throws an exception from b. If b equals zero, a/b will be an error.
“catch (int e){ }” can catch and handle the exception.
Vector
Vectors are similar to arrays that can change in size. Just like arrays, vectors can
be any data type and its first index starts with zero.
If use vector in coding, C++ <vector> library must be included by #include
<vector> at the beginning of the program.
The syntax of creating a vector looks like this:
Vector <datatype> vector-name (size);
Example 8.12
vector <int> myVector (10); // Line 1
vector <double> prices (60); // Line2
vector <string> titles (18); // Line 3
Explanation:
Line 1: Declares a vector of 10 integer elements.
Line 2: Declares a vector of 60 double elements.
Line 3: Declares a vector of 18 string elements.
Vector.method( )

push_back(value) add an element to the end of the vector

size( ) return the size of the vector


at(index) return the value at specified index
pop_back( ) delete the last element
Example 8.13
#include <vector>
#include <iostream> using namespace std; int main (){
vector < int > myVector(1); // create a vector with 1 element.
myVector.push_back(20); // add an element 20 to the end
myVector.push_back(30); // add an element 30 to the end cout<< "myVector
size: " << myVector.size( ) << endl; // gets the number of elements cout<< "The
third element: " << myVector.at(2) << endl; // gets the value at index 2
myVector.pop_back( ); // removes the final element cout<< "Final element has
been removed."<< endl; return 0;

}
Output:
myVector size: 3
The third element: 30
Final element has been removed.
Explanation:
vector < int > myVector ( 1 ) creates a vector with 1 element.
myVector.push_back(20) adds an element with value 20 to the end of the vector.
myVector.push_back(30) adds an element with value 30 to the end of the vector.
myVector.size( ) gets the number of elements in myVector.
myVector.at(2) gets the value whose index is 2.
myVector.pop_back( ) removes the final element in myVector.
Vector.method( )
front( ) return the value of the first element

back( ) return the value of the last element

clear( ) clear the vector

empty( ) return 1 if the vector is empty, or 0 if not empty


Example 8.14
#include <vector> #include <iostream> using namespace std; int main (){
vector < int > myVector ( 1 ); myVector.push_back(20);
myVector.push_back(30); cout<< "The first element: " << myVector.front( )
<<endl; // get the value of the first element cout<< "The last element: " <<
myVector.back( ) <<endl; // get the value of the last element myVector.clear(
); // clear all elements cout<< "myVector is empty? " << myVector.empty( )
<<endl; // check if the vector is empty return 0;

}
Output:
The first element: 0
The last element: 30
myVector is empty? 1
Explanation:
vector < int > myVector ( 1 ) creates a vector with 1 element.
myVector.push_back(20) adds an element with value 20 to the end of the vector.
myVector.push_back(30) adds an element with value 30 to the end of the vector.
myVector.front( ) returns the value of the first element.
myVector.back( ) returns the value of the last element.
myVector.clear( ) clears myVector.
myVector.empty( ) tests myVector to see if is empty.
“1” represents true, “0” represents false.
Hands-On Project: Error Occurs!
Exception Handling Program
Write C++ codes to your favorite editor.

#include<stdexcept> #include<iostream> using namespace std;


int main(){
string myString1 = "Java in 8 Hours" ; string myString2 = "eBook";
try{ // exception may occur!
cout<<"Original: "<<myString1<<endl;
myString1.insert(100,myString2); // exception cout<<"New String: "
<<myString1<<endl; }
catch(out_of_range){ // process the exception cout<< "Exception: Out of
range!"; return 0; }

Save, and run the program.


Output:
Original: Java in 8 Hours Exception: Out of range!
Explanation:
“myString1.insert(100,myString2);” inserts mystring2 to mystring1 at the index
of 100.
Because mystring1 has no index 100, an exception occurs.
“try block” contains the codes where an exceptional error may occur.
“catch block” contains the codes where the exception error will be caught and
handled.
Appendix
C++ 100 Tests & Answers
100 Tests
1. The file extension of C++ is___?
A. .hpp
B. .cbb
C. .cpp
D. .c++

2. C++ program must have a function called__?


A. function( )
B. main( )
C. compile( )
D. iostream( )

3. What does #include <iostream> mean__?


A. include anther c++ file named iostream
B. include ios’s app
C. include information from the input/output library named isotream
D. All above

4. After the execution of a program, return 0 means__?


A. return false
B. return true
C. the program executed wrongly
D. the program executed correctly

5. About C++ comments, which following is correct?


A. // is used in multiple line comments
B. /* */ are used in single line comments
C. Both // and /* */ can be used in single line or multiple comments.
D. // is used in single line comments and /* */ are used in multiple
comments.
6. Which following variables naming rules is correct__?
A. 3vars
B. has space
C. class
D. goodvar

7. Which following is not the C++ data type?


A. varChar
B. char
C. int
D. bool

8. Which following express is correct?


A. cout >> “Hi, Enter your name:”;
B. cin<< myvar;
C. cout>>”You name is:”>>myvar>>endl;
D. cout<<”You name is: ”<<myvar<<endl;

9. Which following express is correct?


A. double arr[3]={100, 200, 300};
B. int arr[3]={true, false, true};
C. int arr[3]=[2.00, 3.08, 22.9];
D. char arr[3]={‘a’, ‘b’, ‘c’};

10. About Vectors, Which following is not correct?


A. back( ), gets the value of the final element
B. clear( ), erases all variable’s value
C. front( ), gets the value of the first element
D. size ( ), gets the number of elements

11. To declare a vector, which following is correct?


A. vector <datatype> vector-name (size, value);
B. vector-name <datatype> vector (size, value);
C. vector-name (size, value) vector <datatype>;
D. vector (size, value) vector-name <datatype>;

12. To define a constant, use__?


A. #declare CONSTANT-NAME “text-string”
B. #include CONSTANT-NAME “text-string”
C. #create CONSTANT-NAME “text-string”
D. #define CONSTANT-NAME “text-string”

13. To convert a data type, use__?


A. variable-name = (convert) variable-name;
B. variable-name = (change) variable-name;
C. variable-name = (modify) variable-name;
D. variable-name = (datatype) variable-name;

14. Which following statement is not correct?


A. ++ means increment
B. - - means decrement
C. * means multiplication
D. % means division

15. Which following statement is not correct?


A. === means logical EQUAL
B. && means logical AND
C. || means logical OR
D. ! means logical NOT

16. Which following express is not correct?


A. a += b means a = (a + b)
B. a != b means a = (a ! b)
C. a = b means a = (a b)
D. a %= b means a = (a % b)
17. Which following statement is not correct?
A. == means equal to
B. !== means not equal to
C. >= means greater than or equal to
D. <= means less than or equal to

18. About? and: conditional operator, use__?


A. if( ) ? then{ }: else{ }
B. switch( ) ? case “ “: case “ “:
C. (test-expression) ? if-false-do-this : if-true-do-this;
D. (test-expression) ? if-true-do-this : if-false-do-this;

19. sizeof( ) operator returns__?


A. a float value that is a number of bytes
B. a float value that is a number of megabytes
C. an integer value that is the number of bytes
D. a bool value

20. Which following has the highest precedence?


A. ||
B. !
C. &&
D. %

21. Which following is a correct statement?


A. if ( ) { } else { }
B. if ( ) then { } else { }
C. if ( ) then { } then else { }
D. if ( ) then { } if else { }

22. What is the output?


#include <iostream> #include <string> using namespace std; int main(){
char myvar = '4'; switch ( myvar ) {
case'1':cout<<'1'; break; case'2':cout<<'2'; break; case'3':cout<<'3'; break;
default: cout<<"The number is not 1,2,3"<<endl; }
return 0; }
If myvar is 4, What is the output?
A. 1
B. 2
C. 3
D. The number is not 1,2,3.

23. What is the output?


#include <iostream> #include <string> using namespace std; int main(){
int result = 0; for( int n=1; n<=100; n++){
result+=n;

cout<<"result="<<result<<endl; return 0; }
What is the output?
A. 100
B. 1000
C. 5000
D. 5050

24. What is the output?


#include <iostream> #include <string> using namespace std; int main(){
int i =1, result=0; while(i<=100) {
result=result + i;
i++;

cout<<"result="<<result<<endl; return 0; }
What is the output?
A. 100
B. 1000
C. 5000
D. 5050

25. What is the output?


#include <iostream> using namespace std; int main( ) {
int i=1,result=0; do {
result = result + i;
i++;
}while(i<=100); cout<<"result="<<result<<endl; return 0; }
What is the output?
A. 100
B. 1000
C. 5000
D. 5050

26. What is the output?


#include <iostream> using namespace std; int main( ) {
int i=0; while(i< 10) {
++i;
if(i==3) break; cout << "The number is "<< i <<endl; }
return 0; }
What is the output?
A. The number is 1
B. The number is 1 The number is 2
C. The number is 1 The number is 2 The number is 3
D. The number is 1,2,3

27. What is the output?


#include <iostream> using namespace std; int main( ) {
int i=0; while (i<4) {
++i;
if ( i ==2) continue; cout<< "The number is " <<i<< " "; }
return 0; }
What is the result?
A. The number is 1
B. The number is 1 The number is 2
C. The number is 1 The number is 3 The number is 4
D. The number is 1,2,3

28. To declare a string, which following is not correct?


A. string str1 (“This is string 1”);
B. string str2; (“This is string 2”);
C. string str3 = “This is string 3”;
D. string str4; str4 = “This is string4”;

29. To get a string input, use__?


A. input>>
B. input<<
C. cin>>
D. cin<<

30. To get the length of a string, use__?


A. str.size( )
B. str.length( )
C. str.count( )
D. str.calculate( )

31. What does #include <string> mean__?


A. include anther c++ file named string
B. include <string> class so as to allow string datatype available.
C. include STRING constant
D. all above

32. To test an empty string, use__?


A. str.empty( )
B. str.none( )
C. str.isString( )
D. str.blank( )

33. To concatenate two strings, use__?


A. str.connect(“New String”;)
B. str.concatenate(“New String”;)
C. str.join(“New String”;)
D. str.append(“New String”;)

34. To compare two strings, use__?


A. str1.contrast.str2
B. str1.identify. str2
C. str1.compare.str2
D. if (str1===str2) { }

35. To copy string variable value, use__?


A. str1.copy(str2)
B. str1.duplicate (str2)
C. str1.reproduce(str2)
D. str1.assign(str2)

36. To exchange two string variable values, use__?


A. str1.exchange(str2)
B. str1.swap(str2)
C. str1.trade(str2)
D. str1.barter(str2)
37. To locate a substring from a string , use__?
A. str. locate(substring, begin position)
B. str. trace(substring, begin position)
C. str. find(substring, begin position)
D. str. seek(substring, begin position)

38. To insert a string to another string, use__?


A. str.insert(begin position, substring)
B. str.add(begin position, substring)
C. str.create(begin position, substring)
D. str.put(begin position, substring)

39. To delete a substring from a string, use__?


A. str.delete(begin position, removed length)
B. str.remove(begin position, removed length)
C. str.erase(begin position, removed length)
D. str.clear(begin position, removed length)

40. To replace a substring from a string, use__?


A. str.replace(begin position, removed length, substr)
B. str.substitute(begin position, removed length, substr)
C. str.change(begin position, removed length, substr)
D. str.alternate(begin position, removed length, substr)

41. To get a character from a string, use__?


A. str.retrieve(begin position)
B. str.get(begin position)
C. str.extract(begin position)
D. str.at(begin position)

42. What does #include <fstream> mean?


A. include a C++ file named fstream.cpp
B. include <fstream> stream that can work with files
C. include <fstream> class that can work with files
D. All above

43. What is the output?


#include <iostream> using namespace std; int main( ) {
int integers[50]; cout << sizeof (integers) << endl; return 0; }
A. 200
B. 100
C. 50
D. 0

44. What is the output?


#include <iostream> using namespace std; int main( ) {
int a=35, b; float x=3.5; b=a%(int)x; cout<<b<<endl; return 0; }
What is the output?
A. 0
B. 1
C. 2
D. 3

45. To read characters from a file, use__?


A. fileObject.read(charVariable)
B. fileObject.retrieve(charVariable)
C. fileObject.get(charVariable)
D. fileObject.obtain(charVariable)

46. To read a line of text from a file, use__?


A. readline(fileObject, strVariable)
B. retrivevline(fileObject, strVariable)
C. obtainline(fileObject, strVariable)
D. getline(fileObject, strVariable)
47. Which following code is writing a file?
A. file-object<<str-var<<endl;
B. file<<str-var<<endl;
C. file-object>>str-var>>endl;
D. file>>str-var>>endl;

48. Which following manipulator example is not correct?


A. cout<< hex<<num<<endl;
B. cout<< oct<<num<<endl;
C. cout<< dec<<num<<endl;
D. cout<< boolapha<<num<<endl;

49. Which following statement is not correct?


A. To declare a function:
return-type function-name (arguments-list)
B. To define a function:
return-type function-name (arguments-list) {//code }
C. To call a function:
function-name ( );
D. To call a function:
function-name ( ) { }

50. What is the output?


#include <iostream> using namespace std; void calculate(int a, int b); int
main( ) {
int a=1; int b=2; calculate(a,b);
return 0; }

void calculate(int a, int b){


int sum=0; sum= a + b;
cout << "a+b=" << sum <<endl; }
What is the output?
A. a+b=1
B. a+b=2
C. a+b=3
D. a+b=4

51. What is the output?


#include <iostream> using namespace std; void testFunction(int num); int
twoTime(int num); int main( ) {
int num=9; testFunction(num);
return 0; }

void testFunction(int num) {


cout<<twoTime(num)<<endl; }
int twoTime(int num) {
return ( num*2); }
What is the output?
A. 16
B. 17
C. 18
D. 19

52. To define a class, use__?


A. define class class-name { }
B. new class class-name { }
C. create class class-name { }
D. class class-name { }

53. To define an object, use__?


A. define object object-name;
B. new object object-name;
C. create object object-name;
D. class-name object-name;
54. To define a class method, use__?
A. class-name:: method-name( ) { }
B. define method-name( ) { }
C. new method-name( ) { }
D. create method-name( ) { }

55. A special pointer named “this” that means__.


A. a class itself
B. an object itself
C. a method itself
D. a function itself

56. How “this” refer to a member?


A. this::member
B. this.member
C. this->member
D. this(member)

57. About constructor, which following statement is not correct?


A. The constructor method needs arguments which will initial value of the
class members
B. The constructor method must not include any return value.
C. The constructor method’s name must be the same as class name.
D. The constructor method is the same as destructors

58. About destructor method, which following is not correct?


A. destructor method has the same name as the class name.
B. destructor method has no any arguments
C. destructor method has no any return-data-type.
D. For example: &dest( ) is a destructor method.

59. What does testMethod const {//code}; means?


A. It is a constant object method, and never change its class member value.
testMethod is a name.
B. It is a method, which has a constant inside the code.
C. It is a function, it will be called by a constant.
D. All above

60. What will cout<<&variable<<endl; output?


A. It will output a variable name.
B. It will output a variable value.
C. It will output an object.
D. It will output a memory address of the variable.

61. Which following statement is not correct?


A. A pointer is a variable that stores the memory address of another
variable.
B. A pointer variable is declared by a *.
C. Assign an address to a pointer by &variable.
D. A pointer variable name references a memory address in decimal.

62. Which following statement is not correct?


A. ++ operator can move a pointer.
B. - - operator can move a pointer.
C. *= and /= can move a pointer.
D. += and -= can move a pointer.

63. Given an array: string myArr[5] = {“one”,”two”,”three”,”four”,”five”};


*mypointer=myArr; mypointer+=2; Where will pointer move to?
A. move to 1st element.
B. move to 2nd element.
C. move to 3rd element.
D. move to 4th element.

64. What is the output?


#include <iostream> using namespace std; int main( ) {
int x = 8; int *xpointer = &x; cout<<*xpointer<<endl; return 0; }
What is the output?
A. 7
B. 8
C. 9
D. 10

65. Which following statement is not the advantage of pointer?


A. Can be used very easily.
B. Can be declared without initialization.
C. Can be reassigned again.
D. Can be included a null value.

66. Which following statement is not correct?


A. A reference is an alias for an object or variable.
B. A reference must be initialized when declared.
C. A reference is declared by $ in prefixed.
D. A reference is the same as a pointer.

67. Which following statement is not correct?


A. ofstream obj (“myfile.txt”) create an output file object.
B. ifstream obj(“myfile.txt”) create an input file object.
C. #include<fstream> includes fstream class.
D. fstream class is used in an input/output stream.

68. Which following statement is not correct?


A. int &Myvir = myVir; //myVir is a variable.
B. myClass &Myobject = myClass; //myClass is a class.
C. myClass &Myobject = myObject; //myObject is object.
D. int a; int &b=a;

69. What is the output?


#include <iostream> using namespace std; void myFunction(int &refer); int
main( ) {
int num=2; int &renum=num; myFunction (renum);
cout<<num<<endl; return 0; }

void myFunction (int &refer) {


refer=refer refer refer; }
What is the output?
A. 6
B. 7
C. 8
D. 9

70. Which following error is not the main type of errors?


A. Code errors
B. Logic errors
C. Syntax errors
D. Exceptional errors

71. What is the output?


#include <iostream> using namespace std; int main( ){
string str = "Hello"; try{
str.erase (6, 8);

catch (exception &e){


cout<<"Exception: "<<e.what( )<<endl; }
return 0; }
What is the output?
A. 6
B. 8
C. Hello
D. Exception: basic_string::erase.

72. What is the output?


#include <stdexcept> #include <iostream> using namespace std; int main( ){
string str; try{
str.replace (20, 8, "Hello"); }
catch(logic_error){
cout<<"Exception: Logic error!"<<endl; }
return 0; }
What is the output?
A. 20
B. 8
C. Hello
D. Exception: Logic error!

73. What is the output?


#include <stdexcept> #include <iostream> using namespace std; int main( ){
string str = "Hello"; try{
str.erase (6, 8);

catch (out_of_range){
cout<<"Exception: Out of range!"<<endl; }
return 0; }
What is the output?
A. 6
B. 8
C. Hello
D. Exception: Out of range!

74. What is the output?


#include <iostream> using namespace std; void swap(int x, int y); int main( )
{
int a, b; a=80; b=60;
swap (a,b);
return 0; }
void swap(int x, int y){
int t; t=x; x=y; y=t; cout<<x<<" "<<y<<endl; }
What is the output?
A. 60 60
B. 60 80
C. 80 80
D. 80 60

75. If flag’s value is true, what is the output?


cout<< flag<<endl; What is the output?
A. flag
B. true
C. 1
D. 0

76. If flag’s value is true, what is the output?


int a=0;
a=a+flag+true; cout<<a<<endl; What is the output?
A. 0
B. 1
C. 2
D. 3

77. What is the output?


#include <iostream> using namespace std; int main( ){
bool flag; flag=100;
cout<<flag<<endl; return 0; }
What is the output?
A. 0
B. 1
C. 2
D. 3

78. What is the output?


#include <iostream> using namespace std; int main( ){
float x=3.6; int y; y=(int)x; cout<<y<<endl; return 0; }
What is the output?
A. 3
B. 4
C. 5
D. 6

79. What is the output?


char str[10]; str = “Hello!”; cout<<str<<endl; What is the output?
A. Hello!
B. str[10]
C. false
D. Logic error

80. Which following code defines a pointer variable?


A. int &pointer
B. int * pointer
C. int ~pointer
D. int $pointer

81. What is the output?


#include <iostream> using namespace std; int main( ){
int a=100, b=200; int *pointer1, *pointer2; pointer1=&a;
pointer2=&b;
cout<<*pointer1<<" "<<*pointer2<<endl; return 0; }
What is the output?
A. 0 0
B. 100 100
C. 100 200
D. 200 200

82. Which following code defines the reference variable?


int a;
A. int &b;
B. int $b;
C. int &b=a;
D. int $b=a;

83. What is the output?


#include <iostream> using namespace std; int main( ){
int a=10; int &b = a; a= a*a;
b=b/5;
cout<<a<<endl; return 0; }
What is the output?
A. 100
B. 80
C. 60
D. 20

84. What is the output?


#include <iostream> using namespace std; class Time {
public: int hour; };
int main() {
Time timeObject; timeObject.hour=int(16.9999999);
cout<<timeObject.hour<<endl; return 0; }
What is the output?
A. 15
B. 16
C. 17
D. 18

85. Please find out the wrong code.


#include<iostream> using namespace std; int main( ){
int a, b; //Line 1
a=100, b=200; //Line 2
c = a + b; //Line 3
cout<<"c = "<<"300"<<endl; //Line 4
return 0; }

A. Line 1
B. Line 2
C. Line 3
D. Line 4

86. What is the result?


#include<iostream> using namespace std; int main( ){
int a=3, b; b = (int)(a+7.5)%2+(a=5); cout << b << endl; return 0; }
What is the value of “b”?
A. 3
B. 4
C. 5
D. 6

87. What is the result?


#include<iostream> using namespace std; int main( ){
int a=12; a+=a-=a*=a;
cout<<a<<endl; return 0; }
What is the value of “a”?
A. 0
B. 1
C. 2
D. 3

88. What does #include <stdexcept> mean__?


A. include another c++ file named stdexcept.cpp
B. include exception.cpp
C. include the exception class that can identify the type of exception
thrown to a catch block.
D. All above

89. Which following operator has the highest precedence?


A. +=
B. !=
C. ++
D. ()

90. getline( ) function reads from an input stream, its Syntax is ___?
A. getline(input, str);
B. getline(cin, str);
C. getline(enter, str);
D. getline(type, str);

91. What is the output?


#include<iostream> using namespace std; int main( ){
int a; double x=5.8; a=x;
cout<<a<<endl; return 0; }
What is the output?
A. 5
B. 6
C. 7
D. 8

92. Which following express is not correct?


A. int a[3]={1,2};
B. int a[3]={1,2,3,4};
C. int a[ ]={1,2,3};
D. int a[3]={1,2,3};

93. What is the output?


#include<iostream> using namespace std; int main( ){
int a[4]={3,-6,50,26}; int max=a[0]; for (int i=1; i<4; i++){
if (a[i]>max){ max=a[i]; }

cout<<"max="<< max <<endl; return 0; }


What is the output?
A. max=3
B. max=-6
C. max=50
D. max=26

94. What is the output?


#include<iostream> using namespace std; int main( ){
int sum=0, i, array[3]={6,7,8}; int *p=array; for (i=0; i<3; i++) sum+=* (p+i);
cout<<sum<<endl; return 0; }
What is the output?
A. 20
B. 21
C. 22
D. 23

95. What is the output?


#include<iostream> using namespace std; int main( ){
char *str="hello"; int n=0; while (*str != 0) {
n++;
str++;

cout<<n;
return 0; }
What is the output?
A. 3
B. 4
C. 5
D. 6

96. Which following keyword is not the access specifier?


A. public
B. private
C. protected
D. friend

97. What is the output?


#include<iostream>
using namespace std; int main( ){
int a; int &r = a; r=5;
cout<<"a="<<a<<" "<<"r="<<r<<endl; return 0; }
What is the output?
A. a=0 r=5
B. a=0 r=0
C. a=5 r=0
D. a=5 r=5

98. Which following statement is correct?


A. int &*p;
B. int &a[10];
C. int &&r;
D. int &r=a;

99. What is the output?


#include<iostream> using namespace std; int main( ){
int a=6, b; b=++a-3;
cout<<b<<endl; return 0; }
What is the output?
A. 2
B. 3
C. 4
D. 5

100. What is the output?


#include<iostream> using namespace std; int main( ){
int a=6, b; b=a++-3;
cout<<b<<endl; return 0; }
What is the output?
A. 2
B. 3
C. 4
D. 5
100 Answers
1. C 26. B 51. C 76. C
2. B 27. C 52. D 77. B
3. C 28. B 53. D 78. A
4. D 29. C 54. A 79. D
5. D 30. A 55. B 80. B
6. D 31. B 56. C 81. C
7. A 32. A 57. D 82. C
8. D 33. D 58. D 83. D
9. D 34. C 59. A 84. B
10. B 35. D 60. D 85. C
11. A 36. B 61. D 86. C
12. D 37. C 62. C 87. A
13. D 38. A 63. C 88. C
14. D 39. C 64. B 89. D
15. A 40. A 65. A 90. B
16. B 41. D 66. D 91. A
17. B 42. C 67. D 92. B
18. D 43. A 68. B 93. C
19. C 44. C 69. C 94. B
20. B 45. C 70. A 95. C
21. A 46. D 71. D 96. D
22. D 47. A 72. D 97. D
23. D 48. D 73. D 98. D
24. D 49. D 74. B 99. C
25. D 50. C 75. C 00. B
Highly Recommend Computer Books on Amazon:
Linux Command Line
JAVA Programming
PHP Programming
JavaScript Programming
C++ Programming
AngularJS Programming
JQuery Programming
Python Programming
HTML CSS Programming
C# Programming
Visual Basic Programming
JavaScript 50 Useful Programs
Advanced Java Programming
Advanced C++ Programming
Source Code for Download
Please download the source code of this book: C++ Source Code for Download

Dear My Friend, If you are not satisfied with this eBook, could you please
return the eBook for a refund within seven days of the date of purchase?
If you found any errors in this book, could you please send an email to me?
[email protected]
I will be very grateful for your email. Thank you very much!
Sincerely
Ray Yao

My friend, See you!

You might also like