Day 5 (Part B) Material for the 7-day Computer Course

(Updated in October 2009 by Rituraj Kalita as per the syllabus. Copyright reserved.)

Elementary Programming Concepts

Computer programming, the art of designing useful programs (including the massive ones such as Microsoft Word and Adobe Photoshop) so as to be used by the end-users of computers, revolves around variables and constants. Variables (also called memory variables) may be thought of as memory locations wherein you can keep a constant (such as 3.00 or "Smith"), during programming. Every such variable must have a definite name (maximum 6 or 10 or more characters, depending on the programming language such as Fortran, C++, Basic, Visual Basic or FoxPro) that starts with an alphabet and may contain alphabets, digits (1 to 9) and underscore character ("_" sign, not allowed in Fortran) etc., examples of variable names being x, y, xx, xn, job, DA, Address1 etc. Generally, variable-names are case-insensitive, which means that it is immaterial whether you write the name in uppercase (capital letters), lowercase, or mixed case.

Variables can store constants, which may be of several types: (i) numeric (a number such as 3 or 4.2 or –5.6), (ii) character or string (a string or set of characters such as "gh5#*lk" or "Smith" or even "121"), (iii) date (a date such as Nov 28, 2003), (iv) logical, which may have only two values 'true' or 'false'. In a program, whenever a variable appears, it generally stands for the value of the constant it is storing at that instant. Depending on the type of constants they are storing, variables are also classified into the above-mentioned classes such as numeric, character, date, logical etc. (A character constant is always kept enclosed with either single quotes (i.e., ') – as in Fortran, or with double quotes (") – as in FoxPro, whereas a numeric constant is kept free.) Fortran also maintains a weird division between real and integer numeric constants and variables.

A variable is assigned a constant by using assignment statements such as A = 3 or Address1 = "Avenue 34". In such statements, the value of the RHS is assigned to a variable named in the LHS (left hand side). The RHS in such assignment statements may also contain an expression, i.e., a combination of variables and constants (such as 2*A + 3) instead of a pure constant. An expression involves variables and constants connected through operators such as +, –, * (multiplication), / (division) etc. as well as through functions such as sin, cos, asin, log, log10, sqrt etc. As assignment statements are not mathematical equations (though they sometimes look like them), so odd-looking lines such as A = A + 3 appear in computer programs in fully legal ways! A = A + 3 simply means that the old value of the (numeric) variable A plus the number 3 will now be stored as the new value of the variable A (in FoxPro or in Visual FoxPro, we can also write Store A + 3 to A to mean exactly the same activity). A computer program is a collection of several (generally too many) such lines, which are commonly executed one by one from top to bottom, unless there's any specific instruction in any of the lines to violate this top to bottom movement.

In addition to the assignment statement lines, a program invariably contains input statement and output statement lines. An input statement (such as READ(*,*) x,y in Fortran or Input xx, Accept char_1, @ 4,5 get x1 etc. in Visual FoxPro) allows the program to take up the value of a variable (or several variables) from a keyboard input (or from a disk-stored data file). You can type in your Yahoo! username and password to open your Yahoo! mail account because of some underlying input statements in Yahoo! website program. An output statement (such as WRITE(*,*) x,y in Fortran or ?xx,Address1 in FoxPro) allows the value of a variable to be displayed on the console (VDU or monitor), or to be stored in a data file (or to be printed by a printer). Together, these statements are called I/O (input/output) statements, and without them a program will have no communication with the user. One thing must be noted here about I/O statements: an I/O statement asking for a variable-value keyboard-input, or showing a variable-value as the output must in general be immediately preceded by an output statement that tells the user what user-input the program is asking for, or what program-output it is showing! Thus, had your mail account webpage (such as from Yahoo! or Rediff) provided you with just two blank spaces without their associated terms (i.e., User ID and Password) anywhere near it, you'd never have understood that you're required to fill in your username and password at these two blank spaces! The use of such associated fixed-output output statements will be obvious in the worked-out examples below.

Other than assignment and I/O statements, programs also contain conditional statement lines that control the direction of flow of program execution. Conditional statements generally appear in predefined groups in the form of conditional structures: (i) If - Else - Endif structures (ii) Do Case - Case1 - Case2 - Otherwise - Endcase structures (iii) Do - Enddo structures or Do loops. An If - Else - Endif structure starts with a 'If (Condition) Then' statement line (e.g., If A .GT. 20 Then in Fortran that means 'if A is greater than 20 then', as we know that .GT. , .LT. ,  .GE. , .LE. , .EQ. and .NE. are six 'comparison operators' in Fortran – on both sides of such a comparison operator sits a variable or a constant to be compared). If that stated condition is true, then the intervening lines between this line and the Else statement line is executed, but not the lines between the Else and the Endif line. If that condition is false, then execution goes to the line after the Else statement line, and the intervening lines between the Else and the Endif statement lines are executed. After the Endif statement, there is no effect of that If-Else-Endif structure to the execution of the following lines, and the normal downward flow of execution continues. In other words, the odd-looking word Endif  is necessary to demarcate the lines up to which the If-Else-Endif structure would have its effect. The Else statement line may however be missing in the structure, and in that case no lines are executed if the stated condition is false. (In some programming languages, the word Then in the If (Condition) Then line may not be explicitly present, in that case it is simply understood. Also, in some languages, there are one-line If - Endif structures allowed, in that case the Endif word may be absent but understood to be meant at the end of that line.)

The Do Case -- Case (Condition-1) - Case (Condition-2) ------ Otherwise -- Endcase structure is a generalisation of the If - Else - Endif structure, where the truth of a (J-th) condition stated in a Case (Condition-J) statement line governs whether the immediately following lines (till the next Case Condition… statement or the Otherwise statement line appears) will be executed. (In a Do Case .... Endcase structure, only the first encountered true-condition case is executed, even if a latter condition remains true.) In the face of such complicated mumbo-jumbo that I'm talking, how exactly a written program runs may look intriguing to you, but it can always be found out if you mentally sit in the place of the computer, executing statements and following the flow of program execution, just as if like the computer.

Do -- Enddo structures, starting with a Do statement line and ending with an Enddo (Continue in some languages such as in Fortran) statement line, results in several repeated executions of the intervening statement lines (based on some conditions stated somewhere). Because of their characteristic of repeating the intervening lines, this type of structures is called Do Loops. The do loops makes possible repeated operations, such as repeated multiplications in a factorial evaluation problem (for a natural number). The first line of this structure is a Do While (Condition) statement line in Visual FoxPro (the repeated execution of the intervening lines depending on this condition), or a Do 23 NN = NB, NE, NI type of statement line in Fortran (where NN, NB, NE, NI are numeric variable names with integral values stored therein, and 23 here refers to the Fortran-language line-number for the last, demarcating line of the do loop structure). So in FoxPro, the condition must involve at least one (or more) variable(s) that changes value during the execution of those intervening lines, so that program execution finally comes out of the loop. This will ensure that no infinite do-loop is encountered that plunges the computer into a meaningless, futile drudgery (in programming, unexpected and undesired formation of an infinite do loop is a common problem). In the above do… statement in Fortran, NN is a similar loop-defining variable that is auto-assigned the value of NB initially. This loop-variable automatically changes its value by the increment NI after every execution of the set of intervening lines, and finally the repeated execution of the loop gets stopped when its value crosses that of its final allowed value NE (and so, execution goes to the next line after the do loop). Note: Obviously, here you can keep any other variable name in the place of NN, and any numeric variables or constants in place of NB, NE & NI. The line-number just following the Do word may also have any integral value within 1 to 9999 instead of 23 here!

In some languages such as Fortran and (DOS) Batch-file programming language, loops that work just like do loops may also be formed by using the GO TO (line-number) statement line, at the end of the (virtual) loop. Existence of such GO TO (also written as GOTO) statements imply that there's a provision for numbering statement lines (offered by that language, say Fortran), and that such an GOTO statement orders the execution to go to that specific numbered line (somewhere up or down) in the program. The line-number here doesn't mean the physical number of the line in the program, but a programmer-assigned line-number (it may be any positive integer up to some maximum limit, say 9999), that is written at the left (beginning) part of a line (as in Fortran or Basic). It's obvious that such forced movement only in the upward direction will form a loop working like a do-loop. A GOTO statement is generally enclosed inside an IF-Else-Endif or a Do Case -......- Endcase structure, so that their execution is dependent on a proper condition.

Another provision present in all programming languages is that of comment lines: they're not executed by the computer but serves to explain the aim of and reasoning used in the program to the fellow programmers and to the programmer herself. A comment line generally starts with a * (asterix) character at the beginning of the line; Fortran allows C (only uppercase C) while FoxPro allows ! also as the starting character of a comment line (in Visual FoxPro, you can also write comment segments even at the end of any statement by following it with a && sign-pair, as shown in the illustrative examples). Even if no other programmer is working with you, you should put sufficient comments so that you understand your own programs several years later!

When you become able to write a meaningful program, the question of its execution comes. In modern forms of programming languages, you can run a written program by clicking at the Program menu, or by other methods from within the (Program) Design Environment. But the users using your created program must be provided with a self-executable file (with .exe or .com extension), which they can double-click to run the program. To make such a file, you need to create a project which must be supplied with the pathname of the main program file containing the main program (the main program may, in some cases, refer to other sub-programs and/ or subroutines). Then the project manager (it's not a human being) may be asked to build the executable .exe file, which it'll obediently do (in Visual FoxPro, enter the command Modify Project MyProj in the command window to invoke the project manager - here MyProj stands for the name of your project file). However, for a user at another computer to run your so-called self-executable program file successfully, the run-time form of the programming package (say, of Visual FoxPro 6 or of Visual Basic) need also be installed in the user's computer. After your program has been perfectly built and tested, such a run-time form inclusive complete program-installer may be generated by invoking the Setup Wizard within the software package.

Below are attached several working programs written in Visual FoxPro and Fortran languages. For some more examples, click at More Visual FoxPro, More Fortran, More Batch-file and at A big program in Visual FoxPro.
For a discussion of how Visual FoxPro does database management, click here.

* A Visual FoxPro Program to check whether a given number is prime
clear && clears the screen
close all && closes all pre-opened files
clear all && clears all pre-defined variables
on escape quit && instructs to shut down program if Esc key pressed by user
set talk off  && turns off undesired extra response to program statements
?   && creates empty line on screen
?" Program to check whether a given number is prime"
?
Input " Enter the number to be checked: " to number
?
if abs(int(number)) <> number
?" I'm in no mood of a joke!"
number = 0
endif
divisor = 2
Do while divisor <= sqrt(number)
dividend = (number / divisor)
If dividend = int(dividend)
?" The number is not prime!"
?
?" ",ltrim(str(number)), "=", ltrim(str(dividend)), "x", ;
ltrim(str(divisor))
divisor = sqrt(number) + 1
Endif
divisor = divisor + 1
Enddo
If divisor <> sqrt (number) + 2
?" The number is prime!"
Endif
?
?" Press any key, Click anywhere or Wait to finish.... "
out = inkey(60,'ms')
return

* A Visual FoxPro Program to find the roots of Ax2 + Bx + C = 0 
clear
close all
clear all
on escape quit
set talk off
?
?" Program to find the roots of Ax2 + Bx + C = 0"
?
?
input " Enter value of A: " to a
?
input " Enter value of B: " to b
?
input " Enter value of C: " to c
?
if a <> 0
if b*b >= 4*a*c
x1 = (-b + sqrt(b*b - 4*a*c))/(2*a)
x2 = (-b - sqrt(b*b - 4*a*c))/(2*a)
?
?" The values of X are:",x1," and",x2
else
?
?" No real roots exist!"
endif
else
?
?" The value of A can't be zero!"
endif
?
?" Press any key, Click anywhere or Wait to finish.... "
out = inkey(60,'ms')
return

C       T1  RULER  2  RULER  3  RULER  4  RULER  5  RULER  6  RULER  7
C2345  Fortran program to Find whether a given natural number is prime.
       WRITE(*,*) 'Give your input now i.e., the number:'
       READ(*,*) A
       A2 = A - 2.0
       AA2 = ABS(A2)
       WAA2 = ANINT (AA2)
       IF (WAA2 .NE. A2) THEN
         WRITE(*,*) 'Cannot you give a proper input?'
         GO TO 1001
       ELSE
         DIVSOR = 2.0
       ENDIF
 1     RATIO = A/DIVSOR
       IF(DIVSOR .GT. RATIO) THEN
         WRITE(*,*) ' Prime'
         GO TO 1001
       ELSE
         QUOTNT = ANINT(RATIO)
       ENDIF
       IF (QUOTNT .EQ. RATIO) THEN
         WRITE(*,*) ' Not prime'
         GO TO 1001
       ELSE
         DIVSOR = DIVSOR + 1.0
         GO TO 1
       ENDIF
 1001  STOP
       END

C2345 Fortran Program to solve a pair of linear co-equations
      WRITE(*,*) ' Program to solve a pair of linear co-equations'
  1   WRITE(*,*) ' Give your inputs now: A1, B1, C1, A2, B2, C2'
      READ(*,*) A1, B1, C1, A2, B2, C2
  6   DENOM = A1*B2 - A2*B1 
      IF (DENOM .EQ. 0.0) THEN
        WRITE(*,*) ' Inputs are not valid'
        GO TO 1001
      ELSE
        X = (B1*C2 - B2*C1)/DENOM
        Y = (C1*A2 - C2*A1)/DENOM
        WRITE(*,*) ' The results are :'
        WRITE(*,*) ' x = ',X,'  y = ',Y
      ENDIF
 1001 STOP
      END  

C2345 Finds the real roots, if any, of a quadratic equation
  1   WRITE(*,*) 'Enter quadratic-equation coefficients (a,b,c) now:'
      READ(*,*) A,B,C
      B24AC = B*B - 4.0*A*C
      IF (B24AC .LT. 0.0) THEN
        WRITE(*,*) 'The roots are complex!'
        GO TO 1001
      ENDIF
      ROOT1 = ( -B + SQRT(B24AC) )/(2.0*A)
      ROOT2 = ( -B - SQRT(B24AC) )/(2.0*A)
  999 WRITE(*,*) 'The two real roots of the quadratic equation are:'
 1000 WRITE(*,*) ROOT1, ROOT2
 1001 STOP
      END

C2345 Fortran program that performs linear least-square fitting
      WRITE(*,*) ' Program to perform linear least-square fitting'
      WRITE(*,*) ' '
      WRITE(*,*) ' Enter the number of data-points (say, 10):'
      READ(*,*) N
      IF (N .LE. 2) THEN
        WRITE(*,*) ' Too small number of data-points!'
        GO TO 1001
      ENDIF
      EN = FLOAT(N)
      SUMX = 0.0
      SUMY = 0.0
      SUMXY = 0.0
      SUMXX = 0.0
  21  WRITE(*,*) ' Enter the point-pairs (x,y) one by one' 
      WRITE(*,*) ' '
      DO 20 ICOUNT = 1,N,1
        WRITE(*,*) ' Enter the Point-Pair No.', ICOUNT
        READ(*,*) X, Y
        SUMX = SUMX + X
        SUMY = SUMY + Y
        SUMXY = SUMXY + X*Y
        SUMXX = SUMXX + X*X
  20  CONTINUE
      DENOM = EN*SUMXX - SUMX*SUMX
      EM = (EN*SUMXY - SUMX*SUMY)/DENOM
      C = (SUMY*SUMXX - SUMX*SUMXY)/DENOM
      WRITE(*,*) ' The least-square fitting y = mx + c is given by:'
      WRITE(*,*) ' m = ', EM, '  c = ',C
 1001 STOP
      END

C2345 Fortran program that performs a host of linear analysis
      SUMX = 0.0
      SUMY = 0.0
      SUMXY = 0.0
      SUMXSQ = 0.0
      SUMYSQ = 0.0
      WRITE(*,*) 'How many points are there ? '
      READ(*,*) EN
      EN2 = EN - 2.0
      WAEN2 = ANINT(ABS(EN2))
      IF (WAEN2.NE.EN2) THEN
        GO TO 1000
      ELSE
        N = IFIX(EN)
        ICOUNT = 0
      ENDIF
      WRITE(*,*) ' O.K., Give the point-pairs (x,y) now ' 
  1   ICOUNT = ICOUNT + 1
      IF (ICOUNT.GT.N) THEN
        GO TO 999
      ELSE
        WRITE(*,*) ' Enter a point-pair now: '
        READ(*,*) X, Y
        SUMX = SUMX + X
        SUMY = SUMY + Y
        SUMXY = SUMXY + X*Y
        SUMXSQ = SUMXSQ + X*X
        SUMYSQ = SUMYSQ + Y*Y
        GO TO 1
      ENDIF
 999  DIFF = EN*SUMXY - SUMX*SUMY
      DIFFX = EN*SUMXSQ - SUMX*SUMX
      DIFFY = EN*SUMYSQ - SUMY*SUMY
      IF(DIFFX .EQ. 0.0) GO TO 1000
      IF(DIFFY .EQ. 0.0) GO TO 1000
      WRITE(*,*) 'The number of data is:', N
      AVEX = SUMX/EN
      AVEY = SUMY/EN
      WRITE(*,*) 'The averages are:', AVEX , AVEY
      DEVX = SQRT(DIFFX)/EN
      DEVY = SQRT(DIFFY)/EN
      WRITE(*,*) 'The standard deviations are:', DEVX , DEVY
      CORREL = DIFF/SQRT(DIFFX*DIFFY)
      EM = DIFF/DIFFX
      C = (SUMY*SUMXSQ - SUMX*SUMXY)/DIFFX
      WRITE(*,*) 'The coefficient of correlation is:', CORREL
      WRITE(*,*) 'The least-square fitting is given by: '
      WRITE(*,*) 'm = ', EM, ' c = ',C
      GO TO 1001
 1000 WRITE(*,*) 'I am in no mood of a joke! '
 1001 STOP
      END