Welcome to Higher Computing 1B

Also known as COMP1721

Andrew Taylor

andrewt@cse.unsw.edu.au


Objectives

This subject introduces:

After completing this subject, you should be able to:


Prerequisites

COMP1011 or COMP1711 is a prerequisite for COMP1721/COMP2811.

If you failed COMP1011 or COMP1711, you must repeat COMP1011 and pass it before taking COMP1021.

If you passed COMP1011 or COMP1711 but obtained a mark less than 75% can only enrol in COMP1021 not COMP1721.

You can check your enrollment at:

https://www.student.online.unsw.edu.au/student/


Lectures

Lecture Times
DayTimeRoom
Thursday11:00-12:00EE LG1
Thursday13:00-14:00EE LG1
Friday12:00-13:00EE LG1

Subject Materials

All subject materials will be placed on the class web page:

http://www.cse.unsw.edu.au/~cs1721/

Urgent information will be sent by e-mail.


Tutorial and Laboratory Class Allocation

Use NSS to change your tute-lab allocation

https://www.student.online.unsw.edu.au/student/

Do so by Sunday.

Choose carefully!

Tute/labs begin in week 2.


Accelerated Labs

Two accelerated tut-labs will be run.

These are for students who would find the pace of COMP1721 far too slow.

If you have a HD from 1011/1711 and experience with C or similar languages, you may wish to attend an accelerated tute-lab.

Tentative times on class web page.


Assessment Summary

The assessable components of the subject are: Plus:

Final Exam

Part of the final exam will be held on-line in the CSE computer labs.

The exam questions will ask you to write all or part of a C program.

You will be able to compile and test your answers.

The rest of the final exam will be on paper.

Part of the exam will be shared with COMP1021.


Textbooks

The textbook for Computing 1B is

The C Programming Language, Second Edition

by Brian Kernighan and Dennis Ritchie, 2nd Edition.


Other C Books

There are hundreds of bad books on C.

If you wish to purchase second C book look at:


Top 10 Ways to Piss off your Lecturer

  1. Don't think, just take notes in lectures/tutorials.
  2. Don't participate in tutorials.
  3. Skip lectures or tutes and then ask for help.
  4. Ask "Is this on the exam?".
  5. Don't explore .
  6. Don't do the lab exercises.
  7. Copy someone else's lab exercises.
  8. Talk in lectures.
  9. Disrupt lectures with mobile phones/laser pointers.
  10. Cheat on assignments.

C, What is it Good For?

C is good for:

For many applications you are better off using one of sh, perl, Prolog, Haskell, Java, ...


C - Phylogeny


C - Ontogeny

See http://cm.bell-labs.com/cm/cs/who/dmr/chist.html for more detail.


C Offspring


Why has Computing 1B changed to Java from C


A C Program


#include <stdio.h>

int
main(void) {
    printf("Hello world.\n");
    return 0;
}


Functional vs Procedural Programming

Consider this Haskell function.

square x = x * x

It is essentially an equation and a Haskell program is essentially a set of equations.

We say functional programming languages such as Haskell are declarative.

A Haskell program defines more what is to be computed rather than how to compute it.


Functional vs Procedural Programming

Programs in procedural programming language such as C, Basic, Pascal or Java give a sequence of operations (actions) to produce result.

A C program must defines explicitly how to compute a result.

We say procedural programming languages such as C are imperative.


Programs and States

Procedural programs work by state-change.

The state of a program:

The program comprises:

State is dynamic; program is static.


Variables

Variables are ``containers'' that hold values.

Variables are implemented as memory cells.

Each variable has three properties:

Variables are defined by giving name, type and (optionally) an initial value.

int    i, j, k;
int    x, y, z;
char   ch, ch1;
double length, width;


Names

Names are used to identify variables and other components of C programs. They must start with a letter followed by letters, digits or both. The characters '_' may also appear in names.

Some examples:

i              j12               X
nchars         numberOfChars   Student
square_root    squareRoot      Bool
Upper and lower case are distinguished.

C has 32 reserved words (keywords) that you cannot use as names.


Keywords

These are reserved words in C and can not be used as identifiers:


auto break case char const continue default do double else enum extern float for goto if int long register return short signed sizeof static struct switch typedef union unsigned void volatile while

Its best to avoid these C++ keywords as well:


asm bool catch class const_cast delete dynamic_cast explicit false friend inline mutable namespace new operator private protected public reinterpret_cast static_cast template this throw true try typeid typename using virtual wchar_t

Assignment

Procedural programming is about ``state change''.

Assignment is the basic state-change operation.

Syntax: var = expression ;

E.g. i = 0; sets current value of i to zero.

If the value is not quite the right type, it may be converted.


Functional programming is not about ``state change''.

The operator = in Haskell implies equality not state change.

For example, this is not legal Haskell:


f x = a + b
      where
        y = x - 1
        a = y^2
        y = x + 1
        b = y^2


We are not assigning a value to y in the above Haskell function.

We are making a declarative statement that y is equal to another expression.


Summing the first 1000 integers

Here is an example of developing a program to solve a very simple problem:

``Compute the sum of the first 1000 integers''

Our overall approach for solving it:

Note Haskell solution:

    sum [1..1000]


Summing the first 1000 integers

Problem:

``Compute the sum of the first 1000 integers''

How would you do it e.g. using a hand-held non-programmable calculator?

   clear calculator display
   press 1
   press +
   press 2
   press +
   press 3
   press +
   ...
   press 1000
   press =


Summing the first 1000 integers

We can follow the same approach in C but it is very impractical because it requires 1001 statements:
total = 0;
total = total + 1;
total = total + 2;
total = total + 3;
total = total + 4;
total = total + 5;
total = total + 6;
....

....
total = total + 1000;
....


Summing the first 1000 integers

A better approach requires realising that two quantities are involved:

In each repetition


Summing the first 1000 integers

To be more precise

In C:

Thus, we write:

    total = total + number;
    number = number + 1;


Summing the first 1000 integers

The counters total and number

We describe them as variables of type integer.

In C, we need to declare all such objects.

We declare them as:

int  total;  /* accumulated sum */
int  number; /* next summand */


Summing the first 1000 integers

Again this an obvious impractical approach. This uses 2002 C statements to compute the sum of the first 1000 integers.
total = 0;
number = 1;
total = total + number;
number = number + 1;
total = total + number;
number = number + 1;
total = total + number;
number = number + 1;
total = total + number;
number = number + 1;
total = total + number;
number = number + 1;
total = total + number;
number = number + 1;
total = total + number;
number = number + 1;
total = total + number;
number = number + 1;
....


Summing the first 1000 integers

Fortunately, C contains a number of statements for changing the flow of control in a program.

The keyword while allows us to have statments executed many times:

This gives us a practical solution to our problem:

    while (number <= 1000) {
    	total = total + number;
    	number = number + 1;
    }
Beware: of the while loop condition must be chosen carefully.

Compare this Haskell solution:

sum1000 = addup 0 1
addup total number
    | number > 1000  = total
    | otherwise      = addup (total + number) (number + 1) 


Summing the first 1000 integers

We must also ensure that initial values of total and number are correct.

We also must also print the result:

    total = 0;
    number = 1;
    while (number <= 1000) {
    	total = total + number;
    	number = number + 1;
    }
    printf("%d\n", total);
After this executes, the value of total will be the required answer.

Summing the first 1000 integers

To complete this program, we must


#include <stdio.h>

int
main(void) {
        int number;
        int total;

        total = 0;
        number = 1;

        while (number <= 1000) {
                total = total + number;
                number = number + 1;
        }

        printf("%d\n", total);
        return 0;
}

The if Statement Allows choice between two execution paths.

One form of the if statement:

   if (condition)
      then_statement
   

The boolean_expression is evaluated. If it evaluates to true the then_statement is executed,

Braces can be used to group multiple statements into a single then_statement


The if Statement

Second form of the if statement:

   if (condition)
       then_statement
   else
      else_statement

The boolean_expression is evaluated. If it evaluates to true the then_statement is executed, otherwise the else_statement is executed.

Braces can be used to group multiple statements into a single then_statement or else_statement.


If statement #1 - Flow of Control

   if (condition)
      then_statement

If statement #2 - Flow of Control

   if (condition)
       then_statement
   else
      else_statement

The if statement

If statements are often combined like this:

   if (condition1) {
      statements1;
   }
   else if (condition2) {
      statements2;
   }
   ...
   else if (conditionn-1) {
      statementsn-1;
   }
   else {
      statementsn;
   }
Evaluates conditions until finds a True one;

then executes corresponding statements;

then finishes if statement.


Guards vs. if

Consider the simple Haskell function:
f:: Int -> [Char]
f x
    | x < 0          = "negative"
    | x == 0         = "zero"
    | otherwise      = "positive"

A corresponding C program might contain these statements:

    if (x < 0) {
    	printf("negative\n");
    } else if (x == 0) {
    	printf("zero\n");
    } else {
    	printf("positive\n");
    }


If Example - Dating for Engineers

    int age;
 
    printf("How old are you: ");
    scanf("%d", &age);
 
    if (age < 18) {
        printf("Do you have an older sister/brother?");
    } else if (age < 25) {
        printf("Doing anything tonight?");
    } else if (age < 35) {
        printf("Do you have an younger sister/brother?");
    } else if (age < 65) {
        printf("Do you have a daughter/son?");
    } else {
        printf("Do you have a granddaughter/grandson?");
    }

Another Simple I/O Example: Celsius to Farenheit

We would like to construct a C program which reads a temperature in Celsuis and prints the Farenheit equivalent:
% a.out
Temperature in Celsius: 0
0.0C = 32.0F
% a.out
Temperature in Celsius: 100
100.0C = 212.0F

I/O Example: Celsius to Farenheit

    float celsius, farenheit;
    
    printf("Temperature in Celsius: ");
    scanf("%f", &celsius);
    farenheit = 9.0 / 5.0 * celsius + 32;
    printf("%fC = %fF\n", celsius, farenheit);