• No results found

Lec2 - C++ basics.pdf

N/A
N/A
Protected

Academic year: 2020

Share "Lec2 - C++ basics.pdf"

Copied!
17
0
0

Loading.... (view fulltext now)

Full text

(1)

Structured Programming

Using C++

Lecture 2 : Introduction to the C++ Language

Dr. Amal Khalifa

Lecture Contents:

Introduction to C++

 Origins

 Object-Oriented Programming,

 Terms

Libraries and Namespaces

Console Input/Output

Variables, Expressions, and Assignment Statements

(2)

Introduction to C++

1-3

C++ Origins

 Low-level languages

 Machine, assembly

 High-level languages

 C, C++, ADA, COBOL, FORTRAN

 Object-Oriented-Programming in C++

C++ Terminology

Programs and functions

 Basic Input/Output (I/O) with cin and cout

Dr. Amal Khalifa, 2012

C++ Program

(3)

Program output….

Dr. Amal Khalifa, 2012 1-5

Libraries

 C++ Standard Libraries  #include <Library_Name>

 Directive to "add" contents of library file to

your program

 Called "preprocessor directive"

 Executes before compiler, and simply "copies"

library file into your program file  C++ has many libraries

(4)

Namespaces

1-7

Namespaces defined:

– Collection of name definitions

For now: interested in namespace "std"

– Has all standard library definitions we need

Examples:

#include <iostream>

using namespace std;

• Includes entire standard library of name definitions

#include <iostream>using std::cin;

using std::cout;

• Can specify just the objects we want

Dr. Amal Khalifa, 2012

1-8

Console Input/Output

I/O objects cin, cout, cerr

Defined in the C++ library called <iostream>

Must have these lines (called pre-processor

directives) near start of file:

 #include <iostream> using namespace std;

 Tells C++ to use appropriate library so we can use the I/O objects cin, cout, cerr

(5)

1-9

Console Output

What can be outputted?

 Any data can be outputted to display screen

 literal string  " games played.―  Variables

 Constants

 Expressions (which can include all of above)

Cascading: multiple values in one cout

Dr. Amal Khalifa, 2012

Separating Lines of Output

New lines in output

 Recall: "\n" is escape sequence for the char "newline"

A second method: object endl

Examples:

cout << "Hello World\n";

 Sends string "Hello World" to display, & escape

sequence "\n", skipping to next line

cout << "Hello World" << endl;

(6)

Escape Sequences

Dr. Amal Khalifa, 2012

1-11

 "Extend" character set

 Backslash, \ preceding a character

 Instructs compiler: a special "escape

character" is coming

 Following character treated as

"escape sequence char"

 Display 1.3 next slide

Some Escape Sequences (1 of 2)

(7)

Some Escape Sequences (2 of 2)

Dr. Amal Khalifa, 2012 1-13

C++ Variables

C++ Identifiers

 Keywords/reserved words vs. Identifiers  Case-sensitivity and validity of identifiers

 Meaningful names!

Variables

 A memory location to store data for a program

(8)

Data Types

Dr. Amal Khalifa, 2012 1-15

Data Types:

(9)

Declaring Variables

Dr. Amal Khalifa, 2012

17

 Rule:

 <dataType> identifier

Examples:

 int myValue;  char response;  float price;  double yCoord;

Input Using cin

cin for input, cout for output

Differences:

 ">>" (extraction operator) points opposite

 Think of it as "pointing toward where the data goes"

 Object name "cin" used instead of "cout"  No literals allowed for cin

 Must input "to a variable"

cin >> num;

 Waits on-screen for keyboard entry

(10)

Prompting for Input: cin and cout

Dr. Amal Khalifa, 2012

1-19

Every cin should have cout prompt

 Maximizes user-friendly input/output

Example:

cout << "Enter number of dragons: ";

cin >> numOfDragons;

 Note:

 no "\n" in cout.

 Prompt "waits" on same line for keyboard input as follows:

Enter number of dragons: ____

Formatting Output

Dr. Amal Khalifa, 2012

1-20

 Formatting numeric values for output

 Values may not display as you’d expect! 

"Magic Formula" to force decimal sizes:

cout.setf(ios::fixed);

cout.setf(ios::showpoint);

cout.precision(2);

 To have exactly two digits after the decimal place

 Example:

cout << "The price is $" << price << endl;

 Now results in the following:

(11)

Assigning Data

Dr. Amal Khalifa, 2012

1-21

Initializing data in declaration statement

 Results "undefined" if you don’t!

 int myValue = 0;

Assigning data during execution

 Lvalues (left-side) & Rvalues (right-side)

 Lvalues must be variables  Rvalues can be any expression

Example:

distance = rate * time; Lvalue: "distance" Rvalue: "rate * time"

Data Assignment Rules

Compatibility of Data Assignments

 intVar = 2.99; // 2 is assigned to intVar!

 Only integer part "fits", so that’s all that goes  Called "implicit" or "automatic type conversion"

 Literals

 2, 5.75, "Z", "Hello World"

 Considered "constants": can’t change in program

Type mismatches

 General Rule: Cannot place value of one type into variable of another

(12)

Expressions & Arithmetic Operators

Dr. Amal Khalifa, 2012

23

 Addition +  Subtraction -  Multiplication *  Division /  Mod %

 How to write mathematical formulas in C++??

1-24

Arithmetic Precision

 Precision of Calculations

 "Highest-order operand" determines type of arithmetic

"precision" performed

Examples:

 17 / 5 evaluates to ??

 Both operands are integers  Integer division is performed!

 17.0 / 5 equals ??

 Highest-order operand is "double type"  Double "precision" division is performed!

 int intVar1 =1, intVar2=2; intVar1 / intVar2;

 Result: ??

(13)

1-25

Individual Arithmetic Precision

Calculations done "one-by-one"

 1 / 2 / 3.0 / 4 performs 3 separate divisions.

 First 1 / 2 equals 0  Then 0 / 3.0 equals 0.0  Then 0.0 / 4 equals 0.0!

So not necessarily sufficient to change just "one

operand" in a large expression

 Must keep in mind all individual calculations that will be performed during evaluation!

Dr. Amal Khalifa, 2012

Type Casting

 Casting for Variables

 Can add ".0" to literals to force precision arithmetic, but what

about variables?  We can’t use "myInt.0"!  Two types

 Implicit—also called "Automatic"

 Done FOR you, automatically

17 / 5.5

 Explicit type conversion

 Programmer specifies conversion with cast operator

(double)17 / 5.5

(double)myInt / myDouble

(14)

1-27

Shorthand Operators

 Increment & Decrement Operators

 Increment operator, ++

intVar++;  intVar = intVar + 1;

 Decrement operator, --

intVar--;  intVar = intVar – 1;

Post-Increment : intVar++

 Uses current value of variable, THEN increments it

Pre-Increment : ++intVar

 Increments variable first, THEN uses new value 

No difference if "alone" in statement:

intVar++; and ++intVar;

identical result

Dr. Amal Khalifa, 2012

Example

Post-Increment Pre-Increment

Dr. Amal Khalifa, 2012

28

int n = 2, valueProduced; valueProduced = 2 * (n++); cout << valueProduced << endl;

cout << n << endl;

int n = 2, valueProduced; valueProduced = 2 * (++n); cout << valueProduced << endl;

(15)

Arithmetic Assignment Operators

Dr. Amal Khalifa, 2012 1-29

Constants

Cannot change values during execution

Use Meaningful name to represent data

 const int NUMBER_OF_STUDENTS = 24;

(16)

Dr. Amal Khalifa, 2012 1-31

1-32

Program Style

 Always use comments…

 Make programs easy to read and modify

 // Two slashes indicate entire line is to be ignored

 /*Delimiters indicates everything between is ignored*/

 Identifier naming

 ALL_CAPS for constants

 lowerToUpper for variables

 Most important: MEANINGFUL NAMES!

(17)

Dr. Amal Khalifa, 2012 33

That’s all for today !!

References

Related documents

These data suggest that anadromous fish nursery habitat likely experiences considerable spatial variability in fatty acid profiles of zooplankton prey and that are correlated to

Using a phylogenetic tree of Bantu languages, we then test the prominent hypothe- sis that structured variation in systems of cousin terminology has co-evolved alongside adaptive

MARINE GRADE HARDWARE - STAINLESS STEEL STD STD STD STD STD STD STD STD STD STD STD STD STD STD BOW ANCHOR ROLLER OPT OPT OPT STD OPT N/A N/A N/A N/A N/A N/A N/A N/A N/A

Notably, there were no changes for either percentage of cells phase locked or MRL values between initial exposure and recent recall days, indicating that familiarity did not affect

Here, I found that sphingosine kinase 1 (SPHK1) was expressed at higher levels in TNBCs patients samples than in other breast cancer subtypes and high SPHK1 expression is

In determining whether Mashup Artists are likely to prevail under this first factor, courts will consider the distribution of their work, i.e., whether the Mashup is purely

The function of the PFP is to promote communication and integration between all jurisdictions and provide resources, risk-informed insight, and best practices to improve the

To address the myriad of user access requirements associated with different businesses, the user access service in Fortinet Connect provides administrators, sponsors and users a full