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

Lecture 2 - C++ Basics

The document discusses C++ basics including input/output, data types, operators, control flow statements like if/else and loops, and functions. It covers topics like cout, cin, integers, floats, strings, arithmetic operators, the if/else statement, for, while, do-while loops, and functions.

Uploaded by

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

Lecture 2 - C++ Basics

The document discusses C++ basics including input/output, data types, operators, control flow statements like if/else and loops, and functions. It covers topics like cout, cin, integers, floats, strings, arithmetic operators, the if/else statement, for, while, do-while loops, and functions.

Uploaded by

HuayiLI1
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 68

Computer Aided Engineering

Lecture 2
C++ Basics

C.F. Kwong
[email protected]
Department of Electrical and Electronic Engineering
Faculty of Science and Engineering
Room: PMB 325
Topics
Output in C++: cout
C++ Data Types
Arithmetic Operators
Input in C++: cin
if else, switch
Loops
Functions
Arrays
File Operations

Lecture 2 – C++ Basics


Your First C++ Program: Hello World!

Lecture 2 – C++ Basics


The cout Object
Can be used to send more than one item to cout:
cout << "Hello " << "there!";
Or:
cout << "Hello ";
cout << "there!";

This produces one line of output:


cout << "Programming is ";
cout << "fun!";

Lecture 2 – C++ Basics


endl and \n
You can use the endl manipulator to start a new line
of output. This will produce two lines of output:

cout << "Programming is" << endl;


cout << "fun!";

cout << "Programming is\n"; fun!


cout << "fun!";

Lecture 2 – C++ Basics


Printing Information of Different Types

Now you can understand a little bit why C++ is a higher level
language than C – the format of printing in C++ is not as “strict”
as C, but more humanized.
Lecture 2 – C++ Basics
Formatting Output
Can control how output displays for numeric, string data,
e.g. size, position, number of digits
Requires iomanip header file
Some affect just the next value displayed:
– setw(x): print in a field at least x spaces wide. Use more
spaces if field is not wide enough
Some affect values until changed again:
– fixed: use decimal notation for floating-point values
– setprecision(x): when used with fixed, print floating
point value using x digits after the decimal. Without fixed,
print floating-point value using x significant digits
– showpoint: always print decimal for floating-point values

Lecture 2 – C++ Basics


Stream Manipulators

Lecture 2 – C++ Basics


The setw Example

Lecture 2 – C++ Basics


Topics
Output in C++: cout
C++ Data Types
Arithmetic Operators
Input in C++: cin
if else, switch
Loops
Functions
Arrays
File Operations

Lecture 2 – C++ Basics


Integer Data Types

Lecture 2 – C++ Basics


Floating-Point Data Types

Can be represented in
– Fixed point (decimal) notation:
31.4159 0.0000625
– E notation:
3.14159E1 6.25e-5
Are double by default
Lecture 2 – C++ Basics
The char Data Type
Used to hold characters or very small integer values
Usually 1 byte of memory
Numeric value of character from the character set is
stored in memory:

Lecture 2 – C++ Basics


The C++ string Class
Special data type supports working with strings
#include <string>
Can define string variables in programs:
string firstName, lastName;
Can receive values with assignment operator:
firstName = "George";
lastName = "Washington";
Can be displayed via cout
cout << firstName << " " << lastName;

Lecture 2 – C++ Basics


The string class Example

Lecture 2 – C++ Basics


The bool Data Type
Represents values that are true or false
bool variables are stored as small integers
false is represented by 0, true by 1:
bool allDone = true;
bool finished = false;

Lecture 2 – C++ Basics


Boolean Variables Example

Lecture 2 – C++ Basics


Determining the Size of a Data Type
The sizeof operator gives the size of any data type or
variable:
double amount;
cout << "A double is stored in "
<< sizeof(double) << "bytes\n";
cout << "Variable amount is stored in "
<< sizeof(amount)
<< "bytes\n";

Lecture 2 – C++ Basics


Topics
Output in C++: cout
C++ Data Types
Arithmetic Operators
Input in C++: cin
if else, switch
Loops
Functions
Arrays
File Operations

Lecture 2 – C++ Basics


Arithmetic Operators

Lecture 2 – C++ Basics


A Closer Look at the / Operator
/ (division) operator performs integer division if both
operands are integers
cout << 13 / 5; // displays 2
cout << 91 / 7; // displays 13
If either operand is floating point, the result is floating
point
cout << 13 / 5.0; // displays 2.6
cout << 91.0 / 7; // displays 13.0
% (modulus) operator computes the remainder resulting
from integer division
cout << 13 % 5; // displays 3
% requires integers for both operands
cout << 13 % 5.0; // error
Lecture 2 – C++ Basics
Combined Assignment Operators

Lecture 2 – C++ Basics


Mathematical Library Functions
Require cmath header file
Take double as input, return a double
Commonly used functions:
sin Sine
cos Cosine
tan Tangent
sqrt Square root
log Natural (e) log
abs Absolute value (takes and returns an int)

Lecture 2 – C++ Basics


Topics
Output in C++: cout
C++ Data Types
Arithmetic Operators
Input in C++: cin
if else, switch
Loops
Functions
Arrays
File Operations

Lecture 2 – C++ Basics


The cin Object
Standard input object
Like cout, requires iostream file
Used to read input from keyboard
Information retrieved from cin with >>
Input is stored in one or more variables

Lecture 2 – C++ Basics


The cin Object Example

Lecture 2 – C++ Basics


The cin Object
cin converts data to the type that matches the
variable:
int height;
cout << "How tall is the room? ";
cin >> height;
Can be used to input more than one value:
cin >> height >> width;
Multiple values from keyboard must be separated by
spaces
Order is important: first value entered goes to first
variable, etc.

Lecture 2 – C++ Basics


Displaying a Prompt
A prompt is a message that instructs the user to
enter data.
You should always use cout to display a prompt
before each cin statement.

cout << "How tall is the room? ";


cin >> height;

Lecture 2 – C++ Basics


Example

Lecture 2 – C++ Basics


Input string Objects
Using cin with the >> operator to input strings can
cause problems:
It passes over and ignores any leading whitespace
characters (spaces, tabs, or line breaks)
To work around this problem, you can use a C++
function named getline.

Lecture 2 – C++ Basics


getline Example

Lecture 2 – C++ Basics


Input Characters
To read a single character:
Use cin:
char ch;
cout << "Strike any key to continue";
cin >> ch;
Problem: will skip over blanks, tabs, <CR>
Use cin.get():
cin.get(ch);
Will read the next character entered, even
whitespace

Lecture 2 – C++ Basics


cin.get() Example

Lecture 2 – C++ Basics


Input Characters
Mixing cin >> and cin.get() in the same
program can cause input errors that are hard to
detect
To skip over unneeded characters that are still in the
keyboard buffer, use cin.ignore():
cin.ignore(); // skip next char
cin.ignore(10, '\n'); // skip the next
// 10 char. or until a '\n‘

If you are unsure, keep testing your code.


Practice is the key!

Lecture 2 – C++ Basics


Topics
Output in C++: cout
C++ Data Types
Arithmetic Operators
Input in C++: cin
if else, switch
Loops
Functions
Arrays
File Operations

Lecture 2 – C++ Basics


If/else if Format
if (expression)
statement1; // or block
else if (expression)
statement2; // or block
.
. // other else ifs
else if (expression)
statementn; // or block

Lecture 2 – C++ Basics


switch Statement Format
switch (expression) //integer
{
case exp1: statement1;
case exp2: statement2;
...
case expn: statementn;
default: statementn+1;
}

Lecture 2 – C++ Basics


Topics
Output in C++: cout
C++ Data Types
Arithmetic Operators
Input in C++: cin
if else, switch
Loops
Functions
Arrays
File Operations

Lecture 2 – C++ Basics


The for Loop
Useful for counter-controlled loop
General Format:

for(initialization; test; update)


statement; // or block in { }

No semicolon after the update expression or after


the “)”

Lecture 2 – C++ Basics


The while Loop
General format of the while loop:
while (expression)
statement;
statement; can also be a block of statements
enclosed in { }

Lecture 2 – C++ Basics


Example: while Loop
Input Validation:
cout << "Enter a number less than 10: ";
cin >> number;
while (number >= 10)
{
cout << "Invalid Entry!"
<< "Enter a number less than 10: ";
cin >> number;
}

Lecture 2 – C++ Basics


The do-while Loop
do-while: a posttest loop – execute the loop, then
test the expression
General Format:
do
statement; // or block in { }
while (expression);
Note that a semicolon is required after (expression)

Lecture 2 – C++ Basics


Example: do-while Loop

int x = 1;
do
{
cout << x << endl;
} while(x < 0);

Although the test expression is false, this loop will


execute one time because do-while is a posttest
loop.

Lecture 2 – C++ Basics


Deciding Which Loop to Use
The while loop is a conditional pretest loop
– Iterates as long as a certain condition exits
– Validating input
– Reading lists of data terminated by a sentinel
The do-while loop is a conditional posttest loop
– Always iterates at least once
– Repeating a menu
The for loop is a pretest loop
– Built-in expressions for initializing, testing, and updating
– Situations where the exact number of iterations is known

Lecture 2 – C++ Basics


Topics
Output in C++: cout
C++ Data Types
Arithmetic Operators
Input in C++: cin
if else, switch
Loops
Functions
Arrays
File Operations

Lecture 2 – C++ Basics


Function Prototypes
Ways to notify the compiler about a function before
a call to the function:
– Place function definition before calling function’s
definition
– Use a function prototype (function declaration) –
like the function definition without the body
• Header: void printHeading()
• Prototype: void printHeading();

Lecture 2 – C++ Basics


Also notice how well
the comments are
made.

Lecture 2 – C++ Basics


The exit()Function
Terminates the execution of a program
Can be called from any function
Can pass an int value to operating system to indicate
status of program termination
Usually used for abnormal termination of program
Requires cstdlib header file
Example:
exit(0);
The cstdlib header defines two constants that are
commonly passed, to indicate success or failure:
exit(EXIT_SUCCESS);
exit(EXIT_FAILURE);
Lecture 2 – C++ Basics
Topics
Output in C++: cout
C++ Data Types
Arithmetic Operators
Input in C++: cin
if else, switch
Loops
Functions
Arrays
File Operations

Lecture 2 – C++ Basics


Arrays Initialisation
Named constants are commonly used as size
declarators.
const int SIZE = 5;
int tests[SIZE];
– This eases program maintenance when the size of the
array needs to be changed.
Arrays can be initialized with an initialization list:
const int SIZE = 5;
int tests[SIZE] = {79,82,91,77,84};
The initialization list cannot exceed the array size.

Lecture 2 – C++ Basics


Partial Array Initialisation
If array is initialized with fewer initial values than the
size declarator, the remaining elements will be set to
0:

Lecture 2 – C++ Basics


Implicit Array Sizing
Can determine array size by the size of the
initialization list:
int quizzes[]={12,17,15,11};

Must use either array size declarator or initialization


list at array definition

Lecture 2 – C++ Basics


No Bounds Checking in C++
When you use a value as an array subscript, C++ does
not check it to make sure it is a valid subscript.
In other words, you can use subscripts that are
beyond the bounds of the array.
Be careful not to use invalid subscripts.
Doing so can corrupt other memory locations, crash
program, or lock up computer, and cause elusive
bugs!

Lecture 2 – C++ Basics


Example
The following code defines a three-element array,
and then writes five values to it!

Lecture 2 – C++ Basics


Example: What the Code Does?

Lecture 2 – C++ Basics


Two-Dimensional Array Representation
const int ROWS = 4, COLS = 3;
int exams[ROWS][COLS];

Use two subscripts to access element:


exams[2][2] = 86;
First declarator is number of rows; second is number
of columns
Lecture 2 – C++ Basics
Topics
Output in C++: cout
C++ Data Types
Arithmetic Operators
Input in C++: cin
if else, switch
Loops
Functions
Arrays
File Operations

Lecture 2 – C++ Basics


Using Files for Data Storage
Can use files instead of keyboard, monitor screen for
program input, output
Allows data to be retained between program runs
Steps:
– Open the file
– Use the file (read from, write to, or both)
– Close the file

Lecture 2 – C++ Basics


Files: What is Needed?
Use fstream header file for file access
File stream types:
ifstream for input from a file
ofstream for output to a file
fstream for input from or output to a file
Define file stream objects:
ifstream infile;
ofstream outfile;

Lecture 2 – C++ Basics


Opening Files
Create a link between file name (outside the
program) and file stream object (inside the program)
Use the open member function:
infile.open("inventory.dat");
outfile.open("report.txt");
Filename may include drive, path info.
Output file will be created if necessary; existing file
will be erased first
Input file must exist for open to work

Lecture 2 – C++ Basics


Testing for File Open Errors
}Can test a file stream object to detect if an open
operation failed:
infile.open("test.txt");
if (!infile)
{
cout << "File open failure!";
}
Can also use the fail member function

In software engineering practice, it is important to


develop a program that can deal with errors!
Lecture 2 – C++ Basics
Using Files
Can use output file object and << to send data to a
file:
outfile << "Inventory report";
Can use input file object and >> to copy data from
file to variables:
infile >> partNum;
infile >> qtyInStock >> qtyOnOrder;

Lecture 2 – C++ Basics


Using Loops to Process Files
The stream extraction operator >> returns true
when a value was successfully read, false otherwise
Can be tested in a while loop to continue execution
as long as values are read from the file:
while (inputFile >> number) ...

Lecture 2 – C++ Basics


Closing Files
Use the close member function:
infile.close();
outfile.close();

Don’t wait for operating system to close files at


program end:
– may be limit on number of open files
– may be buffered output data waiting to send to file

Lecture 2 – C++ Basics


Example 1
// copy 10 numbers between files
// open the files
fstream infile("input.txt", ios::in);
fstream outfile("output.txt", ios::out);
int num;
for (int i = 1; i <= 10; i++)
{
infile >> num; // use the files
outfile << num;
}
infile.close(); // close the files
outfile.close();
Lecture 2 – C++ Basics
Example 2 (1)

Lecture 2 – C++ Basics


Example 2 (2)

Lecture 2 – C++ Basics


Questions?

Lecture 2 – C++ Basics

You might also like