1 / 29

C++ Basics

C++ Basics. Prof. Shermane Austin. Learning Programming Language Basics. Data Types – simple Expressions Relational and Logical Operators Conditional Statements Arrays Iteration Memory Allocation I/O Functions. Hello World . //Simple C++ program

bernie
Download Presentation

C++ 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. C++ Basics Prof. Shermane Austin

  2. Learning Programming Language Basics • Data Types – simple • Expressions • Relational and Logical Operators • Conditional Statements • Arrays • Iteration • Memory Allocation • I/O • Functions

  3. Hello World //Simple C++ program #include <iostream> //input and output library #include <string> //string library using namespace std; // predefined objects int main() //first function, { //function delimiter cout << “Hello world!” << endl; //output stream return 0; //ends execution and returns ]

  4. Simple Data Types • Int – 32 bit, optional qualifiers: long, short • Float – 32 bit, IEEE floating point • Double – 64 bit, optional qualifer: long • Char – 8 bit • Byte – 8 bit

  5. Operators • Arithmetic • +, -, /, * • % - modulus or remainder, integer only, e.g. 23%4 • Relational • <, >, <=, >=, !=, == • (c == a) \\ common error is omitting one of the = • Be careful using != or == with floating point values, rounding occurs at the machine level • Logical • And &&, e.g. (c <= a) && (c >= b) • Or ||, e.g. (c <= a) || (c >= b)

  6. Operator shortcuts – Compound Assignment • Increment, Decrement ++, -- a = a + 1; \\can be written as a++; a++, ++a, a--, --a Position of operator is important, e.g. b = f(a++); \\a is incremented after f(a) call c = f(++a); \\a is incremented before f(a) call • Compound Assignment Operators int a; … a = a + 5; a += 5; Can be used with all arithmetic operators

  7. Exercise - 1 • Compute volume of an object • Read in: • Object mass (grams) • Object density (grams per cubic centimeter) • Output: Volume (cubic centimeters) • Relationship: Density = Mass/Volume

  8. Code Needs • Determine variables (with types needed) • Issue prompts – use cout, e.g. Cout << “Object Mass?” << endl; • Read in values – use cin, e.g. Cin >> mass; • Compute Distance and Velocity

  9. Conditional Expressions • Any combination of logical and relational operators • Use () as needed • Examples: Simple if statement if( a < b) s1 else s2

  10. If/else statement • General format – single statement execution on true condition • Long format – multiple statement execution on true condition • General rule: more than one statement under if and/or else condition requires {} • Short-hand format – single statement • Nested if statements

  11. If – single statement Format: if(expression) s1; else s2;

  12. If – multiple statements Format: if(expression) { s1; s2; … } else { s1; s2; … }

  13. If shorthand • Used only with single statements • Format: Expression ? S1 : s2; Example: c != b ? c++ : b++; Example: int a,b; … int min = a <= b ? a : b ;

  14. Short-circuit evaluation • && - evaluation terminates with first false condition • || - evaluation terminates with first true condition • Done to insure objects can be properly manipulated, e.g. • (i != 0) && ((j/i) > 5)

  15. Arrays • Included in C++ for backward compatibility with C • Arrays less popular and class representation of lists, especially the vector class more frequently used • Vector class is an example of container classes is defined in the Standard Template Library (STL)

  16. Simple arrays - Declaration const int N = 20; const int M = 40; const int MaxListSize = 1000; // Note: const qualifier used to denote constant values //Declaration examples: int a[10]; float c[M*N]; int Values[MaxListSize];

  17. Simple Arrays - Referencing • Array elements are referenced using subscripts or indices • First index in C++ is 0 • Examples: a[0] = b; a[i++] = a[j] + 3; a[a[k]] = 12; • Warning: No automatic checking for array boundaries. Illegal subscripts will result in inaccurate memory references or storage

  18. Simple Array - Initialization • Int frequency[5] = {0,0,0,0,0}; • Int total[5] = {0}; // first element set to 0, remainder are uninitialized and default at 0 • Int digits[] = {0,1,2,3,4,5,6,7,8,9}; • Int zero[] = {0}; //one-element array

  19. Iteration • For-loops • While-loops

  20. Iteration using while • Format: while (conditional expression) { s1; … } Statement in the block are executed as long as condition is true If condition is evaluated to false, statements are never executed

  21. Interation using for • Format: for (ForInit ; ForExpression; PostExpression) { } ForInit – initialization step to start loop ForExpression – logical expression PostExpression – next iteration of loop

  22. For examples for( i = 0; i<= maxsize; i++) { } for(j=minsize; j < maxsize; j+=2) { } for(k = maxsize; k > minsize; k--) { }

  23. Exercises • Compute n! using a for loop • Compute the nth Fibonacci term using a while loop

  24. Example, compute roots of a quadratic equation: //Quadratic roots #include <iostream> #include <string> #include <math.h> Using namespace std; int main() { double a, b, c; cout << “Coefficients for quadratic equation: “; cin >> a >> b >> c; if ((a != 0) && ((b*b – 4*a*c) > 0)) { double radical = sqrt(b*b – 4 * a * c); double root1 = (-b + radical) / (2 * a); double root2 = (-b – radical) / (2 * a); cout << “ roots are “ << root1 << “ and “ << root2 << endl; } else { cout << “ No real roots “ << endl; } return 0; }

  25. Compute area of a circle #include <iostream> #include <string> Using namespace std; const float Pi = 3.1415 int main() { float radius; cout << “Enter radius: ”; cin >> radius; //compute area float area = Pi * radius * radius; //output cout << “Area = “ << area; }

  26. More general using functions #include <iostream> #include <string> Using namespace std; float CircleArea(float r) { const float Pi = 3.1415; return Pi * r * r; } int main() { float radius; cout << “Enter radius: ”; cin >> radius; //compute area float area = CircleArea(radius); //output cout << “Area = “ << area; }

  27. Function prototyping • Functions cannot be used until they are defined • Can create problems with functions calling other functions • Use prototype conventions • Define function prototype before main • Implement function after main

  28. Prototype Example #include <iostream> #include <string> Using namespace std; float CircleArea(float r); int main() { float radius; cout << “Enter radius: ”; cin >> radius; //compute area float area = CircleArea(radius); //output cout << “Area = “ << area; } float CircleArea(float r) { const float Pi = 3.1415; return Pi * r * r; }

  29. Homework • Write a program for integrating a quadratic polynomial • User input will be • Quadratic coefficients: a1, a2, a3 • Interval of interest : n1, n2 • Output will be the area

More Related