Sie sind auf Seite 1von 47

COP 3223

Slide Set #1
Introduction to the C
Programming Language

Objectives of this Class


Learn how to program a computer
Learn the syntax and semantics of C
Syntax The rules of the language
Semantics The meaning of the symbols

Give you the ability to use C to solve


real-world problems through
computing
Learn to be creative and resourceful

General Philosophy of
Class
I believe strongly in learning by doing
not so much by listening to my lectures
certainly not by watching others do.

The course grade will be heavily


weighted on homework
assignments/projects (35%).
You will have an assignment pending
almost every week of the semester.

General Structure of
Class
The class sessions will be composed of:
Lectures, where the principles of computing are
explained.
Workshops, where a homework assignment will
be discussed at length.
Exams: Self-explanatory

Having laptops in class will be :


of great help during workshops
(but not essential).

of minimal use during lectures.


inadmissible during exams/tests/quizzes

Computers
First thing to always remember:
Computers are dumb creatures!
They only do exactly what you tell
them to do.
They cant figure out what you mean for
them to do like humans can (You know
what I mean ).

You must tell them what to do and


exactly how to do it!

Computers
To get them to be smart, one must
communicate with them in a way
they understand what you want them
to do.
Unfortunately, they do not speak
English or French or Spanish
They speak terse, vaguely Englishlike languages that are very specific
in what they state.

Computers
To program a computer, one must understand
these languages.
These include C, C++, Java, Python, Pascal, Basic,
Fortran, Lisp, Prolog, , many others
Each has its strengths and its weaknesses.
Of course, we will only cover C in this class.
In my opinion, it is one of the hardest languages
to learn, but once learned, it is one of the most
useful
Plus, it provides a window into how computers
work that other languages do not.

Instructions
As the name implies, these describe to the
computer exactly what we want it to do.
Computers basically perform actions on data,
and move the data around to achieve an objective
A computer program tells the computer exactly
what actions to perform on exactly what data and
in what sequence.
The program does this by providing the
processor with instructions to execute and
the specific relevant data that are to be acted
upon and somehow transformed.

Instructions (continued)
Instructions (as well as data) are all long sequences
of very simple elements called bits that only take
on values of 0s and 1s. For example,
010001101110010011010011001100
If instructions, their specific pattern indicate a
specific action to be executed. This is the so-called
machine language
If data, it will represent a number, a symbol, a
memory location, a pixel color, a sound element or
some other representation of data to be
transformed somehow.

Instructions (continued)
The 0s and 1s are electrical voltage values at
the output of a transistor
The transistors either put out zero voltage (a 0), or
a saturated maximum voltage (interpreted as a 1)
This value can be easily and very rapidly switched
on (1) and off (0) by the hardware as the
instructions might require,
thereby executing large programs very quickly.

But hardware is beyond the scope of this


course.

Computer Languages
OK, then how do we communicate with computers?
Humans think in terms of words, pictures, sounds,
concepts, etc., not in machine language (1s & 0s)
This makes it hard for humans and computers to
communicate.
Imagine writing computer programs in terms of
instructions as 0s and 1s!
This was actually done in the early days of computing

Enter the high level programming languages (e.g.,


C)
These are the (vaguely) English-like statements that are
(relatively) easy to write by a programmer
Compilers then translate these statements into
machine language instructions

Computer Languages
Think of it as when having to speak to a
French person who speaks only French.
To communicate with her, we have to speak
to her in French;
otherwise, she will have no idea what you are
saying
And the desired results will not be achieved.

Instructions written in a high-level language


such as C are called statements and the
program in this form is called source code.

Modern Computer
Programming
Computer programming, therefore, an be defined
as the process of putting together a (possibly
long) sequence of statements that, when
compiled, linked and executed, will cause the
computer to act as desired and produce the
desired result.
Modern computing is very complex, and includes
graphic programming, internet programming and
writing programs that control devices in real time
But at their most fundamental level, these are all
simply a sequence of instructions to a processor, just
as you will learn to do in this class in C.

Some History about C


Developed by Dennis Ritchie at ATT Bell Labs
around 1972
Dr. Ritchie died a few years ago.

Specifically built to work with the Unix operating


system (an overarching computer program that
handles basic functionality for the computer)
Derived from another language called B, which
was (probably) derived from A
Has several low level features not found on other
high level languages, such as pointers and direct
bit manipulation. Well see this later.

Stored-Program Digital
Computer
The oldest computers (1940s) were very large,
special-purpose, hard-wired computers that could only
perform the actions that they were designed to do
Any deviations would require extensive re-wiring.

A major improvement came in the stored program


computer. Now computers could be made general
purpose, and could run any program as long as it used
the instructions defined for its processor, without any
changes to its wiring.
The program could be stored in its memory just as it were
data
This allowed hardware components to become smaller, as
wiring did not have to be manipulated any longer

Stored-Program Digital
Computer
Modern computer are, of course,
programmable.
The instructions (the stored program)
and the data are now stored in the same
memory elements (Random Access
Memory)
Well hopefully have time later in the
semester to discuss memory
organization very important!

Components of the Modern


Computer
Central Processing Unit (CPU)

This is what actually executes the instructions


(i.e., runs the program)
Modern computers have more than one of these

Main Memory (RAM)

Running programs and their data are stored in


main memory
Main memory is volatile - wiped out when you
turn off your computer

Graphics Processor (GPU)

Additional processor charged with processing


graphics
Often used nowadays to assist the CPUs in
some general purpose computing tasks

Components of the Modern


Computer
External Memory

Persistent, long term memory (e.g., hard drive, CD,


flash drives etc.). Non-volatile. Data persists after
system shutdown
To run a program, it must be transferred from
external memory to main memory

Registers

Very fast, hardware memory locations in which to


place instructions about to be executed and the
relevant data.
Also volatile.

Arithmetic Unit (ALU)

Additional processor that performed heavy number


crunching computations
No longer common integrated into CPU or GPU

Components of the Modern


Computer
Operating System (OS) (Windows, Mac OS,
Unix)

Performs the basic functions related to operating the


computer, file manipulations, queuing instructions, etc.
Provides an interface between the machine and the user
Allocates the computer's resources (e.g., memory, etc.)

Compiler

Translates high-level computer language (source code)


into machine language (the 1s and 0s)

Application program

Programs intended for use by the end-user on a


computer
What you will be writing this semester

Operation of the Digital


Computer
When you first start your computer, an operating
system (OS) is loaded into main memory by a
primitive process hardcoded into the system
The OS provides an interface that lets you pick
what programs to run
The OS allows you to move files around (data or
programs) in the external memory (the hard
drive)
When you tell the OS you want to run a program
(say, by double-clicking), the OS loads the
program into main memory and begins its
execution

Preliminaries
You will learn how to program a computer this
semester
That is, create instructions in the C high level language
for a compiler to convert into machine language code
to be linked to other programs and/or libraries
for the processor to execute
and return the desired output

You'll use the Code::Blocks integrated development


environment (IDE) to translate your C statements into
machine language and execute your program in your
computer.
You'll generally follow this cycle:

Programming Cycle
1) Compose the C statements that make up the
program (Edit)
2) Compile the C statements
1) (If it fails to compile, go back to 1)

3) Link the program to other libraries as appropriate


(done automatically no need to worry about this)
4) Execute the object code program (instructions in
machine language)
5) Obtain results
6) Examine the results. Computers often make
mistakes
1. If you're happy with the results, you're done,
2. otherwise go back to step 1 to modify the statements

Editors and Compilers


Any text editor can be used to write a C
program, but some editors are better than
others
Generally, we prefer to use an Integrated
Development Environment (IDE) such as
Code::Blocks
An IDE allows you to edit your code more easily,
and lets you compile and run with the click of a
button, all within the environment.
An IDE also provides debugging tools to
facilitate debugging.

Code::Blocks
Let us first download Code blocks
Its free!

Go to http://www.codeblocks.org
Follow instructions for downloading
Open the downloaded program and
get ready to use it.
Go to create new project
Click on console application.

Code::Blocks
Enter c
Enter the name of the project

Introduce HW #1
At this point, let us now do HW #1

Our First Program


// <your name>
// My first C program
#include <stdio.h>
int main(void)
{
printf("Hello Earth!\n");
system("PAUSE");
return 0;
}

Now Lets see what we did

Basic C Program
Structure
//Comment lines
The C Preprocessor
Header files
Macros

Global data declarations (if any none in this


program)
Function prototypes (if any none in this program)
main() function
C/C++ statements

Definition of other functions (if any none in this


program)

Comment Lines
Sometime we want to write things in the code
that are purely for our (i.e., human) benefit.
We dont want to compiler to translate them

Used to describe things to other humans


The comment indication tells the compiler just
that:
Dont bother translating this line because it is none
of your business

// at the start of a line


/* . */ if inserted into otherwise active code

Comments
Comment lines can be placed
anywhere within the program.
Well discuss this later when we get to
documentation of the code.

Very important to comment code


extensively for (human) readability.

The C Preprocessor
It is sort of awkward to discuss this now,
before even discussing C statements, but they
do come first in the program
These are special commands called
preprocessor directives
Indicate certain things to be done to the
program code prior to compilation.
Include certain other files when compiling
Replace some code by other code

Statements beginning with # are considered


preprocessor directives

Header Files
The #include directive tells the
preprocessor to include the named
files in the compilation process.
Part of the afore-mentioned linking process

Allows the programmer to:


break up the program across several files
for modularity and reusability.
Include Standard C Library files that
contain needed functions.

Header Files (cont.)


The #include directive causes a
copy of the designated file to be
included in place of the directive.
Some important ones are:

math.h
stdio.h
stdlib.h
string.h

As well as many others

Header Files (cont.)


The format of this directive is:
#include filename - the
preprocessor searches in the same
directory as the file being compiled.
Typically used for user-defined files.
#include <filename> - the
preprocessor searches in pre-defined
directories where the standard C
Library files are located. Normally
used for standard library files.

The #define Directive


Symbol replacement
Causes the preprocessor to physically replace in
the source code prior to compilation, the symbol
defined in the macro by the value assigned to
that symbol, wherever that symbol is found in
the source code.
#define A 29.75
The pre-processor will go through the source
code (the C sequence of statements), and will
replace all instances of A with 29.75.

The #define Directive


(cont.)

The macro replacement


The #define directive can also
replace code
Macros may be defined either with
or without arguments.
The replacement code text is put in
place of the macro identifier.
Arguments should be between
parentheses.

The #define Directive


(cont.)
Example:
#define CIRCLE_AREA(x)

( PI * (x) * (x) )

When called:
area = CIRCLE_AREA(4);

the preprocessor replaces


CIRCLE_AREA with
( 3.14159 * (4) * (4) )

The #define Directive


(cont.)
It is important to use parentheses in
the definition. Else, confuses the
compiler:
area = CIRCLE_AREA(c+2)
area = (3.14159 * (c+2) * (c+2)

If no parentheses used, however,


area = (3.14159 * c + 2 * c +2)

which is incorrect (product takes


precedence)

Scope
The scope of something in C means
exactly in what parts of the program
is this element valid.
What is the extent of the validity of a
statement?

More about that when we get to


variables.

The #define Directive


(cont.)
Scope of a macro or symbolic
constant is:
Until the end of the file in which the
directive resides
Until it is undefined with #undef
Whichever comes first!

The main() Function


The main() function is an essential part of every
C and C++ program.
Contains the essence of the program and
controls execution.
Every program in C/C++ begins by executing the
main() function
main() is the only essential function.
A left brace { defines the beginning of its body,
closed by a right brace }.
Every C/C++ program ends when main()
function terminates.

C Statements
Composed of one or more instructions that
will later be compiled into machine language.
Generally conclude with a semicolon ;
Could be grouped together as a block of code
by using the right and left braces. { }
Example:
result = a + b + c * (d + e);
This means compute the mathematical
expression above and set the result to the
variable result.

Comments
// John Smith
// My first C program
These two lines are comments.
They are ignored by the compiler,

Commenting is very important!!


Good and frequent comments make it
easier for a human to understand the
programmers intent in the code.

printf() command
printf() is the basic output
function in C

Well discuss it a much greater depth


later this semester
printf("Hello World!\n");

This writes whatever is in quotes on


to the screen (in our case "Hello
World!")
The "\n" is a newline character, a
special character that tells the
computer to go to the next line

pause and return


commands
system("PAUSE");
This tells the computer to wait for the user
to hit a key before continuing
return 0;
"return" means that the current function
should end
Inside main, hitting "return 0;" means that
the program should end normally
More about returning values later.

Defining Functions
Functions can be defined by the
programmer
Can be called later in the program to
execute their designed computations
Used to abstract long and/or complex
computations into a simple call.
It is the basis of programming in C
and C++
You will be defining many functions.
Much more about this later

Das könnte Ihnen auch gefallen