ENG1410 C Programming: Topic #1 “Introduction to Programming: Part 2” S. Areibi School of Engineering University of Guelph
ENG1410C Programming: Topic #1
“Introduction to Programming: Part 2”
S. AreibiSchool of EngineeringUniversity of Guelph
Topics
The Von Neumann Architecture The C Programming Language
History .. Characteristics .. Features Compiling The first program
Summary
• Computing machine (Computer): “a machine that stores and manipulates information under the control of a changeable program that is stored in its memory.”
– Pocket calculator: not a computer ! Manipulates information, but is built to do a specific task (no changeable stored program)
• This model is named the “von Neumann architecture” (John von Neumann – 1945; EDVAC - Electronic Discrete Variable Automatic Computer – the first stored-program computer)
• Stored-program concept: earlier ideas in theoretical articles of: Alan Turing (1936), Konrad Zuse (1936)
Model of a Computing Machine
5
PrincipleIn 1945, the mathematician Von Neumann (VN)demonstrated in study of computation that acomputer could have a simple structure, capable of executing any kind of program, given a properly programmed control unit, without the need of hardware modification
The Von Neumann Computer
ENIAC - The first electronic computer (1946)6
Structure? A memory for storing program and data.
The memory consists of the word with the same length A control unit (control path) featuring a program counter
for controlling program execution A data path (Arithmetic/logic Unit) for program execution
Datapath
Controllpath
Processor orCentral processing unit
Dataand
Instructions
Addressregister
Memory
Instructionregister PC
Data
Address
Registers
The Von Neumann Computer
7
Input Device Output DeviceALU CU
CPU
Main memory(RAM)
Secondary storage
The Von Neumann Architecture
8
.. Keyboard, Mouse, … .. LCD, Monitor, Printer, …
• Central Processing Unit (CPU): the “brain” of the machine. – CU: Control Unit– ALU: Arithmetic and Logic Unit
• Carries out all basic operations of the computer • Examples of basic operation: adding two numbers, testing to see if two numbers are equal.
• Main memory (called RAM for Random Access Memory): stores programs and data– Fast but volatile
• Secondary memory: provides permanent storage
• How does a computer execute a program? (example programs: a computer game, a word processor, etc)
1. The instructions that comprise the program are copied from the permanent secondary memory into the main memory
2. After the instructions are loaded, the CPU starts executing the program.
3. For each instruction, the instruction is retrieved from memory, decoded to figure out what it represents, and the appropriate action carried out. (the fetch- execute cycle)
4. Then the next instruction is fetched, decoded and executed.
VN Architecture: How it Works?
9
The Von Neumann Computer
CodingA program is coded as a set of instructions to be sequentially
executed
Program execution steps? Instruction Fetch (IF): The next instruction to be executed
is fetched from the memory Decode (D): Instruction is decoded (operation?) Read operand (R): Operands read from the memory Execute (EX): Operation is executed on the ALU Write result (W): Results written back to the memory Instruction execution in Cycle (IF, D, R, EX, W)
10
Execution CycleInstruction
Fetch
InstructionDecode
OperandFetch
Execute
ResultStore
NextInstruction
Obtain instruction from program storage
Determine required actions and instruction size
Locate and obtain operand data
Compute result value or status
Deposit results in storage for later use
Determine successor instruction
11https://www.youtube.com/watch?v=Z5JC9Ve1sfI
Created by Dennis Ritchie at AT&T Labs in 1972
Originally created to design and support the Unix operating system.
There are only 27 keywords in the original version of C.
o for, goto, if, else ……
Easy to build a compiler for C.
o Many people have written C compilers
o C compilers are available for virtually every platform
In 1983 the American National Standards Institute (ANSI) formed a committee to establish a standard definition.
o Called ANSI Standard C.
o As opposed to K&R C (referring to the general “standards” that appeared in the first edition of Brian Kernighan and Ritchie’s influential book: The C Programming Language)
A Brief History
13
C evolved from two previous languages, BCPL (Basic Combined Programming Language) and B.
BCPL developed in 1967 by Martin Richards as a language for writing Operating Systems and Compilers.
Ken Thompson modeled many features in his language, B, after their counterparts in BCPL, and used B to create an early versions of UNIX operating system at bell Laboratories in 1970 on a DEC PDP-7 computer.
Both BCPL and B were typeless languages: the only data type is machine word and access to other kinds of objects is by special operators or function calls.
The C language developed from B by Dennis Ritchie at Bell Laboratories and was originally implemented on a DEC PDP-11 computer in 1972.
It was named C for new language (after B).
Initially, C used widely as the development language of the UNIX OS.
Today, almost all new major OS are written in C including Windows.
A Brief History
14
15
o Developed in the 1970s – in conjunction with development of UNIX operating system● When writing an OS kernel, efficiency is crucial
This requires low-level access to the underlying hardware:♦ e.g. programmer can leverage knowledge of how data is laid
out in memory, to enable faster data access
● UNIX originally written in low-level assembly language – but there were problems:♦ No structured programming (e.g. encapsulating routines as
“functions”, “methods”, etc.) – code hard to maintain
♦ Code worked only for particular hardware – not portable
C & Unix
C takes a middle path between:
low-level assembly language…● Direct access to memory layout through pointer manipulation
● Concise syntax, small set of keywords
… and a high-level programming language like Java:● Block structure
● Some encapsulation of code, via functions
● Type checking (pretty weak)
C: Language Characteristics
17
18
C is not object oriented!• Can’t “hide” data as “private” or “protected” fields• You can follow standards to write C code that looks object-
oriented, but you have to be disciplined – will the other people working on your code also be disciplined?
C has portability issues• Low-level “tricks” may make your C code run well on one
platform – but the tricks might not work elsewhere
The compiler and runtime system will rarely stop your C program from doing stupid/bad things
• Compile-time type checking is weak• No run-time checks for array bounds errors, etc. like in Java
C: Issues
o C is intended as a language for programmers BASIC was for nonprogrammers to program and solve simple
problems. C was created, influenced, and field-tested by working
programmers.o C is powerful and efficient You can nearly achieve the efficiency of assembly code. System calls and pointers allow you do most of the things that you
can do with an assembly language.o C is a structured language Code can be written and read much easier.
o C is standardized Your ANSI C program should work with any ANSI C compiler.
o Foundation of C++ If you know C then you will be able to learn C++ easily
Why Learn/Use C?
20
EditProgram
SourceCode
Compile
ObjectCode
Link ObjectCode Executable
LibraryFiles
The C Development Cycle
21
Library: is a set of programs and utilities that others wrote and maybe used by a programmer
myprogram.c
myprogram.o
myprogram.exe
The C Development Cycle
22
Vi editor to enter source code
Linking with libs will result in file.exe executable
Compiling will result in file.o object file
Main Function• Every program has one function main• Header for main: int main ()• Program is the sequence of statements between the
{ } following main• Statements are executed one at a time from the one
immediately following to main to the one before the }
23
#include <stdio.h>int main ( ){
printf ("Hello, World!\n");return 0;
}
Everyone writes this program first
/* This is a comment *//* stdio.h is a header file used for input/output */#include <stdio.h>/* Every C program includes main() */int main ( ){
printf ("Hello, World!\n");return 0;
}
A Typical C Program
24
C Program Structure
• Program defined by:– global declarations– function definitions
• May contain preprocessor directives• Always has one function named
main, may contain others
Preprocessor Directives
Global Declarations
Function Definitions
int main () {
}
Local Declarations
Statements
25
#define, #include
Global Variables and constants: Seen by everyone
Other functions called by main()
Variables and constants: seen only by main()
Parts of a Program#include <stdio.h>
int x;
int main () { int y;
printf("Enter x and y: "); scanf(&x,&y); printf("Sum is %d\n",x+y);}
Preprocessor Directive
Global Declaration
Function
Local Declaration
Statements
26
• Global Declaration can be used by main() and all other functions used in the C program.
• Local Declaration can only be used by the function that declares them. Other functions can not use them.
Preprocessor Directives
• Begin with #• Instruct compiler to perform some transformation to file before
compiling• Example: #include <stdio.h>
– add the header file stdio.h to this file– .h for header file– stdio.h defines useful input/output functions
27
Declarations• Global
– visible throughout program– describes data used throughout program
• Local– visible within function– describes data used only in function
28
int sum;int main ( ){
int a=3, b=4;sum = a + b;printf (“sum = %d\n“, sum);return 0;
}
global variable
local variable
Functions• Consists of header and body
– header: int main ()– body: contained between { and }
• starts with location declarations• followed by series of statements
• More than one function may be defined• Functions are called (invoked) - more later
29
int main ( ){
int a=3, b=4;c = add(a,b);printf (“C = %d\n“, c);return 0;
}
int add ( int a, int b){
int result; result = a + b;return (result);
}
Compilers & ProgramsWhat is a Compiler? A program that converts another program from
some source language (or high-level programming language / HLL) to machine language (object code). Some compilers output assembly language which
is then converted to machine language by a separate assembler. Is distinguished from an assembler by the fact that
each input statement, in general, correspond to more than one machine instruction.
31
From Source to Exec
32
*.c
Preprocessor
Handles #include, #defineStrips out commentsPreforms Macro Expansion
*.i
Compiler
Translates C to Assembly
*.s
Assembler
Translates Assembly to Object File
*.o
Linker
Transforms all object files and libs to exec
Executable
Compilers & Programs
What is a Source code or program?o The form in which a computer program, written
in some formal programming language, is written by the programmer.
oCan be compiled automatically into object codeor machine code or executed by an interpreter.
o Pascal source programs have extension ‘.pas’o A “C” source program has extension ‘.c’o A “C++” source program has extension `.cpp’
33
Compilation into Assembly L
Compiler
Assembler
SourceProgram
Assembly Language
Assembly Language
MachineLanguage
34
Compilers & Programso Object program
– Output from the compiler– Equivalent machine language translation of the
source program– Files usually have extension ‘.obj’ or ‘.o’
o Executable program– Output from linker/loader– Machine language program linked with necessary
libraries & other files– Files usually have extension ‘.exe’
35
Running Programs
Memory
Input Data
Program Output
Machine language program
(executable file)
Data entered during execution
Computed results
C P U
Steps that the computer goes through to run a program:
36
What is a Linker?o A program that pulls other programs together so
that they can run.o Most programs are very large and consist of
several modules.o Even small programs use existing code provided
by the programming environment called libraries.o The linker pulls everything together, makes sure
that references to other parts of the program (code) are resolved.
37
o A C program consists of source code in one or more fileso Each source file is run through the preprocessor and
compiler, resulting in a file containing object codeo Object files are tied together by the linker to form a single
executable program
Source codefile1.c
Preprocessor/Compiler
Object codefile1.o
Source codefile2.c
Preprocessor/Compiler
Object codefile2.o
LinkerLibraries
Executable codea.out
Separate Compilation
38
Compilation translates your source code (in the file hello.c) into object code (machine dependent instructions for the particular machine you are on).
Linking the object code will generate an executable file. There are many compilers for C under Unix SUN provides the Workshop C Compiler, which you run with the
cc command There is also the freeware GNU compiler gcc
Compilation (1)
39
To compile a program: Compile the program to object code.
machine_name > gcc –c hello.c Link the object code to executable file.
machine_name > gcc hello.o –o hello You can do the two steps together by running:
machine_name > gcc hello.c –o hello To run your program:
machine_name > ./helloHello World!
If you leave off the -oexecutable goes intothe file a.out
Compilation (2)
40
Error messages are a little different than you may be used to but they can be quite descriptive.
Suppose you forgot the semi-colon after the printf
machine_name > gcc hello.c –o hello"hello.c", line 5: syntax error before or at: returncc: acomp failed for hello.c
Notice that the compiler flags and informs you about the error at the first inappropriate token.– In this case, the return statement.
Always try to fix problems starting with the first error the compiler gives you - the others may disappear too!
Compilation (3)
41
Advantage: Quicker compilation– When modifying a program, a programmer typically edits only
a few source code files at a time.– With separate compilation, only the files that have been
edited since the last compilation need to be recompiled when re-building the program.
– For very large programs, this can save a lot of time.
Separate Compilation
42
o To compile and link a C program that is contained entirely in one source file:gcc program.c
• The executable program is called a.out by default.If you don’t like this name, choose another name using the –o option:
gcc program.c –o exciting_executable
o To compile and link several C source files:gcc main.c extra.c more.c
• This will produce object (.o) files, that you can use in a later compilation:gcc main.o extra.o more.c
• Here, only more.c will be compiled – the main.o and extra.o files will be used for linking.
o To produce object files, without linking, use -c:gcc –c main.c extra.c more.c
How to Compile (Unix)
43
o The preprocessor takes your source code and – following certain directives that you give it – tweaks it in various ways before compilation.
o A directive is given as a line of source code starting with the #symbol
o The preprocessor strips out all comments from the c source code.o The preprocessor works in a very crude, “word-processor” way,
simply cutting and pasting –it doesn’t really know anything about C!
Yoursourcecode
Preprocessor
Enhanced andobfuscated
source code
Compiler
Objectcode
The Preprocessor
44
Preprocessor Directives
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
oThe #include directives “paste” the contents of the files stdio.h, stdlib.h and string.h into your source code, at the very place where the directives appear.
oThese files contain information about some library functions used in the program:• stdio stands for “standard I/O”, stdlib stands for “standard library”, and• string.h includes useful string manipulation functions.
oWant to see the files? Look in /usr/include
45
#define MAX_COLS 20
#define MAX_INPUT 1000
The #define directives perform “global replacements”:oevery instance of MAX_COLS is replaced with 20, and
every instance of MAX_INPUT is replaced with 1000.
46
Preprocessor Directives
Function prototypesint read_column_numbers( int columns[], int max );
void rearrange( char *output, char const *input,
int n_columns, int const columns[] );
• These look like function definitions – they have the name and all the type information – but each ends abruptly with a semicolon. Where’s the body of the function – what does it actually do?
• (Note that each function does have a real definition, later in the program.)
47
Use of comments/*
** This program reads input lines from the standard input and prints
** each input line, followed by just some portions of the lines, to
** the standard output.
**
** The first input is a list of column numbers, which ends with a
** negative number. The column numbers are paired and specify
** ranges of columns from the input line that are to be printed.
** For example, 0 3 10 12 -1 indicates that only columns 0 through 3
** and columns 10 through 12 will be printed.
*/
• Use /* … */ for comments –• Some compilers allow // like comments in C++
49
#include <stdio.h>
int main ()
{
int radius, area; /* Local Var */
printf ("Enter radius (i.e. 10) : ");
scanf ( "%d", &radius);
area = 3.14159 * radius * radius;
printf ("\nArea = %d\n\n", area);
return 0;
}
Example #1
50
Print to the Screen
Wait for user to enter value
Compute the area from Radius
Print result to the Screen
Indicate no error occured
#include <stdio.h>int main (){
int i, j;for (i = 0; i < 10; i++){
printf ("\n");for (j = 0; j < i+1; j++ )
printf ( "A");}printf("\n");return 0;
}
Example #2
51
This is a loop
This is another loop
/* Program to calculate the product of two numbers */
#include <stdio.h>int product(int x, int y);int main (){
int a,b,c;/* Input the first number */printf ("Enter a number between 1
and 100: ");scanf ("%d", &a);
/* Input the second number */printf ("Enter another number
between 1 and 100: ");scanf ("%d", &b);
/* Calculate and display the product */c = product (a, b);printf ("%d times %d = %d \n", a, b, c);return 0;
}
Example #3
52
/* Functions returns the product of its two arguments */
int product (int x, int y){
return (x*y);}
Syntax & Semantics• Syntax:
– The structure of strings in some language. A language's syntax is described by a grammar.
– Examples: • Binary number
<binary_number> = <bit> | <bit> <binary_number><bit> = 0 | 1
• Identifier<identifier> = <letter> {<letter> | <digit> }<letter> = a | b | . . . | z<digit = 0 | 1 | . . . | 9
• Semantics:– The meaning of the language
54
Program Errors• Syntax Errors:
– Errors in grammar of the language• Runtime error:
– When there are no syntax errors, but the program can’t complete execution
• Divide by zero• Invalid input data
• Semantic or Logical errors:– The program completes execution, but delivers
incorrect results– Incorrect usage of parentheses
55
Summary The Von Neumann Computer was proposed in 1945 and
consisted of a CPU, Memory and I/O Any CPU within a Computer system goes through several steps
to execute a program (a) fetch an instruction, (b) decode an instruction, (c) fetch operands, (d) Execute the instruction, (e) write back results.
C is a high level language that was developed in the early 70’s and is still currently used extensively by many programmers.
Any programming language such as C requires a compiler that converts the source language (or high-level programming language / HLL) to machine language (object code).
The C preprocessor takes the user source code and – following certain directives that are given – tweaks it in various ways before compilation.
A C programmer may encounter some of these errors while developing their application (a) Syntax Errors, (b) Sematic Errors, (c) Run time Errors
57
C Structure: Resourceso Introduction to C Programming (Youtube)
https://www.youtube.com/watch?v=KJgsSFOSQv0 https://www.youtube.com/watch?v=bPp_Nr71GxY https://www.youtube.com/watch?v=TQx74C27Vu4 https://www.cprogramming.com/tutorial/c/lesson1.html
o Compilers and Linkers: https://www.youtube.com/watch?v=QXjU9qTsYCc
o The Structure of Computers: https://www.youtube.com/watch?v=tiUNjhzVJv4 https://www.youtube.com/watch?v=HB4I2CgkcCo https://www.youtube.com/watch?v=cNN_tTXABUA https://www.youtube.com/watch?v=Qu2njWY3Hjk http://www.computer.org/cms/Computer.org/Publications/timeline.pdf
59