Presentation is loading. Please wait.

Presentation is loading. Please wait.

91.166 Copyright © 2000, Department of Systems and Computer Engineering, Carleton University 1 Program Outline // this slide illustrates the basic outline.

Similar presentations


Presentation on theme: "91.166 Copyright © 2000, Department of Systems and Computer Engineering, Carleton University 1 Program Outline // this slide illustrates the basic outline."— Presentation transcript:

1 91.166 Copyright © 2000, Department of Systems and Computer Engineering, Carleton University 1 Program Outline // this slide illustrates the basic outline of a simple C++ // program. these comments are ignored by the // compiler and are just for the reader’s benefit. /* this illustrates another form of comment, one which can run over many lines */ #include... void main (void) {... } // end main (this is just a comment and can be omitted) C++ does not actually require that we separate our declarations and our executable statements. They can be intermingled (as in the old text), but this is best avoided by beginners. variations are possible e.g. int main () “declarations” go here “executable” statements go here may be other includes

2 91.166 Copyright © 2000, Department of Systems and Computer Engineering, Carleton University 2 Comments //... - the rest of input line is taken as a comment (is completely ignored by the compiler) /*... */ - everything in between the /* and the */ is ignored by the compiler. this form of comment may extend over many input lines, or may affect only a portion of a line. /* this comment extends over three input lines */ a = a % /* modulus */ b; The object of comments is to make a program understandable, and they should be judged on this basis (and not “by volume”).

3 91.166 Copyright © 2000, Department of Systems and Computer Engineering, Carleton University 3 Include Directives #include name of “header” file Include directives cause the compiler to read the specified header file prior to translating your program (dear compiler – before translating my program, please look at the declarations in file such and such). This can be thought of as enabling sets of optional language features. iostream.h: permits use of cin and cout math.h: permits use of M_PI, fabs, sin, etc. stdlib.h: permits use of abs, rand, etc. conio.h: permits use of getch Including files which aren’t actually required is harmless, though the compilation process will take a little bit longer to complete.

4 91.166 Copyright © 2000, Department of Systems and Computer Engineering, Carleton University 4 Main Function Textbook (see p25) int main () {... return 0; } Myself: void main (void) {... // no “return 0” required, // though a simple “return” (no // value) may be used if desired } -The placement of the ‘{‘ is just a matter of style. -The difference in the “header” really doesn’t amount to much. Hard to explain now, but should become clear when we get to functions.

5 91.166 Copyright © 2000, Department of Systems and Computer Engineering, Carleton University 5 Variable Declarations (1) Basic Form: type name; int double... - made up of letters, digits, and undescores - length effectively unlimited - case is significant (“SUM” and “sum” are considered different) - cannot be one of C++’s “reserved words” (appendix 1) - first character cannot be a digit - There are other possible types (bool, long, char, etc.). These will be introduced as we need them. - Variables names should be meaningful. If a variable is used to contain the number of students in a class, for example, “number_of_students” and “numberOfStudents” would be good choices (note the two different styles).

6 91.166 Copyright © 2000, Department of Systems and Computer Engineering, Carleton University 6 Variable Declarations (2) List Form: type name, name, name,...; - Declares a number of variables (all of the same type) all in one fell swoop. With Initializers: type name = exp; type name = exp, name = exp... ; - “exp” represents an “expression”. when initializing variables, this expression is often just a simple value (e.g. 3, 6.7, etc.), but more complex possibilities (e.g. 2 * M_PI) are possible. - in the list case, not all of the variables in the list need by given initial values (one can “mix and match”)

7 91.166 Copyright © 2000, Department of Systems and Computer Engineering, Carleton University 7 Program Format C++ is free format. From the compiler’s point of view your program is just a long sequence of “tokens”, and how these are physically positioned in you.cpp file is immaterial. void main (void) { double x, y, z; is equivalent to void main (void) { double x, y, z; is equivalent to void main (void) { double x, y, z; This gives us considerable scope to improve the appearance and readability of programs (or conversely, to make a real mess of them). Print out and read the course “style guide”.

8 91.166 Copyright © 2000, Department of Systems and Computer Engineering, Carleton University 8 Executable Statements (1) Output Statement: cout << item << item << item <<...; - Each item may be either: - Examples cout << “The answer is “ << a << endl; cout << x + y << endl; - A string (“... “). In this case the string is output verbatim. - An expression. In this case the expression is evaluated and its value is output. The expression may be a simple as a variable name (in which case the value of the expression is the value in the variable) or it may be more complex. - endl. Outputting endl causes the display cursor to move to the start of a new line.

9 91.166 Copyright © 2000, Department of Systems and Computer Engineering, Carleton University 9 Executable Statements (2) Input Statement: cin >> var_name >> var_name >>...; - Values are obtained from the keyboard and placed in the variables listed. The first value read goes into the first variable listed and so on. Assignment Statement: var_name = expression; - The expression is evaluated and the value produced is placed into the variable. - Examples a = b; // a very simple expression g = 7.2; // ditto y = sqrt (f * 6) + alpha; // more complex

10 91.166 Copyright © 2000, Department of Systems and Computer Engineering, Carleton University 10 Executable Statements (3) Return Statement: form i) return expression; form ii) return; - Within the main function, means “stop now”. - Form (i) applies when “int main ()” is used. The value of the expression is immaterial (0 is a reasonable choice). - Form (ii) applies when “void main (void)” is used. In this case a return statement is optional as program execution automatically stops after the last statement has been executed.

11 91.166 Copyright © 2000, Department of Systems and Computer Engineering, Carleton University 11 Expressions (1) int a = 4, b, c = 9 + 2 ; double x, y, z = 13.1, w = M_PI * 4 ; a = (b + 4) / 6 ; cout << “The answers is “ << c << endl; x = sin ( x * 23 ) + 3.39 ; cout << (b + c) * 4 ; All of the circled elements in the above code are “expressions”. Expressions evaluate to a value. Expressions crop all over the place (e.g. in initializing variables, in assignment statements, etc.). The same rules apply in all cases.

12 91.166 Copyright © 2000, Department of Systems and Computer Engineering, Carleton University 12 Expressions (2) An expression may be as simple as a single variable name (value of expression = value stored in variable) or a constant such as 1. In general, expressions consist of one or more “operands” glued together with “operators”. Operands: variable name (e.g. alpha) constant (e.g. 1) function call (e.g. sin(x)) Operators (for now): unary -(negation) +(addition) binary -(subtraction) *(multiplication) /(division) %(modulus = division remainder)

13 91.166 Copyright © 2000, Department of Systems and Computer Engineering, Carleton University 13 Constants The simplest form of constant is a simple number (no decimal point), with or without a minus sign. Such constants are of type “int” (they correspond to the values that can be stored in “int” variables). 4, -9, 1004, 456, etc, Constants containing a decimal point are of type “double” (they correspond to the values that can be stored in “double” variables). 2.3, -9.4, 345.2, etc. Double values may also be expressend in “scientific notation”. 1.26e5(same as 126000.0) -3.6e-8(same as -0.000000036)

14 91.166 Copyright © 2000, Department of Systems and Computer Engineering, Carleton University 14 Function Calls A function call consists of the name of the function (sqrt, sin, cos, etc.) followed by the required number of “arguments”. name_of_function (arg, arg, arg, …) The number of arguments required varies from function to function. “sin” (computes the sin of an angle) requires one argument (the angle). “pow” (raise a value to some power) requires two (the value and the power). x = sin (y); // x gets the sine of y w = pow (n, 6); // w gets n 6 Each argument is (surprise) an expression, and may involve further function calls.

15 91.166 Copyright © 2000, Department of Systems and Computer Engineering, Carleton University 15 Precedence Operators have a pecking order – some of them more important than others. This is known as “precedence”. When a choice exists, more important operations are done first. PrecedenceOperators Highestunary - * / % Lowestbinary - + -a + b is interpreted as (-a) + b a + b * c is interpreted as a + (b * c) Parantheses (round brackets) may be used to explicitly indicate the ordering of operations. It is suggested that this always be done.

16 91.166 Copyright © 2000, Department of Systems and Computer Engineering, Carleton University 16 Associativity Ties between operators having the same precedence are broken by either working from the left to the right (if the operators in question are “left associative”) or from the right to the left (if the operators are “right associative”). Most operators (and all the ones we’ve looked at so far) are left associative. w / 2 * r is interpreted as (w / 2) * r Again, the use of parantheses eliminates any possible confusion and is thus a good idea.

17 91.166 Copyright © 2000, Department of Systems and Computer Engineering, Carleton University 17 Type So far type means either “int” (integer) or “double” (real, or floating point), but there will be other possibilities. Every operand in an an expression has a type. variable: as per declaration constant: depends on format of constant function call: depends on function Some functions produce “int” values, and others produce “double” values (see text Appendix 4). In function “prototypes” the type of value produced appears to the left of the function name. Example: double sin (double); Every intermediate result produced in the course of evaluating an expression also has a type, as does the ultimate result.

18 91.166 Copyright © 2000, Department of Systems and Computer Engineering, Carleton University 18 Arithmetic Results For the time being (things will get more interesting when other types are introduced), the rule which determines the type of arithmetic results is as follows: if either operand is “double” then the result is “double” else the result is “int” If an “int” is divided by an “int”, the result is an “int”. Thus 7/2 is 3 and not 3.5. This causes beginners all kinds of grief. In general, the arithmetic operators will accept any combination of “int” and “double” operands. The exception is %, which can only be used with integral (for now, “int”) operands.

19 91.166 Copyright © 2000, Department of Systems and Computer Engineering, Carleton University 19 Type Conversions C++ permits “int” values to be assigned to “double” variables, and vice versa. In the second case, the fractional part of the “double” value is lost (there is no rounding). The same rules apply in providing function arguments. A function which requires a “double” value may be given an “int” value, and vice versa. If a “double” value is supplied where an “int” value is required, the fractional part is lost. In addition to these automatic conversions, we may explicitly force type conversions by using “casts”.

20 91.166 Copyright © 2000, Department of Systems and Computer Engineering, Carleton University 20 Casts Casts are unary operators which convert a value from one type to another. (int)convert to “int” (double)convert to “double” They have less precedence than unary – but more precedence than *, /, and % (N.B. they are missing from Appendix 2 of the text). Example of use: int vendors, hot_dogs_sold; double avg_hot_dogs; // doesn’t work because of int division avg_hot_dogs = hots_dogs_sold / vendors; // much better avg_hot_dogs = ((double) hot_dogs_sold) / vendors;

21 91.166 Copyright © 2000, Department of Systems and Computer Engineering, Carleton University 21 Named Constants Named constants can be thought of as storage cells which always contain the same value. They are declared in exactly the same way as variables except in that the type is preceded with “const” and an initial value must be specified. const type name = exp, name = exp...; Named constants are useful in avoiding “magic numbers”, so making programs easier to understand and modify. // bad practice distance = 6377.707 * angular_distance; // much better const double earth_radius_in_km = 6377.707;... distance = earth_radius_in_kn * angular_distance;


Download ppt "91.166 Copyright © 2000, Department of Systems and Computer Engineering, Carleton University 1 Program Outline // this slide illustrates the basic outline."

Similar presentations


Ads by Google