Numeric Data Types, Operations and Functions By Kondwani Makanda

Learning outcomes By the end of this presentation you should be able to understand the following:

• • • • • • • • •

Assignment statements and assignment operator Named constants Numerical Datatypes and Operators Numerical Literals Compound Assignment Operators Increment and Decrement Operators Relational and Comparison Operators Logical Operators Functions

Assignment statement and assignment expression • An assignment statement designates a value for a variable

Named Constants or constants • is an identifier that represents a permanent value (values that will not change) • e.g. PI or π

• use the const keyword • The syntax of using const is • const datatype CONSTANTNAME/ IDENTIFIER = value; • const double PI = 3.14159; • Constants are normally in UPPERCASE

Why use constants? • There are three benefits of using constants: • you don’t have to repeatedly type the same value; • if you have to change the constant value (e.g, from 3.14 to 3.14159 for PI), you only change it at a single location in the source code; • descriptive constant names make the program easy to read.

Numerical datatypes and operators • Numeric Types • Every data type has a range of values • The compiler allocates memory space for each variable/constant according to its data type • C++ provides primitive data types for numeric values, characters, and Boolean values. • C++ uses three types of integers: short, int, and long. • Each integer type comes in two flavours: signed and unsigned • Half of the numbers represented by a signed int are negative and the other half are non-negative • All the numbers represented by an unsigned int are non-negative

Numerical datatypes and operators CONT’D • Numeric Types • C++ uses three types for floating-point numbers: float, double and long double. • The double type is usually twice as big as float • the double is known as double precision • float is single precision • The long double is even bigger than double • For most applications using double type is desirable

Type

Typical Bit Width

Typical Range

char

1byte

-127 to 127 or 0 to 255

unsigned char signed char int

1byte 1byte 4bytes

0 to 255 -127 to 127 -2147483648 to 2147483647

unsigned int signed int

4bytes 4bytes

0 to 4294967295 -2147483648 to 2147483647

short int unsigned short int signed short int long int

2bytes Range Range 4bytes

-32768 to 32767 0 to 65,535 -32768 to 32767 -2,147,483,648 to 2,147,483,647

signed long int unsigned long int float

4bytes 4bytes 4bytes

same as long int 0 to 4,294,967,295 +/- 3.4e +/- 38 (~7 digits)

double

8bytes

+/- 1.7e +/- 308 (~15 digits)

long double

8bytes

+/- 1.7e +/- 308 (~15 digits)

wchar_t

2 or 4 bytes

1 wide character

Numerical datatypes and operators CONT’D • Numeric Types • C++ defines constants INT_MIN, INT_MAX, LONG_MIN, LONG_MAX, FLT_MIN, FLT_MAX, DBL_MIN, and DBL_MAX in the header file • The constants are useful in programming • You can know the values of these constants by: • cout << “INT_MIN is” << INT_MIN << endl;

Numerical literals • A literal is a constant value that appears directly in a program • int i = 34; • double footToMeters = 0.305; • By default, an integer literal is a decimal integer number • To denote an octal integer, use a leading 0 (zero) • To denote a hexadecimal integer literal, use a leading 0x or 0X (zero x) • The following code displays the decimal value 65535 for hexadecimal number FFFF and decimal value 8 for octal number 10. • cout << 0xFFFF << “ ” << 010;

Numerical operators • Already learnt during the laboratory practicals

Compound assignment operators Operator name

Syntax

Meaning

Addition assignment

a += b

a=a+b

Subtraction assignment

a -= b

a=a-b

Multiplication assignment

a *= b

a=a*b

Division assignment

a /= b

a=a/b

Modulo assignment

a %= b

a=a%b

Bitwise AND assignment

a &= b

a=a&b

Bitwise OR assignment

a |= b

a=a|b

Bitwise XOR assignment

a ^= b

a=a^b

Bitwise left shift assignment

a <<= b

a = a << b

Bitwise right shift assignment

a >>= b

a = a >> b

Increment and decrement (++, --) • the increase operator (++) and the decrease operator (--) increase or reduce by one the value stored in a variable • they are equivalent to +=1 and -=1, respectively • ++x; • x+=1; • x=x+1;

• The increment operator can be used as a prefix (++x) as well as suffix (x++) operator • In a case of a prefix (++x) of the value, the expression evaluates to the final value of x, once it is already increased • On the other hand, in case that it is used as a suffix (x++), the value is also increased, but the expression evaluates to the value that x had before being increased

Example 1

Example 2

X = 3; x = 3; y = ++x; y = x++; // x contains 4, y contains 4 // x contains 4, y contains 3

Relational and comparison operators (7 == 5) // evaluates to false • Used to compare two expressions (5 > 4) // evaluates to true O perator Description • (3 != 2) // evaluates to true == != < > <= >=

Equal to

Not equal to

(6 >= 6)

Less than

(5 < 5)

// evaluates to true // evaluates to false

Greater than Less than or equal to Greater than or equal to

Suppose that a=2, b=3 and c=6, then: (a == 5) // evaluates to false, since a is not equal to 5 (a*b >= c) // evaluates to true, since (2*3 >= 6) is true (b+4 > a*c) // evaluates to false, since (3+4 > 2*6) is false ((b=2) == a) // evaluates to true

Logical operators (!, &&, ||) • The operator ! is the C++ operator for the Boolean operation NOT • It has one operand to its right and inverts it, producing false if its operand is true, and true if its operand is false

!(5 == 5) // evaluates to false because the expression at its right (5 == 5) is true !(6 <= 4) // evaluates to true because (6 <= 4) would be false !true // evaluates to false !false // evaluates to true

Logical operators (!, &&, ||)

cont’d

• The logical operators && and || are used when evaluating two expressions to obtain a single relational result • The operator && corresponds to the Boolean logical operation AND, which yields true if both its operands are true, and false otherwise.

a true true false false

&& OPERATOR (AND) b a && b true true false false true false false false

Logical operators (!, &&, ||)

cont’d

• The operator || corresponds to the Boolean logical operation OR, which yields true if either of its operands is true • thus being false only when both operands are false

a true true false false

|| OPERATOR (OR) b a || b true true false true true true false false

Logical operators (!, &&, ||)

cont’d

For Example: ( (5 == 5) && (3 > 6) ) // evaluates to false (true && false) ( (5 == 5) || (3 > 6) ) // evaluates to true (true || false)

• In using logical operators, C++ evaluates what is necessary from left to right to come up with the combined relational result, ignoring the rest. • Therefore, in the last example ((5==5)||(3>6)), C++ evaluates first whether 5==5 is true, and if so, it never checks whether 3>6 is true or not. • This is known as short-circuit evaluation Operator && ||

Short-circuit if the left-hand side expression is false, the combined result is false (the right-hand side expression is never evaluated) if the left-hand side expression is true, the combined result is true (the right-hand side expression is never evaluated)

Bit-wise operators

Operator & | ^

asm equivalent AND OR XOR

~

NOT

<< >>

SHL SHR

Description Bitwise AND Bitwise inclusive OR Bitwise exclusive OR Unary complement inversion) Shift bits left Shift bits right

(bit

functions • Functions are blocks of code that perform a number of pre-defined commands to accomplish something productive • C++ functions come in two varieties: • those with return values and those without them.

• An example of function that has return value • sqrt(); • x = sqrt(6.25);

• The expression sqrt(6.25) is termed a function call, the invoked function is termed the called function • The value in the parentheses (6.25) is information that is sent to the function; it is said to be passed to the function • A value that is sent to a function this way is called an argument or parameter

• The sqrt() function calculates the answer to be 2.5 and sends that value back to the calling function; the value sent back is termed the return value of the function

Functions cont’d • Before the C++ compiler uses a function, it must know what kind of arguments the function uses and what kind of return value it has • That is, does the function return an integer? a character? a number with a decimal fraction? or something else? • If it lacks this information, the compiler won’t know how to interpret the return value • The C++ way to convey this information is to use a function prototype statement

• Please note that a C++ program should provide a prototype for each function

used in the program.

• A function prototype does for functions what a variable declaration does for variables: It tells the compiler what types are involved • double sqrt (double);

// function prototype

Functions variations • Some functions require more than one item of information • These functions use multiple arguments separated by commas • For example, the math function pow() takes two arguments and returns a value equal to the first argument raised to the power given by the second argument. It has this prototype: • double pow(double, double); // prototype of a function with two arguments • e.g. answer = pow(5.0, 8.0); // function call with a list of arguments

• Other functions take no arguments • Its prototype looks like this • int rand(void); // prototype of a function that takes no arguments • myGuess = rand(); // function call with no arguments, implicit declaration that there are no arguments

Functions variations cont’d • There are also functions that have no return value • this function sends a value to the screen instead of to the calling program, it doesn’t require a return value • This is indicated using the keyword void for the return type • e.g. void bucks(double); // prototype for function with no

return value

User-defined functions #include using namespace std; void simon (int);

// function prototype for simon()

int main() Simon says touch your toes 3 times. { Pick an integer: 512 simon(3); // call the simon () function Simon says touch your toes 512 times. cout << "Pick an integer: "; Done! int count; cin >> count; simon(count); // call it again cout << "Done!" << endl; return 0; } void simon(int n) // define the simon() function { cout << "Simon says touch your toes " << n << " times." << endl; } // void functions don't need return statements

Function form • The form of the function definition is: function-type functionName (argumentList) { statement(s); }

#include using namespace std; void simon(int); double taxes(double); int main() { }

... return 0;

void simon(int n) { ... } double taxes(double t) { ... return 2.5 * t; }

USING A USER-DEFINED FUNCTION THAT HAS A RETURN VALUE # include using namespace std; int add(int, int);

//Function prototype(declaration)

int main() { int num1, num2, sum; cout<<"Enters two numbers to add: "; cin>>num1>>num2; sum = add(num1,num2); //Function call cout<<"Sum = "<
//Function declarator

//Return statement

The add function is short and simple, yet it has a full range of functional features:

1. 2. 3. 4.

It has a header and a body It accepts an argument It returns a value It requires a prototype.

summary • Declaration statement - A declaration statement announces the name and the type of a variable used in a function. • Assignment statement - An assignment statement uses the assignment operator (=) to assign a value to a variable. • Message statement - A message statement sends a message to an object, initiating some sort of action. • Function call - A function call activates a function. When the called function terminates, the program returns to the statement in the calling function immediately following the function call.

• Function prototype - A function prototype declares the return type for a function, along with the number and type of arguments the function expects. • Return statement - A return statement sends a value from a called function back to the calling function.

THE END

Numeric Data Types, Operations and Functions.pdf

Whoops! There was a problem loading more pages. Retrying... Whoops! There was a problem previewing this document. Retrying... Download. Connect more ...

393KB Sizes 3 Downloads 195 Views

Recommend Documents

On Understanding Types, Data Abstraction, and ... - CiteSeerX
To answer this question we look at how types arise in several domains of ... Types arise informally in any domain to categorize objects according to their usage ...

/ Data Operations \
Jun 8, 2004 - nectivity (“JDBC”) service, and legacy computer systems through the J 2EE ... Server) is often used to read the data and perhaps perform ..... forms and/or the Advanced Business Application Program ming (“ABAP”) platforms ...

/ Data Operations \
Jun 8, 2004 - provide uni?ed access to enterprise information systems 117 such as ..... NET plat forms and/or the Advanced Business Application Program.

Performance Considerations of Data Types - SQL Fool
May 13, 2009 - Selecting inappropriate data types, especially on large tables with millions or billions of ... Fortune 500 company I've worked with learned this the hard way. .... This also resulted in smaller indexes, saving over 100GB of disk.

Abstract Data Types in Object-Capability Systems
Jul 9, 2016 - the ADT are encapsulated together in the ADT, and the code in the. ADT has full access to all the ..... Ada - the project: The DoD high order lan-.

Variables, Data Types, I/O and Operators
balance, etc. This data will be stored in memory locations called variables that we will name ourselves. However so that the data may be represented as aptly as possible the variables will have to be of different types to suit their data. For example

data types 7.pdf
There was a problem previewing this document. Retrying... Download. Connect more apps... Try one of the apps below to open or edit this item. data types 7.pdf.

Abstract Data Types in Object-Capability Systems
Jul 9, 2016 - the ADT are encapsulated together in the ADT, and the code in the. ADT has full access to all the instance's representations. In con- trast, pure ...

17 5.4 APPENDIX 4 DATA TYPES AND SCALING FACTORS.pdf ...
2_2_1 GERD Financed by Abroad Total domestic intramural expenditure on R&D during a given period as. a percentage of GDP. Intramural R&D expenditure is all expenditure for. R&D performed within a statistical unit or sector of the economy during a. sp

Pointwise Generalized Algebraic Data Types
Department of Computer Science. Portland State University ...... on Generic Programming [16] and the 2007 Central European Functional Programming School ...

Different types of data, data quality, available open ...
processing tools ... data: Europeana, Digital Public Library of America & The European ... Influential national libraries moving to co-operative open (linked) data.

Different types of data, data quality, available open ...
1. Have data. 2. Magic (?). 3. Something interesting shows up. 4. Profit! “Any sufficiently advanced technology is indistinguishable from magic.” - Arthur C. Clarke ... Types of data. • Structured (databases) vs unstructured (text, image, video

Data 8R Data Types and Arrays Summer 2017 1 A Test of Skill - GitHub
1 A Test of Skill ... errors) of the following lines of Python code! >>> 6 / 3 ... Luckily, they've supplied a function named bar(labelArray, dataArray) to do.

Data 8R Data Types and Arrays Summer 2017 1 A Test of Skill - GitHub
Data 8R. Data Types and Arrays. Summer 2017. Discussion 4: July 6, 2017 ... Impress the squirrels with your knowledge of data types! .... 4 Data Manipulation.

Enumerated Types
{SMALL, MEDIUM, LARGE, XL}. • {TALL, VENTI, GRANDE}. • {WINDOWS, MAC_OS, LINUX} ... Structs struct pkmn. { char* name; char* type; int hp;. }; ...

Enumerated Types
This Week. • Hexadecimal. • Enumerated Types. • Structs. • Linked Lists. • File I/O ... Data structure composed of a set of structs. • Each struct contains a piece of ...

types of queue in data structure pdf
Loading… Page 1. Whoops! There was a problem loading more pages. types of queue in data structure pdf. types of queue in data structure pdf. Open. Extract.

Traceable Data Types for Self-Adjusting Computation - University of ...
Jun 5, 2010 - ... and Standard ML [19]. To achieve automatic and correct updates under data modifica- ..... ment of values from the discrete type τ to each equivalence class. Formally, the ..... A halt action isn't subject to any repair. Any action.

Numeric Literals Strings Boolean constants Boolean ... - GitHub
iRODS Rule Language Cheat Sheet. iRODS Version 4.0.3. Author: Samuel Lampa, BILS. Numeric Literals. 1 # integer. 1.0 # double. Strings. Concatenation:.