CSCE 110 PROGRAMMING FUNDAMENTALS WITH C++

50
Prof. Amr Goneid, AUC 1 CSCE 110 CSCE 110 PROGRAMMING FUNDAMENTALS PROGRAMMING FUNDAMENTALS WITH WITH C++ C++ Prof. Amr Goneid AUC Part 2. Overview of C++

description

CSCE 110 PROGRAMMING FUNDAMENTALS WITH C++. Prof. Amr Goneid AUC Part 2. Overview of C++. Overview of C++. Overview of C++. Historical C++ Basics Some Library Functions Expressions & Assignment Simple Input/Output. Historical. 1967: BCP language (Martin Richards, Cambridge) - PowerPoint PPT Presentation

Transcript of CSCE 110 PROGRAMMING FUNDAMENTALS WITH C++

Prof. Amr Goneid, AUC 1

CSCE 110CSCE 110PROGRAMMING FUNDAMENTALSPROGRAMMING FUNDAMENTALS

WITHWITH C++C++

Prof. Amr Goneid

AUC

Part 2. Overview of C++

Prof. Amr Goneid, AUC 2

Overview of C++Overview of C++

Prof. Amr Goneid, AUC 3

Overview of C++Overview of C++

Historical C++ Basics Some Library Functions Expressions & Assignment Simple Input/Output

Prof. Amr Goneid, AUC 4

HistoricalHistorical

1967: BCP language (Martin Richards, Cambridge)

1969: B language (Ken Thompson, Bell labs) Early 1970’s: C language & Unix Operating

System (Dennis Ritchie, Bell Labs)

Prof. Amr Goneid, AUC 5

HistoricalHistorical

Mid-1980’s: Early C++ derived from C (Bjarne Stroustrup, Bell labs)

1998: Formally standardized C++, an OOP language

Prof. Amr Goneid, AUC 6

1. C++ Basics1. C++ Basics

Example Program Style, Declarations Data Types Constants Declaring Constants & variables

Prof. Amr Goneid, AUC 7

1.1 Example Program:1.1 Example Program:Sorting an Array of IntegersSorting an Array of Integers

Prof. Amr Goneid, AUC 8

Sorting an Array of IntegersSorting an Array of Integers

# include <iostream>

using namespace std;

// Functions Used

void selectsort (int a[ ] , int n); // Function Prototype

int main() // Start of main function

{

const int MAX = 100; // Data Declarations

int a[MAX], k, n;

Prof. Amr Goneid, AUC 9

Example Program:Example Program:Main Function ActionsMain Function Actions

/* Begin Main Actions */cin >> n; // Read size of data if (n > MAX) n = MAX; // to prevent array overflowfor (k = 0; k < n; k++) cin >> a[k];

// Read data into array selectsort(a,n); // Call sorting module for (k = 0; k < n; k++) cout << a[k];

// Write sorted data cout << ‘ \n ’ // Move to a new linereturn 0; // No errors

} /* End. Main Function */

Prof. Amr Goneid, AUC 10

Example Program:Example Program:Sorting Module (Function)Sorting Module (Function)void selectsort (int a[ ], int n)

{ // Begin Moduleint i, j, min, temp; // Module Local Data for (i = 0; i < n-1; i++ ) // Begin module action {

min = i;for ( j = i+1; j < n; j++)

if (a[j] < a[min] ) min = j;temp = a[min]; a[min] = a[i]; a[i] = temp;

} } // End Module

Prof. Amr Goneid, AUC 11

1.2 Style1.2 Style

Lines Separators (spaces, lines, comments) Comments ( //.. Single line or /*..*/ ) Case sensitive ( e.g. MAX, max) Keywords ( e.g. for if return ..)

use lowercase letters User Identifiers (e.g. MAX, min, a, n,

selectsort,.. etc)

Prof. Amr Goneid, AUC 12

Style (continued)Style (continued)

Constants (e.g. MAX ,100 , ‘\n’ etc) Operators (e.g. <= ++ + >> etc) Punctuators (e.g. ( ) ; { } etc) Keywords, identifiers, constants,

operators and punctuators are called

TOKENS Compiler Directives

Prof. Amr Goneid, AUC 13

Compiler DirectivesCompiler Directives

#include Compiler directive Processed at compilation time Instructs compiler on what you want in the

program

#include <iostream> Adds library files to program Used with < > Also “ “ user defined

Prof. Amr Goneid, AUC 14

Some Declaration KeywordsSome Declaration Keywords

Modules (Functions):

main() void <function name>(..) Data Declaration:

const for constant data

int , float , etc, for data types

string for user defined strings

Prof. Amr Goneid, AUC 15

1.3 A Classification of Data 1.3 A Classification of Data TypesTypes

Data Type

Scalar Data Structure

IntegerFloatingCharacter

Logical(bool)

Pointer ArraysStructsUnionsClasses

FilesStreamsstrings……..

Prof. Amr Goneid, AUC 16

Some Scalar Data TypesSome Scalar Data Types

Integers:

int short unsigned int long Floating:

float double long double Character:

char unsigned char Logical (Boolean):

bool

Prof. Amr Goneid, AUC 17

Ranges of Scalar Data TypesRanges of Scalar Data Types

int , short 2 bytes -32,768 .. 32,767 unsigned int , unsigned short 2 bytes

0 .. 65,535 long 4 bytes -2G .. 2G unsigned long 4 bytes 0 .. 4G float 4 bytes ~ E +/- 38 (7 digits) double 8 bytes ~ E +/- 308 (15 digits) long double 10 bytes ~ E +/- 4932 (19 digits)

Prof. Amr Goneid, AUC 18

Ranges of Scalar Data TypesRanges of Scalar Data Types

char 1 byte -128 .. 127 unsigned char 1 byte 0 .. 255 bool 1 byte true / false

non-zero / zeroNote:Integer , character and boolean types are

called Ordinal Types because their members can be listed by rank.

Prof. Amr Goneid, AUC 19

1.4 Examples of Constants1.4 Examples of Constants

Predefined:

true false SHRT_MAX (32767) Integer:

79 (decimal of type int)

232467L (decimal of type long) Floating:

1.35 2.34e-3 5.705E+5 (decimal of type double) Character: ‘A’ ‘\n’ (type char) String Literals: “Hello” (class string)

Prof. Amr Goneid, AUC 20

1.5 Declaring & Initializing 1.5 Declaring & Initializing ConstantsConstants Syntax : const <type> <name> = <value>; Examples:

const int MAX = 100; {integer}const bool says = true; {Boolean}const string message = “warning!”;

{String literal}const float KmperMile= 1.609344F; {float}const alpha = 1.2345E-15; {double}const Large = -2345678L; {long}

const char Initial = ‘H’; {char}

Prof. Amr Goneid, AUC 21

Declaring & Initializing Declaring & Initializing VariablesVariables Syntax: <type> <name>, <name> .. ;

or <type> <name> = <value>; Examples:

unsigned char pixel ;

int k = 2197;

float x , y ;

char c ;

bool test ;

string name = “Ann W. Wolf”;

Prof. Amr Goneid, AUC 22

Assigning Constants to VariablesAssigning Constants to Variableschanges initial valueschanges initial values Examples:

pixel = 212;k = -16329;x = 3.1415926;c = ‘H’;test = false;name = “John W. Wolf ”;k = SHRT_MAX;

Prof. Amr Goneid, AUC 23

2. Some Library Functions2. Some Library Functions

Prof. Amr Goneid, AUC 24

Some Library FunctionsSome Library Functions

To invoke: FunctionName (x)

returns value of function for argument x Examples:

char(65) returns ‘A’

int(‘A’) returns 65

sqrt(4) returns 2.0

abs(-6) returns 6

sin(1.5708) returns 1.00

Prof. Amr Goneid, AUC 25

Library Functions(continued)Library Functions(continued)

cos(0.0) returns 1.0

atan(1.0) returns pi/4

tan(0.0) returns 0.0

log(2.0) returns 0.693147

exp(2.0) returns 7.38906

pow(4,1.5) returns 8.00 = 41.5

ceil(2.67) returns 3.0

floor(2.67) returns 2.0

Random(n) returns random int 0 .. n-1

Prof. Amr Goneid, AUC 26

Using a Library FunctionUsing a Library Function

//Computes w = (1+z)2.6 z 1.45 / (1-z)3.2

# include <cmath> // pow function# include <iostream> // I/O functionsusing namespace std;

int main ( ){

float w , z ;cout << “Enter z: “ ; cin >> z ;w = pow(1+z,2.6) * pow(z,1.45) / pow(1-z,3.2);cout << “Value of w = “ << w << endl;return 0 ;

}

Prof. Amr Goneid, AUC 27

3. Expressions & Assignment3. Expressions & Assignment

Syntax Arithmetic Expressions Logical Expressions Relational Expressions Assignment Statement Overall Operator Precedence More on Arithmetic and Assignment

Prof. Amr Goneid, AUC 28

3.1 Syntax 3.1 Syntax

Form1 Form2

e.g -5 a + b

!found x > y

+ 32 (c >= 65) && (c <=90)

U-Op operand B-Opoperand operand

Prof. Amr Goneid, AUC 29

SyntaxSyntax Operands:

Constants e.g. 5 false Variables e.g. x a[3] Functions e.g. sqrt(7) sin(y) Expression e.g. x + y a > b

Operators:Arithmetic Logical Relational AssignmentCompound

Prof. Amr Goneid, AUC 30

3.2 Arithmetic Expressions3.2 Arithmetic Expressions

Operators: Unary Minus and Plus (-) (+) Multiplication, Division, Modulus

( * / % ) Addition, Subtraction ( + - )

Examples:-5 a*b sqrt(5)/2.0 x % m y - b (a+sqrt(y))/(6- sin(pi*y)) m / n - k

Prof. Amr Goneid, AUC 31

Arithmetic ExpressionsArithmetic Expressions

Examples:

5 / 2 is 2 (int operands, int value)

5.0 / 2.0 (float operands, float value)

5.0 / 2 (Mixed operands, float value)

7 % 2 is 1 3 % 5 is 3 (% for int only)

2 + 6 /3 + 5 is 9 but (2 + 6) / (3 + 5) is 1

Prof. Amr Goneid, AUC 32

Arithmetic ExpressionsArithmetic Expressions

Operator Precedence:

( ) Highest

unary + -

* / %

Add (+) , Subtract (-) Lowest

Prof. Amr Goneid, AUC 33

ExampleExample

How many Hours, Minutes, Seconds are in n seconds?

int n, hrs, mins, secs, rem;

hrs = n / 3600;

rem = n % 3600;

mins = rem / 60;

secs = rem % 60;

Prof. Amr Goneid, AUC 34

3.3 Logical Expressions3.3 Logical Expressions

Operators:

! (unary not) || (or) && (and) Operands of Boolean type Result: Boolean ( true , false ) Examples:

! true is false a || b ! (x<y)

c && d

Prof. Amr Goneid, AUC 35

Truth Table for Logical Truth Table for Logical OperatorsOperators0 false , 1 true

x y !x x || y x && y

0 0 1 0 0

0 1 1 1 0

1 0 0 1 0

1 1 0 1 1

Prof. Amr Goneid, AUC 36

3.4 Relational Expressions3.4 Relational Expressions Operators:

== < > <= >= != Result: Boolean Examples:

a > b c <= 6 sqrt(x) >= y

z != w a+b == c+d ‘A’ < ‘a’

name1 != name2

Prof. Amr Goneid, AUC 37

The Assignment operator ( = ) Syntax: variable = expression; Examples:

int x , y ; bool a,b,c ;

x = 3; y = 2*x; a = true;

a = x > y; c = a || b;

3.5 Assignment Statement3.5 Assignment Statement

Prof. Amr Goneid, AUC 38

3.6 Overall Operator 3.6 Overall Operator PrecedencePrecedence Parentheses ( ) Highest Unary: ! + - Multiplicative: * / % Additive: + - Relational: < > <= >= Relational: == != Logical: && Logical: || Assignment = Lowest Example:

d = !(x+y < z) && (2*b == c);

Prof. Amr Goneid, AUC 39

3.7 More on Arithmetic and 3.7 More on Arithmetic and AssignmentAssignment

Increment and Decrement Operators:++operand --operand

(increment/decrement operand then evaluate expression)

operand++ operand--

(evaluate expression then increment/decrement operand )

e.g. n++ , ++n is shorthand for n = n + 1

Prof. Amr Goneid, AUC 40

Increment and Decrement Increment and Decrement OperatorsOperators

Examples:

int a = 3; int b = 5; int c; c = a + b++; yields a == 3, b == 6, c == 8 c = a + ++b; yields a == 3, b == 6, c == 9 c = a + b--; yields a == 3, b == 4, c == 8 c = a + --b; yields a == 3, b == 4, c == 7

Prof. Amr Goneid, AUC 41

Multiple & Compound Multiple & Compound AssignmentAssignment Multiple Assignment:

c = a = b; d = (a = b + 3) / c; Compound Assignment:

(Reassign after doing operation)e.g. a = a + b; //var = var op expr;can be written:a += b; //var compound-op expr;

compound operators += -= *= /= %=

e.g. c /= (x + 2); is c = c / (x + 2);

Prof. Amr Goneid, AUC 42

4. Simple Input/Output4. Simple Input/Output

Prof. Amr Goneid, AUC 43

Simple Input/OutputSimple Input/Output

Standard I/O Devices:cin standard input stream (keyboard)cout standard output stream (screen)Defined in #include <iostream>

Extraction Operator:>> DataVariableextracts one data item from cin to a variable

Insertion Operator:<< DataElementinserts one data element in cout

Prof. Amr Goneid, AUC 44

Simple Input/OutputSimple Input/Output

Keyboard Input:cin >> v ;cin >> v1 >> v2…;

Variables are entered with spaces between them. ENTER or RETURN end input.

e.g. int a,b; float x; string name;cin >> name; cin >> a >> b >> x;

A.W.Wolf12 524 2.567

Prof. Amr Goneid, AUC 45

Data Types and cinData Types and cin

Don’t mix types with cinint x;

cin >> x;

If Keyboard input is

16.6

The value placed in x would be 16

Prof. Amr Goneid, AUC 46

Other Characteristics of cinOther Characteristics of cin

Leading blanks ignored (floats, int, char, bool and strings)

Char read 1 at a time (1 non blank) Case issues int or float will read until space Stings same as int and float

Prof. Amr Goneid, AUC 47

Simple Input/OutputSimple Input/Output

Screen Output:cout << d; cout << d1 << d2 ..;

Examples:int a,b,c; float z;cout << “Enter a,b,c: “; Enter a,b,c: 600 2 500cin >> a >> b >> c;cout << a << 2*b << endl; 6004z = sqrt(a + b * c);cout << “Result is “;

cout << z; Result is 40.00

Prof. Amr Goneid, AUC 48

Example Program : Example Program : Hello.cppHello.cpp

// FILE: Hello.cpp// DISPLAYS A USER'S NAME

#include <iostream>#include <string>

using namespace std;

int main (){

Prof. Amr Goneid, AUC 49

Hello.cppHello.cpp

char letter1, letter2; string lastName;

// Enter letters and print message. cout << "Enter 2 initials and last name: "; cin >> letter1 >> letter2 >> lastName; cout << "Hello " << letter1 << ". " <<

letter2 << ". " << lastName << "! "; cout << "We hope you enjoy studying C++." <<

endl; return 0;}

Prof. Amr Goneid, AUC 50

Hello.cppHello.cpp

Program Input/output

Enter 2 initials and last name: SAWolf

Hello S. A. Wolf! We hope you enjoy

studying C++.