9: Programming in any language
- Page ID
- 40097
\( \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}}\) \( \newcommand{\AA}{\unicode[.8,0]{x212B}}\)
\( \newcommand{\vectorA}[1]{\vec{#1}} % arrow\)
\( \newcommand{\vectorAt}[1]{\vec{\text{#1}}} % arrow\)
\( \newcommand{\vectorB}[1]{\overset { \scriptstyle \rightharpoonup} {\mathbf{#1}} } \)
\( \newcommand{\vectorC}[1]{\textbf{#1}} \)
\( \newcommand{\vectorD}[1]{\overrightarrow{#1}} \)
\( \newcommand{\vectorDt}[1]{\overrightarrow{\text{#1}}} \)
\( \newcommand{\vectE}[1]{\overset{-\!-\!\rightharpoonup}{\vphantom{a}\smash{\mathbf {#1}}}} \)
\( \newcommand{\vecs}[1]{\overset { \scriptstyle \rightharpoonup} {\mathbf{#1}} } \)
\( \newcommand{\vecd}[1]{\overset{-\!-\!\rightharpoonup}{\vphantom{a}\smash {#1}}} \)
\(\newcommand{\avec}{\mathbf a}\) \(\newcommand{\bvec}{\mathbf b}\) \(\newcommand{\cvec}{\mathbf c}\) \(\newcommand{\dvec}{\mathbf d}\) \(\newcommand{\dtil}{\widetilde{\mathbf d}}\) \(\newcommand{\evec}{\mathbf e}\) \(\newcommand{\fvec}{\mathbf f}\) \(\newcommand{\nvec}{\mathbf n}\) \(\newcommand{\pvec}{\mathbf p}\) \(\newcommand{\qvec}{\mathbf q}\) \(\newcommand{\svec}{\mathbf s}\) \(\newcommand{\tvec}{\mathbf t}\) \(\newcommand{\uvec}{\mathbf u}\) \(\newcommand{\vvec}{\mathbf v}\) \(\newcommand{\wvec}{\mathbf w}\) \(\newcommand{\xvec}{\mathbf x}\) \(\newcommand{\yvec}{\mathbf y}\) \(\newcommand{\zvec}{\mathbf z}\) \(\newcommand{\rvec}{\mathbf r}\) \(\newcommand{\mvec}{\mathbf m}\) \(\newcommand{\zerovec}{\mathbf 0}\) \(\newcommand{\onevec}{\mathbf 1}\) \(\newcommand{\real}{\mathbb R}\) \(\newcommand{\twovec}[2]{\left[\begin{array}{r}#1 \\ #2 \end{array}\right]}\) \(\newcommand{\ctwovec}[2]{\left[\begin{array}{c}#1 \\ #2 \end{array}\right]}\) \(\newcommand{\threevec}[3]{\left[\begin{array}{r}#1 \\ #2 \\ #3 \end{array}\right]}\) \(\newcommand{\cthreevec}[3]{\left[\begin{array}{c}#1 \\ #2 \\ #3 \end{array}\right]}\) \(\newcommand{\fourvec}[4]{\left[\begin{array}{r}#1 \\ #2 \\ #3 \\ #4 \end{array}\right]}\) \(\newcommand{\cfourvec}[4]{\left[\begin{array}{c}#1 \\ #2 \\ #3 \\ #4 \end{array}\right]}\) \(\newcommand{\fivevec}[5]{\left[\begin{array}{r}#1 \\ #2 \\ #3 \\ #4 \\ #5 \\ \end{array}\right]}\) \(\newcommand{\cfivevec}[5]{\left[\begin{array}{c}#1 \\ #2 \\ #3 \\ #4 \\ #5 \\ \end{array}\right]}\) \(\newcommand{\mattwo}[4]{\left[\begin{array}{rr}#1 \amp #2 \\ #3 \amp #4 \\ \end{array}\right]}\) \(\newcommand{\laspan}[1]{\text{Span}\{#1\}}\) \(\newcommand{\bcal}{\cal B}\) \(\newcommand{\ccal}{\cal C}\) \(\newcommand{\scal}{\cal S}\) \(\newcommand{\wcal}{\cal W}\) \(\newcommand{\ecal}{\cal E}\) \(\newcommand{\coords}[2]{\left\{#1\right\}_{#2}}\) \(\newcommand{\gray}[1]{\color{gray}{#1}}\) \(\newcommand{\lgray}[1]{\color{lightgray}{#1}}\) \(\newcommand{\rank}{\operatorname{rank}}\) \(\newcommand{\row}{\text{Row}}\) \(\newcommand{\col}{\text{Col}}\) \(\renewcommand{\row}{\text{Row}}\) \(\newcommand{\nul}{\text{Nul}}\) \(\newcommand{\var}{\text{Var}}\) \(\newcommand{\corr}{\text{corr}}\) \(\newcommand{\len}[1]{\left|#1\right|}\) \(\newcommand{\bbar}{\overline{\bvec}}\) \(\newcommand{\bhat}{\widehat{\bvec}}\) \(\newcommand{\bperp}{\bvec^\perp}\) \(\newcommand{\xhat}{\widehat{\xvec}}\) \(\newcommand{\vhat}{\widehat{\vvec}}\) \(\newcommand{\uhat}{\widehat{\uvec}}\) \(\newcommand{\what}{\widehat{\wvec}}\) \(\newcommand{\Sighat}{\widehat{\Sigma}}\) \(\newcommand{\lt}{<}\) \(\newcommand{\gt}{>}\) \(\newcommand{\amp}{&}\) \(\definecolor{fillinmathshade}{gray}{0.9}\)Programming
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.
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
|
C++
|
Python
|
Octave/Matlab
|
IDL
|
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) |
<none> (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 |
string |
words |
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
- Addition, subtraction, multiplication, division, and the like
- ¬ 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
- Subroutines differ from functions in that their arguments include both the input and the output
- ¬ 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
- Loop statements can be used to process a set of statements a number of times
- ¬ 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
- Some languages can do this with pattern matching (the extinct language SNOBOL concept)
- ¬ 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.
9: Programming in any language is shared under a CC BY-NC-SA license and was authored, remixed, and/or curated by LibreTexts.