basic elements of c++ chapter 1. 2 chapter topics the basics of a c++ program data types ...

42
Basic Elements of C++ Chapter 1

Upload: blaise-osborne

Post on 03-Jan-2016

224 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Basic Elements of C++ Chapter 1. 2 Chapter Topics  The Basics of a C++ Program  Data Types  Arithmetic Operators and Operator Precedence  Expressions

Basic Elements of C++

Chapter 1

Page 2: Basic Elements of C++ Chapter 1. 2 Chapter Topics  The Basics of a C++ Program  Data Types  Arithmetic Operators and Operator Precedence  Expressions

2

Chapter Topics

The Basics of a C++ Program Data Types Arithmetic Operators and Operator

Precedence Expressions Input Increment and Decrement Operators Output Preprocessor Directives Program Style and Form More on Assignment Statements

Page 3: Basic Elements of C++ Chapter 1. 2 Chapter Topics  The Basics of a C++ Program  Data Types  Arithmetic Operators and Operator Precedence  Expressions

3

The Basics of a C++ Program

A C++ program is a collection of one or more subprograms (functions)

Function• Collection of statements• Statements accomplish a task

Every C++ program has a function called main

Page 4: Basic Elements of C++ Chapter 1. 2 Chapter Topics  The Basics of a C++ Program  Data Types  Arithmetic Operators and Operator Precedence  Expressions

4

Example Program

#include <iostream>using namespace std;int main(){ cout<<"Welcome to C++ Programming"<<endl;

return 0;}

Welcome to C++ Programming

Program Output

Page 5: Basic Elements of C++ Chapter 1. 2 Chapter Topics  The Basics of a C++ Program  Data Types  Arithmetic Operators and Operator Precedence  Expressions

5

The Basics of a C++ Program

Programming language• a set of rules, symbols, special words

Rules• syntax – specifies legal instructions

Symbols• special symbols ( + - * ! … )

Word symbols• reserved words • (int, float, double, char …)

Page 6: Basic Elements of C++ Chapter 1. 2 Chapter Topics  The Basics of a C++ Program  Data Types  Arithmetic Operators and Operator Precedence  Expressions

6

Identifiers

Rules for identifiers• must begin with letter or the underscore _• followed by any combination of numerals

or letters• recommend meaningful identifiers

Evaluate the followingElectricCharge

23Skidoo

snarFbLat

Page 7: Basic Elements of C++ Chapter 1. 2 Chapter Topics  The Basics of a C++ Program  Data Types  Arithmetic Operators and Operator Precedence  Expressions

7

Data Types

Definition:• a set of values• combined with a set

of operations

Page 8: Basic Elements of C++ Chapter 1. 2 Chapter Topics  The Basics of a C++ Program  Data Types  Arithmetic Operators and Operator Precedence  Expressions

8

Data Types

Simple data types include• Integers• Floating point• Enumeration

Integer data types includecharshortintlongbool

Numerals, symbols, lettersNumbers without decimals

Values true and false only

Page 9: Basic Elements of C++ Chapter 1. 2 Chapter Topics  The Basics of a C++ Program  Data Types  Arithmetic Operators and Operator Precedence  Expressions

9

Floating-Point Types

Stored using scientific notation• the sign of the number, • the significant digits of the number• the sign of the power of 10• the power of 10

Page 10: Basic Elements of C++ Chapter 1. 2 Chapter Topics  The Basics of a C++ Program  Data Types  Arithmetic Operators and Operator Precedence  Expressions

10

Data Types

Different floating-point types

Note that various types will• have different ranges of values• require different amounts of memory

Page 11: Basic Elements of C++ Chapter 1. 2 Chapter Topics  The Basics of a C++ Program  Data Types  Arithmetic Operators and Operator Precedence  Expressions

11

Data Types

The string Type• a programmer-defined type

• requires #include <string> A string is a sequence of characters

"Hi Mom"

"We're Number 1!"

"75607"

Page 12: Basic Elements of C++ Chapter 1. 2 Chapter Topics  The Basics of a C++ Program  Data Types  Arithmetic Operators and Operator Precedence  Expressions

12Arithmetic Operators and Operator Precedence

Common operators for calculations+ - * / %

Precedence same as in algebraic usage• Inside parentheses done first• Next * / % from left to right• Then + and - from left to right

Note operator precedence chart, page 1035

Page 13: Basic Elements of C++ Chapter 1. 2 Chapter Topics  The Basics of a C++ Program  Data Types  Arithmetic Operators and Operator Precedence  Expressions

13

Expressions

An expression includes• constants• variables• function calls

• combined with operators

3 / 2 + 5.0sin(x) + sqrt(y)

Page 14: Basic Elements of C++ Chapter 1. 2 Chapter Topics  The Basics of a C++ Program  Data Types  Arithmetic Operators and Operator Precedence  Expressions

14

Expressions

Expressions can include• values all of the same type3 + 5 * 12 – 7

• values of different (compatible) types1.23 * 18 / 9.5

An operation is evaluated according to the types of the operands • if they are the same, the result is the type of the

operands• if the operands are different (int and float) then the

result is float

Page 15: Basic Elements of C++ Chapter 1. 2 Chapter Topics  The Basics of a C++ Program  Data Types  Arithmetic Operators and Operator Precedence  Expressions

15

Type Casting

Implicit change of type can occur• when operands are of different type

It is possible to explicitly specify that an expression be converted to a different type

static_cast < type > (expression)

static_cast <int> (3.5 * 6.9 / x)

Page 16: Basic Elements of C++ Chapter 1. 2 Chapter Topics  The Basics of a C++ Program  Data Types  Arithmetic Operators and Operator Precedence  Expressions

16

Input

Storing data in the computer's memory requires two steps

1. Allocate the memory by declaring a variable

2. Have the program fetch a value from the input device and place it in the allocated memory location

x

123cin >> x

Page 17: Basic Elements of C++ Chapter 1. 2 Chapter Topics  The Basics of a C++ Program  Data Types  Arithmetic Operators and Operator Precedence  Expressions

17

Allocating Memory

Variable • A memory location whose content may

change during program execution

Declaration:• Syntax:

type identifier;• Example:

double x; int y = 45;

Note optional initialization of the

variable

Page 18: Basic Elements of C++ Chapter 1. 2 Chapter Topics  The Basics of a C++ Program  Data Types  Arithmetic Operators and Operator Precedence  Expressions

18

Allocating Memory

Named Constant• A memory location whose content cannot

be changed

Declaration• Syntax:const type identifier = value;

• Exampleconst double PI = 3.14159;

Note required initialization of the

named constant

Page 19: Basic Elements of C++ Chapter 1. 2 Chapter Topics  The Basics of a C++ Program  Data Types  Arithmetic Operators and Operator Precedence  Expressions

19

Putting Data Into Variables

At initialization time Assignment statement

• Syntax:variable = expression;

• Examplex = 1.234;volume = sqr (base) * height;

Input (read) statement• Syntax:cin >> variable ;

• Examplecin >> height;

Program Example

Page 20: Basic Elements of C++ Chapter 1. 2 Chapter Topics  The Basics of a C++ Program  Data Types  Arithmetic Operators and Operator Precedence  Expressions

20Increment and Decrement Operators

Pre-increment ++x;equivalent to x = x + 1;• Pre-decrement --x;• Changes the value before execution of a

statement y = ++x; Post-increment intVal++;

• Post-decrement intVal--;• Changes the value after execution of the

statement y = x++;

Page 21: Basic Elements of C++ Chapter 1. 2 Chapter Topics  The Basics of a C++ Program  Data Types  Arithmetic Operators and Operator Precedence  Expressions

21

Output

Values sent to an output device• Usually the screen• Can also be a file or some device

Syntax for screen output:cout << expression << …

Examplecout << "The total is "<< sum << endl;

Sample Program

Output command Insertion

operatorValues to be printed

Manipulator for carriage

return

Page 22: Basic Elements of C++ Chapter 1. 2 Chapter Topics  The Basics of a C++ Program  Data Types  Arithmetic Operators and Operator Precedence  Expressions

22

Output

Escape sequences also used to manipulate output

cout << "The total is\t "<< sum << endl;

Page 23: Basic Elements of C++ Chapter 1. 2 Chapter Topics  The Basics of a C++ Program  Data Types  Arithmetic Operators and Operator Precedence  Expressions

23

Preprocessor Directives

Commands supplied to the preprocessor• Runs before the compiler• Modifies the text of the source code before

the compiler starts

Syntax• start with # symbol• #include <headerFileName>

Example #include <iostream>

Page 24: Basic Elements of C++ Chapter 1. 2 Chapter Topics  The Basics of a C++ Program  Data Types  Arithmetic Operators and Operator Precedence  Expressions

24

Preprocessor Directives

Note the preprocessorstep in the sequence

Page 25: Basic Elements of C++ Chapter 1. 2 Chapter Topics  The Basics of a C++ Program  Data Types  Arithmetic Operators and Operator Precedence  Expressions

25

Namespace

The #include <iostream> command is where cin and cout are declared

They are declared within a namespace called std

When we specify using namespace std;• Then we need not preface the cin and cout commands with std::cin and std::cout

Page 26: Basic Elements of C++ Chapter 1. 2 Chapter Topics  The Basics of a C++ Program  Data Types  Arithmetic Operators and Operator Precedence  Expressions

26

Program Style and Form

Every program must contain a function called mainint main (void){ … }

The int specifies that it returns an integer value

The void specifies there will be no arguments

Also can say void main( ) { … }

Page 27: Basic Elements of C++ Chapter 1. 2 Chapter Topics  The Basics of a C++ Program  Data Types  Arithmetic Operators and Operator Precedence  Expressions

27

Program Style and Form

Variables usually declared• inside main• at beginning of program

Use blanks and space to make the program easy for humans to read

Semicolons ; required to end a statement

Commas used to separate things in a list

Page 28: Basic Elements of C++ Chapter 1. 2 Chapter Topics  The Basics of a C++ Program  Data Types  Arithmetic Operators and Operator Precedence  Expressions

28

Program Style and Form

Documentation• Comments specified between /* this is a comment */and following // also a comment

• Always put at beginning of program /* name, date, cpo, purpose of program*/

Page 29: Basic Elements of C++ Chapter 1. 2 Chapter Topics  The Basics of a C++ Program  Data Types  Arithmetic Operators and Operator Precedence  Expressions

29

Program Style and Form

Names of identifiers should help document program

double electricCharge; // instead of ec

Prompt keyboard entrycout << "Enter the value for x -> ";cin >> x;

Page 30: Basic Elements of C++ Chapter 1. 2 Chapter Topics  The Basics of a C++ Program  Data Types  Arithmetic Operators and Operator Precedence  Expressions

Example 1

#include <iostream> using namespace std; int main( ) { int numberOfLanguages; cout << "Hello reader.\n" << "Welcome to C++.\n"; cout << "How many programming languages have you used? "; cin >> numberOfLanguages; if (numberOfLanguages < 1) cout << "Read the preface. You may prefer\n" << "a more elementary book by the same author.\n"; else cout << "Enjoy the book.\n"; system("pause"); return 0; }

30

Page 31: Basic Elements of C++ Chapter 1. 2 Chapter Topics  The Basics of a C++ Program  Data Types  Arithmetic Operators and Operator Precedence  Expressions

Example 2

#include <iostream> // Required for cout, endl. #include <cmath> // Required for sqrt() using namespace std; int main() { // Declare and initialize objects. double x1(1), y1(5), x2(4), y2(7), side1, side2, distance; // Compute sides of a right triangle. side1 = x2 - x1; side2 = y2 - y1; distance = sqrt(side1*side1 + side2*side2); // Print distance. cout << "The distance between the two points is " << distance << endl; // Exit program. system("pause"); return 0; }

31

Page 32: Basic Elements of C++ Chapter 1. 2 Chapter Topics  The Basics of a C++ Program  Data Types  Arithmetic Operators and Operator Precedence  Expressions

// my first program in C++ #include <iostream> int main() { std::cout << "Hello World!"; }

Page 33: Basic Elements of C++ Chapter 1. 2 Chapter Topics  The Basics of a C++ Program  Data Types  Arithmetic Operators and Operator Precedence  Expressions

// my second program in C++ #include <iostream>

int main () { std::cout << "Hello World! "; std::cout << "I'm a C++ program"; } In one line int main () { std::cout << " Hello World! "; std::cout << " I'm a C++ program "; }

Page 34: Basic Elements of C++ Chapter 1. 2 Chapter Topics  The Basics of a C++ Program  Data Types  Arithmetic Operators and Operator Precedence  Expressions

Comments

Comments

1

2

// line comment /* block comment */

As noted above, comments do not affect the operation of the program; however, they provide an important tool to document directly within the source code what the program does and how it operates.

C++ supports two ways of commenting code:

Page 35: Basic Elements of C++ Chapter 1. 2 Chapter Topics  The Basics of a C++ Program  Data Types  Arithmetic Operators and Operator Precedence  Expressions

/* my second program in C++ with more comments */

#include <iostream>

int main (){ std::cout << "Hello World! "; // prints Hello World!

std::cout << "I'm a C++ program"; // prints I'm a C++ program

}

Page 36: Basic Elements of C++ Chapter 1. 2 Chapter Topics  The Basics of a C++ Program  Data Types  Arithmetic Operators and Operator Precedence  Expressions

Using namespace std

Using namespace std If you have seen C++ code before, you may have seen cout being

used instead of std::cout. Both name the same object: the first one uses its unqualified name (cout), while the second qualifies it directly within the namespace std (as std::cout).

cout is part of the standard library, and all the elements in the standard C++ library are declared within what is a called a namespace: the namespace std.

In order to refer to the elements in the std namespace a program shall either qualify each and every use of elements of the library (as we have done by prefixing cout with std::), or introduce visibility of its components. The most typical way to introduce visibility of these components is by means of using declarations:

using namespace std

Page 37: Basic Elements of C++ Chapter 1. 2 Chapter Topics  The Basics of a C++ Program  Data Types  Arithmetic Operators and Operator Precedence  Expressions

// my second program in C++ #include <iostream> using namespace std;

int main () { cout << "Hello World! "; cout << "I'm a C++ program"; }

Page 38: Basic Elements of C++ Chapter 1. 2 Chapter Topics  The Basics of a C++ Program  Data Types  Arithmetic Operators and Operator Precedence  Expressions

Variables and types The usefulness of the "Hello World" programs shown in the previous chapter is rather

questionable. We had to write several lines of code, compile them, and then execute the resulting program, just to obtain the result of a simple sentence written on the screen. It certainly would have been much faster to type the output sentence ourselves.

However, programming is not limited only to printing simple texts on the screen. In order to go a little further on and to become able to write programs that perform useful tasks that really save us work, we need to introduce the concept of variable.

Let's imagine that I ask you to remember the number 5, and then I ask you to also memorize the number 2 at the same time. You have just stored two different values in your memory (5 and 2). Now, if I ask you to add 1 to the first number I said, you should be retaining the numbers 6 (that is 5+1) and 2 in your memory. Then we could, for example, subtract these values and obtain 4 as result.

The whole process described above is a simile of what a computer can do with two variables. The same process can be expressed in C++ with the following set of statements:

a = 5; b = 2; a = a + 1; result = a - b;

Page 39: Basic Elements of C++ Chapter 1. 2 Chapter Topics  The Basics of a C++ Program  Data Types  Arithmetic Operators and Operator Precedence  Expressions

a = 5; b = 2; a = a + 1; result = a - b;

Page 40: Basic Elements of C++ Chapter 1. 2 Chapter Topics  The Basics of a C++ Program  Data Types  Arithmetic Operators and Operator Precedence  Expressions

#include <iostream>

using namespace std;

int main() { int a; int b; cout<<"Enter first number:\n"; cin >> a; cout <<"Enter the second number:\n"; cin>> b; cin.ignore(); int result = a + b; cout<<"Result is"<<" "<<result<<endl; cin.get(); return 0; }

Page 41: Basic Elements of C++ Chapter 1. 2 Chapter Topics  The Basics of a C++ Program  Data Types  Arithmetic Operators and Operator Precedence  Expressions

#include <iostream> #include <string> using namespace std; int main () { string s; cout << "jhun \n" ; cin >> s; cout << "Hello, " << s << '\n' ; return 0; // this return statement isn't necessary }

Page 42: Basic Elements of C++ Chapter 1. 2 Chapter Topics  The Basics of a C++ Program  Data Types  Arithmetic Operators and Operator Precedence  Expressions

#include <iostream> using namespace std; int main() { cout << "Hello World!" << endl; return 0; }

*/ #include <iostream> #include <cmath> using namespace std; int main() { int x = 0; while(x < 10) { double y = sqrt((double)x); cout << "The square root of " << x << " is " << y << endl; x++; } return 0; }