1 / 54

Basics

Basics. A First Program Variables, Objects, and Types C++ Built-In Types and Operations Input and Output Operator Precedence and Associativity if Statements Loops Declarations Arrays. Pointers Pointers and Arrays const Pointers and Pointers to const Objects Runtime Array Size

aiden
Download Presentation

Basics

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. Basics • A First Program • Variables, Objects, and Types • C++ Built-In Types and Operations • Input and Output • Operator Precedence and Associativity • if Statements • Loops • Declarations • Arrays

  2. ... • Pointers • Pointers and Arrays • const Pointers and Pointers to const Objects • Runtime Array Size • Character Strings • References • Functions

  3. Statements, Functions, {}, ;, Comments, ... • void f() { • int a = 1, b = 2, c = 3; • a = b + c; // This part is a comment. • /* This is a comment. */ • } C Programmers: Prefer C++ style comments: //... instead of /* ... */ if (a > b) { /* int t = a; /* swap a and b */ a = b; b = t; */ } if (a > b) { // int t = a; // swap a and b // a = b; // b = t; }

  4. The most trivial C++ programm • int main() { • return 0; • } Every C++ program must contain exactly one function named main. It should return an integer value.

  5. First program with I/O • #include <iostream> • int main() { • // Read and print three floating point numbers • double a, b, c; • std::cin >> a >> b >> c; • std::cout << a << ", " << b << ", " << c << std::endl; • return 0; • } Include iostream in any file that contains C++ input or output operations. C Programmers: Use iostream instead of stdio.h.

  6. First program with I/O: new/old C++ • #include <iostream> • int main() { • // ... • std::cin >> a >> b >> c; • std::cout << a << ", " << b << ", " << c << std::endl; • // ... • } • #include <iostream> • using namespace std; • int main() { • //... • cin >> a >> b >> c; • #include <iostream> • using std::cin; • using std::cout; • using std::endl; • int main() { • //... • cin >> a >> b >> c; • #include <iostream.h> • int main() { • //... • cin >> a >> b >> c;

  7. x- and y-intercepts of ax + by + c = 0 • #include <iostream.h> • int main() { • // Read the coefficients of a line equation in the form • // ax+by+c = 0 • // then print the line's x- and y-intercepts. • // Read the equation coefficients. • float a, b, c; • cin >> a >> b >> c; • // Print the equation coefficients. • cout << "Coefficients: " << a << ", " << b << ", " << c << endl;

  8. // Compute and print the x-intercept. • cout << "x-intercept: "; • if (a != 0) { • cout << -c / a << ", "; • } • else { • cout << "none, "; • } • // Compute and print the y-intercept. • cout << "y-intercept: "; • if (b != 0) { • cout << -c / b << endl; • } • else { • cout << "none" << endl; • } • return 0; • }

  9. Basics • A First Program • Variables, Objects, and Types • C++ Built-In Types and Operations • Input and Output • Operator Precedence and Associativity • if Statements • Loops • Declarations • Arrays

  10. Microscopic Viewpoint to a Program A program specifies a procedure for altering the values of objects, using symbolic references to the objects called variables. • An object is an area of the computer´s memory that has a value (a particular bit pattern) stored in it. • The type of an object specifies how the bits are stored as the object´s value are to be manipulated. • A variable is an association between a name and an object; the type of a variable specifies the type of objects that the variable can be associated with.

  11. int 3 float 12.1 float 12.1 int 5 float 10.0 int i float x float x int i : : : : float x float a float r int j : : : : float or int Variables, References, Unions • int i = 3; • float x = 10.0; • i = 5; • x = 12.1; • float& a = x; • union { • float r; • int j; • } Avoid union types.

  12. Numeric Types and Typical Sizes • C++ Type Size (bytes) • char 1 • short int 2 signed • int 2 or 4 unsigned • long int 4 or 8 • float 4 • double 8 • long double 16 • 1 = sizeof(char)  sizeof(short)  sizeof(int)  sizeof(long) • sizeof(float)  sizeof(double)  sizeof (long double) • Check the header files: <limits.h> <float.h> <limits> .. Do not use unsigned integers. Use int and double.

  13. Constants • 1234 decimal integer • 0643 octal integer • 0x37cd hex integer • 8.4e-2, 93.2 double floating-point • Suffixes for Constants • no suffix, decimal int, long int, unsigned long int • no suffix, octal or hex int, unsigned int, long int, unsigned long int • l or L long int, unsigned long int • u or U unsigned int, unsigned long int • ul or UL unsigned long int • no suffix, floating-point double • f or F float • l or L long double

  14. x ++ Postincrement ++ x Preincrement x -- Postdecrement -- x Predecrement + x Unary plus - x Unary minus x * y Multiply x / y Divide x % y Modulus x + y Add x - y Subtract int i = 1; cout << i << ", "; cout << (++i) << ", "; cout << i << ", "; cout << (i++) << ", "; cout << i << endl; Arithmetic Operators

  15. Logical Values and Operators • 0 False value • nonzero True value • !x Logical negation • x && y Logical and • x || y Logical inclusive or Characters cout << ('a'<'b') << " " << ('1'>='3') << " " << ('a'!='A') << " " << ('a'=='a') << ('z'>'y') << endl; • \n Newline \r Carriage return \? Question mark • \t Horizontal tab \f Form feed \' Single quote • \v Vertical tab \a Alert \" Double qoute • \b Backspace \\ Backslash \ddd Octal code

  16. Enumerations • An enumeration is an ordered set of names: • enum Color {red, orange, yellow, green, blue, indigo, violet); • Color c = green; • enum Polygon {triangle = 3; quadrilateral = 4; pentagon = 5}; Assignment Operators • = • += -= *= /= %= >>= <<= &= ^= |= • a op= expression; is equivalent to a = a op (expression) • a += b; is equivalent to a = a + b;

  17. streams: cin cout cerr << >> • cin >> x; • cin >> x >> y; • cout << x; • cout << endl; • int i = 1; int i = 1; • int j = 2; int j =2; • cout << i << j; cout << i << " " << j; • cout << endl; cout << endl; • int i = 1;Insert your own whitespace on output. • int j = 2; • cout << i << endl << j << endl;

  18. Fortran compatible I/O • #include <iostream.h> • #include <iomanip.h> • double a = 3.14159; • double b = 1 / a; • double c = 10 * a; • // Use FORTRAN compatibility output. • cout << setiosflags(ios::showpoint | ios::uppercase); • // Write data in G15.8 format. • cout << setw(15) << setprecision(8) << a; • cout << setw(15) << setprecision(8) << b; • // Write in F10.3 format • cout << setiosflags(ios::fixed); • cout << setw(10) << setprecision(3) << c << endl;

  19. File I/O • #include <iostream.h> • #include <fstream.h> • //... • ofstream out("pi.out"); • out << 3.14159 << endl; • ofstreamoutput file stream • ifstreaminput file stream

  20. Quick Reference: Expressions 1 • Each box holds operators with the same precedence. • Operators in higher boxes have higher precedence. • Unary and assignment operators are right-associative. • All others are left associative.

  21. Quick Reference: Expressions 2

  22. Quick Reference: Expressions 3

  23. Quick Reference: Expressions 4

  24. Quick Reference: Expressions 5

  25. Quick Reference: Expressions 6 Use parentheses and spacing to make expressions easier to read.

  26. if Statements • if (current_temp > maximum_safe_temp) { • cerr << "EMERGENCY: Too hot--flushing" << endl; flushWithWater(); • } • if (current_temp > maximum_safe_temp) • cerr << "EMERGENCY: Too hot--flushing" << endl; • // WRONG! • if (current_temp > maximum_safe_temp) • cerr << "EMERGENCY: Too hot--flushing" << endl; • flushWithWater(); Select a code formatting style and use it consistently. Use a block for an if statement body.

  27. if (current_temp > maximum_safe_temp) { • // Emergency cool down. • cerr << "EMERGENCY: Too hot--flushing" << endl; • flushWithWater(); • } else { • // Normal control strategy. • if (current_temp > operating_temp + temp_tolerance) { • heaterOff(); • if (current_temp > operating_temp + 2*temp_tolerance) { • coolingWaterOn(); • } • } • if (current_temp < operating_temp - temp_tolerance) { • coolingWaterOff(); • if (current_temp < operating_temp - 2*temp_tolerance) { • heaterOn(); • } • } • }

  28. if ?: • if (expression) { • block-contents; • } • if (expression) { • block-1-contents; • } else { • block-2-contents; • } • expression ? true-value : false-value; • x = (x<0) ? -x : x; // x = abs(x) Use the conditional operator only for simple tests that fit on one line.

  29. switch In switch statements each choice must have a closing break, or be on the same line as another choice or there should be a comment to indicate that the fall-through is the desired action. • switch(cin.get()){ • case 'X': exit(0); • case 'H': • help(); • break; • case 'A': • case 'B': • // do something • break; • default: • cout << "try again" << endl; • }

  30. Loops: while, do-while • float x; • while (cin >> x) { • cout << setw(25) << x << setw(25) << sqrt(x) << endl; • } • ch2/Newton.C • x = initial_guess; • do { • dx = f(x) / fprime(x); • x -= dx; • } while (abs(dx) > desired_accuracy); Use a while loop when it is possible that the loop body should not be executed. Use a do loop when the body should always be executed at least once.

  31. Loops: for • for(init-statement; continue-expression; increment-expression) { • ... // loop body • } • for(int i = 1; i <= 10; i++) { • cout<< "i= " << i << endl; • }

  32. break , continue,goto • break: terminate innermost enclosing while, do, for, or switch • continue: go to bottom of loop in while, do or for • ch2/break.C • int x; • while(cin >> x) { • if(x < 0) { • cout << "Negative number " << x << " read" << endl; • break; • } • // regular input processing • } Use break and continue sparingly and only when their meaning will be clear. Do not use goto.

  33. Quick Reference:Control Statements • break; leave current block or case • continue; continue with next iteration • goto label; jump to label • label: statement set label • while(expr)statement repeat stmt as long as expr is true • do statement while(expr) repeat stmt until expr is false • expr1; • while(expr2){ • for(expr1;expr2;expr3) statement statement • expr3; • } • if(expr)statement • if(expr)statement else statement • switch (expr) { expr is evaluated and compared to • case const_expr: statement the case const_expr; execution • case const_expr: statement continues at the first match; • ... caution: must use break to leave the • default: statement switch • }

  34. Declarations • Declaration Attributes Declarator Initializer • int x; int x • int x = 3; int x = 3 • float y = 1.1; float y = 1.1 • int a[3]; int a[3] • const float e=2.7 const,float e = 2.7 Use one declaration statement for each variable; declare each variable just before its first use and initialize it at the same time.

  35. const, typedef • const float h = 6.6256e-34; // Planck's constant (mks units) • void f() { • float x; • cin >> x; // Read value of x • const float xc = x; • ... • } • ch2/typedef.C • typedef float distance; • typedef float force; • distance d = 10; • force f; • f = d; Use typedefs for C++ built-in types to ensure portable numerical results and persistence schemes.

  36. Arrays • float x[100]; // x[0] ... x[99] • float x[3] = {1.1, 2.2, 3.3}; • float x[] = {1.1, 2.2, 3.3}; • float m[3][3], m1[3][3], m2[3][3]; • // Code that initializes m1 and m2 ... • // m = m1 * m2 • for (int i = 0; i < 3; i++) { • for (int j = 0; j < 3; j++) { • double sum = 0.0; • for (int k = 0; k < 3; k++) { • sum += m1[i][k] * m2[k][j]; • } • m[i][j] = sum; • } • }

  37. C++ arrays use 0-origin subscripting and the elements are stored row-wise. • Warning: m[1,2] is a valid C++ expression, but it does not access a multidimensional array. • Multidimensional arrays are arrays of arrays. • int m[2][3] = { • {1,2,3}, • {4,5,6} • }; • m consists of two elements (rows), each a one-dimensional array of three elements.

  38. Basics • A First Program • Variables, Objects, and Types • C++ Built-In Types and Operations • Input and Output • Operator Precedence and Associativity • if Statements • Loops • Declarations • Arrays

  39. ... • Pointers • Pointers and Arrays • const Pointers and Pointers to const Objects • Runtime Array Size • Character Strings • References • Functions

  40. int* p int* p : : int j int i int i : : : int 3 int 3 int* int 4 int* Pointers • int* p; • int i = 3; • p = &i; • int j = 4; • P = &j; • *p = 5; • p = 0; • ... • if (p != 0) cout << "Pointer " << p << " points to " << *p << endl; &x address of x *p indirection, value of object pointed to by p

  41. float[5] x : x[0]: x[1]: x[2]: x[3]: x[4]: float float float float float Conversion float* Pointers and Arrays • float x[5]; Whenever x is used in an expression - except as the operand of &, sizeof or to initialize a reference - it is converted into a pointer to the first element of the array. x is of type array of float, but used as pointer to float.

  42. float[5] x : x[0]: x[1]: x[2]: x[3]: x[4]: float float float float float Conversion float* Arithmetic on Pointers • x + 2 • x points to x[0] • x+i points to x[i] • *(x+i)is equivalent to x[i] • x+i is equivalent to &x[i] • Integers can be added (or subtracted) to a pointer to an array element. • It acts as offset. The result is a pointer of the same type, which points to the element the specified number of elements away.

  43. float x[10]; • // ... initialize x ... • float* left = &x[0]; • float* right = &x[9]; • while (left < right) { • float temp = *left; • *left++ = *right; • *right-- = temp; • } • float x[10]; • float* p = &x[10]; • while (p != x) *--p = 0.0;

  44. const Pointers, Pointers to const Objects • const float pi = 3.14159; • const float* p = &pi; • pi = 2; // Compile Error • *p = 2; // Compile Error • float a, b; • float* const p1 = &a; • *p1 = 10; • p1 = &b; // Compile Error • const float e = 2.718281828; • const float* const p2 = &e; Read complex declarations from the identifier back toward the beginning of the statement. C Programmers: Do not use #define to define symbolic constants, use const for individual constants or enum for enumerations.

  45. // Create arrays with the // desired number of elements int n; cin >> n; float* const x = new float[n]; float* const y = new float[n]; // Read the data points for (int i = 0; i < n; i++) { cin >> x[i] >> y[i]; } // Accumulate sums Sx and Sy // in double precision double sx = 0.0; double sy = 0.0; for (i = 0; i < n; i++) { sx += x[i]; sy += y[i]; } // Compute coefficients double sx_over_n = sx / n; double stt = 0.0; double b = 0.0; for (i = 0; i < n; i++) { double ti = x[i] - sx_over_n; stt += ti * ti; b += ti * y[i]; } b /= stt; double a = (sy - sx * b) / n; delete [] x; delete [] y; cout << a << " " << b << endl; Runtime Array Size

  46. Pointer Operators • *p Indirection • &x Pointer to object • a[i] Array subscript • p->m Class member selection • ++p, p++ Pre(Post)increment to next element • --p, p-- Pre(Post)decrement to previous element • p+=n Increment by n elements • p-=n Decrement by n elements • p+n Offset by n elements • p-n Negative offset by n elements • new T Allocate object • new T[n] Allocate array of n objects • delete p Delete object • delete []p Delete array of objects

  47. H H e a n I i \0 i c w s \0 ? t ? a ? N ? o Character Strings • C character strings are a special case of arrays and array initialization: • char hello1[] = {'H','i'}; • char hello2[] = "Hi"; • char name[15] = "Isaac Newton"; Use the C++ standard library (or STL) string class rather then const char* where possible.

  48. ... • Pointers • Pointers and Arrays • const Pointers and Pointers to const Objects • Runtime Array Size • Character Strings • References • Functions

  49. Functions, void doNothing(){} • doublecoulombsLaw(double q1, double q2, double r) { • // Coulomb's law for the force acting on two point charges • // q1 and q2 at a distance r. MKS units are used. • const double k = 8.9875e9; // nt-m**2/coul**2 • return k * q1 * q2 / (r * r); • } • int main() { • cout << coulombsLaw(1.6e-19, 1.6e-19, 5.3e-11) << " newtons\n"; • return 0; • } • return-value-typefunction-name(argument-list) { • function-body • }

  50. Function Prototypes and Header Files • extern double coulombsLaw(double q1, double q2, double r); • #include <iostream.h> • #include "coulombsLaw.h" • int main() { • cout << coulombsLaw(1.6e-19, 1.6e-19, 5.3e-11) << ... • return 0; • } • #include "coulombsLaw.h" • double coulombsLaw(double q1, double q2, double r) { • ... • return k * q1 * q2 / (r * r); • }

More Related