Sei sulla pagina 1di 64

COMS11500: Introduction to C

Julian Gough

October 1, 2013
Introduction to C

Outline

1 Introduction to C
Revision from this morning
Second Simple Program
Good Programming Hygiene
Coursework
Introduction to C Revision from this morning

Homework
Understanding Plagiarism

Tasks to do before this afternoons lecture


1 Read the SAFE submission guidelines
2 Do the CS plagiarism questionnaire
Both are linked from the course website
Introduction to C Revision from this morning

Terminology

Programming Visual Studio


Language Run
C Bug
Code Algorithm
Build Top-Down
Compilation Bottom-Up
Introduction to C Revision from this morning

Terminology

Programming Visual Studio


Language Run
C Bug
Code Algorithm
Build Top-Down
Compilation Bottom-Up
The process of solving problems by writing a suitable program.
Introduction to C Revision from this morning

Terminology

Programming Visual Studio


Language Run
C Bug
Code Algorithm
Build Top-Down
Compilation Bottom-Up
A limited set of instructions combined with a strict set of rules on how to
combine these.
Introduction to C Revision from this morning

Terminology

Programming Visual Studio


Language Run
C Bug
Code Algorithm
Build Top-Down
Compilation Bottom-Up
A still-popular programming language from the 70s, the topic of this course.
Introduction to C Revision from this morning

Terminology

Programming Visual Studio


Language Run
C Bug
Code Algorithm
Build Top-Down
Compilation Bottom-Up
A piece of human-readable text expressed in a programming language.
Introduction to C Revision from this morning

Terminology

Programming Visual Studio


Language Run
C Bug
Code Algorithm
Build Top-Down
Compilation Bottom-Up
The (automated) process of turning code into an executable.
Introduction to C Revision from this morning

Terminology

Programming Visual Studio


Language Run
C Bug
Code Algorithm
Build Top-Down
Compilation Bottom-Up
A substep of building
Introduction to C Revision from this morning

Terminology

Programming Visual Studio


Language Run
C Bug
Code Algorithm
Build Top-Down
Compilation Bottom-Up
A Microsoft program to help write (for instance) C code.
Introduction to C Revision from this morning

Terminology

Programming Visual Studio


Language Run
C Bug
Code Algorithm
Build Top-Down
Compilation Bottom-Up
Execute (requires building first).
Introduction to C Revision from this morning

Terminology

Programming Visual Studio


Language Run
C Bug
Code Algorithm
Build Top-Down
Compilation Bottom-Up
A flaw in your code that prevents correct compilation or execution.
Introduction to C Revision from this morning

Terminology

Programming Visual Studio


Language Run
C Bug
Code Algorithm
Build Top-Down
Compilation Bottom-Up
A precise (possibly verbal) description of the steps required to solve a prob-
lem.
Introduction to C Revision from this morning

Terminology

Programming Visual Studio


Language Run
C Bug
Code Algorithm
Build Top-Down
Compilation Bottom-Up
A problem-solving approach based on gradual refinement (example: going
to the moon).
Introduction to C Revision from this morning

Terminology

Programming Visual Studio


Language Run
C Bug
Code Algorithm
Build Top-Down
Compilation Bottom-Up
A problem-solving approach based on gradual extension (example: bichrome
dot printing).
Introduction to C Revision from this morning

A First Simple C Program


/* The traditional first program
in honour of Dennis Ritchie */
#include <stdio.h>

int main(void)
{
printf("Hello, world!\n");
return 0;
}
Introduction to C Revision from this morning

A First Simple C Program


/* The traditional first program
in honour of Dennis Ritchie */
#include <stdio.h>

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

Comments are bracketed by the /* and */ pair.


Visual Studio displays comments in green.
Comments are vital to make code easier to read,
both for yourself at a later point in time and for others.
Introduction to C Revision from this morning

A First Simple C Program


/* The traditional first program
in honour of Dennis Ritchie */
#include <stdio.h>

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

#include <stdio.h>
Lines that begin with a # are called preprocessing directives.
Visual Studio displays reserved words in blue.
<stdio.h> is a standard library needed for the printf function.
Introduction to C Revision from this morning

A First Simple C Program


/* The traditional first program
in honour of Dennis Ritchie */
#include <stdio.h>

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

int main(void)
Every C program needs exactly one function called main()
The program will start its execution at the top of main.
Introduction to C Revision from this morning

A First Simple C Program


/* The traditional first program
in honour of Dennis Ritchie */
#include <stdio.h>

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

Statements are grouped using braces,


{ ... }
For instance, the braces tell the compiler where the main function ends.
It helps to provide structure to your code.
The text in between the braces for main are called the body of the program
Introduction to C Revision from this morning

A First Simple C Program


/* The traditional first program
in honour of Dennis Ritchie */
#include <stdio.h>

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

printf()
One of the pre-defined library functions being called (invoked) using as
single argument the string: "Hello, world!\n" (strings in red).
The \n means print the single character newline.
The function printf relies on including <stdio.h>
Introduction to C Revision from this morning

A First Simple C Program


/* The traditional first program
in honour of Dennis Ritchie */
#include <stdio.h>

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

return 0
Instruct the OS that the function main() has completed successfully.
Notice all declarations and statements are terminated with a semi-colon.
Introduction to C Revision from this morning

A First Simple C Program


Dissection: Recapitulation

Comments are bracketed by the /* and */ pair.


#include<stdio.h> is a preprocessing directive.
int main(void) is obligatory for any C program.
Statements are grouped using braces, { ... }.
printf() is a library function that prints a single string
"Hello, world!\n" to the screen.
The \n means print the single character newline.
return 0; instructs the OS that main() has completed successfully.
All declarations and statements are terminated with a semi-colon.
Introduction to C Second Simple Program

A Second Simple C Program


//program to compute the volume of a box
#include <stdio.h>
int boxvolume(int x, int y, int z);
int main(void){
int length, width, depth, volume;
printf("What are the dimensions of the box? ");
scanf("%d%d%d", &length, &width, &depth);
volume = boxvolume(length, width, depth);
printf("The volume of the box is: %d\n", volume);
return 0;
}
int boxvolume(int x, int y, int z){
return x * y * z;
}
Introduction to C Second Simple Program

A Second Simple C Program


//program to compute the volume of a box
#include <stdio.h>
int boxvolume(int x, int y, int z);
I int main(void){
I int length, width, depth, volume;
I printf("What are the dimensions of the box? ");
I scanf("%d%d%d", &length, &width, &depth);
I volume = boxvolume(length, width, depth);
I printf("The volume of the box is: %d\n", volume);
I return 0;
I }
int boxvolume(int x, int y, int z){
return x * y * z;
}
Introduction to C Second Simple Program

The Preprocessor

I #include <stdio.h>

A # in the first column signifies a preprocessor statement.


#include <file.h>
Exchange this line for the entire contents of file.h,
(to be found in a standard place).
#include "file.h"
Idem, but for (user-written) file.h in local directory.
#define ROUGH_PI (22.0f/7.0f)
Replace all occurrences of ROUGH_PI with (float)
(22.0/7.0).
Include files generally contain other #defines and #includes.
Introduction to C Second Simple Program

Variables
int main(void){
I int length, width, depth, volume;
printf("What are the dimensions of the box? ");

type name;
Variables are used to hold changing values of various types.
Some standard types are int, float, and void.
Variables need to have a name, aka identifier.
Finding good names drastically improves readability of code!
Variables must be declared.
Once declared, they can be assigned a value.

Later we will learn about scope and how to create our own types.
Introduction to C Second Simple Program

Variables
int main(void){
int length, width, depth, volume;
printf("What are the dimensions of the box? ");

Declare-then-initialize
int volume;
volume = 0;

WRONG: Assign before declaration


volume = 0;
int volume;

Declare-and-initialize
int volume = 0;
Introduction to C Second Simple Program

Variables
int main(void){
int length, width, depth, volume;
printf("What are the dimensions of the box? ");

A note on identifiers (naming)


The only allowed characters in an identifier are letters, numbers, and
the underscore.
Identifiers cannot start with a number.
Using reserved words (int, void) is illegal.
Avoid identifiers used in the standard libraries, e.g. printf.
Beware that C is case sensitive: One, ONE, and one are all distinct.
Introduction to C Second Simple Program

Basic Arithmetic

int boxvolume(int x, int y, int z){


I return x * y * z;
}

+, -, *, /, %
Add, Subtract, Multiply, Divide, Modulus.
Integer division / discards remainder i.e.
1/2 is 0 , 7/2 is 3.
Modular remainder % is only available for integer arithmetic
7%4 is 3, 12%6 is 0.
Introduction to C Second Simple Program

Functions
int boxvolume(int x, int y, int z);
...
volume = boxvolume(length, width, depth);
...
int boxvolume(int x, int y, int z){
return x * y * z;
}

type name(type1 arg1, ...)


Introduction to C Second Simple Program

Functions
I int boxvolume(int x, int y, int z);
...
volume = boxvolume(length, width, depth);
...
int boxvolume(int x, int y, int z){
return x * y * z;
}

type name(type1 arg1, ...)


declaration Prototype that describes expected type of input and output.
Introduction to C Second Simple Program

Functions
int boxvolume(int x, int y, int z);
...
I volume = boxvolume(length, width, depth);
...
int boxvolume(int x, int y, int z){
return x * y * z;
}

type name(type1 arg1, ...)


declaration Prototype that describes expected type of input and output.
calls Causes the function to be evaluated.
Introduction to C Second Simple Program

Functions
int boxvolume(int x, int y, int z);
...
volume = boxvolume(length, width, depth);
...
I int boxvolume(int x, int y, int z){
I return x * y * z;
I }

type name(type1 arg1, ...)


declaration Prototype that describes expected type of input and output.
calls Causes the function to be evaluated.
definition Describes how the return value is computed as a function of
the input parameters.
Introduction to C Second Simple Program

Functions
int boxvolume(int x, int y, int z);
...
volume = boxvolume(length, width, depth);
...
int boxvolume(int x, int y, int z){
return x * y * z;
}

type name(type1 arg1, ...)


Prototype should appear before main and first call.
Arguments are passed by value.
The scope of the parameters is local:
You can change them, but the original arguments remain unchanged.
Introduction to C Second Simple Program

Structured Programming
Programming Language Pragmatics IIIpage 242

Structured programming was the hot trend of the 1970s, in


much the same way that object-oriented programming was the
trend in the 1990s. Structured programming emphasizes
top-down design (i.e., progressive refinement), modularization
of code, structured types (records, sets, pointers,
multidimensional arrays), descriptive variable and constant names,
and extensive commenting conventions. The developers of
structured programming were able to demonstrate that within a
subroutine, almost any well-designed imperative algorithm can be
elegantly expressed with only sequencing, selection, and iteration.
Michael L. Scott
Introduction to C Second Simple Program

Using printf()

I printf("What are the dimensions of the box? ");


scanf("%d%d%d", &length, &width, &depth);
volume = boxvolume(length, width, depth);
I printf("The volume of the box is: %d\n", volume);

printf(format-string, arg1, arg2, ...);


Where format-string is a string "Some text" that can include two
types of special symbols:
Escape Characters such as \n (for newline) or \t (for tab).
Format Specifiers such as %d (for ints) or %e (for floats).
Introduction to C Second Simple Program

Using printf()

printf("What are the dimensions of the box? ");


scanf("%d%d%d", &length, &width, &depth);
volume = boxvolume(length, width, depth);
printf("The volume of the box is: %d\n", volume);

printf(format-string, arg1, arg2, ...);


Where format-string is a string "Some text" that can include two
types of special symbols:
Escape Characters such as \n (for newline) or \t (for tab).
Format Specifiers such as %d (for ints) or %e (for floats).
For each format specifier in format-string there must be a
corresponding argi (as part of the printf command).
The value of argi is supplanted into the format-string on the place
of the format specifier.
Introduction to C Second Simple Program

Using scanf()

printf("What are the dimensions of the box? ");


I scanf("%d%d%d", &length, &width, &depth);
volume = boxvolume(length, width, depth);

scanf(format-string, &arg1, &arg2, ...);


Similar to printf() but deals with input rather than output.
Note that the arguments are preceeded by an empercent &
This indicates passing by address instead of value.
Often format-string consists purely of format specifiers, such as
%d for ints and %f for floats.
Adding normal symbols to the format-string can force parsing
behaviour, e.g "%d/%d" or (better) "%d /%d" for fractions.
scanf does not deal well with unsuspected input.
Introduction to C Second Simple Program

A Second Simple C Program (Repeat)


//program to compute the volume of a box
#include <stdio.h>
int boxvolume(int x, int y, int z);
int main(void){
int length, width, depth, volume;
printf("What are the dimensions of the box? ");
scanf("%d%d%d", &length, &width, &depth);
volume = boxvolume(length, width, depth);
printf("The volume of the box is: %d\n", volume);
return 0;
}
int boxvolume(int x, int y, int z){
return x * y * z;
}
Introduction to C Good Programming Hygiene

A Simple C Program (Abstracted)

Preprocessor directives
Function prototypes
int main(void){
Declarations
Statements
}
Function definitions
Introduction to C Good Programming Hygiene

A Simple C Program (Abstracted)

Preprocessor directives
Function prototypes
int main(void){
Declarations
Statements
}
Function definitions

Do not mix up declarations and statements!


Introduction to C Good Programming Hygiene

Structured Programming
Programming Language Pragmatics IIIpage 242

Structured programming was the hot trend of the 1970s, in


much the same way that object-oriented programming was the
trend in the 1990s. Structured programming emphasizes
top-down design (i.e., progressive refinement), modularization of
code, structured types (records, sets, pointers, multidimensional
arrays), descriptive variable and constant names, and
extensive commenting conventions. The developers of
structured programming were able to demonstrate that within a
subroutine, almost any well-designed imperative algorithm can be
elegantly expressed with only sequencing, selection, and iteration.
Michael L. Scott
Introduction to C Good Programming Hygiene

Literate Programming
I believe that the time is ripe for significantly better documentation of
programs, and that we can best achieve this by considering programs
to be works of literature. Hence, my title: Literate Programming.
Let us change our traditional attitude to the construction of programs:
Instead of imagining that our main task is to instruct a computer what
to do, let us concentrate rather on explaining to human beings what we
want a computer to do.
The practitioner of literate programming can be regarded as an
essayist, whose main concern is with exposition and excellence of style.
Such an author, with thesaurus in hand, chooses the names of variables
carefully and explains what each variable means. He or she strives for a
program that is comprehensible because its concepts have been
introduced in an order that is best for human understanding, using a
mixture of formal and informal methods that reinforce each other.
Donald E. Knuth
Introduction to C Good Programming Hygiene

Style
Layout examples

/* The traditional first program


in honour of Dennis Ritchie */

#include <stdio.h>

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

The original program


Introduction to C Good Programming Hygiene

Style
Layout examples

/* The traditional first program


in honour of Dennis Ritchie */

#include <stdio.h>

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

The program with increased indentation


Introduction to C Good Programming Hygiene

Style
Layout examples

/* The traditional first program


in honour of Dennis Ritchie */

#include <stdio.h>

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

The program with more indented bracing


Introduction to C Good Programming Hygiene

Style
Layout examples

/* The traditional first program


in honour of Dennis Ritchie */

#include <stdio.h>

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

The program with more elliptical bracing


Introduction to C Good Programming Hygiene

Style
Layout examples

/* The traditional first program


* in honour of Dennis Ritchie
*/

#include <stdio.h>

int main(void)
{
printf("Hello, world!\n");
return 0;
}
The program with more elaborate comments
Introduction to C Good Programming Hygiene

Style
Layout examples

// The traditional first program


// in honour of Dennis Ritchie

#include <stdio.h>

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

The program with C99 style comments


Introduction to C Good Programming Hygiene

Style
Layout examples

/* The traditional first program


in honour of Dennis Ritchie */
#include <stdio.h>
int main(void)
{
printf("Hello, world!\n");
return 0;
}

The program with indentation removed


Introduction to C Good Programming Hygiene

Style
Layout examples

/* The traditional first program


in honour of Dennis Ritchie */
#include <stdio.h>
int main(void){
printf("Hello, world!\n");
return 0;}

The braces contracted


Introduction to C Good Programming Hygiene

Style
Layout examples

/* The traditional first program

in honour of Dennis Ritchie */


#include <stdio.h>
int main(void){printf(
"Hello, world!\n"
);return 0;}

A deliberate mess
Introduction to C Good Programming Hygiene

Style
Good style keeps code readable
Makes it easier to maintain
Reduces the number of bugs
Usually faster to write

For most problems, C oers several solutions.


Good style requires consistency in your choices!
Bad style often betrays sloppiness.
Introduction to C Good Programming Hygiene

Style
Good style keeps code readable
Makes it easier to maintain
Reduces the number of bugs
Usually faster to write

For most problems, C oers several solutions.


Good style requires consistency in your choices!
Bad style often betrays sloppiness.

Layout aspect
How to format comments
How to position braces
How to indent
Introduction to C Good Programming Hygiene

Style
Good style keeps code readable
Makes it easier to maintain
Reduces the number of bugs
Usually faster to write

For most problems, C oers several solutions.


Good style requires consistency in your choices!
Bad style often betrays sloppiness.

Naming aspect
Using descriptive names for variables
but also for functions and constants
Avoid similar names
Introduction to C Good Programming Hygiene

Style
Good style keeps code readable
Makes it easier to maintain
Reduces the number of bugs
Usually faster to write

For most problems, C oers several solutions.


Good style requires consistency in your choices!
Bad style often betrays sloppiness.

Commenting
To state what a piece of code does
To explain how a piece of code does something
To remark why a piece of code is there
Introduction to C Good Programming Hygiene

Bugs
Or problems with your program...

Rough classification of bugs


1 Build errors are clearly marked by the compiler.
You know there is a bug and the compiler signals where(ish).
2 Obvious runtime errors, such as crashes and infinite loops.
You know there is a bug, but takes some skill locating it.
3 Subtle runtime errors, occurring once in a while.
You need to program carefully and test meticulously.

Rough classification of causes


Typos: you typed too fast and forgot some symbol.
Syntax confusion: you wrote = where you meant ==.
Logical mistakes: you are simply not computing the right thing.
Introduction to C Coursework

COMSM11500 Assessment
Courseworks with increasing weight
what weight announced work on deadline
CW1 5 oct 1 lab 1 oct 7
CW2 10 oct 29 lab 5 nov 1
CW3 15 nov 2 lab 4/6 nov 11
CW4 20 nov 12 lab 7/8 dec 2
Final 50 dec 3 lab 10/11/12 dec 20

Courseworks will be made available online ahead of time.


Typically hand in on Monday 23.59 using SAFE.
Exception: CW2 will be an in lab (debugging) exercise.
Automated marking hand-tuned for partial solutions and elegance.
Labs 2,3, and 9 are dedicated to non-assessed exercises.

Hand in C source code only


Introduction to C Coursework

Ethics

Computer Science Ethos


Talk to your friends, ask for help, work together.
Never pass o another persons work as your own.
Do not pass work to otherseither on paper or electronically.

COMS11500 Guidelines
Stick to C99 and standard libraries (no C++).
If in doubt, ask!
We will develop style guidelines jointly.
Introduction to C Coursework

Help
Labs
There will be a team of teaching assistants in the labs. They are not
allowed to write pieces of code for you! What they can do:
Help you with any Visual Studio issues.
Explain the coursework problem.
Explain general C syntax etc.
Point out simple bugs if prompted.
Suggest debugging routines.

Forum
To avoid duplication (answering the same question over and over), we will
make extensive use of a bulletin board/forum.

Any problems with the computers see the central service desk:
http://www.bristol.ac.uk/it-services/contacts/
Introduction to C Coursework

Coursework
Typical Workflow

Read
problem
descrip-
tion

Create
Think about program

Oops
Works? Fix

OK
Oops
Check style

OK
Submit!
Introduction to C Coursework

Terminology
Variable
#include
Identifier
<stdio.h>
Type
main
Declaration
return
Statement
int
Function
float
Prototype
void
Definition
printf
Body
scanf
Parameter
"%d"
Argument
"\n"
Return value

Potrebbero piacerti anche