Notes N3

Math 10 -- D. C. Smolarski, S.J.
Santa Clara University, Department of Mathematics and Computer Science

[Return to Math 10 Homepage | Return to Notes Listing Page]

Contents


Variables and Types

It is not very useful or fun to write programs which merely print "Hello, how are you." Thus, we need more C/C++ concepts and structures.

DEFINITION: Variables are the names used to refer to information stored by the program in the computer. In concept and function, they are similar to Post Office Box numbers. They are ways of referring to memory locations and the information stored there. Variable names is any legitimate identifier in C/C++ and other languages.

DEFINITION: Type refers to fundamental differences and similarities in information employed by a program.

In general, we can distinguish between NUMERIC and NON-NUMERIC information.

C/C++ have several fundamental types.

   int   integer (whole number)			1, 2, 3, 4
   float real number (decimal point number)	3.1415926, 1.0, 3.5
   char	 character (letter, number, symbol)  	a, 5 (as a symbol), %
There are also variants of the numeric types.
	short			short integer (fewer digits)
	long or long int	long integer (more digits)
	double			double precision float
	long double		extra long float
	unsigned int		integer without plus or minus sign

Variable Declaration

In C/C++, variables must be declared before use. In other words, the program must be told that certain identifiers are used as variables, and which type they are. For the duration of the program, variables can only have ONE type, and the compiler must be told which type you want each variable to be.

In C/C++, variables can be declared in any block and they exist until the end of that block (i.e., within the enclosing { ... } ).

Although variables can be declared anywhere in a block (as long as they are declared before use), it is usual custom to declare all variables at the beginning of the block, i.e., immediately after the opening brace {.

In C/C++, variables are declared by indicating the type first, followed by the identifiers corresponding to the variables of that type (if there are more than one variable in the list, they are separated by commas).

	<type>  <identifier(s)> ;
        \----can be repeated----/
NOTE: <identifier(s)> can be a list of various C/C++ identifiers, separated by COMMAs.

EXAMPLE:

	int a,b,c,d;
	float orange;
        char name;

NOTE: Computers cannot second-guess humans. Misspellings (or mis-typings) of variables in a program will cause errors. If you see an error message, "identifier not declared," it could mean that you forgot to declare it before its use, or that you mis-typed it someplace.

Initialization

One can also initialize a variable, that is, give it an initial value when one declares it. This can be done as follows:
	double sum = 0.0;
	int    tot = 100;
This is not the same as declaring these variables to have an unchanging, constant value (that will be explained later). But it does make explicit and obvious what the starting values of these identifiers will be when the program begins execution. Without such initialization, starting values of all variables are undefined and, if the variables are not assigned a value before being referenced, a run-time error may occur.

Constants

We can include constants (i.e., specific values) of the same basic types as the variables. How do we write these constant values?
	integer	-	NO decimal point		-  123

	float	(1) fixed point - regular decimal point notation - 235.67
		(2) floating point - scientific or exponential
				notation -
		   235.67 = 2.3567x100 = 2.3567x102 = 2.3567e02

	chararacter  -	'7' or 'a' (i.e. the single character is
				enclosed in single quotes ')

Arithmetic Operations and "Assignments"

The four basic arithmetic operations have obvious symbols: +, -, /, and * (multiplication). C/C++ does not have a symbol of pair of symbol to indicate exponentiation as in some other languages (e.g., Fortran).

"Assignment" gives to a variable a specific value. This is NOT equality as in algebraic equations, although we frequently use it as such. Assignment is indicated by a using the equals sign, = . It can be interpreted (and pronounced) as "is set equal to" or "gets (replaced by)."

EXAMPLES:

			i = 2;
			a = 3*j + k/l;
NOTE: because "assignment" replaces an old memory value with a new one, an expression such as "n=n+1" is legal in C/C++ even though it may not seem to make much mathematical sense.

Increment Operators

Since the assignment i = i+1 (or i=i-1) occurs so often in certain mathematical applications programs, C/C++ have two special "unary" operators to perform this single increment or decrement.

++ is an operator that can be juxtaposed with any integer variable, either before or after (i.e., i++ or ++i). This increments the value of i by one, i.e., this is equivalent to i = i + 1,

-- is an operator similar to ++ which decreases the value by one.

NOTE: There are subtle and important differences as to how ++ (--) is used and they MUST be understood or they can lead to significant problems when used in assignment statement or elsewhere.

i++ indicates that i is incremented by one after its value has been used (if it is used). For example,

	i = 5;
	j = i++;
results in i receiving a new value of 6, but only after j receives the old value from i of 5. Such an effect occurs when the operator ++ is placed after the variable it increments.

On the other hand, ++i indicates that i is incremented by one before its value has been used (if it is used). For example,

	i = 5;
	j = ++i;
results in i receiving a new value of 6, and then j receives the new value from i of 6. Such an effect occurs when the operator ++ is placed before the variable it increments.

Output Values

To write out the value of a variable, one merely lists the identifier in an output expression after the << operator.

EXAMPLE:

			a = 2;
			cout << a << endl;
			cout << 'a' << endl;
			cout << 2 << endl;
OUTPUT
			|  |  |
			v  v  v
			 2
			 a
			 2

Another Sample Program

In particular, this program segment shows that what is important is the semi-colon to separate statements, rather than the new-lines.
		a = 2;
		b = 3;
		c = 2
			*a + b; cout << a << endl;
		cout << b; cout << c << b << endl;
		cout << c;
		d = b-a;
			cout   << a << d << c << b << endl;
		cout << a; cout << c << a << endl;
OUTPUT:
			|  |  |
			v  v  v
			2
			373
			72173
			272
NOTE: there are no spaces between the output values as one might hope or expect. The way to introduce spacing will be discussed later.

Operator Precedence

What is 2*3 + 1? (==> 7)

What is 1 + 2*3? (==> 7)

Why is this true? Why, in the second question, don't we first add 1+2 (to get 3) and then multiply by 3 (to get 9 instead of 7)?

Normal arithmetic has "precedence" rules, and the normal rules are that * and / are done first before + and -, unless the order is deliberately changed by parentheses.

In C/C++, FORTRAN, Pascal and many other languages, if two operators of the SAME precedence are in the same line, they are evaluated left to right (i.e., as one normally reads them). (We will mention the FORTRAN exception to this rule when we get to FORTRAN.)

If there is any chance of confusion, don't rely on the normal arithmetic rules of precedence (order of evaluation) -- use parentheses for safety's sake!

Type Conversions and "Casts"

One can convert information from one data type to another by using the new type name enclosed in parentheses. For example, if one wishes explicitly to convert 3.14159 to an integer obtaining the value 3, one can do the following:
		pi = 3.14159;
		i = (int) pi;
Whereas pi began with a value approximating pi, i receives the integer value of 3. The use of the type name in parentheses to convert the value which immediately follows is called a cast.

C++ also permits casting in the form of a function call, in other words enclosing the value in parentheses rather than the data type name. Thus, the previous two lines could be alternatively written as:

		pi = 3.14159;
		i = int(pi);

Proper use of casts can be important, particularly when one understands the rules associated with integer division. To avoid problems, one should explicitly convert numeric values (if appropriate) by means of a casting.

Integers and Division

The difference between the integer 1 and the float (real number) 1.0 is particularly noticeable in expressions involving division. (In reality, they are stored differently in memory, but that is a topic for another course.)

Unlike the language Pascal which has two different division operators ( / and div), C/C++ and FORTRAN only use the symbol / as the division operator, but it can have different meanings and give different results depending on the data type of the operands.

If the arguments to a quotient are both of type integer, then the output value will also be integer (any fractional part is ignored). If either argument is of type float, then the output value will also be float. (This rule also holds for the other arithmetic operators as well.)

EXAMPLES:

			9 / 5  ==>  1
			9 / 5.0  ==>  1.8
THUS (Beware!),
			3 * 8 / 9  ==> 2
			8 / 9 * 3  ==> 0
			3 * 8.0 / 9 ==> 2.66666	
Also, because of rules regarding operator precedence rules (namely, that equal precedence operators are evaluated left to right),
			15 / 4 * 5  ==>  15
			80/5/3.0    ==>  5.3333333
NOTE: You should always keep variables, constants and operators type-consistent.

There is another operator associated with integer division -- the modulus operator which is indicated by the percent sign %. (This has a meaning similar to the MOD operator in Pascal.) The modulus operator gives the result of the remainder after INTEGER division.

EXAMPLE

			9 % 5 ==> 4
			32 % 3 ==> 2

One needs to be careful in assigning values to variables. You will not get an error if, for example, you try to assign numeric values to a char variable. Problems can also occur with numeric inconsistency as well. It is legal to assign INTEGER values to REAL variables, and with most compilers it is also permitted to try to assign a REAL value to an INTEGER variable (what happens to the fractional part?).

EXAMPLE:

	#include<iostream.h>
	int main()
	 {char i; int j; float k;
		k = 109.01;
		j = k;
		i = j;
		cout << "int j=" << j << endl;
		cout << "real k=" << k << endl;
		cout << "char from int i=" << i << endl;
		i = k;
		cout << "char from real i=" << i << endl;
		return 0;
	}
OUTPUT:
		|  |  |
		v  v  v
		int j=109
		real k=109.01
		char from int i=m
		char from real i=m
NOTE: No error is given when the program executes, even though attempts are made (and actually succeed) in moving information from one data type into storage space reserved for a different data type. The results are different. Integer into float merely converts. Float into integer truncates the "decimal" section. Integer into character converts into the ASCII character according to the ASCII code. Float into character converts the number into the corresponding ASCII character.

Variable Field Width in cout Statements (Formatted Output)

If variables are listed alone in a cout statment, they are printed in certain 'default' field widths. As seen in an earlier example, for an integer value, the width is the number of digits in the number and no spaces are included between numbers.

There are various ways to override this default spacing and "format" the output.

Some manipulators are called "stream" manipulators since they are used as an element that follows the operator << in a cout "stream output" statement. To access these manipulators, one includes the header file iomanip.h.

Some manipulators can be used either as a standalone "member" function of the object cout or as an element that follows the operator << in a cout statement. Different books use different styles in describing manipulators but the results are the same, even though there might be a difference in the manipulator name between the "member" function version and the "stream" version.

Common "Stream" Manipulators: There are three common "steam" manipulators:

For example,
		cout << setprecision(2) << 3.14159 << endl;
would output 3.14 since the precision was set to 2 decimal places. We could force spacing by using the manipulator setw for example as in
		cout << setw(20) << "Hello"  << endl;
which would print "Hello" (5 characters long) right justified in a field of 20 spaces, thereby prefacing "Hello" with 15 blanks.

When using a manipulator as a "member" function of the object cout, one writes it after the object name cout and a period.

One common "member" function is cout.setf(...). This is used to set a flag for the output stream. The flags are listed within the parentheses following setf. The following are the most common:

Instead of using the member function setf, one can also use the stream manipulator setiosflags(...) with the same results.

As an example of using the manipulators,

	cout << setiosflags(ios::fixed); // forces fixed format
	cout.setf(ios::left); // forces left justification
One can use the member function cout.precision(n) as an alternative to the stream manipulator setprecision(n) with the same results.

Although manipulators are often used to determine the format of numeric output, remember that one can also use such manipulators for character variables and constants, particularly to force blank spaces (see earlier example).

Programming Style

  1. Mnemonic Variable Names

    In algebra, it is difficult to use variables with more than one letter. In programming languages, it is almost of necessity to use variables (identifiers) of more than one letter. Otherwise, you cannot keep your concepts straight.

    Make sure the identifiers you choose for your variables have obvious meaning. What does x mean?

    The problems that can arise with name is illustrated with the Abbott and Costello dialogue, "Who's on first." The basic problem is the (mis-) communication that goes on when "who" is a question word for one person but a man's name for the other.

  2. Physical Appearance of Code

    (a) INDENTATION - subsections (sometimes called 'blocks') should be indented. Some systems have a special program to do the work for you. (Unfortunately we don't have such a program on math, but the emacs editor will help indent appropriately when the tab key is pressed.)

    (b) COMMENTS - There should be 3 types of comments as mentioned in the Introduction (i.e., Notes N1).


This page is maintained by Dennis C. Smolarski, S.J. dsmolarski@math.scu.edu
© Copyright 1997, 1998, 2000 Dennis C. Smolarski, SJ, All rights reserved.
Last changed: 26 September 2000.