460 likes | 567 Views
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 */
E N D
Basic Program Elements Chapter 2 CS 117 Spring 2002
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 */ // comments which extend to // the end of the line
Program format // # compiler directive // you will nearly always need: #include <iostream.h> // for your header files #include "myHeader.h"
Program format // Global constants and variables should be declared here // constants const type CONST_NAME // global variables - use sparingly type globalVar
main program int main ( void) { // declarations type varName // body of main program return 0; // 0 => success } // end of main
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
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.
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
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
Examples • Output • cout << "enter data: "; • Input: • cin >> data;
Variables Variables provide a means to store values that may change as the program runs.
Declarations • format • type varID; • Example • int i; • Comma used to separate multiple identifiers • double var1, var2, var3;
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.
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
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
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.)
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 \
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
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.
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
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
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
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
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
Arithmetic Operators • standard arithmetic operations defined for all the primitive numeric types • + - * / • a few extras • % ++ --
Arithmetic Operators • The usual • + addition • - subtraction • * multiplication • / division - different for integers • plus • % the remainder from an integer division
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.
mathematical functions • need to include math.h
Arithmetic Expressions • combination of variables, constants, operators and assignment • number • variable • function(argList) • (expression) • expression operator expression • var = expression
Example expressions 25 var1 a + b c = a + b (a + b) / (c + d) i % j sqrt(x)
Equations in C++ wp = we * mp / me
Equations in C++ g = G * mass / (radius * radius)
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.
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
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
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)
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
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
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
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
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.