Notes: Pascal/FORTRAN/C++ OVERVIEW/REVIEW

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

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


PRENOTE: These notes were compiled as a brief review and overview of the languages Pascal, FORTRAN-77, Fortran-90, and C/C++ for students beginning Math 61, Data Structures, taught in the Department of Mathematics and Computer Science at Santa Clara University. Such a review has been found particularly helpful for students who did not take the introductory course, Math 10, at Santa Clara or who took Math 10 the previous academic year and need a quick review.

These notes are NOT MEANT to be a complete summary of any of the languages.

In particular, these notes do not cover the following topics, which will be address in some detail in Math 61: arrays, records (classes and structures), recursion, pointers.


Contents

  1. Identifiers
  2. Program Skeleton
  3. Program Line Format
  4. Variables
  5. Arithmetic Operators
  6. Assignments
  7. Pascal and C++ Blocks
  8. Counted Loops
  9. Boolean/Logical Expressions
  10. Conditional Loops
  11. If Statements
  12. Multiple Choice
  13. Variable Scope
  14. Input/Output Functions
  15. Subprograms
  16. Sample Programs
  17. Additional Fortran Comments
  18. Additional References

1. Identifiers

In ALL languages, an identifier must begin with a LETTER and then any combination of letters and numbers may follow. (Fortran-90 and C++ also permit the inclusion of the underscore character after the initial letter of an identifier.) On most systems, there is no difference between upper-case and lower-case letters for Pascal or Fortran. C++ is "case-sensitive," so upper case and lower case letter are considered to be different.

The permitted length of identifiers is:

FORTRAN-77 ignores blanks, so blanks can be put between parts of an identifier name. When using Fortran-90, this rule also holds in "fixed source code format" files, but NOT in "free source code format."

2. Program Skeleton

Pascal

	PROGRAM progname(input,output);

	VAR ...
					
	{procedures and functions go here}

	BEGIN
		...
	END.

FORTRAN-77 or Fortran-90 "Fixed Source Code Form"

(column 	00000000011...
 numbers)	12345678901...
		      PROGRAM prognam
		C  variable declarations
		      INTEGER ....
		C	  
		       .....
		      STOP
		      END
		C  code for subroutines and functions
		      SUBROUTINE SUB1(ARG1,ARG2)
			...
		      RETURN
		      END
		C  more subroutines and functions go here

Fortran-90 "Free Source Code Form"

		PROGRAM prognam
		!  variable declarations
		INTEGER ....
		!	  
		.....
	        STOP
	        END
		!  code for subroutines and functions
	        SUBROUTINE SUB1(ARG1,ARG2)
		  ...
	        RETURN
	        END
		!  more subroutines and functions go here

C++

                #include<iostream.h>
		// other includes and global class declarations
		void sub1(int arg1, int arg2)
		{...
		}
		// other functions
		int main ()
		{    //variable declarations for the main program
		   ...
		}

3. Program Line Format

Pascal is "free-format." In Pascal this means you can put as much or as little as you want on any line. E.g., an arithmetic expression can be extended over several lines, or several equations can be put on one line. No special codes are required, except that a SEMI-COLON must separate every statement from the next one (except before an END). New lines are meaningless as statement separators. Comments are enclosed by either braces { ... } or by a special two-character parentheses adaptation (* ... *).

C++ is also "free-format." In C++ this means something very similar to what it means in Pascal. The difference is that with C++ the semi-colon ends a statement and must come after every statement, but is not needed after a closing brace. Comments are begun by a // and continue to the end of that line. Alternatively, one may begin a single or multi-line comment by /* and end it by */ as in standard C.

FORTRAN-77 and Fortran-90 "fixed source code format" is strictly formatted.

columns 1-5 are reserved for the statement number (similar to the line number in BASIC). Numbers are only necessary in special cases.

column 6 is unused, except to indicate that the present line is a continuation of the previous line (if something other than a blank occurs).

columns 7-72 are for FORTRAN statements.

columns 73-80(+) are ignored by the compiler.

If a C (or *) occurs in column 1, the line is considered to be a comment line.

In Fortran-90 "free source code format," as in Pascal and C++, statements may be put anywhere on a line. Longer expressions need to use an indicator, the ampersand, &, at the end of a line to indicate that the next line will be a continuation. Comments are begun anywhere on a line by the exclamation point, ! , and continue until the end of that line.

4. Variables

In Pascal, variables must be declared before use according to standard types (i.e., INTEGER, REAL, CHAR [single characters], or BOOLEAN) or user-defined types. The type follows the identifier list as follows:
  	VAR i,j:INTEGER;
	    a,b:REAL;
In C++, variables must be declared before use according to standard types (i.e., int, float, or char [single characters]) or user-defined types. The type precedes the identifier list as follows:
  	int i,j;
	float a,b;
In FORTRAN-77 or Fortran-90, numeric scalar variables may be explicitly declared. If not, they are "typed" according to the following default rules: Identifiers beginning with I through N (inclusive) are INteger. All others are real. E.g.,
	NUM, IN, KAP are all integer by default.
	X,Y,A,B2 are all real by default.
Double Precision, character, logical and complex variables must be declared (along with ALL arrays). As in C++, the type precedes the identifier list as follows:
	INTEGER I1,I2,X1,X2
	DOUBLE PRECISION A,B,C
NOTE on FORTRAN STYLE: contemporary style rules suggest that ALL FORTRAN variables should be explicitly declared and that nothing should be given a type by default. To turn off the default typing and force error messages when variables are not declared, use
        IMPLICIT NONE
before the first type declaration statement.

Fortran-90 style permits a double colon after the type name (and attributes), and before the list of identifiers. E.g.

        INTEGER :: I1, I2, X1, X2
	CHARACTER (LEN = 8) :: J, K
	REAL, DIMENSION(1:100) :: C
NOTE: Pascal and FORTRAN demand that all variables be declared before the first executable statement and do not permit additional declarations mixed with executable program code.
C++ permits new variables to be declared anywhere in the program before they are first used.

5. Arithmetic Operators

ALL languages have the standard: +, -, *, / .

FORTRAN also has ** for exponentiation, i.e., A**B <==> AB. In FORTRAN and C++, / works for integer divide and for real divide.

I.e., 3/2 ==> 1, 2/3 ==> 0
3/2.0 ==> 1.5, 2.0/3 ==> 0.6666667

Standard Pascal or C++ does NOT have an exponentiation operator, and in Pascal, div is the integer divide operator.

I.e., 3/2 ==> 1.5, 3 div 2 ==> 1

In addition, in Pascal, mod is an operator and not a function, as in FORTRAN. Using this operator results in the remainder after division. In C++, % is used as the mod operator.

E.g., in Pascal, 5 mod 3 ==> 2
In C++, 5 % 3 ==> 2
In FORTRAN, MOD(5,3) ==> 2

C++ also has an increment and decrement operators, whose symbols are ++ and --. i++ increases the value of i by 1, and i-- decreases its value.

6. Assignments

To assign a value to a variable, FORTRAN and C/C++ use the (plain) equals sign, = .
Pascal uses a double symbol, the colon-equals, := , with OUT any space in between. It is frequently read as "gets."

7. Pascal and C++ Blocks

In Pascal, groups of statements are enclosed as a block with the reserved words BEGIN and END. C++ does the same with braces, { ... }. In a sense they form a set of parentheses around a group of statement so that the block is considered as one unit and can be used in structures whenever the structure definition allows a single statement.

FORTRAN has no need for the BEGIN, because of different forms for structures. Some FORTRAN statements have a variant of an END (e.g., END IF or END DO), or other statement terminator.

8. Counted Loops

In Pascal, the counted loop key word is FOR. E.g.,
	FOR i := 1 TO 9 DO
		BEGIN ... END;
-or-
	FOR i := 20 DOWNTO 5 DO
		BEGIN ... END;
NOTE that no step size is possible in Pascal.

In FORTRAN, the counted loop key word is DO. The terminating statement in FORTRAN-77 is NORMALLY a "CONTINUE" statement, although technically it can be any executable statement. The FORTRAN-77 version uses a statement label after the DO which is the label of the terminating statement.
Starting with FORTRAN-77, the begin and end values could be real, and, given a negative step, the DO-loop can also count down (not permitted in earlier versions). E.g.,

	DO 102 I=1,9,2
		...
  102	CONTINUE
This repeats the statements interior to the structure with I starting at a value of 1, with step value of 2 (i.e., each time through the loop, I gets incremented by 2), and final value of 9.

In Fortran-90, the statement label could be omitted, and the loop ends with the END DO statement. E.g.,

        DO I=1,9,2
	     ...
	END DO
In C++, the header structure, a for statement, has three sections, the first being the initialization part, the middle section being the testing condition, and the final part being the incrementation part. E.g.,
        for ( i = 1; i <= 9 ; i=i+2)
	{ ...
	 }

9. Boolean/Logical Expressions

Pascal, C++, Fortran-90 use symbols for relational operators.
FORTRAN-77 uses 2 letter codes surrounded by periods.
Pascal        <      >    <=    >=    =     <>
C++           <      >    <=    >=    ==    !=
FORTRAN	     .LT.  .GT.  .LE.  .GE.  .EQ.  .NE.
Fortran-90    <      >    <=    >=    ==    /=
Boolean/Logical Constants
Pascal	 true	 false
FORTRAN	.TRUE.	.FALSE.
C++       1       0
Other operators
Pascal	   not	   and	   or
FORTRAN	  .NOT.	  .AND.	  .OR.
C++         !      &&      ||

10. Conditional Loops

Pascal has two conditional loops--these loops are not based on the explicit value of a variable, but on a boolean/logical condition. The two loops differ as to when the test is performed and whether the loops continues as long as the condition is true or the condition is false.
	WHILE a < b DO
		BEGIN...END;
As long as the condition (e.g., a < b ) is TRUE, this WHILE loop is repeated.
	REPEAT
		...
	UNTIL a > b;
As long as the condition (e.g. a > b) is FALSE, this REPEAT loop is repeated (i.e., it is repeated only UNTIL the condition becomes TRUE).

FORTRAN-77 had neither loop, although both could be imitated with an IF and a GO TO.

Fortran-90 has a conditional loop and a general loop whose operations model the Pascal WHILE loop:
DO WHILE

	DO WHILE (A <= B)
		...
	END DO
The general loop requires an internal IF statement with an EXIT statement which which causes a termination of the loop.
General Loop
	DO 
	   ...
	   IF (A <= B) EXIT
	   ...
	END DO
The C++ for loop can be used in a more general fashion as a while loop by leaving the initialization and incrementation clauses blank.

C++ also has a while loop and a do ... while loop:
while

        while ( a < b )
	{ ...
	}
do ... while
	do
	{ ...
	}
        while ( a < b )
NOTE that the C++ do ... while loop is NOT the same as the Fortran-90 DO WHILE. The Fortran-90 loop is operationally identical to the C++ and Pascal while loops.

11. If Statements

NOTE: The use of square brackets in the examples below are meant to indicate OPTIONAL sections of the structure. The brackets themselves are NOT to be included in the code.

Pascal

	IF a < b THEN 
	    BEGIN ... END
	[ELSE
            BEGIN ... END ]
FORTRAN
	IF (A < B) THEN
	    ...
	[ELSE]
	    ...
	END IF
-or-
	IF (A .LT. B) 

-or- "arithmetic IF"
	IF (numeric value)101,102,103
if the numeric value is less than zero, the program continues from statement 101, if it equals zero, it continues from 102, else (if greater than zero), it continues from 103.

C++

        if (a < b)
	{ ... }
	[else
	{ ... } ]

12. Multiple Choice

Pascal uses a CASE statement to choose between multiple alternatives. E.g.,
	CASE i OF
	    1 : action1;
	    2 : action2;
	    3,4 : action34;
	END
If i has the value of 1, action1 is done and the rest are omitted. Similarly with the other values.

FORTRAN-77 has no comparable statement, but the program flow can be simulated by repeated IF ... ELSE IF ... statements.

Fortran-90 uses a SELECT CASE statement. E.g.,

	SELECT CASE (I)
	    CASE(1)
		 action1
	    CASE(2)
	         action2
	    CASE(3:4)
		 action34
	    CASE DEFAULT
	         actiondef
	END SELECT
C++ uses a switch statement. Note that the C/C++ switch statement needs a break command at the end of each option to exit from the structure. Otherwise, the program flow will go to the statements in the next option rather than to the statements after the switch structure.
        switch (i)
	{
	    case (1) : action1; break;
	    case (2) : action2; break;
	    case (3) : case (4) : action34; break;
	    default  : actiondef;
	 }

13. Variable Scope

Pascal variables are defined for the body in which they are declared and all interior structures. In other words, variables declared in the main program are also "visible" in a subprogram, unless they are re-declared. However, variables declared within a subprogram are not visible to the main program.

FORTRAN variables are all LOCAL.

C/C++ variables are all LOCAL if they are declared within a function or the main program. They are "global" if they are declared outside any function code, between the #include statements and the first function. Declaring variables globally is legal but a discouraged practice.

14. Input/Output Functions

Pascal: There are two I/O functions: read and write. If you wish to force a carriage return after a read or write, use readln or writeln instead. There are no FORMAT statements in Pascal--the 'formatting' takes place within the write/read statement.

What is read/written is put in parentheses after the keyword. Character strings are surrounded by single quotes. Everything can have a field width specified (else a machine-dependent default width is used). E.g.,

	writeln('a=',a:5:2,' i=',i:2,' ':10,'xx')
		       ^^#1             ^^#2
#1 - the 5 indicates 5 spaces for the variable a, and the 2 indicates that of those 5 spaces two will be reserved for digits to the right of the decimal point.
#2 - the 10 indicates that the single blank character will be printed in a field of 10 spaces, thereby forcing 10 blanks before the last 'xx' of the line.

FORTRAN uses WRITE and READ. After the key word come parentheses with (usually) two numbers: the first referring to the output/input device and the second to the FORMAT number. The first number is 5 (for a READ) if referring to the keyboard, 6 (for a WRITE) if referring to the monitor, or (at SCU on the DEC Alpha) 20-25 if referring to a file FOR020.DAT, etc. One can omit the FORMAT number and put an asterisk, thereby forcing a 'Pascal-like' or 'C++-like' 'free' formatting to take place.

The FORTRAN FORMAT statement contains the 'field descriptors' corresponding to the variables listed in the READ/WRITE statement. The field descriptor indicates the type of variable along with the field width, e.g. I4 indicates an INTEGER with field width 4; F10.4 indicates a FIXED real number with width 10, and of those 10 places, 4 will be decimal places.

C++ uses "stream" I/O, composed of two parts: (1) The file/device name, and (2) the I/O operators.

File/Device names
cout refers to standard output (i.e., the monitor), but one may declare another identifier (e.g., Outfile) to refer to a disk file.
cin refers to standard input (i.e., the keyboard), but one may declare another identifier (e.g., Infile) to refer to a disk file.

I/O operators
<< is the output operator and must precede any variable or character string or function that goes into the output stream.
>> is the input operator and must precede any identifier which receives a new values from the next value in the input stream.

For example,
        cout << "a=" << a << endl;
	cin >> a >> b >> c;
Note that endl is a stream function which forces a new line in the output.

NOTE that C++ may also make use of the standard C library of I/O functions (including scanf and printf). For more information, see this link.

15. Subprograms

In Pascal, 'Procedures' and functions are written according to the same rules as for main programs, except that the header uses the reserved word 'procedure' or 'function' instead of 'program.' The code must come BEFORE it is called. Procedures are called by name ALONE, without the FORTRAN statement 'CALL sub1'.

In FORTRAN, 'SUBROUTINES' and functions are written as in Pascal. The code comes AFTER that of the main program. SUBROUTINEs are called via the statement 'CALL ...' In FORTRAN, the last statement before the END should be a RETURN.

In Pascal and FORTRAN, the value returned by a FUNCTION is assigned within the function to the function's name, which internally is a local variable.

In C++, "void" functions (corresponding to "procedures" or SUBROUTINES) and "valued" functions (corresponding to "functions") are written as in the other languages. No special keyword is needed, but the data type must be put before the name of the routine (or the word void used in the case of functions returning no one specific value, i.e., what Pascal calls a "procedure").

In C++, the value which a function returns is indicated in a return after the keyword return.

In C++ and Pascal by default, parameters are passed via "call by value," in which the value of the actual arguments are copied to the subprogram's parameters but do not affect the actual arguments when the subprogram finishes.
In C++ and Pascal, any parameter can be designated to be a "variable" parameter, or a "call by address/reference" parameter. In Pascal, one adds the keyword var before any variable parameter and in C++, one places the ampersand, &, between the type and the identifier. Such parameters use the memory location of the actual arguments, which are changed when the subprogram finishes, if the subprogram should modify the corresponding parameter.
In Fortran, scalar variables are usually "call by value-result" in which the value of the actual parameter is copied to the subprogram's parameter but any changes are copied back to the actual parameter when the subprogram finishes. Arrays are passed as "call by address/reference" parameters. There is no way to change either default method.

16. Sample Programs

Pascal

	program sample(input,output);

	var a,b,c:real;
	    root1,root2:real;

	procedure roots(a,b,c:real; var x1,x2:real);
	var rad:real;
	begin
		rad := sqrt(b*b-4*a*c);
		x1 := (-b+rad)/(2*a);
		x2 := (-b-rad)/(2*a)
	end;
	
	begin (* main program *)
		a :=1; b:=2; c:=-3;
		roots(a,b,c,root1,root2);
		writeln('The roots of ',a:3:1,'x*x+',
			b:3:1,'x+',c:3:1,' are ',
			root1:5:2,' and ',root2:5:2)
	end.

FORTRAN (Fixed Source Code)

		PROGRAM SAMPLE
		REAL A,B,C,ROOT1,ROOT2
		A=1
		B=2
		C=-3
		CALL ROOTS(A,B,C,ROOT1,ROOT2)
		WRITE(5,102)A,B,C,ROOT1,ROOT2
	  102	FORMAT(1X,'The roots of ',F3.1,'x*x+',F3.1,
	       1	'x+',F3.1,' are ',F5.2,' and ',F5.2)
		STOP
		END
	  C
		SUBROUTINE ROOTS(A,B,C,X1,X2)
		REAL A,B,C,X1,X2,RAD
		RAD=SQRT(B*B-4*A*C)
		X1=(-B+RAD)/(2.0*A)
		X2=(-B-RAD)/(2.0*A)
		RETURN
		END

FORTRAN (Free Source Code)

		PROGRAM SAMPLE
		REAL A,B,C,ROOT1,ROOT2
		A=1
		B=2
		C=-3
		CALL ROOTS(A,B,C,ROOT1,ROOT2)
		WRITE(5,102)A,B,C,ROOT1,ROOT2
		102 FORMAT(1X,'The roots of ',F3.1,'x*x+',F3.1, &
	    	    'x+',F3.1,' are ',F5.2,' and ',F5.2)
		STOP
		END
		!
		SUBROUTINE ROOTS(A,B,C,X1,X2)
		REAL A,B,C,X1,X2,RAD
		RAD=SQRT(B*B-4*A*C)
		X1=(-B+RAD)/(2.0*A)
		X2=(-B-RAD)/(2.0*A)
		RETURN
		END

C++

        #include<stdio.h>
	#include<math.h>
        #include<iostream.h>
	       
	void roots(float a,float b,float c,float & x1,float & x2)
	    {float rad;

	    rad = sqrt(b*b-4*a*c);
	    x1 = (-b+rad)/(2*a);
	    x2 = (-b-rad)/(2*a);
	    }

       int main()
           {
	   float a,b,c;
	   float root1,root2;

	   a = 1;
	   b = 2;
	   c = -3;	   
	   roots(a,b,c,root1,root2);
	   cout << "The roots of " << a << " x*x+ " << b ;
	   cout << "x+ " << c << " are " 
		<< root1 << " and " << root2 << endl ;
	  // alternate output statement
	   printf("The roots of %3.1f x*x+ %3.1f \
	     x+ %3.1f are %5.2f and %5.2f\n",
	     a,b,c,root1,root2);
	   return 0;
	   }

17. Additional Fortran Comments

To avoid programming problems with FORTRAN, only use GO TOs when imitating Pascal statements (e.g. WHILEs, REPEATS, CASEs). Otherwise, FORTRAN degenerates into spaghetti code, for the most part unreadable.

FORTRAN is very flexible with many of its structures, and their relative order. In the following figure, vertical lines separate statement types that can be interspersed. For example, DATA statements can be interspersed with executable statements. Horizontal lines indicate statement types that cannot be interspersed. For example, type declaration statements cannot be interspersed with executable statements.

     +-------+-------------------------------------------------------+
     |       |              OPTIONS Statement                        |
     |       |-------------------------------------------------------|
     |       |PROGRAM, FUNCTION, SUBROUTINE, or BLOCK DATA Statements|
     |       |--------+----------------------------------------------|
     |COMMENT|        |  IMPLICIT NONE Statement                     |
     | lines |        |------------------------------+---------------|
     |   &   |NAMELIST|  IMPLICIT Statements         |               |
     |INCLUDE| FORMAT |------+-----------------------|   PARAMETER   |
     |State- |   &    |      | Other Specification   |   Statements  |
     | ments | ENTRY  | DATA |      Statements       |               |
     |       | State- |State-|-----------------------+---------------|
     |       |  ments | ments|   Statement Function Definitions      |
     |       |        |      |---------------------------------------|
     |       |        |      |       Executable Statements           |
     |-------+--------+------+---------------------------------------|
     |                    END Statement                              |
     +---------------------------------------------------------------+

18. Additional References

For slightly more detailed references on Fortran, see this link to CSCI 10 Lecture Notes on FORTRAN 77 and Fortran 90.

For more detailed references on C++, see the homepage for CSCI 10, containing links to Lecture Notes on C++ and other references.


This page is maintained by Dennis C. Smolarski, S.J. dsmolarski "at" scu.edu
© Copyright 1987, 1998 Dennis C. Smolarski, SJ, All rights reserved.
Last changed: 4 March 1998. Minor changes: 28 February 2011.