Programming 1, fall 2007 -- Demonstration 1

Note:The English exercise set (''demonstrations'') is a bit shortened from the Finnish version. The purpose is to support learning, and show the overall picture of what the Finnish students are doing during the fall. The course grade will be based on the exam only, but doing the exercises is recommended, as the exam is going to be exactly the same as the Finnish one, and based on the exercises of the course. (The only difference is that the questions are translated to English)

The first demonstration is anticipatory of the future work. It is important to understand the workings of the computer on a profound level in order to do programming. This starts with some knowledge about files, directories and the file system, data encodings and the proper way to produce plain text files (requisite of producing programming language source code files).

Contents

Computer usage

Every answer that you may produce during the fall, must be one of the following:

  • properly named "plain text" file, the name of which ends with the character string .txt (for example: introducing_myself.txt).
  • properly named Java compilation unit whose name ends with .java (proper naming in Java includes the aspect that the filename before .java must be exactly the name of the "public class" which is in the compilation unit. THE first example: HelloWorld.java)
  • A combination of plain text and/or Java source code files. (Demonstrations 6 or 7 at the earliest; until then, we make exactly one file per one answer)

Rules for safe file names:

There must be no spaces or special characters in filenames. Try to use only letters A-Z, a-z, 0-9, underscore ('_') or dash ('-') so that the first character of a filename is never a dash. Following these naming rules will help the files to be portable across different computer systems and storage medias.

Exercise 1:

If you don't yet know what these things are about, go find information about them, and learn the concepts:

  • file
  • file system
  • directory
  • directory tree
  • console-based computing (other names: text terminal, command prompt, shell)
  • working directory of a shell (or command prompt)

After learning the concepts, create a directory for the exercise answers of Programming 1. Create a subdirectory for demonstration 1, and already another one for demonstration 2. Your directory structure should become something like the following:

your_home_directory/programming1/
your_home_directory/programming1/demo1
your_home_directory/programming1/demo2

Exercise 2:

Write a plain text file in which you introduce yourself to your coursemates and tell something about your expectations regarding the course Programming 1. There has to be at least 80 and at most 150 words, and you have to have at least two separated paragraphs. What is important, is the format of the file:

  • You may not use an "office" software like MS Word or OpenOffice. They are for "word processing" and not for proper text editing. Use a proper text editor software, such as ConTEXT (free of charge, for Windows) or Emacs (free as in freedom -software, for almost any computer) or any other proper text editor.
  • No line shall be longer than 80 characters.
  • Each line must end with the end-of-line character (i.e., you have to explicitly press the "enter" key before there are 80 characters written; or you must remember to use an automatic formatting function of your text editor.)
  • You must not hyphenate words explicitly (if hyphenation is required, it is not to be done in the original text but in an automatically generated PDF print-out or such.)
  • There must be at least one empty line between paragraphs, and between headings and text.
  • Begin your text with a visible heading that tells what the text is about.

This is text editing. Always follow at least the above rules when producing plain text. Sometimes it is good to write even shorter lines than at most 80 characters. At most 70 or at most 60 can be chosen.

Almost everything we ever do in programming is producing text files -- programming language is always text, and usually it is done in some sort of a text editor. And people will read programs and documentation with text terminals and very small text windows within their do-it-all and see-a-million-windows-on-the-screen Integrated Development Environments. This necessitates the line length limit.

A recap: Programming, at the coding level, is producing text files (of the best attainable quality). The files always reside in a directory hierarchy in a file system. In order to make programs, we must be knowledgeable of this fact and feel comfortable with it.

Tools of the course

Exercise 3:

Make sure that in some place you have access to the minimal set of tools required by the course, and that you know how to use them:

  • A proper text editor program ("proper" means for example, that the editor can show a programming language text with the words highlighted (colored) according to their meaning in the language, and you have a good set of automation such as multilevel-undo, copy-paste, search-and-replace, ...)
  • Java 5 SDK (or Java 6; you need the SDK (Software Development Kit), which I think is called JDK (Java Development Kit) in the Java world).
  • A way to use Java tools from a command line (In windows, this means the Command Prompt program, and setting the environment variable PATH according to the JDK installation directories)
  • Connection to the Internet
  • (About half-way of the course, the Eclipse IDE may be taken as a tool; the first half is to be done with command-line JDK because this allows better grass-root level understanding of many important issues)

In the computer classrooms of Agora you will find all these. It is possible to get everything free-of-charge from the Internet, but installing and setting up everything at home has to be done wihtout guidance. Look in the Internet for how-to's, or ask a knowledgeable friend to install everything.

Try things out in practice:

  • Download the traditional first program in a programming language, this time Java:

    http://www.cc.jyu.fi/~nieminen/ohj1/HelloWorld.java

  • Using the command line tools of Java, compile the program into Java bytecode, and run it. The program for compiling is javac (java compiler); this is how it is used:

    java NameOfTheProgram.java
    

    Java programs are always run on top of the Java Virtual Machine. With JDK it is done using the command:

    java NameOfTheProgram
    

    The command is java and you should not include the filename extension .class when using java.

  • Your working directory must be the one in which your programs reside.

Syntax (or Grammar) for the first time

Exercise 4:

In order to make programs, you always need to follow a very strict syntax. In this exercise, there are some syntactically wrong "programs" in languages that you may not have ever seen. Without knowing more about the subject, try to guess the syntactic rules that have been broken, and fix each piece of text to be syntactically correct:

a):

f(x) = (2x + 1) / (x - 1

b):

(defun factorial (n)
  (if (= n 1)
     1
     (* n (factorial (- n 1)))
)

c):

% First slide of the syntax lecture:
  \begin{itemize}
\begin{slide}{ Syntax (grammar) }
     \item Why bother with learning syntax
     \item What does ''formal grammar'' mean in the first place
     \item What is the syntax of Java like.
  \end{itemize}
\end{slide}

d):

"Terrifying are the attent sleek thrushes on the lawn" is a
lines from a poem Ted Hughes by. It an example used in plenty of
english laguage textbook is.

Additional consideration: Think about the differences between the above languages. Can you fix the examples in multiple different ways to be syntactically correct, but having a different meaning?

Making changes to programs

Making changes to programs is possible even without complete knowledge about programming!

Exercise 5:

Before we have even considered programming, guess how to do the suggested changes in the below examples. Change the programs to function as requested.

You may try to compile and run the complete program b as you did in exercise 3. The program a is not complete, but you may try to turn it into a working program by looking at HelloWorld.java (in exercise 3) or the program b, and figuring out what additions seem to be necessary and done in the same way in all functioning Java programs.

  1. Change the following to output the word "Jippii" thirty times and not just ten, as it seems to do at the moment:

    ...
    for (int counter=1; counter <= 10; counter++){
        System.out.println("Jippii");
    }
    ...
    
  2. Change the following to ask for a third number and calculate it into the sum:

    /* In real life there should always be proper comments, but
     * I omit them from most of the exercises to save all the
     * copying/printing paper I can...
     */
    import java.util.Scanner;
    public class Summaaja{
        /** Asks for two numbers, and outputs their sum. */
        public static void main(String[] args){
            Scanner lukija = new Scanner(System.in);
    
            System.out.print("Input an integer number>");
            int luku1 = lukija.nextInt();
    
            System.out.print("Input another integer>");
            int luku2 = lukija.nextInt();
    
            int tulos = luku1 + luku2;
            System.out.printf("The sum of the integers is %d\n", tulos);
        }
    }
    

    Remember that in order to compile the above program, it's filename must be exactly Summaaja.java ("summaaja" is Finnish for "the thing that does addition").

Data representation in a Computer

Exercise 6:

In a computer, everything has to be encoded into numbers -- on the hardware level, actually in binary numbers where there are two digits: 0 and 1. Everything useful is then constructed from some ordered sets of numbers. All information is encoded in numbers, including the executable program code ("machine language") and all data (text, graphics, audio, animation) that the programs manipulate. It is important to understand hardware concepts because in today's world there seems to be no escape from executing computer programs with computers. We need to know what possibilities, limitations and pitfalls the computer as a device brings. Let us start with some transformations of binary numbers into the decimal system (the one with ten digits), that most of us learn in elementary schools.

In the binary system, a digit is called a bit (short for 'binary digit') The least significant bit (the rightmost to be written in a binary number) means the number one (as in "number or count of things"), the second least significant bit means the number two, third least significant means number 4 and so on, each time multiplying the previous by two (8, 16, 32, 64, ...). A complete binary number encodes a number. To find out what the decimal number representation that encodes the same number (as in the philosophical meaning of "how many things there are"!) you may compute the sum of the meanings of each bit in decimals. For example, the binary number 1000101 would be represented as follows in the 10-based number system:

1*64 + 0*32 + 0*16 + 0*8 + 1*4 + 0*2 + 1*1 == 69

As an exercise, transform the following binary numbers to the 10-based number system:

  1. 10110
  2. 1001100101
  3. 1000000000000000
  4. 1001010101010100
  5. 10000000000000001
  6. 10000000000000010
  7. 10000000000000011

In contemporary computers, the main memory (the place in which data is stored as bits during computations) is typically divided into memory locations that contain 8 bits each. This set of 8 bits is called a byte, and a byte usually has its own memory address. If you buy a computer with 512MB of memory, you buy a computer that can store approximately 500 000 bytes at the same time, at the most. (Of course programs may use the hard disk to store things temporarily; a hard disk contains a lot more space than the main memory, but is a lot slower to access).

Question: How many different numbers is it possible to store in a memory location of one byte? How many different numbers is it possible to store in a memory area consisting of two bytes? How about 4 bytes?

Preliminary consideration: What is the greatest positive number that fits in a two-byte storage area, if we disregard negative numbers?

Preliminary consideration 2: How would you invent the storage of negative integer numbers? What would be the largest and the smallest number that would fit in two bytes in your invented representation scheme? (You may already know how this is done in real life computers, in which case there is not much point in re-inventing it :-))

Algorithms

Exercise 7:

A computer program usually contains a set of subprograms, or in the Java terminology, methods, that perform some computations. (Other names for almost the same thing are "function" and "subroutine"). In order to be able to produce programs, you need to be familiar with the idea of an algorithm. An algorithm is a set of detailed instructions for completing a specified task. Let us think about algorithms in English first, and only later try to see how algorithms get to be implemented using a programming language.

For the following real-life tasks, divide the task coarsely into a set of subtasks, and divide each subtask into further, more detailed subtasks ("subsubtasks"). For this exercise, do only two levels, but realize that there is no limit to how much detail there could be... Consider microdetails like "move your hand left 10 cm; grip teapot; move your hand back to previous position" -- a computer needs low level instructions, but as a human you have to come from the top down to the programmable level by thinking through multiple levels of detail and finding a manageable set of subtasks for each task considered so far.

Try with the following real life tasks, providing two levels of subtask details in the English language (or better yet, your own native language!)

  1. Washing dishes

  2. Producing a cup of tea

  3. Sorting a deck of name tags ("Paavo Nieminen from JYU" etc., printed for the guests of a conference, for example) alphabetically by the surname of people.

  4. Getting a Yahtzee, i.e., 5 same numbers in the game of Yahtzee with a minimal number of dice rolls taking into account that each dice roll produces a random number from 1-6, which you find out only after the throw. You'll need to ''iterate'' somehow.

    In Yahtzee you throw 5 dice at first, and then you can choose to "lock" some of the numbers, leaving those dice untouched, and throw only the rest of the dice. In the game you have a maximum of three re-throws, but for our purpose there's no such limit. Each time you may change the lockings of previous dice on and off.