Presentation is loading. Please wait.

Presentation is loading. Please wait.

CS 117 Spring 2002 Basic Program Elements Chapter 2.

Similar presentations


Presentation on theme: "CS 117 Spring 2002 Basic Program Elements Chapter 2."— Presentation transcript:

1 CS 117 Spring 2002 Basic Program Elements Chapter 2

2 hello.cpp // hello.cpp #include 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 // 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 \nnewline \ttab \'single quote in char \"double quote in strings \\\ in string otherssee your text

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 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 7 / 2 = 3 7 % 2 = 1 299 / 100 = 2 299 % 100 = 99 49 / 5 = 9 49 % 5 = 4 15 / 0 illegal 15 % 0 undefined

31 mathematical functions need to include math.h sqrt(x)square root sin(x), cos(x), atan(x) trigonometric functions log(x), log10(x)log functions exp(x)exex pow(x, y)xyxy rand(), srand(n)random numbers

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 / 2is an integer 5 / 2.5 is a double 5.0 / 2.0is 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 errorscompiler will catch these –run-time errorsthese will halt your program (e.g. dividing by 0, trying to read from a file that doesn't exist,...) –logic errorsthese are errors in the program design.


Download ppt "CS 117 Spring 2002 Basic Program Elements Chapter 2."

Similar presentations


Ads by Google