Top Banner
course «Programming in C++» Introduction To Programming for Engineering & Science for students of DonNTU Prykhodko Tatyana Alexandrovna docent of CST, CE department DonNTU 2014
46

Course «Programming in C++» Introduction To Programming for Engineering & Science for students of DonNTU Prykhodko Tatyana Alexandrovna docent of CST,

Dec 28, 2015

Download

Documents

Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: Course «Programming in C++» Introduction To Programming for Engineering & Science for students of DonNTU Prykhodko Tatyana Alexandrovna docent of CST,

course«Programming in C++»

IntroductionTo

Programming for Engineering & Science

for students of DonNTU•Prykhodko Tatyana Alexandrovna

docent of CST, CE departmentDonNTU 2014

Page 2: Course «Programming in C++» Introduction To Programming for Engineering & Science for students of DonNTU Prykhodko Tatyana Alexandrovna docent of CST,

Lecture 2

C Data Typesand operators

Page 3: Course «Programming in C++» Introduction To Programming for Engineering & Science for students of DonNTU Prykhodko Tatyana Alexandrovna docent of CST,

Types of variables

• We must declare the type of every variable we use in C.

• Every variable has a type (e.g. int) and a name.

• We already saw int, double and float.

• This prevents some bugs caused by spelling errors (misspelling variable names).

• Declarations of types should always be placed together at the top of main or a function (see later).

• Other types are char, signed, unsigned, long, short and const.

3

Page 4: Course «Programming in C++» Introduction To Programming for Engineering & Science for students of DonNTU Prykhodko Tatyana Alexandrovna docent of CST,

Type Declaration

#include <stdio.h>

int main(void)

{

int a, b, c;

float x = 0.0f, y = 3.3f, z = -7.7f;

printf( “Input two integers: ” );

scanf( “%d%d”, &b, &c );

a = b + c;

x = y + z;

return 0;

}

DeclarationDeclarationDeclaration with initialization

always initialize!!!

Declaration with initialization always initialize!!!

Function callsFunction calls

Assignment statements

Assignment statements

4

Page 5: Course «Programming in C++» Introduction To Programming for Engineering & Science for students of DonNTU Prykhodko Tatyana Alexandrovna docent of CST,

Data Types• C programming language which has the ability to divide

the data into different types.

• The ‘type’ of a variable determines what kind of values it

may take on.

• Datatype of an object determines the set of value it can

have & what operations can be performed on it.

5

Data typeData type

Simple Data typeSimple Data type User Defined Data typeUser Defined Data type

StringString EnumEnum StructureStructure UnionUnionVoidVoidRealRealintegerinteger CharChar

Structured Data typeStructured Data type

ArrayArray5

Page 6: Course «Programming in C++» Introduction To Programming for Engineering & Science for students of DonNTU Prykhodko Tatyana Alexandrovna docent of CST,

• void (type) is a generic type. We will use this a lot. Much more later.

• int – for integer (a whole number).

• char – for character –a single character; always enclosed in single quotes. Is NEVER more than a single character. The internal representation of characters is in ASCII on most

computers.ASCII is a character code set; a mechanism for internal

representation.

• float –a number with a fractional part.

6

Page 7: Course «Programming in C++» Introduction To Programming for Engineering & Science for students of DonNTU Prykhodko Tatyana Alexandrovna docent of CST,

Standard Data types

Only really four basic types:char

int (short, long, long long, unsigned)

float

double

Size of these types on

CLEAR machines:

Sizes of these types

vary from one machine

to another!

Type Size (bytes)

char 1

int 4

short 2

long 8

long long 8

float 4

double 8

7

Page 8: Course «Programming in C++» Introduction To Programming for Engineering & Science for students of DonNTU Prykhodko Tatyana Alexandrovna docent of CST,

• Integral Types:Integral Types: • char signed char unsigned char• short int long• unsigned short unsigned unsigned long

• Floating Types:Floating Types:• float double long double

• Arithmetic Types:Arithmetic Types: • integral types • floating types

Very important: the default type for floating constants is a double! If you say 16.4 this will be represented internally as a double precision number; if you wish a smaller version, then write 16.4f or 16.4F.

• Numeric constants without a decimal point default to int.

Functionality Groups

8

Page 9: Course «Programming in C++» Introduction To Programming for Engineering & Science for students of DonNTU Prykhodko Tatyana Alexandrovna docent of CST,

Sizes and ranges are machine dependent; vary from computer to computer

• short (and short int)- two bytes; 16 bits; range: -32768 to 32767 or unsigned (uses all 16 bits for magnitude) – doubles range: max value is 65535.

• int - some machines 16 bits; both signed and unsigned; -32768 to 32767 or 65535most machines use ints of 4 bytes; 32 bits; signed or unsigned; Range: -2,147,483,648 to 2,147,483,647.

• long (and long int) - most use 48 or 64 bits for very large integers….

• To find out the size of any data type on a computer, use the built-in function, sizeof(argument).

e.g. sizeof (short int); It is true, according to ANSI standards: sizeof (short int) <= size of (int) <= sizeof (long int)

Also have defined constants: INT_MIN and INT_MAX. Will use these later.

Standard Data types(extra)

9

Page 10: Course «Programming in C++» Introduction To Programming for Engineering & Science for students of DonNTU Prykhodko Tatyana Alexandrovna docent of CST,

• Numbers with fractional parts: 4.2, 0.0628, 7.0, plus scientific notation (3.5e15)The internal representation of a float is entirely different than an int. Thus 4 does not equal 4.0!

• Different sizes: float (4 bytes; 32 bits); double (8 bytes, 64 bits; long double (10 bytes, 80 bits)

• Here again, can do sizeof(double)More specifically: int s;

s = sizeof(double); /* s, an int, shorter than double */ printf (“Size of a double is %d”, s);

• Floats are always signed internally.

Standard Data types(extra)

10

Page 11: Course «Programming in C++» Introduction To Programming for Engineering & Science for students of DonNTU Prykhodko Tatyana Alexandrovna docent of CST,

More types: Signed/unsigned, long, short, const (extra)

• unsigned means that an int value can only be positive. signed means that it can be positive or negative.

Note: a signed int and an unsigned int both require the same size memory block; however, an unsigned type can represent a value of a magnitude larger than a signed type, since the signed type must use one of its binary digits to represent the sign of the number.

• To determine whether a numeric conversion will work properly or not, the following order applies:high: long double

doublefloatlong intint

low: short int

Automatic conversion alwaysmoves from a more narrow type to a wider type.

11

Page 12: Course «Programming in C++» Introduction To Programming for Engineering & Science for students of DonNTU Prykhodko Tatyana Alexandrovna docent of CST,

Constants• A constant is a quantity which does not change its value

during execution of the program.

• The syntax for constant declaration is:

const <data type> <var_name> = <value>;

12

ConstantConstant

Primary ConstantPrimary Constant Secondary ConstantSecondary Constant

StringString arrayarray pointerpointer structurestructurecharactercharacterfloatfloatintegerinteger

Page 13: Course «Programming in C++» Introduction To Programming for Engineering & Science for students of DonNTU Prykhodko Tatyana Alexandrovna docent of CST,

Constants• Constants may be defined using the preprocessor directive, #define.

#define - used to define a constant. Wherever the constant appears in your source file, the preprocessor replaces it by its value.

Example:#define pi 3.1415#define idNum 12345

• So, for instance, every "pi" in your source code will be replace by 3.1415. The compiler will only see the value 3.1415 in your code, not "pi".

• The problem with this technique is that the replacement is done lexically, without any type checking, without any bound checking and without any scope checking.

• Every "pi" is just replaced by its value. The technique is outdated, exists to support legacy code and should be avoided.

13

Page 14: Course «Programming in C++» Introduction To Programming for Engineering & Science for students of DonNTU Prykhodko Tatyana Alexandrovna docent of CST,

Constants (continued)• In the earlier slide we saw that C declarations take the format:

[typeQualifiers] typeSpecifier variable;

• The keywords const and volatile (to be discussed later) can be applied to any declaration as a type qualifier.

• const - if used declares an identifier whose value may NOT change during the life of the program.

• A few representative examples:

• Note: if used, the variable being declared MUST be initialized to a beginning value (with an “=“ operator).

const char failingGrade = ‘f’ ;const unsigned long int = 23456;const float pi = 3.1415;const int idNum = 12345;

14

Page 15: Course «Programming in C++» Introduction To Programming for Engineering & Science for students of DonNTU Prykhodko Tatyana Alexandrovna docent of CST,

Constants (continued)

• Enumerations - the third technique for defining constants is called enumeration. An enumeration defines a new type and limits the values of this type to a programmer defined set. Note: may not be supported by all C compilers.

Example:

enum COLOR { RED, BLUE, GREEN};enum SHAPE {SQUARE, RECTANGLE, TRIANGLE, CIRCLE, ELLIPSE}

each enumerated constant has an integer value. Unless specified, the first constant has a value of zero. The values increase by one for each additional constant in the enumeration. So, RED equals 0, BLUE equals 1, etc. SQUARE equals 0, RECTANGLE equals 1, TRIANGLE equals 2 and so forth. The values of each constant can also be specified.

Example:

enum SHAPE {SQUARE=5,RECTANGLE,TRIANGLE=17,CIRCLE};Here, SQUARE equals 5, RECTANGLE equals 6, TRIANGLE equals 17, CIRCLE

equals 18). 15

Page 16: Course «Programming in C++» Introduction To Programming for Engineering & Science for students of DonNTU Prykhodko Tatyana Alexandrovna docent of CST,

Constants (continued)• The advantage of enumerations is that if a variable is declared

to be the type of an enumeration, it has a type and its values are limited and checked during compiling.

• Consider the following program:{  enum color {RED, GREEN, BLUE};     

color myColor = RED; 

. . .    

if (myColor == RED) {  

/* some code */     

}     

if (myColor == BLUE) {          

/* some more code */      

}     

if (myColor == GREEN) {          

/* still some more code */      

}     . . .

}

Note: myColor can only be assigned one of the enumeration literals (RED, GREEN, BLUE).

The assignment statement:

myColor = 0; is NOT the same.

16

Page 17: Course «Programming in C++» Introduction To Programming for Engineering & Science for students of DonNTU Prykhodko Tatyana Alexandrovna docent of CST,

Variable• Variables are memory locations in computer memory to hold

different types of data.

• It may vary during the program execution.

• The syntax of variable declaration is:

<datatype> <variable name>;

- here ‘datatype’ is the type value stored in variable ‘varname’

17

short int small_no; unsigned int number;long double precise_number;short float not_so_precise;

Page 18: Course «Programming in C++» Introduction To Programming for Engineering & Science for students of DonNTU Prykhodko Tatyana Alexandrovna docent of CST,

Variable Declarationsmust be declared prior to using a variable!

Values shown in memory are NOT what is actually there.These are only representative values.Recognize that EVERYTHING internally is in binary (0’s & 1’s).

18

Page 19: Course «Programming in C++» Introduction To Programming for Engineering & Science for students of DonNTU Prykhodko Tatyana Alexandrovna docent of CST,

Variable Declarations - may initialize during declaration, if desired.

int x=4; float a=4.15; double b=4.15; char grade; int p, d, q; /* not the best stylistically */ int c=4, d, e, f=16; /* not the best stylistically */

Better style: only declare one variable (and its initial value) per line.A better technique, all in all, is to declare variables in a declarations section of your program; assign values to variables via assignment statements.

Note: when a variable is defined, it is NOT initialized. It is assigned to a memory location and will likely contain garbage.

19

Page 20: Course «Programming in C++» Introduction To Programming for Engineering & Science for students of DonNTU Prykhodko Tatyana Alexandrovna docent of CST,

Expressions• An expression is a sequence of operands and operators that reduces to a

single value. e.g. 2 + 5 • Operator: a language-specific syntactical token that requires actions be

taken ( +, -, *, /, % ) are most familiar

• All programming languages have these

• Operand: receive the operator’s actions. – An operator may have one or more operands.– Can combine operators and operands into very complex expressions.– Still - must be able to be evaluated and reduced to a single value.

• Above: 2 and 5 are operands; + is the binary operator, addition(binary in this sense because it requires two operands)

In C there are unary, binary, and ternary operators (operators requiring one, two, or three operands respectively.

20

Page 21: Course «Programming in C++» Introduction To Programming for Engineering & Science for students of DonNTU Prykhodko Tatyana Alexandrovna docent of CST,

1.Arithmetic Operators

– Modulus returns remainder of division between two integers

– Example 5%2 returns a value of 1

21

Page 22: Course «Programming in C++» Introduction To Programming for Engineering & Science for students of DonNTU Prykhodko Tatyana Alexandrovna docent of CST,

2.Relational OperatorRelational operators are used to compare their first operand to

second operand to test the validity of their relationship.

22

Operators Meaning Example

< Less than x < 5

> Greater than x > 2

<= Less than equal to x <= 4

>= Greater than equal to x >= 4

== Equal to x == 4

!= Not equal to x != 5

Page 23: Course «Programming in C++» Introduction To Programming for Engineering & Science for students of DonNTU Prykhodko Tatyana Alexandrovna docent of CST,

3. Logical OperatorIt is used to connect two or more condition.

Operators Meaning

&& Logical AND

|| Logically OR

! Logically NOT

Operators Meaning

& Bitwise AND

| Bitwise OR

^ Bitwise XOR

>> Bitwise right shift

<< Bitwise left shift

- One’s component

4. Bitwise Operator:

Page 24: Course «Programming in C++» Introduction To Programming for Engineering & Science for students of DonNTU Prykhodko Tatyana Alexandrovna docent of CST,

It is used to carry out conditional operations.

• It can be used in place of if – else.

• Syntax is:

expr1 ? expr2 : expr3

• E.g. x = (y>12) ? 2 : 400

• If y>12 holds true, the value 2 is assigned to variable x.

else value 400 is assigned to variable x.

24

Condition

5. Conditional Operator (?):

Page 25: Course «Programming in C++» Introduction To Programming for Engineering & Science for students of DonNTU Prykhodko Tatyana Alexandrovna docent of CST,

It is used to assign the result of an expression to a variable.

• The most commonly used assignment operator is “=”

• Syntax is: identifier = expression

• E.g. x = 5, means the value 5 is assigned to variable ‘x’.

• x = y, in this expression the value of ‘y’ is assigned to variable ‘x’ i.e. the value of variable on RHS is assigned to a variable on LHS.

25

6. Assignment Operator:

Page 26: Course «Programming in C++» Introduction To Programming for Engineering & Science for students of DonNTU Prykhodko Tatyana Alexandrovna docent of CST,

Statements

• A statement causes the computer to carry out some action.

• There are three different classes of statements:

1. Expression Statement: It consist of an expression followed by a semicolon (;)

e.g. a = 5; /*assignment type statement*/

c = a+b; /*assignment type statement*/

++i; /*increment type statement*/

printf(“Area= %f”, area); /*function to be evaluated*/

; /*Does nothing. Only a semicolon*/

26

Page 27: Course «Programming in C++» Introduction To Programming for Engineering & Science for students of DonNTU Prykhodko Tatyana Alexandrovna docent of CST,

2. Compound Statement: It consist of several individual

statements in it enclosed within a pair of braces { }.

• It provides a capability for embedding statements within another

statement.

e.g. { pi = 3.142;

circumference = 2 * pi *radius;

area = pi *radius *radius; }

• Above compound statement consist of three assignment type

expression statement, though it is considered in a single entity

within the program in which it appears.

27

Statements

Page 28: Course «Programming in C++» Introduction To Programming for Engineering & Science for students of DonNTU Prykhodko Tatyana Alexandrovna docent of CST,

C: An Operator Rich Language

• ALL operators in C have ‘precedence.’• 1: functions, ( ), postfix increment; postfix decrement and

others.• 2: prefix increment ++ and prefix decrement -- ; sizeof(), unary +, unary - and several others …• 3. Binary arithmetic operators: multiplication, division,

modulus• 4. Binary arithmetic operators: addition, subtraction• 5. Some operators have VERY low operator precedence:

Assignment operators and variations, such as= += -= *= /= %= But they STILL have precedence!

Higher the precedence, the earlier it is evaluated in an expression.There are about 15 different precedence levels. We will learn them

by groups (see next slide)

28

Page 29: Course «Programming in C++» Introduction To Programming for Engineering & Science for students of DonNTU Prykhodko Tatyana Alexandrovna docent of CST,

Precedence of OperatorsOperators Associativity

() [] . -> ++ (postfix) -- (postfix) Left to right

++ (prefix) -- (prefix) ! ~ (one’s complement) sizeof

(typeCast)

+ (unary) - (unary) & (address) * (deference)

Right to left

* / % (modulus) Left to right

+ - Left to right

<< (shift left) >> (shift right) Left to right

< <= > >= Left to right

== (equality != (inequality) Left to right

& (bitwise and) Left to right

^ (bitwise exclusive or) Left to right

| (bitwise inclusive or) Left to right

&& (logical and) Left to right

|| (logical or) Left to right

?: Right to left

= += -= *= /= %= >>= <<= &= ^= |= Right to left

, (comma operator, used in for statement) Left to right

high

low

Page 30: Course «Programming in C++» Introduction To Programming for Engineering & Science for students of DonNTU Prykhodko Tatyana Alexandrovna docent of CST,

Operator Precedence

• All we are saying is that operators having a higher precedence are evaluated before those having lower precedence

• How would you evaluate: 5 * 4 + 3? Could be 35 or 23!

• In C and most languages, the multiplication takes place first and then the addition.

• Most of these operations do not have ‘side effects.’ A few do.

• This means that they do things besides the obvious!• The prefix and postfix addition and subtraction DO have

side effects…We will cover in a minute.

30

Page 31: Course «Programming in C++» Introduction To Programming for Engineering & Science for students of DonNTU Prykhodko Tatyana Alexandrovna docent of CST,

Priority of Operators

1 Parentheses Inner most first2 Unary operators Right to left

(+ -)

3 Binary operators Left to right(* / %)

4 Binary operators Left to right(+ -)

31

Page 32: Course «Programming in C++» Introduction To Programming for Engineering & Science for students of DonNTU Prykhodko Tatyana Alexandrovna docent of CST,

a 14 6+(a*b)

a++

+a -4 a + b

x+y ? 4 : 5

x = a + b;

Useful in the ‘C’

for statement

32

Operators

Page 33: Course «Programming in C++» Introduction To Programming for Engineering & Science for students of DonNTU Prykhodko Tatyana Alexandrovna docent of CST,

33

Page 34: Course «Programming in C++» Introduction To Programming for Engineering & Science for students of DonNTU Prykhodko Tatyana Alexandrovna docent of CST,

(expression can be quite long and complex)

34

Page 35: Course «Programming in C++» Introduction To Programming for Engineering & Science for students of DonNTU Prykhodko Tatyana Alexandrovna docent of CST,

Consider an example…No side effects

• x = a + b; (This is an assignment expression)• Assume x = 10; a = 4 and b = 5.• In the assignment statement: x=a+b;

the addition takes place first, and the value of

9 is assigned to x, the target variable.

The original values of a and b remain unchanged.

35

Page 36: Course «Programming in C++» Introduction To Programming for Engineering & Science for students of DonNTU Prykhodko Tatyana Alexandrovna docent of CST,

Consider a = 4 and x = 10 prior to the assignment. So, what happens??

Now let’s look at the postfix (unary) operators…These HAVE side effects.

AFTER execution, x=4 and a=5!!!Marked contrast to almost all other expressions!Side effect is that a is incremented by 1!

36

Page 37: Course «Programming in C++» Introduction To Programming for Engineering & Science for students of DonNTU Prykhodko Tatyana Alexandrovna docent of CST,

Prefix (unary) operator.Assume x = 10 and a = 4

Prefix operator has higher precedence than assignment.After execution: x has a value of 5; a has value of 5.

Side effect: value of a is incremented! 37

Page 38: Course «Programming in C++» Introduction To Programming for Engineering & Science for students of DonNTU Prykhodko Tatyana Alexandrovna docent of CST,

How about by itself?

• Using a++ or a-- by themselves as in:

other statements….

a++;

a--;

other statements….

These are valid C statements and are equivalent to:

a = a+1 and a = a-1.

Regardless, a is incremented and then decremented by 1.

38

Page 39: Course «Programming in C++» Introduction To Programming for Engineering & Science for students of DonNTU Prykhodko Tatyana Alexandrovna docent of CST,

Shortcut OperatorsExample Calculation Shortcut Equivalent

sum = sum + 9; sum += 9;

diff = diff - 2; diff -= 2;

prod = prod * 3; prod *= 3;

quot = quot / 16; quot /= 16;

rem = rem % 12; rem %= 12;

39

Page 40: Course «Programming in C++» Introduction To Programming for Engineering & Science for students of DonNTU Prykhodko Tatyana Alexandrovna docent of CST,

Most associativity is to the left. That is, most operators associate left.

40

Page 41: Course «Programming in C++» Introduction To Programming for Engineering & Science for students of DonNTU Prykhodko Tatyana Alexandrovna docent of CST,

Integer Division

• Division between two integers results in an integer. • The result is truncated, not rounded• Example:

5/3 is equal to 13/6 is equal to 0

• Division between any two expressions of the same type (e.g., double, long, etc.) results in a value of the same type.

41

Page 42: Course «Programming in C++» Introduction To Programming for Engineering & Science for students of DonNTU Prykhodko Tatyana Alexandrovna docent of CST,

Example float x = 2.0f;

int y = 2; /* what results? */

x = 4 * 6; x = ??

y = y * x * 4.0; y = ??

y = 6.28*10**23 + 4 + x - y; y = ??

42

Page 43: Course «Programming in C++» Introduction To Programming for Engineering & Science for students of DonNTU Prykhodko Tatyana Alexandrovna docent of CST,

But in evaluating the expression on the right, or in assigning the value on the right to the operand on the left, it is very possible that promotion will occur.

Automatic conversions are called ‘implicit type conversions.’

Mixed Type ExpressionsCalled ‘promotion/coercion and involves type conversion

In any assignment, the ultimate value on the right must be converted, if necessary, to the type on the left.

43

Page 44: Course «Programming in C++» Introduction To Programming for Engineering & Science for students of DonNTU Prykhodko Tatyana Alexandrovna docent of CST,

Explicit Conversion (cast operator)

(float) a cast operator requires a unary expression.

(float) (x + y) evaluates x plus y and then floats the result.

(float) x + y will float x first and then try to add it to y. y may need to be coerced to float if

it is a more narrow type than float.

average = totalScores / (float) numScores; What happens??

(float) (a / 10) ?? If a = 3 initially?

44

Page 45: Course «Programming in C++» Introduction To Programming for Engineering & Science for students of DonNTU Prykhodko Tatyana Alexandrovna docent of CST,

Underflow & Overflow• Overflow and underflow occur when the value of a variable exceeds the maximum or

minimum value that can be stored in the variable. How some systems might respond - maybe not yours - check out the rules of your system!!

Example 1:

Suppose we execute the following statements:

float a = 1.0e+20;float b = 2.0e+30;float c;c = a * b;

Say the range of values for variables of type float is 3.4e-38 to 3.4e+38. The values assigned to a & b are within this range. The result of the multiplication is not!

This is not detected during compilation, but rather when the last statement is executed. The program terminates and displays -

floating point error: overflow Abnormal terminationgcc will result in “c = inf” being printed.

Example 2:

Suppose we execute the following statements:

float a = 1.0e-30;float b = 2.0e+20;float c;c = a / b;

The result of the division is 5.0e-51, which is smaller than the minimum value that can be stored in a variable of type float.

This is not detected during compilation, but rather occurs when the last statement is executed.

In this case no error message is displayed. Instead, the result is set equal to zero, and so the variable c will be assigned the value 0.

gcc will result in “c = 0.000000” being printed

45

Page 46: Course «Programming in C++» Introduction To Programming for Engineering & Science for students of DonNTU Prykhodko Tatyana Alexandrovna docent of CST,

Underflow & OverflowSome of the more common reasons for overflow and underflow are:

• Variables that have not been initialized,• Variables that have been initialized to an incorrect value,• A wrong arithmetic operation is specified,• A denominator having a zero value is used during a division,• When a program that worked correctly on one system is run on another system

(range of values may differ from system to system),• Usually occur when you are working with very large or very small numbers.

How to correct??

In many cases you can switch to a data type that has a wider range, for example, switch from a float to a double or a long double.

46