1 / 43

C++ Basics 2

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

Download Presentation

C++ Basics 2

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. C++ Basics 2 More on basic data types Declarations Simple mathematical Operators Basic programming techniques

  2. Data Types • Atomic data types • Integral, Floating Point, Character • More advanced data types • Address • Structured

  3. 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

  4. 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!)

  5. 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.

  6. Declaration StatementSyntax: data-type variable name; • Examples: int my_age; int count; float deposit; float amount; float totalpay; double balance; char answer2;

  7. Note , Multiple DeclarationsSyntax:data-type var1, var2, var3; Examples: int my_age; int count; float deposit, amount, totalpay; double balance; char answer2 ;

  8. 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;

  9. Constants • Syntax • const type VAR = value; • const int Imax = 1000; • const char BLANK = ‘ ‘;

  10. 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;}

  11. 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)

  12. 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

  13. 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 *

  14. Arithmetic Operators • addition + • subtraction ¾ • multiplication * • division / • modulus %

  15. Arithmetic Operators Syntaxoperand operator operand Example7 + 15 34 — 189 92 * 31 345 / 6.02 86 % 3 *

  16. 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. * *

  17. 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 * * *

  18. 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. *

  19. 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.

  20. 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.

  21. 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.

  22. 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

  23. 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

  24. 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 * *

  25. Beware! C++ requires the asterisk to indicate multiplication. valid invalid 5*(8+3) 5(8+3) (x-y)*(x+y) (x-y)(x+y)

  26. 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 *

  27. Assignments • This operator assigns from right to left.valid invalidx = 5 5 = xpicard = 6.02 vg_grd = 87.5

  28. 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”.

  29. 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

  30. 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.

  31. 4 bytes of storage 4 bytes of storage Storage Locationsint deposit, balance; deposit balance ?? ?? Rubbish *

  32. Storage Locationsdeposit = 234;balance = 1000; deposit balance 2 3 4 1 0 0 0

  33. 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.

  34. 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

  35. 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;

  36. 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

  37. 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;

  38. 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.

  39. 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;

  40. Example: enter a sequence of numbers from the keyboard and find the average. Defining diagram

  41. Test data • 10 numbers 1-10 should add up to 55 therefore average should be 5.5

  42. 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

  43. Program (see demo)

More Related