You are on page 1of 49

# MCIS 6204 - Data Structure and

Algorithms (C++ Labs)
Day 2
Dr. Jongyeop Kim

MCIS 2016

Overview
 Increase

and Decrease ( ++, -- )
 Operators ( ==, !=, >, < , >=, <=)
 Logical Operator( !, &&, ||)
 Conditional operator(?), Comma operator ( , )
 Casting Operator
 Basic Input/Output
 While / do while
 for
 Jump Statement
 Switch

2

Southern Arkansas University

Increase and Decrease ( ++, --)
 The

increase operator (++) and Decrease operator(--) increase
or reduce by one the value stored in variable.
 Increase by one c++; c+=1; c=c+1;
are all equivalent in its functionality.
 A characteristic of this operator is that it can be used both as a
prefix and as a suffix – It can be written either before the
variable identifier (++a ) or after it (a++).

 In

Example 1, B is increased before its value is copied to A.
Example 2, the value of B is copied to A and then B is increased.

3

Southern Arkansas University

Logical operators ( !, &&, || )

The operator ! is the C++ operator to perform the
Boolean operation Not. Producing false if its operand
is true and true if its operand is false.
Expression

Returns

! ( 5 == 5)
! ( 6 <= 4 )
!true
!false

Evaluates to false
true
false
true

Be careful The operator = ( one equal sign ) is not the same as
the operator == (two equal signs).
4

Southern Arkansas University

( || corresponds with OR )  ( ( 5==5) && ( 3 > 6 ) ) 5 ( ( 5==5) && ( 3 > 6 ) ) Southern Arkansas University .  The operator && corresponds with Boolean logical operator AND. &&. || ) The logical operator && and || are used when evaluating two expression to obtain a single relational result.Logical operators ( !.

Conditional Operator ( ? )  The conditional operator evaluates an expression returning a value if that expression is true and a different one if the expression is evaluated as false. condition ? result1 : result2 Expression Returns 7==5 ? 4 : 3 7==5+2 ? 4: 3 5>3 ? a:b a >b ? a: b 6 Southern Arkansas University .

Conditional Operator ( ? ) 7 Southern Arkansas University .

) The comma operator (. a = ( b = 3. variable a would be contain the value 5 while b would be contain value 3. at the end . So. would first assign the value 3 to b.) is used to separate two or more expression that are included where only one expression is expected. 8 Southern Arkansas University . b + 2) . and then assign b +2 to variable a.Comma operator ( .

#include <iostream> 9 Southern Arkansas University .Basic Input/ Output Input stream: A sequence of characters from an input device to the computer. Output Stream: A sequence of characters from the computer to an output device.

the standard output of a program is the screen.Basic Input/ Output The standard C++ library includes the header file iostream. The cout is used in conjunction with the insertion operator. and the C++ stream object defined to access it is cout. which is written as << (two less than sign) 10 Southern Arkansas University . Standard Ouput (cout) : By default. where the standard input and output stream objects are declared.

Cout Examples The insertion operator ( << ) may be used more than once in a single statement: Constant strings of characters must enclose them between double quotes(“) so that they can be clearly distinguished from variable name. 11 Southern Arkansas University .

cout does not add a line break after its output will shown on the screen on following the other without any line break between them: This is a sentence. This is another sentence. I am” << age << “years old”. 12 Southern Arkansas University .Cout Examples-1 Print out a combination of variables and constants or more than one variable: cout << “hello.

” << endl. Additionally.Cout Examples-2 Line break on the output we must explicitly insert a new-line character into cout. cout << “Second sentence. 13 Southern Arkansas University . to add a new-line.” << endl. you may also use the endl manipulator. Second sentence. cout << “First sentence. First sentence. Third Sentence.

int age. /* waits for an input from cin (the keyboard) in order to store it to the variable age. // declares a variable of type int called age. cin can only process the input from the keyboard on the return key has been pressed.Standard Input(cin) The standard input device is usually the keyboard. cin >> age. */ 14 Southern Arkansas University . Handling the standard input in C++ is done by the applying the operator >> on the cin.

Chapter 4 15 Southern Arkansas University .Control Structures ow of execution : C++ Programming Design including Data Structure.

16 Southern Arkansas University . Its form is: if (condition) statement where condition is being evaluated. if ( x == 100) cout << “x is 100”. //Code segment prints “x is 100” only if the value stored in the x variable is indeed 100.Control Structures ( if and else ) The if keyword is used to execute a statement or block only if a condition is fulfilled.

we can specify a block using braces { }.Control Structures ( if and else )-1 If we want more than a single statement . cout << x. if ( x == 100) { cout << “x is “. } 17 Southern Arkansas University .

18 Southern Arkansas University . else cout << “x is not 100”.Control Structures ( if and else )-2  We can additionally specify what we want to happen if the condition is not fulfilled by using the keyword else. if (condition) statement1 else statement2 if ( x == 100) cout << “x is 100”.

else cout << “x is not 100”.Control Structures ( if and else )-3 The following statement show an example of a syntax error. if ( x == 100) . 19 Southern Arkansas University . cout << “x is 100”.

it execute the code inside the braces { }. 20 Southern Arkansas University . if executes the code inside the braces { } This process continues. it checks the second test expression. If the second test expression is true.Control Structures ( Nested if … else ) The nested if … else statement has more than one test expression.  But if the first test expression is false. If the first test expression is true.

Control Structures ( Nested if … else )-1 21 Southern Arkansas University .

22 Southern Arkansas University .Repeat a statement number of times to be executed .Must group them in a block by enclosing them in braces { }  Flowchart of while loop condition true statement false  format while ( expression ) statement.while loop  Loops .

// Initialize counter cout << "number number Squared\n".while loop example -1 This program displays the numbers 1 through 10 and their squares #include <iostream. while (num <= 10) { cout << num << "\t\t" << (num * num) << endl. num++. cout << "-------------------------\n". // Increment counter } } 23 Southern Arkansas University .h> void main(void) { int num = 1.

program output -1 number number Squared ------------------------1 1 2 4 3 9 4 16 5 25 6 36 7 49 8 64 9 81 10 100 24 Southern Arkansas University .

 Flowchart of do while  Format do statement while ( condition ). do-while loop is evaluated after the execution of statement. 25 Southern Arkansas University . granting at least one execution of statement.do while loop  Its functionality is exactly the same as the while loop.

do { cout << "Enter number (0 to end): ". return 0. }26 Enter number (0 to end): 12345 You entered: 12345 Enter number (0 to end): 160277 You entered: 160277 Enter number (0 to end): 0 You entered: 0 Southern Arkansas University . cin >> n.do while loop -1 // number echoer #include <iostream> using namespace std. } while (n != 0). cout << "You entered: " << n << "\n". int main () { unsigned long n.

} while (n != 0). cin >> n. int main ( ) { unsigned long n. do { cout << "Enter number (0 to end): ".for loop -1 // number echoer #include <iostream> using namespace std. return 0. }27 Enter number (0 to end): 12345 You entered: 12345 Enter number (0 to end): 160277 You entered: 160277 Enter number (0 to end): 0 You entered: 0 Southern Arkansas University . cout << "You entered: " << n << "\n".

Tests the loop control variable to see if it is time to quit looping: ex. 28 Southern Arkansas University . condition.for loop  Specially designed to perform a repetitive action with a counter which is initialized and increased on each iteration. i < 10. increase ) statement. i++  Format for (initialization . Initializes the loop control variable: ex.  For loop provides specific location to contain an initialization statement and an increase statement. i = 0. Increments the loop control variable: ex.

otherwise the loop ends and statement is skipped 3. > 0. As usual.3. Statement is executed.for loop – steps  It works in the following way 1. cout << n << “ . initialization is executed. Generally it is an initial value settings for a counter variable.)back { to10. it can be either a single statement or block enclosed in braces { } 4. ( Executed only once) 2. 29 Southern Arkansas University .5.9.1. whatever is specified in the increase field is fire! for ( int n and = 10. } cout << “fire”. gets n -.7. Finally. If it is true the loop continues. condition is checked. executed thenloop step 2.4.2.8.6.“ .

using the comma operator (.for loop with .) – More than one expression in any of the field included in a for loop initialization condition for ( n=0. { whatever statements here } Increase n ++. n! = i . The loop condition will become become false after the 50th loop 30 Southern Arkansas University .  n Starts with a value of 0.)  This loop will execute for 50 times in neither n or i are modified within the loop. and i with 100. condition is n! = i. i = 100. i -. operator  Optionally.

9.7. break.4. If (n==3) { cout << "countdown aborted!". n>0.break statement  Using break we can leave a loop even if the condition for its end is not fulfilled.5. } 31 10.3. … int main () { int n.countdown aborted! Southern Arkansas University .6. n--) { cout << n << ". for (n=10. } } return 0.8. ".

for (n=10.fire Southern Arkansas University .3. n--) { cout << n << ". cout << “fire" } } return 0.continue statement  Using break we can leave a loop even if the condition for its end is not fulfilled.9. n>0.8.4. If (n==5) continue.7.5. } 32 10.1.6.2. ". … int main () { int n.

selective structure: switch  Flow 33 of switch Southern Arkansas University .

default: default group of statements } 34 Southern Arkansas University . switch (expression) { case constant1: group of statements 1.Evaluate constant and execute group of statements and jumps to the end of the switch. break.  Operation . case constant2: group of statements 2. break .selective structure: switch  switch statement similar to if and else if statement.

Switch Example switch (x) { case 1: cout << "x is 1". default: cout << "value of x unknown".selective structure: an example  Both of the following code fragments have the same behavior. } 35 If-else equivalent if (x == 1) { cout << "x is 1". } else { cout << "value of x unknown". break. break. } Southern Arkansas University . } else if (x == 2) { cout << "x is 2". case 2: cout << "x is 2".

cout << value. data bytes flow from the program to an output sink. In output operations.  Formatted output is carried out on streams via the stream insertion << and 36 Southern Arkansas University .  In input operation.Stream IO  C++ IO are based on streams. cin >> variable. data byte flow from an input source into the program. which are sequence of bytes flowing in and out of the program(just like water flowing through a pipe).

3.. file open) and set the mode of file operation.e. Connect it to a file(i. 37 Southern Arkansas University . Perform output operation via insertion >> operator or write( ). Disconnect and free the ofstream object.File Output  The steps are: 1. put( ) functions. Construct an ofstream object. 2. 4.

Connect it to a file(i. getline functions.File Input  The steps are: 1.. Disconnect and free the ifstream object. 2. 4. file open) and set the mode of file operation. 3. Construct an ifstream object. 38 Southern Arkansas University . get( ).e. Perform output operation via extraction << operator or read( ).

the initial position is the beginning of the file. ios::trunc If the file is opened for output operations and it already existed. ios::ate Set the initial position at the end of the file. 39 Southern Arkansas University . If this flag is not set. appending the content to the current content of the file.File Open Modes  The available file mode flags are: ios::in Open for input operations. its previous content is deleted and replaced by the new one. ios::app All output operations are performed at the end of the file. ios::out Open for output operations. ios::binary Open in binary mode.

return 0.close( ). SaveFile. } 40 Southern Arkansas University .open (“D:\\C++\\Day4\\Lab4. #include <iostream> #include <fstream> //To use C++’s function for File I/O. int main ( ) { ofstream SaveFile.basic file I/O – write  Create file and put some text into it.txt". SaveFile. ios::out). SaveFile << “Save some text into file “. using namespace std.

cin >> aNumber.txt". return 0.basic file I/O – read  Create file and put some text into it.open ("D:\\C++\\Day4\\Lab4. double aNumber. while (!InFile.eof()) // { InFile >> aNumber. InFile. Southern Arkansas University 41 } .ios::in). #include <iostream> #include <fstream> //To use C++’s function for File I/O using namespace std. cout << aNumber << " \n". int main ( ) { ifstream InFile.close(). } OpenFile.

Exception Handling • An exception is a problem that arises during the execution of a program. • Exception provide a way to transfer control from one part of a program to another.htm . A C++ exception is a responses to an exceptional circumstance that arise while a program is running.com/cplusplus/cpp_exceptions_handling.tutorialspoint. • 42 http://www. catch. C++ exception handling is built upon three keywords: try. such as an attempt to divide by zero. and throw.

com/cplusplus/cpp_exceptions_handling.Exception Handling • throw – A program throws an exception when a problem shows up. • catch – A program catches an exception with an exception handler at the place in a program where you want handle problem.htm .tutorialspoint. • try – A try block identifies a block of code for which particular exceptions will be activated 43 http://www.

codeproject. } 44 http://www. } catch(IndexOutOfRangeException * e ) { // Handle out-of-memory exception } catch(NullReferanceException * e ) { // Handle null reference exception } catch( Exception* e ) { // Handle general exceptions here.Exception Handling –Try /catch try { // Execute some code that might throw an exception.com/Articles/4681/Exception-handling-inManaged-C .

try { ifstream file. } 45 http://www. file.File not found exception #include <iostream> #include <fstream> using namespace std. } system("pause").codeproject.com/Articles/4681/Exception-handling-inManaged-C . return 0. int array[90].txt").good()) throw 10.open("somefile. int main() { int x. if(!file. } catch(int e) { cout<<"File not found "<< e <<endl.

-The value of the expression can be either string or a number. //where n is the decimal places fixed -To output floating-point numbers in a fixed decimal format 46 Southern Arkansas University . cout << setw(5) << x << endl.Formatting Output setw -Output the value of an expression in specific columns. -The output is right-justified. setpression -controls the output of floating-point numbers -cout setpression(n).

Formatting Output Limit the output to 8 characters with setw(8) and setprecision(3) sets the decimal precision to be used to format floating-point values on output operations. #include <iomanip> … cout << setw(6) << setprecision(3) << fixed << aVar << “\n”. 47 Southern Arkansas University .

Lab2 #B #include <iostream> #include <fstream> //To use C++’s function for File I/O using namespace std. cout << aNumber << " \n".close(). } return 0. while (!OpenFile.ios::in). double aNumber. if(!InputFile) throw 40. } Southern Arkansas University 48 . } catch(int e) { cout << “File not found “ << e << endl. } InputFile. InputFile.txt“.open ("D:\\C++\\Day4\\Lab4.eof()) // { OpenFile >> aNumber. int main ( ) { try { ifstream InputFile.

Labs  Lab2A – If Statement  Lab2B – While Loops 49 Southern Arkansas University .