comp104 notes

43
Class Test Date(s): Wednesday, 17/12/2014 Time: 10:00-12:00 Room: BROD-305

Transcript of comp104 notes

Class Test

Date(s): Wednesday, 17/12/2014

Time: 10:00-12:00

Room: BROD-305

ELEC431 LECTURE

INTRODUCTION TO C/C++

L1

Content

What is C++

Why C++

Generation form and feature of C++

Programme style

Data type

I/O

What is C++?

C++ is a programming language.

A computer program performs a specific task, and

may interact with the user and the computer

hardware.

Human work model:

Computer work model:

What is C++? The most popular programming languages:

Basic (Beginner All-purpose Symbolic Instructional Code)

C++ (an object-oriented language, based on C)

Fortran (FORmula TRANslation)

Java

Pascal (named for Blaise Pascal)

Visual Basic (Basic-like visual language developed by Microsoft)

C (developed by the designer of the B language)

The most common versions of C++:

Microsoft VC++

Eclipse

g++ (for Unix machines)

Why C++?

Bad News:

C++ is not easy to learn

Good News:

Lots of good-paying jobs for programmers because C++ is not easy to learn!

Java uses C++ syntax, it is easy to learn Java if you know C++.

Though C++ is not the easiest language (Basic and Pascal are easier), it is not the hardest either (Prolog and Assembly languages are really difficult!)

Who Uses C++?

Computer makers such as Sun, SGI, IBM, and HP

Airport

Computer chip manufacturers

like Motorola & Intel

Software companies

Banks

Government

Hospital Authority

Telecommunications

Universities

Most Important Feature of C++

Most important feature of C++: its strong and efficient support of both Structured Programming and Object-Oriented Programming.

C++ runs on:

PC

Macintosh

Unix workstations (also, Unix versions of C++ are free!)

supercomputers

Computer Software Relationships

User

Interface

Basic Input and Output Services (BIOS)

• needed for a computer to boot up

User Interface Operating System

User Interface Application Programs

Computer Hardware

Introduction to C++

C is a programming language developed in the 1970's alongside the UNIX operating system.

C provides a comprehensive set of features for handling a wide variety of applications, such as systems development and scientific computation.

C++ is an “extension” of the C language, in that most C programs are also C++ programs.

C++, as opposed to C, supports “object-oriented programming.”

General form of a C++ program

// Program description

#include directives

int main()

{

constant declarations

variable declarations

executable statements

return 0;

}

C++ keywords

Keywords appear in blue in Visual C++.

Each keyword has a predefined purpose in the language.

Do not use keywords as variable and constant names!!

Common keywords:

bool, break, case, char, const,

continue, do, default, double, else,

extern, false, float, for, if, int, long,

namespace, return, short, static, struct,

switch, typedef, true, unsigned, void,

while

Example – adding 2 numbers

Peter: Hey Frank, I just learned how to add two numbers together.

Frank: Cool!

Peter : Give me the first number.

Frank: 2.

Peter : Ok, and give me the second number.

Frank: 5.

Peter : Ok, here's the answer: 2 + 5 = 7.

Frank: Wow! You are amazing!

after Frank says “2”, Peter has to keep this number in his mind.

2 5 7 First number: Second number: Sum:

after Frank says “5”, Peter also needs to keep this number in his mind.

The Corresponding C++ Program

#include <iostream>

using namespace std;

int main()

{

int first, second, sum;

cout << "Peter: Hey Frank, I just learned how to add”

<< “ two numbers together."<< endl;

cout << "Frank: Cool!" <<endl;

cout << "Peter: Give me the first number."<< endl;

cout << "Frank: ";

cin >> first;

cout << "Peter: Give me the second number."<< endl;

cout << "Frank: ";

cin >> second;

sum = first + second;

cout << "Peter: OK, here is the answer:";

cout << sum << endl;

cout << "Frank: Wow! You are amazing!" << endl;

return 0;

}

#include <iostream>

using namespace std;

int main()

{

int number_of_pods, peas_per_pod, total_peas;

cout << "Press return after entering a number.\n";

cout << "Enter the number of pods:\n";

cin >> number_of_pods;

cout << "Enter the number of peas in a pod:\n";

cin >> peas_per_pod;

total_peas = number_of_pods * peas_per_pod;

Demo Example

cout << "If you have ";

cout << number_of_pods;

cout << " pea pots\n";

cout << "and ";

cout << peas_per_pod;

cout << " pea in each pod, then \n";

cout << "you have ";

cout << total_peas;

cout << " peas in all the pods.\n";

return 0;

}

Demo Example

Identifiers appear in black in Visual C++.

An identifier is a name for a variable, constant, function, etc.

It consists of a letter followed by any sequence of letters, digits, and underscores.

Examples of valid identifiers: First_name, age, y2000, y2k

Examples of invalid identifiers: 2000y

Identifiers cannot have special characters in them. For example: X=Y, J-20, ~Ricky,*Michael are invalid identifiers.

Identifiers are case-sensitive. For example: Hello, hello, WHOAMI, WhoAmI, whoami are unique identifiers.

C++ identifiers

C++ comments

Comments appear in green in Visual C++.

Comments are explanatory notes; they are ignored by the compiler.

There are two ways to include comments in a program:

// A double slash marks the start of a

//single line comment.

/* A slash followed by an asterisk marks

the start of a multiple line comment. It

ends with an asterisk followed by a

slash. */

C++ compiler directives

Compiler directives appear in blue in Visual C++.

The #include directive tells the compiler to include

some already existing C++ code in your program.

The included file is then linked with the program.

There are two forms of #include statements:

#include <iostream> //for pre-defined

files

#include "my_lib.h" //for user-defined

files

Programming Style

C++ is a free-format language, which means that:

Extra blanks (spaces) or tabs before or after identifiers/operators are ignored.

Blank lines are ignored by the compiler just like comments.

Code can be indented in any way.

There can be more than one statement on a single line.

A single statement can continue over several lines.

In order to improve the readability of your program, use the following conventions:

Start the program with a header that tells what the program does.

Use meaningful variable names.

Document each variable declaration with a comment telling what the variable is used for.

Place each executable statement on a single line.

A segment of code is a sequence of executable statements that belong together.

Use blank lines to separate different segments of code.

Document each segment of code with a comment telling what the segment does.

Programming Style (cont. )

What makes a bad program?

Writing Code without detailed analysis

and design

Repeating trial and error without

understanding the problem

Debugging the program line by line,

statement by statement

Writing tricky and dirty programs

C++ Data Type

A type defines a set of values and a set of

operations that can be applied on those values.

The set of values for each type is known as the

domain for the type.

C++ contains 5 standard types:

void int char float bool

Standard

Data Types

void

The void type has no values and no operations. In

other words, both the set of values and the set of

operations are empty. Although this might seem

unusual, we will see later that it is a very useful data

type.

Integer

An integer type is a number without a fractional

part. It is also known as an integral number. C++ supports three different sizes of the integer data type: short int, int and long int.

sizeof(short int)<= sizeof(int)<= sizeof(long int)

Short int

int

long int

Floating Point

A floating-point type is a number with a fractional

part, such as 43.32. The C++ language supports

three different sizes of floating-point: float, double

and long double.

sizeof(float)<= sizeof(double)<= sizeof(long double)

float

double

long double

Floating Point

type Byte size Number of Bits

float 4 32

double 8 64

long double 10 80

Although the physical size of floating-point types is

machine dependent, many computers support the

sizes shown below.

Declarations

Constants and variables must be declared before they can be used.

A constant declaration specifies the type, the name and the value of the constant.

A variable declaration specifies the type, the name and possibly the initial value of the variable.

When you declare a constant or a variable, the compiler: Reserves a memory location in which to store the value of the

constant or variable.

Associates the name of the constant or variable with the memory location. (You will use this name for referring to the constant or variable.)

Constant declarations

Constants are used to store values that never change during the program execution.

Using constants makes programs more readable and maintainable.

Syntax: const <type> <identifier> = <expression>;

Examples: const double UK2USD = 1.6;

//Exchange rate of £ to $

const double fee = 16000;

//Tuition fee

Variables are used to store values that can be changed

during the program execution.

A variable is best thought of as a container for a value.

3445 y -3.14

Syntax: < type > < identifier >;

< type > < identifier > = < expression >;

Examples: int sum;

int total = 3445;

char answer = 'y';

double temperature = -3.14;

Variable declarations

A variable has a type and it can contain only values of that type. For example, a variable of the type int can

only hold integer values.

Variables are not automatically initialized. For example,

after declaration int sum;

the value of the variable sum can be anything (garbage).

Thus, it is good practice to initialize variables when they

are declared.

Once a value has been placed in a variable it stays

there until the program deliberately alters it.

Variable declarations

Character data

A variable or a constant of char type can hold an ASCII

character (see Appendix A of the textbook).

When initializing a constant or a variable of char type, or

when changing the value of a variable of char type, the

value is enclosed in single quotation marks.

Examples:

const char star = '*';

char letter, one = '1';

Rules for Division

C++ treats integers differently from decimal numbers.

100 is an int type.

100.0 , 100.0000, and 100. are double type.

The general rule for division of int and double types is:

double/double -> double (normal)

double/int -> double (normal)

int/double -> double (normal)

int/int -> int (note: the decimal part is discarded)

Rules for Division

Examples:

220. / 100.0 double/double -> double result is 2.2

220. / 100 double/int -> double result is 2.2

220 / 100.0 int/double -> double result is 2.2

220 / 100 int/int -> int result is 2

Summary: division is normal unless both the numerator and denominator are int, then the result is an int (the decimal part is

discarded).

Assignment Conversions

A decimal number assigned to an int type variable

is truncated.

An integer assigned to a double type variable is

converted to a decimal number.

Example 1:

double yy = 2.7;

int i = 15;

int j = 10;

i = yy; // i is now 2

yy = j; // yy is now 10.0

Assignment Conversions

Example 2:

int m, n;

double xx;

m = 7;

n = 2.5;

xx = m / n;

n = xx + m / 2;

// What is the value of n?

Assignment Conversions

Example 2:

int m, n;

double xx;

m = 7;

n = 2.5; // 2.5 converted to 2 and assigned to n

xx = m/n; // 7/2=3 converted to 3.0 and assigned to xx

n = xx+m/2;

// m/2=3 : integer division

// xx+m/2 : double addition because xx is double

// convert result of m/2 to double (i.e. 3.0)

// xx+m/2=6.0

// convert result of xx+m/2 to int (i.e. 6)

// because n is int

Forcing a Type Change

You can change the type of an expression with a cast

operation.

Syntax: variable1 = type(variable2);

variable1 = type(expression);

Example: int x=1, y=2;

double result1 = x/y; // result1 is 0.0

double result2 = double(x)/y; // result2 is 0.5

double result3 = x/double(y); // result3 is 0.5

double result4 = double(x)/double(y);// result4 is 0.5

double result5 = double(x/y); // result5 is 0.0

int cents = int(result4*100); // cents is 50

Standard Input/Output

cin - the standard input stream

Input operator “>>”

Extracts data from input “stream” (the keyboard by default).

Skips over white spaces.

Extracts only characters of the right form and performs

automatic conversion to the type specified.

Standard Input/Output

cout - the standard output stream

Output operator “<<”

Inserts data into the output “stream” (the screen by default).

Example:

int id, score;

cout << "Enter student ID and score: ";

cin >> id >> score;

cout << "Student ID: " << id << " score: "

<< score << endl;

Standard Input/Output

Some special output characters:

\a bell

\t tab

\n new line

\' single quote

\" double quote

Format Manipulation

#include <iomanip>

setw(int size)

Specifies the number of characters to use in displaying the next value,

which is right-justified.

Ex: cout << setw(5) << 12;

//output 3 spaces and then 12

setprecision(int digit)

Specifies the number of significant digits for all subsequent output.

cout << fixed << setprecision(2);

the precision is: two digits after the decimal point.

Fixed: uses fixed-point notation in the float field