Skip to main content
Engineering LibreTexts

9: Programming in any language

  • Page ID
  • \( \newcommand{\vecs}[1]{\overset { \scriptstyle \rightharpoonup} {\mathbf{#1}} } \) \( \newcommand{\vecd}[1]{\overset{-\!-\!\rightharpoonup}{\vphantom{a}\smash {#1}}} \)\(\newcommand{\id}{\mathrm{id}}\) \( \newcommand{\Span}{\mathrm{span}}\) \( \newcommand{\kernel}{\mathrm{null}\,}\) \( \newcommand{\range}{\mathrm{range}\,}\) \( \newcommand{\RealPart}{\mathrm{Re}}\) \( \newcommand{\ImaginaryPart}{\mathrm{Im}}\) \( \newcommand{\Argument}{\mathrm{Arg}}\) \( \newcommand{\norm}[1]{\| #1 \|}\) \( \newcommand{\inner}[2]{\langle #1, #2 \rangle}\) \( \newcommand{\Span}{\mathrm{span}}\) \(\newcommand{\id}{\mathrm{id}}\) \( \newcommand{\Span}{\mathrm{span}}\) \( \newcommand{\kernel}{\mathrm{null}\,}\) \( \newcommand{\range}{\mathrm{range}\,}\) \( \newcommand{\RealPart}{\mathrm{Re}}\) \( \newcommand{\ImaginaryPart}{\mathrm{Im}}\) \( \newcommand{\Argument}{\mathrm{Arg}}\) \( \newcommand{\norm}[1]{\| #1 \|}\) \( \newcommand{\inner}[2]{\langle #1, #2 \rangle}\) \( \newcommand{\Span}{\mathrm{span}}\)


    To review, the purpose of programming on an electronic computer is to solve problems in a timely manner that are a difficult to solve by hand. Here we will review five languages as our examples: Octave (MatLab/Scilab), IDL1 (PV-Wave or GDL), Python, Fortran, and C++, with a heavy emphasis on Octave (the other languages are included to show similarities between these languages, as most languages are very similar).

    While you could, as examples, use Octave, Python, or IDL to just add, subtract, divide, or multiply numbers as a sort of calculator that is not the best use of programming languages. A calculator would be better for that sort of work. What makes programming languages powerful is variables, not dissimilar to variables in regular mathematics, especially "variables" that are structures which are reminiscence of matrices or matrices themselves (see parachute person).

    We will use Octave for the examples herein and other chapters to show what is being discussed in the text. Please run them and feel free to modify them and run them again (NB: your modifying the programs does not effect them for others...just you. So feel free to play.)

    • Here we do simple math in Octave which makes Octave a great calculator, but does not nearly demonstrate its true power.
    • Here we do simple math in Octave but add a variable component. This increase the power but still doesn't get to the full power of a programming language.
    x = 0;
    x = input("Enter degrees in radians ");
    printf("The sine of %f is %f\n",x,sin(x))

    In this last example we use a variable which we will discuss in the next mini-section.

    Numbers, variables, arrays, and other structures

    In general we would like our computer programs to provide the user with a method to do either complicated calculation, complicated string matching and pattern matching, or a combination of both of these. Everything a computer does we can do by hand but with less ease (though some might argue after struggling with a program that that is not true, but as your skill grows you will find that indeed it is true). In order to do these complicated calculations there must be a way to have and use variables. Variables in a computer languages work just like they do in mathematics (and other fields)...a way of expressing an unknown or many unknowns.

    Variables for calculations in computer languages are either declared as or given a specific type of number. A number (a scalar) in mathematics can be a counting number, an integer, a real number, a complex number, etc. In computers we have similar designations though the syntax differs depending on the programming language. The very basic data types are shown for a set of chosen languages below.

    Basic data types Fortran
    (mostly required)
    (doesn't exist)
    (doesn't exist)
    Your math class
    Integers integer int Python does this for you Octave does this for you int integers
    Real real float, double Python does this for you Octave makes all numbers <double> float, double real numbers
    Complex complex <none> Python does this for you (using j as the imaginary number) Octave does this for you (using either i or j as imaginary number)


    (Need to use a function)

    complex number (real and imaginary)
    String character (len=#) char var_name(len) Python does this for you Octave does this for you



    There are many other data types that you will learn as you become a more sophisticated programmer, but for now these are a good start. It is likely that for engineering and science programs a programmer will need to use matrices (or structures) with the numbers having a specific type like in the above table. For equations most programming languages allow you to write it just as you would in mathematics, however just solving one equation still is more like a calculator rather than a programming language. For more utility a programming language would allow you to loop, do conditional branches (if A do B or else do C), and input and output data. These type of statements are the program control statements. But first let us introduce operators and functions (which we have already used above but let's complete the discussion).

    Computer Operators

    Programming in any language requires operators (like + and -) to do useful functions. has three main control statements.

    • Just like in mathematics there are operands and operators
    • For most languages computer operators follow the same precedence as mathematics operators
    • Below we will briefly look at three of the most common operators
    ¬ Arithmetic operators
    • Addition, subtraction, multiplication, division, and the like
      • Addition, subtraction, and division look just like the do in ordinary mathematics
      • Multiplication is normally represent by the * symbol and taking something to a power can be either represented by a ^ symbol or a ** combination symbol depending on the language
      • In MATLAB/Octave/Scilab the * symbol can also mean matrix multiplication
        • If you want to do element by element multiplication on a matrix you would need to use .* combination symbol
        • In IDL the matrix multiplication symbol is a # and ## (IDL has a convention on matrices that is contrary to mathematics so the two symbols are needed; study up on IDL before you do matrices)
      • The ++ and -- are incremental addition or incremental subtraction
      • Some operators are represented as functions such as square root (sqrt)
    • Some of the arithmetic operators are strictly computer science oriented operators
    ¬ Relational operators
    • Operators that compare operands
    • Greater than, less then, greater than or equal to, equal to, and the like
    • Most languages just use the symbols we are familiar with (>, <, >=, <=, ==,!=)
      • A number of languages use the == for relational equals and = for assignment equals
      • The != relational operator is not equal to in computer parlance
    • Some languages use letters instead of symbols like EQ, GE, LE, GT, LT, and NE)
      • Sometimes the symbols must be contained by periods like .EQ.
      • Two of the languages we will focus on still use these symbols (IDL and Fortran)
    ¬ Logic operators
    • Performs logic operations (that is only 0 and 1)
    • Includes bitwise operators (using the bits of the operands) and short-circuit operators (operators that stop a process is an answer is already reached)
    • In Python the symbol ^ is used as a bitwise operator (XOR) so the ** combination symbol has to be used for powers
    • Bitwise operators are an advanced topic so we will just give a taste of this through Python
      • Python has the following bitwise operators x<<y shift left y places, x>>y shift right y places, x^y XOR, x|y bitwise OR, x&y bitwise AND, and ~x which returns the complement of x
      • In Python 2^4 is equal to six, that is because in binary 2 is 0010 and 4 is 0100 which when XORed is 0110 or 6
        • If you were expecting 16 then you wanted powers so you should have done 2**4 in Python
      • Bitwise operators are useful for image manipulation as well as just logic

    Computer Functions

    Programming in any language has functions like print or write.

    ¬ Functions
    • Functions are "programs" that do a single task like print or write
    • Functions include standard mathematical functions like sine and cosine (sin and cos) which is a good way to envision functions
    • Functions can be created by a user though some are given as default (like sin and cos)
    • Consists of a value output (can be null), the function name, and the arguments that you pass into the function
      • Example: ans = sin(pi/4) where the ans is the output and pi/4 is the input
      • Can have as many arguments as you need
      • Arguments can be passed by "value" or by "reference"
        • Some languages choose the method, some languages you can choose the method
      • Traditionally functions only had one output but that has changed as programming languages evolved
        • Example from a next chapter: function [t,v]=paraperson(ti,tf,vi,c,m,g,tsteps)
        • Function name: paraperson Output: t and v Input: ti,tf,vi,c,m,g,tsteps
    ¬ Subroutines
    • Subroutines differ from functions in that their arguments include both the input and the output
      • This feature was more relevant when function output was only one variable
      • Fortran has subroutine while most programming languages have shifted to calling subroutines functions
      • This is a callable unit (functions are callable unit as well)
    • Example: subroutine inverse(a,n,np,indx,y,yy)
      • To use: call inverse(dum,idatapnt,idatamax,indx,cminv,cm)
      • Subroutine name: inverse Output: cminv, cm Input: dum,idatapnt, idatamax,indx
    • There are some subtle differences between subroutines and functions in some languages
    ¬ Script
    • This is not really a piece of a program like a function or subroutine, but a quick program that you can do in interpreted languages
    • Scripts are not programs and do not substitute for programs
    • Scripts are convenient but not meant to do powerful work
    • In this class you should try to learn to program and avoid the use of scripts except for single use quick type calculations

    Control Statements

    Programming in any language has three main control statements.

    ¬ Loops
    • Loop statements can be used to process a set of statements a number of times
      • Do or For type statements process a set of statements a predetermined number of times
      • While, Until, DO while, etc. process a set of statements a certain number of times that depends on a condition that must be met
      • Loops can be placed inside other loops which programmers call "nested"
    • Some programming languages don't have loops per se but another method call recursion that can achieve the same result
    ¬ Conditionals
    • Conditional statements allow the user to control the process of different statements depending on certain conditions
    • This is very useful - as a simple example if you were dividing by a zero you would want to do something different for division by zero (given x/y if y is 0 then give error else do the division)
    • if, then, else statements is the most common syntax for a conditional statement
    • switch, case, or select statements are used for multiple conditional statements which is quite useful
      • Some languages can do this with pattern matching (the extinct language SNOBOL concept)
        • This concept is a little bit more sophisticated than a case statement
        • Since science and engineering is more about the numbers it is not as useful in those fields
      • Python is the only major programming language that does not have this feature which is not necessary but useful
    ¬ Input and output
    • Clearly without input and output programming would have no true use as you eventually want some sort of answer to your problems
    • Computers are not meant to be machines with no purpose, though it sometimes seem like some people view them that way
    • There are many many different types of commands for input and output so the list here is not complete
    • Display input and output
      • Some input and output statements are meant to go directly to your computer screen
      • Input: input, read, reads, scanf, gets, getchar, cin, etc.
      • Output: print, write, printf, puts, putchar, cout, etc.
    • File input and output
      • Some input and output statements are meant to go to a file on your computer, especially if there is a lot of input or a lot of output
      • Input: read, fscanf, fread, fgets, readf, readu, ifstream, etc.
      • Output: write, fprintf, fwrite, fputs, writef, writeu, ofstream, etc.
      • Input and Output: fstream
      • On a personal note: if you save a file of hundreds of numbers for a project, don't print them out to hand in - make a graph, please

    Below is a script example of each of the major control statements2

    • This is an example of a loop.
    for i = 1: 10
    	printf('This is a loop in Octave (or Scilab or Matlab)...counting numbers %i\n',i)
    • This is the example of a conditional statement, however it does have input and output as well.
    yn = input("Is engineering fun? (Y/N)","%s");
    if (yn == "Y" || yn == "y") 
    	printf("Yes engineering is fun!!!");
    • This is the example for input and output, however it does have a conditional statement as well.
    snumber = input("The input statement allows us to input numbers or letters.  How many suns do we have? ");
    if (snumber == 1)
    	printf("That is correct.\n");
        printf("An astronomy course is recommended for you.\n");
    name = input("My name is ","%s");
    printf("Hello %s, as you can see the printf statement is a form of output.\n",name);

    So we have used Octave (as our example program) as a fancy calculator (which has its uses) but we have not used the true power of Octave. The true power of a programming language is to write a program (or function).

    • This is an example of a function that has input and output, a conditional, and some loops. This is a different example of input and output where it uses a file (you are more likely to use files in "real world" work). Normally this program is saved in a file with an extension of name_of_program.m (or in this case readwritefile.m) and when you run it in octave you just run readwritefile(), but in this Libretext format we have the file a special area so you can see it, edit it (yes you can edit this - it won't be permanent) and run it.
    % Reading and writing files ("advanced" input and output)
    function nul = readwritefile()
    num1 = [1,2,3];
    num2 = [];
    sznum1 = size(num1);
    % Note there are many commands to write a file in octave including 
    % fprintf (which we use here), fputs, fwrite, dlmwrite, etc...
    % this does not include octaves own method of 
    % saving matricies (for a much faster access) of just "save"...the better way to go for 
    % mathematical work...
    fidw = fopen("testfile","w");
    for i = 1:sznum1(2)
        disp("Wrote in testfile"), disp(num1(i))
    end %for
    disp("File written and closed")
    disp("Now we will read it and print the result")
    % Note there are many commands to read a file in octave including 
    % fgets (which we use here), fread, fscanf, dlmread, importdata, etc....
    % this does not include ocaves own method of 
    % reading its matricies (for much faster access) of just "load"
    fidr = fopen("testfile","r");
    test = fgets(fidr);
        rnumber = str2num(test);
        num2 = [num2,rnumber];
        test = fgets(fidr);
    until(test == -1)
    for i = 1:sznum1(2)
    end %for
    disp("This is the end - JM")

    There are multiple languages to write programs in but herein we will just detail five languages. In order to do this we will show examples of the same routine written in different languages, starting with Octave (because it can run on in this format and it is an excellent language for engineers).

    Example of different languages

    In this section we will compare five languages (Octave, GDL, Python, Fortran, and C++) using the same routine for calculating a root of a number \(ans = \sqrt[n]{A}\). First the function as a simple Octave routine (this is not for comparison) as it should be written, but is not as good for an example.

    % Function to figure out roots: A^(1/n)  x0 is initial guess; 
    % tol is the tolerance that we are willing to accept
    % Example:  octave:2> root = nroot(20,3,2.2,1e-6)
    %           root =  2.7144
    function root=nroot(A,n,x0,tol)
    x2 = 1/n*[(n-1)*x0+A/(x0)^(n-1)];
    while (abs(x2-x1) >= tol)
       x2 = 1/n*[(n-1)*x1+A/(x1)^(n-1)];
    end %while
    return  % root

    Here we have a function that has all the inputs in the function itself, rather then asking the user to enter them one by one. In the next example we will ask questions rather than putting the inputs in the function. Doing this makes the program more interactive but it does not make it very reusable, so this is mostly for an academic exercise. If you were to use a function use the one above.

    % Function to figure out roots: A^(1/n) 
    % Need a tolerance for how close you want the answer to be
    % And an initial guess 
    % This is a demo program to show control structures in action while solving
    % a math problem (the nth root of A). While most programing languages
    % can do that without a program being written this is a method to examplify
    % writing simple program.
    function nul=control_root()
    base = input("What is your base? ");
    degree = input("What is the degree for the root you want? ");
    tol = input("What tolerance do you wish to work towards? ");
    guess = input("You will need an initial guess, what would it be? ");
    answr = 1/degree*((degree-1)*guess+base/guess^(degree-1));
    while (abs(answr-guess) >= tol)
       guess = answr;
       answr = 1/degree*((degree-1)*guess+base/guess^(degree-1));
    end %while
    printf("The answer is %g\n",answr);

    Note that the comments section (indicated by the %) are useful in Octave as that is where the help comes from.


    To compare the programming languages to each other we will first present the program and how it runs, then compare the programs to either Octave or Fortran.


    octave_program.png octave_run.png
    The program above is written in Octave, we have input and output, and a conditional and loop all in one (while statement). This is the run of the program on the left. First Octave itself has to be executed and then the program called control_root is executed in the Octave program.
    octave_program.png fortran_program.png
    Comparing the Octave program here to the Fortran program on the right shows some differences but a number of similarities. Octave does not have data declarations and combines the print and read statements (into input). But the equation is the same (except for the power symbol) and there is a similar while statement. Comparing Fortran to the Octave program on the left has some differences, but is essentially the same. The data declarations being the biggest difference.

    GDL (IDL)

    gdl_program.png gdl_run.png
    The program above is written in GDL, we have input and output, and a conditional and loop all in one (while statement) This is the run on the program on the left. First GDL itself has to be executed and then the program called control_root is executed in the GDL program. GDL is a freely available software that can run IDL programs. IDL is a common program at NASA/GSFC which is local to the Washington DC area. PV-Wave similar to IDL but is primarily used in California.
    gdl_program.png octave_program.png
    Comparing the GDL program here to an Octave program on the right shows some differences but a number of similarities. GDL is very much like Octave with similar function and motivations. Note there are no data declarations in either programming language because they are interpreted languages which in general declare on the fly. GDL does have some features that are reminiscent of Fortran (like the print and read). Comparing Octave to the GDL program on the left shows some differences but many more similarities.


    python_program.png python_run.png
    The program above is written in Python (Python 3 in this case), we have input and output, and a conditional and loop all in one (while statement). Because in Python input returns a string, the function float is used to convert it to a number. Most languages have commands to convert strings to numbers and numbers to strings. Please note how a program is written as most Python tutorials do not spend much time on the def command. This is the run of the program on the left. First Python itself has to be executed and then the program control_root has to be imported and then run. Python is a bit more complicated to run programs than either Octave or GDL.
    python_program.png octave_program.png
    Comparing the Python program here to an Octave program on right shows a lot more similarities then differences. One big difference is the indenting of the lines which are required for Python. Python does not have endwhile, or ends of any kind, so the way Python tells where the end of a loop is is by the indentation. Comparing Octave to the Python program on the left shows a lot more similarities then differences. Here input is used in a similar fashion for both of these programming languages. However, input in Octave by default returns a number and for Python it is always a string (hence the float commands). Octave's input can be made to produce a string with an additional parameter. Python is more natural for string manipulation; Octave is more natural in the numerical world - hence the popularity of Octave/MATLAB/Scilabs among engineers.


    cpp_program.png cpp_run.png
    The program above is written in C++ (not C which is different but very similar since C++ is a direct descendant of C), we have input and output, and a conditional and loop all in one (while statement). Note that C++ requires include statements to be able to do a lot of its functions like fabs, cin, and cout. You might also notice that this has data declarations like Fortran. This is the compiling, linking, and running of the program on the left. Note that g++ (open source C++) is used here. gcc is used for C, not for C++. The executable now can be shared with anyone who has a similar operating system without the user having a compiler. (Note the file ends in .cpp which is the convention for C++ files, if this was a C file it would end in .c, so look at the ending carefully).
    cpp_program.png fortran_program.png
    Comparing the C++ program here to the Fortran program on the right shows more similarities then they did to the interpretive language. C++ has data declarations like Fortran and does not have a combined print and read statement like Fortran. Comparing Fortran to the C++ program on the left has some differences, but is essentially the same.


    Fortran has already been compared to C++ and Octave so we will not do that here. We will just show the program and the run.

    fortran_program.png fortran_run.png

    The program above is written in Fortran (which is the same as used in the comparisons), we have input and output, and a conditional and loop all in one (while statement). Note that Fortran does not include include statements like C and C++. A number of Fortran's packages are presumed in linking. This makes Fortran easier for scientists and engineers and one of many reasons Fortran never seems to go away.

    Modern Fortran (2008 and beyond) does have a command that is similar to the C/C++ include called use which is associated with a module.

    This is the compiling, linking, and running of the program on the left. Note that gfortran is used here. The executable now can be shared with anyone who has a similar operating system without the user having to have a compiler.

    Comparison of programming languages (morale of previous section)

    • Most programming languages are very similar in looks
      • Syntax is the major difference with each programming language having its own unique syntax
      • Program flow is essentially the same in all the five languages introduced above
        • This is true for most languages
        • LISP and LabVIEW are notable exceptions
    • The main difference above beyond the syntax is the difference between the interpreted languages and the compiled languages
      • Interpreted languages like MATLAB/Octave/Scilab, Python, and IDL/GDL require another program to run before you can execute your functions
        • That is you cannot execute a function you have made in this languages without running the MATLAB/Octave/Scilab, Python, or IDL/GDL main program
        • Some of these programs do have a way of making a compilable executable but then this makes them a compiled language...
      • Compiled languages like C++ and Fortran do not require another program to execute on any similar machine (with the same OS)
        • Of course you need to compile it first so would need gcc or gfortran (or a similar compiler) before you send your executable to someone else
        • The advantage of the compiled executable is you can send your program to people who do not have a compiler

    End of chapter statement

    The conclusion to this section is that you can learn to program in any language as long as you have the basic ideas of programming. Hence programming in any language is in your grasp. So you might ask why should I learn how to program in any programming language when company XYZ says they only use Python? Company XYZ might not keep you on forever so what happens when you go to company ABC and they use Julia? Knowing how to program is like learning how to fish. Using the modern proverb originating from Anne Isabella Thackeray Ritchie \(\rightarrow\)If you give a person a fish, the person eats for a day; If you teach a person to fish, the person eats for a lifetime. Using the same philosophy, we can conclude that it is better to learn programming not learn a specific programming language. At least one author of this text has seen literally hundreds of new programming languages appear since University (of course, Fortran has been there and is still if you want one language, go for that).

    In the following chapter we will develop a program from a simple physics problem in order to demonstrate the process of writing a program for engineering (or science). It is limited in scope so as to gently introduce the concept however it will take effort on the students part...


    1Interactive Data Language (IDL) is primarily a local language for PG Community College because of its proximity to NASA/GSFC, other colleges or universities might want to substitute a different regional language. The other languages are global and relatively popular.

    2While scripts are good for educational purposes and quick calculations, they are not full fledged program which is the final goal. See parachute person for an example of a full fledged (albeit simple) program

    9: Programming in any language is shared under a CC BY-NC-SA license and was authored, remixed, and/or curated by LibreTexts.