Presentation is loading. Please wait.

Presentation is loading. Please wait.

1 ENERGY 211 / CME 211 Lecture 3 September 26, 2008.

Similar presentations


Presentation on theme: "1 ENERGY 211 / CME 211 Lecture 3 September 26, 2008."— Presentation transcript:

1 1 ENERGY 211 / CME 211 Lecture 3 September 26, 2008

2 2 What's in a C++ Program? A program consists primarily of the declarations and definitions of its entities –Functions: for performing operations –Variables: for storing data A declaration includes a name and type The definition of an entity includes its declaration, but more importantly, it describes its code and data

3 3 Variables and Functions A variable is a named memory location Its type indicates the nature of the data stored in this memory location A function consists of –The declaration of its name and type –Zero or more statements A function's type consists of the types of its input arguments, and the type of its return value

4 4 Statements Statements describe the operations performed by a function Types of statements: –Variable declarations or definitions –Expressions –Flow-control statements –Compound statements (enclosed in { }) Non-compound statements must be terminated with a semicolon

5 5 A Simple Program #include // std objects defined in iostream int main() { int i; // i is an integer int largest(0); // largest is initially zero do { // following statements are to be repeated std::cout << "Enter a positive number: "; std::cin >> i; // read integer, store in i if (i < 1) break; // terminate repetition if (i > largest) largest = i; // update largest value } while (true); // repeat forever std::cout << "Largest is " << largest << std::endl; } // print largest value and exit

6 6 Variable Definitions The statements int i; // i is an integer int largest(0); // largest is initially zero declare that i and largest are variables of type int (for integer) and define both (i.e. allocate storage) The (0) initializes the value to zero Initialization is not required Unlike MATLAB, the type of a variable must be declared before it is used

7 7 Scope A variable defined within a compound statement is unknown outside of it A variable declared outside of any function is at file scope, and known to any function within the file A variable declared with the extern qualifier is declared, not defined (unless initialized), can be used in several files A variable can only be defined once within a given scope

8 8 What is a Type? A type is a specification for entities that have specified behavior Categories of types: –Value: two instances with the same data are interchangeable –Object: each instance has its own identity For now, we only discuss value types Instances of value types can exist as pure values, called literals

9 9 Examples of Literals Character: 'a', '\n' (newline), '\223' (ASCII code for ô, in octal) String: "Hello" Boolean: true or false Integer: –Decimal: 0, 2, -3 –Octal: 040 (= 32 in decimal) –Hexadecimal: 0xA5 (= 165 in decimal) Floating-point: -1.0, 1e-4,.14E5

10 10 Fundamental Types Fundamental types are value types on which all other types are built All fundamental types in C++ are either integral, or floating-point Integral types: –char (ASCII characters), –bool (Boolean values, true or false), –integer types

11 11 Signed Integer Types One bit used to indicate sign short –at least 2 bytes (16 bits) –Supports values from –32,767 to 32,767 int –"natural" integer type for given hardware –usually 4 bytes (32 bits) long –at least 4 bytes –Supports values from –2,147,483,647 to 2,147,483,647

12 12 Unsigned Integer Types unsigned short –At least 2 bytes –Supports values from 0 to 65,535 unsigned int –Usually 4 bytes unsigned long –At least 4 bytes –Supports values from 0 to 4,294,967,295

13 13 Names in C++ The names given to variables and functions are known as identifiers Identifiers contain letters, digits, underscores Must begin with letter or underscore Any length is allowed Identifiers are case-sensitive! Identifiers in simple program: main, i, largest, std, cout, cin Can’t use keywords! (see p. 47 in text)

14 14 Beware of Bad Users The preceding program expects the user to input integers The >> operator, followed by an integer variable, assumes an integer is followed by a space or newline character (so it knows when to stop) >> knows to skip over "white space" What if the user types something else? In this case, std::cin has the bool value false

15 15 Handling Bad Input int main() { try { // attempt to run the following code int i; int biggest(0); do { std::cout << "Enter a positive number: "; std::cin >> i; // bad input, report failure if (std::cin == false) throw std::exception(); if (i < 1) break; if (i > biggest) biggest = i; } while (true); std::cout << "Largest is " << biggest << '\n'; } // end of try block catch (...) { // any exception sends control to this point std::cerr << "Exception thrown"; } // end of catch block }

16 16 Graceful Failure int i; int biggest(0); do { std::cout << "Enter a positive number: "; std::cin >> i; if (std::cin == false) { // any code in this try block, after the throw, // will not be executed, so we should print out // the largest value now std::cout << "Largest is " << biggest << '\n'; throw std::exception(); } if ( i < 1 ) break; if ( i > biggest ) biggest = i; } while ( true ); std::cout << "Largest is " << biggest << '\n';

17 17 Characters A variable of type char is stored in a single byte (8 bits) The data stored in this byte is the ASCII code of the corresponding character The value zero denotes a null character, which marks the end of a string Literals for special characters, such as non-printing characters, are specified using escape sequences (like \n for newline) or the ASCII code in octal

18 18 Reading a Line of Text #include int main() { try { char c; int count(0); // initially count is zero std::cout << "Type a line." << std::endl; do { // repeat the following c = std::cin.get(); // read character if ( std::cin == false ) throw std::exception(); if ( c == '\n' ) break; // quit on newline ++count; // update count of characters entered std::cout << c; // echo character } while ( true ); std::cout << "You typed " << count << " characters\n"; } catch (...) { std::cerr << "Exception thrown"; }

19 19 Floating-point Types float –usually 4 bytes –At least 6 significant digits of precision –Not a good choice unless space is limited double –usually 8 bytes –At least 10 digits of precision –Should almost always be used long double –Usually 10 bytes –Not supported by many C++ compilers

20 20 First Floating-Point Program #include #include // needed to use math functions int main() { try { // initially total = 0.0, value is uninitialized double total(0.0); double value; do { std::cout << "Type in a number <= 9999. "; std::cin >> value; if ( std::cin == false ) throw std::exception(); if ( value > 9999.0 ) break; total += value * value; // sum of squares } while ( true ); // print length of vector of values, which is the // square root of the sum of squares std::cout << "Length is " << sqrt(total) << '\n'; } catch (...) { std::cerr << "Exception thrown\n"; } }

21 21 More About Literals Integer literals can have suffixes –L or l to be interpreted as a long –U or u to be interpreted as unsigned Floating-point literals followed by f or F are of type float rather than double, or by l or L for extended precision String or character literals preceded by L are stored as wide-character strings (2-4 bytes each)

22 22 Next Time Probably finishing these slides because you asked too many questions :P Ok, it’s really because I had too many slides Arrays


Download ppt "1 ENERGY 211 / CME 211 Lecture 3 September 26, 2008."

Similar presentations


Ads by Google