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

MCIS 6204 - Data Structure & Algorithms (Labs) - Day 2

This document provides an overview of various C++ concepts covered in Day 2 of an MCIS 6204 data structures and algorithms course, including operators like increment/decrement, relational, logical, and conditional operators. It also covers basic input/output using cin and cout, control structures like if/else, while, do-while and for loops, and statements like break and continue. The document is divided into sections with headings and code examples to illustrate each concept.

Uploaded by

bharathkumar
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views

MCIS 6204 - Data Structure & Algorithms (Labs) - Day 2

This document provides an overview of various C++ concepts covered in Day 2 of an MCIS 6204 data structures and algorithms course, including operators like increment/decrement, relational, logical, and conditional operators. It also covers basic input/output using cin and cout, control structures like if/else, while, do-while and for loops, and statements like break and continue. The document is divided into sections with headings and code examples to illustrate each concept.

Uploaded by

bharathkumar
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 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

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.

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

Logical operators ( !, &&, || )


The logical operator && and || are used when
evaluating two expression to obtain a single relational
result.
The operator && corresponds with Boolean logical
operator AND. ( || corresponds with OR )

( ( 5==5) && ( 3 > 6 ) )


5

( ( 5==5) && ( 3 > 6 ) )


Southern Arkansas University

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 ( ? )

Southern Arkansas University

Comma operator ( , )
The

comma operator (,) is used to separate two or


more expression that are included where only one
expression is expected.
a = ( b = 3, b + 2) ;
would first assign the value 3 to b, and then assign b +2 to
variable a. So, at the end , variable a would be contain the
value 5 while b would be contain value 3.

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.
#include <iostream>

Southern Arkansas University

Basic Input/ Output


The

standard C++ library includes the header file


iostream, where the standard input and output stream
objects are declared.
Standard Ouput (cout) : By default, the standard
output of a program is the screen, and the C++ stream
object defined to access it is cout.
The cout is used in conjunction with the insertion
operator, which is written as << (two less than sign)

10

Southern Arkansas University

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 Examples-1
Print

out a combination of variables and constants or


more than one variable:

cout << hello, I am << age << years old;


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.

12

Southern Arkansas University

Cout Examples-2
Line

break on the output we must explicitly insert a


new-line character into cout.

First sentence.
Second sentence.
Third Sentence.
Additionally, to

add a new-line, you may also use the


endl manipulator.

cout << First sentence. << endl;


cout << Second sentence. << endl;
13

Southern Arkansas University

Standard Input(cin)
The

standard input device is usually the keyboard.


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

Southern Arkansas University

Control Structures

ow of execution : C++ Programming Design including Data Structure, Chapter 4


15

Southern Arkansas University

Control Structures ( if and else )


The

if keyword is used to execute a statement or block


only if a condition is fulfilled. 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;

16

Southern Arkansas University

Control Structures ( if and else )-1


If

we want more than a single statement , we can


specify a block using braces { };
if ( x == 100)
{
cout << x is ;
cout << x;
}

17

Southern Arkansas University

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;

18

Southern Arkansas University

Control Structures ( if and else )-3


The

following statement show an example of a syntax


error.
if ( x == 100) ;
cout << x is 100;
else
cout << x is not 100;

19

Southern Arkansas University

Control Structures ( Nested if else )


The

nested if else statement has more than one test


expression. If the first test expression is true, it
execute the code inside the braces { }.
But if the first test expression is false, it checks the
second test expression.
If the second test expression is true, if executes the
code inside the braces { }
This process continues.

20

Southern Arkansas University

Control Structures ( Nested if else )-1

21

Southern Arkansas University

while loop
Loops

- 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;

22

Southern Arkansas University

while loop example -1


This

program displays the numbers


1 through 10 and their squares

#include <iostream.h>
void main(void)
{
int num = 1;
// Initialize counter
cout << "number
number Squared\n";
cout << "-------------------------\n";
while (num <= 10)
{
cout << num << "\t\t" << (num * num) << endl;
num++;
// Increment counter
}
}
23

Southern Arkansas University

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

do while loop
Its

functionality is exactly the same as the while loop, do-while


loop is evaluated after the execution of statement, granting at
least one execution of statement.
Flowchart of do while

Format

do statement while ( condition );


25

Southern Arkansas University

do while loop -1
// number echoer
#include <iostream>
using namespace std;
int main ()
{
unsigned long n;
do {
cout << "Enter number (0 to
end): ";
cin >> n;
cout << "You entered: " << n
<< "\n";
} while (n != 0);
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

for loop -1
// number echoer
#include <iostream>
using namespace std;
int main ( )
{
unsigned long n;
do {
cout << "Enter number (0 to
end): ";
cin >> n;
cout << "You entered: " << n
<< "\n";
} while (n != 0);
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

for loop
Specially

designed to perform a repetitive action with a counter


which is initialized and increased on each iteration.
For loop provides specific location to contain an initialization
statement and an increase statement.
Initializes the loop
control variable:
ex. i = 0;
Tests the loop control
variable to see if it is
time to quit looping:
ex. i < 10;

Increments the loop


control variable:
ex. i++

Format

for (initialization ; condition; increase ) statement;


28

Southern Arkansas University

for loop steps


It

works in the following way


1. initialization is executed. Generally it is an initial value
settings for a counter variable. ( Executed only once)
2. condition is checked. If it is true the loop continues,
otherwise the loop ends and statement is skipped
3. Statement is executed. As usual, it can be either a single
statement or block enclosed in braces { }
4. Finally, whatever is specified in the increase field is
fire!
for
( int n and
= 10;
> 0; gets
n -- )back
{ to10,9,8,7,6,5,4,3,2,1,
executed
thenloop
step 2.
cout << n << , ;
}
cout << fire;

29

Southern Arkansas University

for loop with , operator


Optionally, using

the comma operator (,) More than one


expression in any of the field included in a for loop

initialization
condition
for ( n=0, i = 100;
n! = i ;
{
whatever statements here
}

Increase
n ++, i -- )

This

loop will execute for 50 times in neither n or i are modified


within the loop.
n Starts with a value of 0, and i with 100,
condition is n! = i. The loop condition will become become
false after the 50th loop
30

Southern Arkansas University

break statement
Using

break we can leave a loop even if the condition for its


end is not fulfilled.

int main ()
{
int n;
for (n=10; n>0; n--)
{
cout << n << ", ";
If (n==3)
{
cout << "countdown
aborted!";
break;
}
}
return 0;
}

31

10,9,8,7,6,5,4,3,countdown
aborted!

Southern Arkansas University

continue statement
Using

break we can leave a loop even if the condition for its


end is not fulfilled.

int main ()
{
int n;
for (n=10; n>0; n--)
{
cout << n << ", ";
If (n==5) continue;
cout << fire"
}
}
return 0;
}

32

10,9,8,7,6,5,4,3,2,1,fire

Southern Arkansas University

selective structure: switch


Flow

33

of switch

Southern Arkansas University

selective structure: switch


switch

statement similar to if and else if statement.


Operation
- Evaluate constant and execute group of statements and jumps
to the end of the switch.
switch (expression)
{
case constant1:
group of statements 1;
break;
case constant2:
group of statements 2;
break
.
default:
default group of statements
}
34

Southern Arkansas University

selective structure: an example


Both

of the following code fragments have the same behavior.

Switch Example
switch (x) {
case 1:
cout << "x is 1";
break;
case 2:
cout << "x is 2";
break;
default:
cout << "value of x
unknown";
}

35

If-else equivalent
if (x == 1) {
cout << "x is 1";
}
else if (x == 2) {
cout << "x is 2";
}
else {
cout << "value of x unknown";
}

Southern Arkansas University

Stream IO
C++

IO are based on streams, which are sequence of bytes


flowing in and out of the program(just like water flowing
through a pipe).
In input operation, data byte flow from an input source into the
program. In output operations, data bytes flow from the
program to an output sink.
cout << value;
cin >> variable;
Formatted

output is carried out on streams via the stream


insertion << and

36

Southern Arkansas University

File Output
The

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

37

Southern Arkansas University

File Input
The

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

38

Southern Arkansas University

File Open Modes


The

available file mode flags are:

ios::in

Open for input operations.

ios::out

Open for output operations.

ios::binary Open in binary mode.


ios::ate

Set the initial position at the end of the file.


If this flag is not set, the initial position is the beginning of
the file.

ios::app

All output operations are performed at the end of the file,


appending the content to the current content of the file.

ios::trunc

If the file is opened for output operations and it already


existed, its previous content is deleted and replaced by the
new one.

39

Southern Arkansas University

basic file I/O write


Create

file and put some text into it.

#include <iostream>
#include <fstream> //To use C++s function for File I/O.
using namespace std;
int main ( )
{
ofstream SaveFile;
SaveFile.open (D:\\C++\\Day4\\Lab4.txt",
ios::out);
SaveFile << Save some text into file ;
SaveFile.close( );
return 0;
}
40

Southern Arkansas University

basic file I/O read


Create

file and put some text into it.

#include <iostream>
#include <fstream>
//To use C++s function for
File I/O
using namespace std;
int main ( )
{
ifstream InFile;
InFile.open ("D:\\C++\\Day4\\Lab4.txt",ios::in);
double aNumber;
while (!InFile.eof()) //
{
InFile >> aNumber;
cout << aNumber << " \n";
}
OpenFile.close(); cin >> aNumber;
return 0;
Southern Arkansas University
41
}

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

42

http://www.tutorialspoint.com/cplusplus/cpp_exceptions_handling.htm

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.
try A try block identifies a block of code for
which particular exceptions will be activated
43

http://www.tutorialspoint.com/cplusplus/cpp_exceptions_handling.htm

Exception Handling Try /catch


try
{
// Execute some code that might throw an exception.
}
catch(IndexOutOfRangeException * e )
{
// Handle out-of-memory exception
}
catch(NullReferanceException * e )
{
// Handle null reference exception
}
catch( Exception* e )
{
// Handle general exceptions here.
}
44

http://www.codeproject.com/Articles/4681/Exception-handling-inManaged-C

File not found exception


#include <iostream>
#include <fstream>
using namespace std;
int main()
{
int x; int array[90];
try
{
ifstream file;
file.open("somefile.txt");
if(!file.good())
throw 10;
}
catch(int e)
{
cout<<"File not found "<< e <<endl;
}
system("pause");
return 0;
}
45

http://www.codeproject.com/Articles/4681/Exception-handling-inManaged-C

Formatting Output
setw
-Output the value of an expression in specific columns.
-The value of the expression can be either string or a number.
-The output is right-justified.
cout << setw(5) << x << endl;
setpression

-controls the output of floating-point numbers


-cout setpression(n); //where n is the decimal places
fixed

-To output floating-point numbers in a fixed decimal format


46

Southern Arkansas University

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;
int main ( )
{
try {
ifstream InputFile;
InputFile.open ("D:\\C++\\Day4\\Lab4.txt,ios::in);
if(!InputFile) throw 40;
double aNumber;
while (!OpenFile.eof()) //
{
OpenFile >> aNumber;
cout << aNumber << " \n";
}
InputFile.close();
}
catch(int e)
{
cout << File not found << e << endl;
}
return 0;
}
Southern Arkansas University
48

Labs
Lab2A

If Statement
Lab2B While Loops

49

Southern Arkansas University

You might also like