430 likes | 446 Views
Learn about declaration statements, constants, special data types, structured variables, arithmetic operators, and more in C++ programming. Explore atomic data types, identifiers, memory addresses, and operator overloading.
E N D
C++ Basics 2 More on basic data types Declarations Simple mathematical Operators Basic programming techniques
Data Types • Atomic data types • Integral, Floating Point, Character • More advanced data types • Address • Structured
Variables • A place to store information • contents of a location in memory • has an address in RAM • uses a certain number of bytes • size depends upon the data type
Identifiers (names of things) Examples: x num1 num2 name row c237 index tax_rate Not valid: 1num bye[a] tax-rate tax rate newPos newpos (beware of this!)
Declaration Statement • A declaration statement associates anidentifier with a data object, a function,or a data type so that the programmercan refer to that item by name.
Declaration StatementSyntax: data-type variable name; • Examples: int my_age; int count; float deposit; float amount; float totalpay; double balance; char answer2;
Note , Multiple DeclarationsSyntax:data-type var1, var2, var3; Examples: int my_age; int count; float deposit, amount, totalpay; double balance; char answer2 ;
can change can NOT change Constants Literaltyped directly into the program as needed ex. y = 23.4 pi = 3.1416 Symbolic (Named)similar to a variable, but cannot be changed after it is initialized ex. const int class_size = 87; const double PI = 3.1416;
Constants • Syntax • const type VAR = value; • const int Imax = 1000; • const char BLANK = ‘ ‘;
declarations constants Sample Program #include<iostream> using namespace std; void main(void) { float t; float length; const float g = 9.8; const float PI = 3.1416; t = 1.0; length = g*(t/(2*PI))*(t/(2*PI)); cout << “length of pendulum = “<< length;}
Special Data Types Address Data • Recall all data stored in RAM at a specific address. • We can refer to this address using a name e.g. length rather than by referring to the actual address. • We can however access addresses in memory using special variables. • Pointers (used later in the course for dynamic memory allocation) • References (used later in the semester for modular programming with functions)
Special data types – structured data • We can create special data types to represent things in the world. • For example we may want to represent a student record, comprising of • Name, ID, grade • We want to be able to refer to an individual student and know that they have associated attributes or fields. • We can do this using Structured data types array struct union class
Operators • An operator is a symbol that causesthecompiler to take an action. • Operators operate on data • Different data types allow different operations • E.g. multiplication division addition and subtraction are legal on numerical data; they are not legitimate operations for characters *
Arithmetic Operators • addition + • subtraction ¾ • multiplication * • division / • modulus %
Arithmetic Operators Syntaxoperand operator operand Example7 + 15 34 — 189 92 * 31 345 / 6.02 86 % 3 *
12/3 14/3 4 3 12 12 0 4 3 14 12 2 12%3 14%3 What is the Modulus operator • The modulus operator yields the remainder of integer division. * *
Modulus Examples. 18 % 4 is 2 13 % 4 is 117 % 3 is 2 35 % 47 is 3524 % 6 is 0 24 % 4 is 0 4 % 18 is 4 0 % 7 is 0 12 % 2.5 error 6.0 % 6 error * * *
type int / type int 9 / 5 operator performs int division type double / type double 9.0 / 5.0 operator performs double division A Glimpse of Operator Overloading Operator overloadUsing the same symbol for more than one operation. *
Mixed-Mode Expressions • Operator overload. Same operator will behave differently depending upon the operands. • Operands of the same type give results of that type. E.g. int / int -> integer division • In mixed-mode, floating point takes precedence. • e.g. 6 / 10.0 is int / float therefore whole thing treated as float. The 6 is converted into a float.
Problems with Integer Division int a, b; a = 8; b = 3; cout << “The result is “ << a / b << endl; 8 / 3 is 2 and not 2.6667The result must be an integer. The result is truncated to 2.
Problems with Integer Division int a, b; a = 8; b = 3; cout << “The result is “ << b / a << endl; 3 / 8 is 0 and not 0.375The result must be an integer. The result is truncated to 0.
Basic rules on order of operations P then M DM then A S from left to right 8 + 3 * 4 is ? Show associativity with round brackets to clarify. ( 8 + 3 ) * 4 is 44 8 + ( 3 * 4 ) is 20
Order of Operations Expression Value 10 / 2 * 3 10 % 3 - 4 / 2 5.0 * 2.0 / 4.0 * 2.0 5.0 * 2.0 / (4.0 * 2.0) 5.0 + 2.0 / (4.0 * 2.0) 15 -1 5.0 1.25 5.25
10 % 3 - 4 / 2 10 / 2 * 3 1 2 2 3 3 1 2 3 1 1 5.0 * 2.0 / 4.0 * 2.0 5 * 2 / (4.0 * 2.0) 2 Evaluation Trees * *
Beware! C++ requires the asterisk to indicate multiplication. valid invalid 5*(8+3) 5(8+3) (x-y)*(x+y) (x-y)(x+y)
Assignment Operator = • Subtle difference to the meaning in mathematics. In mathematics the meaning is like balances with. • So simple equations like x = 5 in maths causes you to INFER that x is 5, or 2x = x + 3 causes you to infer that x = 3. • The assignment operator (=)causes the operand on the left to take on the value to the right side of the statement. • The compiler is instructed to store the value on the right in the address associated with the variable on the left *
Assignments • This operator assigns from right to left.valid invalidx = 5 5 = xpicard = 6.02 vg_grd = 87.5
Assignment Statement Syntax: variable = expression; • Examples:quiz1score = 14;balance = balance + deposit;Do NOT use the word equals here. Use “assigned to” or “takes the value of”.
Assignment Statement in declarations • Examples:int myage = 33;int width = 10, length;double ex1 = 85, ex2 = 73, ex3 = 82;char ans, key = ‘Q’, ch; • Why do this? • Remember that in order to use a variable we must declare it first. • We must also make sure that a variable has a sensible value stored before it is used. • Programmers often like to put in “default” sensible values when they declare variables
Recall Storage Locations int deposit, balance;deposit = 234;balance = 1000; 1. Deposit and balance are given memory addresses. 2. 234 is put into the memory address for deposit. 3. 1000 is put into the memory address for balance.
4 bytes of storage 4 bytes of storage Storage Locationsint deposit, balance; deposit balance ?? ?? Rubbish *
Storage Locationsdeposit = 234;balance = 1000; deposit balance 2 3 4 1 0 0 0
Storage Locationsint deposit, balance;deposit = 234;balance = 1000;balance = balance + deposit; Add the contents of the deposit address to the contents of the balance address. Store the result at the balance address.
Storage Locationsbalance = balance + deposit; deposit balance 2 3 4 1 2 3 4 9 8 7 6 5 The addition “balance + deposit” is done somewhere else, the result of the calculations is copied into the address associated with balance
Basic Programming Techniques 1 Accumulation • Adding up lists of numbers, doing running totals. • We need a variable to store the running total e.g. sum • We need to add to whatever has been accumulated in sum. • We get lines like sum = sum + new_value;
Example • Suppose we want to accumulate numbers 96, 70, 85 and 60. • Need an accumulator variable sum say. • Need to initialise it • sum = 0; //sum now holds 0 • Then accumulate the numbers. • sum = sum + 96; //sum now holds 96 • sum = sum + 70; //sum now holds 166 • sum = sum + 85; //sum now holds 251 • sum = sum + 60; //sum now holds 311
Basic Programming Techniques 2Counting • Very similar to accumulating. • Need a counter variable. • Normally initialised to 0; • Normally add one on each time.E.g. • count = 0; • count = count + 1; • Can count in steps of more than one, e.g. • count = count + 2;
Accumulating/Counting Down • It is also common for counting and accumulating to be done in reverse. • Start an accumulator not with 0 • Keep subtracting numbers • Sum = 100; // sum holds 0 • Sum = sum – 10; // sum now holds 90 • Sum = sum – 10; // sum now holds 80 • Count downs • start = 10; //start = 10 • start = start – 1; //start = 9 • Etc.
Increment/Decrement operators • Counting by adding 1 (incrementing) so common C++ has a special operator for adding 1; • count++; // same as count = count + 1; • Note there is a decrement operator for subtracting 1 • count--; // same as count = count – 1;
Example: enter a sequence of numbers from the keyboard and find the average. Defining diagram
Test data • 10 numbers 1-10 should add up to 55 therefore average should be 5.5
PDL Design • Initialise accumulator (sum) • Initialise counter (count) • do • prompt for a number • enter a number • increment counter • accumulate number • While we have more data ?? • How do we do this in C++ • Use sentinel or prompt for more data • Calculate average = sum/count • Display average