1 / 46

Basic Program Elements

Basic Program Elements. Chapter 2. hello.cpp. // hello.cpp #include <iostream.h> int main( void) { cout << “Hello, class! << endl; return 0; }. Program format. /* begins a c-style comment * (ignored by compiler) * which spans all lines occurring * before the concluding */

tom
Download Presentation

Basic Program Elements

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. Basic Program Elements Chapter 2 CS 117 Spring 2002

  2. hello.cpp // hello.cpp #include <iostream.h> int main( void) { cout << “Hello, class! << endl; return 0; }

  3. Program format /* begins a c-style comment * (ignored by compiler) * which spans all lines occurring * before the concluding */ // comments which extend to // the end of the line

  4. Program format // # compiler directive // you will nearly always need: #include <iostream.h> // for your header files #include "myHeader.h"

  5. Program format // Global constants and variables should be declared here // constants const type CONST_NAME // global variables - use sparingly type globalVar

  6. main program int main ( void) { // declarations type varName // body of main program return 0; // 0 => success } // end of main

  7. Basic Syntax • { } can be used to group statements into blocks • () used in two ways • can be used in arithmetic expressions to control order of evaluation • used to enclose function arguments • [] are used for array indices

  8. Basic syntax • Built into the language are • reserved words or keywords • special symbols {}, //, *, … • Identifiers are words you make up • statement corresponds to a sentence • it ends with a semicolon. • may span multiple lines.

  9. Identifiers • Consist of letters (a…z, A…Z), digits (0 …9), underscore (_) • cannot start with a digit • must not be the same as keywords • case sensitive

  10. Input and Output • C++ uses streams for input and output • sequential - data comes out in same order as it goes in • character based. • >> extraction operator for input • << insertion operator for output

  11. Examples • Output • cout << "enter data: "; • Input: • cin >> data;

  12. Variables Variables provide a means to store values that may change as the program runs.

  13. Declarations • format • type varID; • Example • int i; • Comma used to separate multiple identifiers • double var1, var2, var3;

  14. Types • Numeric • Integer types - short, int, long, long long, unsigned • Real types - float, double, long double • Character • char a single character • Logical - bool • Two values - true and false. • Useful for decision making.

  15. Other Types • Arrays - multiple elements of the same type • Enumerated types - limited number of values • struct - multiple data elements • class - consist of both data and behavior

  16. Integer Types • int - the basic integer type • range is system dependent (It depends on how many bits are used to store an int.) • Written with no decimal point (89). • short, int, long and long int have progressively larger ranges

  17. Floating Point Types • double - the basic floating point type • Have integer and fractional parts • It is stored in a binary format analogous to scientific notation. • It's range is larger than for the integer types • Must contain a decimal point, (i.e. 1.23). • May be written like scientific notation as in 4.56e7. • float is a smaller real number and a long double is a bigger one.)

  18. Special Characters • Some characters can't be entered into the program directly • unprintable characters such as tab, newline, new page • characters that have a special meaning in C++ such as " and ’ • Represented by two-character sequence that begins \

  19. Special Characters

  20. Jan 28 • Exam next week • Wednesday 2/6/02 • Chapters 1, 2 and part of 3 • sample test problems in web notes • links to sample exams on main web page • review questions in text • in-class review next Monday

  21. Types • Numeric • Integer types - short, int, long, long long, unsigned • Real types - float, double, long double • Character • char a single character • Logical - bool • Two values - true and false. • Useful for decision making.

  22. Other Types • Arrays - multiple elements of the same type • Enumerated types - limited number of values • struct - multiple data elements • class - consist of both data and behavior

  23. Class types • C++ provides some classes for you to use • iostream - hierarchy of classes for input and output • cin • cout • string - to store text strings

  24. Literal string • A literal string constant is a sequence of zero or more characters enclosed in double quotes • "Are you aware?\n" • Individual characters of string are stored in consecutive memory locations • The null character ('\0') is appended to strings so that the compiler knows where in memory strings ends

  25. string Class • used to store character strings #include <string> string text; text = "a literal string"; cin >> text; // gets one word of text getline( cin, text); // gets to next newline

  26. Constants • Named constants are declared like variables with const in front of the type. They must be assigned at the time they are declared. • const double PI = 3.14159; • const int MAX_FIELDS = 8; • const double LIGHT_SPEED = 2.99e8

  27. Arithmetic Operators • standard arithmetic operations defined for all the primitive numeric types • + - * / • a few extras • % ++ --

  28. Arithmetic Operators • The usual • + addition • - subtraction • * multiplication • / division - different for integers • plus • % the remainder from an integer division

  29. Integer division • For int variables, / gives only the integer part of the result. The result is truncated, not rounded. • 5 / 2 = 2 • Modulus operator (%) gives the remainder from an integer division. • 5 % 2 = 1 • Result of / and % for negative values is implementation dependent.

  30. Examples

  31. mathematical functions • need to include math.h

  32. Arithmetic Expressions • combination of variables, constants, operators and assignment • number • variable • function(argList) • (expression) • expression operator expression • var = expression

  33. Example expressions 25 var1 a + b c = a + b (a + b) / (c + d) i % j sqrt(x)

  34. Equations in C++ wp = we * mp / me

  35. Equations in C++ g = G * mass / (radius * radius)

  36. Assignment • use = to assign a value to a variable • aVar = 10; stores 10 in aVar • a = c + b means store the value of c + b in a.

  37. Precedence • There are rules for deciding the order in which operations get done • From highest to lowest • unary - • * / % • + - • = • Use ( ) to force a different order • left to right for operations of equal precedence

  38. Evaluation

  39. Precedence Example

  40. Mixed-type expressions • The type of an expression is determined by its arguments • two int arguments => int • one or two double argument => double • Examples 5 / 2 is an integer 5 / 2.5 is a double 5.0 / 2.0 is a double

  41. Conversion between types • You convert between compatible types by casting. • For example, if n is an int and d is a double, • (int)d will be an int (fractional part is truncated) • to round a double to the nearest integer, add 0.5 before casting • (double)n will be a double • the variable itself isn't changed • In mixed arithmetic, casting will be done automatically • result may not be what you want so be careful. (e.g. integer division)

  42. Conversion Examples • (double)25 = 25.0 • (int)2.3 = 2 • (int)3.9 = 3 • (int)0.5 = 0 • (int)2.5e3 = 2500 • (int)1.3e-27 = 0

  43. Coin Collection Case Study • Problem statement • Saving nickels and pennies and want to exchange these coins at the bank so need to know the value of coins in dollars and cents. • Analysis • Count of nickels and pennies in total • Determine total value • Use integer division to get dollar value • / 100

  44. Coin Collection Case Study • Analysis (cont) • Use modulus % to get cents value • % 100 • Design • Prompt for name • Get count of nickels and pennies • Compute total value • Calculate dollars and cents • Display results

  45. Coin Collection Case Study • Implementation • Write C++ code of design • Verify correct data types needed • Mixed mode types and promotion • Testing • Test results using various input combinations

  46. Errors • programs won't always compile or work correctly on the first try • There are several types of errors you can run into • syntax errors compiler will catch these • run-time errors these will halt your program (e.g. dividing by 0, trying to read from a file that doesn't exist, ...) • logic errors these are errors in the program design.

More Related