Вы находитесь на странице: 1из 60

COMMONWEALTH OF AUSTRALIA

Copyright Regulation 1969

WARNING

This material has been copied and communicated to


you by or on behalf of Curtin University of
Technology pursuant to Part VB of the Copyright
Act 1968 (the Act)

The material in this communication may be subject


to copyright under the Act. Any further copying or
communication of this material by you may be the
subject of copyright protection under the Act.

Do not remove this notice


Clinics Starts Week 2 (12 Aug)
When
Wed, 9am 1pm
Fri, 1pm 5pm
Where
204:305
Volunteers Required
To Teach is to Learn Japanese Proverb
Student learners required as peer mentors to
assist other students in the lab
If that is you, email me to express your
interest any time within this semester. Please
include your lab class day and time in your
email
Feedback
Our Feedback
Where to get them?
Your Feedback
Useful to maintain quality learning
environment
Engineering Programming
Lectures 2 & 3: Fundamentals

Dr Tele Tan
Last Week
Introduction to computer architecture
The Unix environment
Compiling a C program
This Week
Simple C expressions
Variables and data types
Common C operators
Simple input and output
Hurray ! - C Compiler for Windows
New Release of Orwell Dev C++ (both 32 and 64 bits)
http://www.sourceforge.net/projects/orwelldevcpp/
Dev-C++ Compiler (unsupported version)
http://www.bloodshed.net/devcpp.html (Win XP and
Win 7)
http://www.windows8downloads.com/win8-dev-c--
wdoxnrth/ (Win 8 only)
Open Source
Easy to use editing environment
Must save file with a .c extension eg. program.c
What about Mac users?
Option 1
Need to first install Xcode by visiting App
Store. Xcode is free for Mac OS X users
Then follow instructions from this link to
install the gcc compiler -
http://www.cyberciti.biz/faq/howto-apple-
mac-os-x-install-gcc-compiler/
Example program
Program to multiply two numbers together

#include <stdio.h>

int main(void)
{
int i,j,k;
printf("input two integers to multiply:" );
scanf("%d %d", &i, &j);
k = i * j; pseudo code
printf("result: %d\n",k);
start
} i, j integers
output input two integers to multiply
input i and j
k is i * j
output result: k
end

code2_1.c
Dev-C++
Identifiers
Used to name variable, data structures and
other entities (e.g. constant) in the program
Symbolically represent memory locations
Let the compiler sort out the memory address
Basic attributes: name, type, size, value
Rules for naming identifiers:
Alphabetic characters, digits and
underscore _ are all ok
First character cannot be a digit
Identifiers - Name
Valid names:
a, a1, student_number, _year
e.g. a = a1 + 3;
e.g. student_number = 1324575;
e.g. _year = 2011;
Invalid names:
2names // cant start with a number
student number // cant have spaces
int // cant be a reserved word
Reserved Words
Do not use the following for identifier names:

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

These are predefined for certain operations in


the C language
Will give compiler errors
Identifiers - Type
Integers (or whole numbers):
0, 1, 2, ...
different sizes/range: short int, int, long int
can be unsigned (e.g. positive numbers only)
Floating point numbers (or decimal numbers):
0.3, 3.14152, 2E10, ...
different memory sizes/precision: float, double
always signed (e.g. positive and negative
numbers)
Characters:
A, B, y, n, 1, 2, %, $, ...
Series of characters make up a string. e.g.
Engineering Programming
Strings
Would expect the need to represent a number of
characters in a variable
Student name
Address etc.
String: char name[50];
Reserves 50 bytes for the name
Eg. Representing Chris would be
name[0]=C; name[1]=h;
name[2]=r; name[3]=i;
name[4]=s;
Special type of an array (see later in the unit)
String - Code
/* Demonstrate the String Data Type */

#include <stdio.h>

int main(void)
{
char name[50]="Tele Tan";

printf("name is %s\n", name);


printf("First character is %c\n",name[0]);
printf("Second character is %c\n",name[1]);
printf("Third character is %c\n",name[2]);
printf("Fourth character is %c\n",name[3]);
printf("Fifth character is %c\n",name[4]);
printf("Sixth character is %c\n",name[5]);
printf("Seventh character is %c\n",name[6]);
printf("Eighth character is %c\n",name[7]);

return(0);
}

code2_2.c
Identifiers - Memory Size
Important to choose right memory size of a
variable:
Whole numbers can be:
char - 1 byte (8 bits) -> -128 to 127
unsigned char - 1 byte (8 bits) -> 0 to 255
short - 2 bytes (16 bits) -> -32768 to 32767
int - 4 bytes (32 bits) -> -2147483648 to 2147483647
long long - 8 bytes
Decimal numbers can be:
float - 4 bytes
double - 8 bytes
long double - 12 bytes
Important - will be machine specific!
/* Report on size of data types */

#include <stdio.h>

int main()
{
printf("Size of char is %d byte\n",sizeof(char));
printf("Size of unsigned char is %d byte\n",sizeof(unsigned char));
printf("Size of short is %d bytes\n",sizeof(short));
printf("Size of int is %d bytes\n",sizeof(int));
printf("Size of long long is %d bytes\n",sizeof(long long));

printf("Size of float is %d bytes\n",sizeof(float));


printf("Size of double is %d bytes\n",sizeof(double));
printf("Size of long double is %d bytes\n",sizeof(long double));

return (0);
}

code2_3.c
Data Type
Each data value has a type
Gives meaning to identifiers (e.g. variables)
Compiler needs this information
Challenge is choosing the best type
Which is best for the following?
temperature ?
year_of_birth ?
student_name ?
Data Type
Each data value has a type
Gives meaning to identifiers
Compiler needs this information
Challenge is choosing the best type
Which is best for the following?
temperature - float (e.g. 37.4)
year_of_birth int (e.g. 1987)
student_name string (e.g. Chris)
What about these?
date_of_birth:
Day-Month-Year
one 6 (or 8) digit integer or 3 integers?
age:
Year-Month-Day or Year only
one 6 digit integer, 3 integers or 1 float?
phone_number:
one integer or a string of characters?
You, the designer/programmer, have to
choose the most appropriate data type
Example Data Types
int amount; // declare amount of type integer
int amount = 0; // can assign initial value, in this case 0
float salary; // declare salary of type float
float salary = 2134.04; // assigned an initial value of 2134.04
char response; // declare response of type character
char response = "y"; // assigned an initial value of "y"
char name[50]; // declare name of type string
char name[50] = "Tele Tan"; // assigned an initial value

Note use of the assignment operator =


Previous Code Example

10 #include <stdio.h>
20
30 int main(void)
40 {
50 int i,j,k; /* declare integers i, j and k */
60 printf("input two integers to multiply:" );
70 scanf("%d %d", &i, &j);
80 k = i * j; /* assign the value of k as i*j */
90 printf("result: %d\n",k);
100 return(0);
110 }
Constants
Need to be able to define variables that cant
change
Use of #define:
#define PI 3.141592653
#define E 2.718281828
Every occurrence of the symbol changed
to the value by the compiler
Use of const:
const float PI = 3.1415912653;
const float E = 2.718281828;
Treated like a variable but any attempt to
change produces a compiler error
Example Code for Constant

10 /* Compute the area of a circle */


20 /* given the radius */
30
40 #include <stdio.h> pseudo code
50 #define PI 3.141592653
start
60 /* constant PI defined here */ radius, area: float
70 output input the radius
80 int main(void) input radius
90 { area = PI*radius*radius
100 float radius, area; output result: area
end
110 printf("input the radius:" );
120 scanf("%f", &radius);
130 area = PI * radius * radius;
140 printf("area: %f\n",area);
150 return(0);
160 }

code2_4.c
Example Code for Constant

10 /* Compute the area of a circle */


20 /* given the radius */
30
40 #include <stdio.h>
50 #include <math.h> /* include the built in math library */
60 #define PI 3.141592653
70 /* constant PI defined here */
80
90 int main(void)
100 {
110 float radius, area;
120 printf("input the radius:" );
130 scanf("%f", &radius);
140 area = PI * pow(radius,2); // using the pow math library here
150 printf("area: %f\n",area);
160 return(0);
170 }

code2_5.c
Arithmetic expressions
Use:
add (+), subtract (-), multiply (*), divide (/), brackets
Examples:
x = 3;
x = y + 5;
x = x + 2;
x++; // increment x by 1
x--; // decrement x by 1
x = a + b + c;
x = (a + b + c) / ( y * 10);
y = sin(x) / cos(x); // uses built in functions
Evaluating expressions
Generally processed in the following order:
Functions,
Multiply/divide
Add/subtract
BODMAS: Brackets, pOwers, Division, Multiplication,
Addition, Subtraction
If in doubt, use parentheses
Special case:
y = 3 + x++; // if x = 6, what is y?
y = 3 + ++x; // if x = 6, what is y?
Evaluating expressions
Generally processed in the following order:
Functions,
Multiply/divide
Add/subtract
BODMAS: Brackets, pOwers, Division, Multiplication,
Addition, Subtraction
If in doubt, use parentheses
Special case:
y = 3 + x++; // result: y = 9, when x = 6
y = 3 + ++x; // result: y = 10, when x = 6
Evaluating expressions
Special case:
y = 3 + x++; /* result: y = 9, when x = 6 */
Equivalent to
y = 3 + x; /* x = 6; y = 9; */
x++; /* x = 7 */
Special case:
y = 3 + ++x; /* result: y = 10, when x = 6 */
Equivalent to
x++; /* increment x. eg. x = 7; */
y = 3 + x; /* y = 10; */
Math Built In Functions
Some common math operations are prewritten and
available as a library of functions.
Must include the Math library in C
e.g. #include<math.h>
Compilation
gcc program.c -lm
Math functions include:
sin(x), cos(x), tan(x),
asin(x), acos(x), atan(x),
sinh(x), cosh(x), tanh(x),
exp(x), log(x), log10(x),
pow(x,y), sqrt(x), fabs(x)
Further learning from

https://www.youtube.com/watch?v=b00HsZvg-V0
Linux VM is on the EFY Studio PC
Last Week
Identifier name, type, size, value.
Data Types char, int, float and string.
Define Constant eg. PI and E.
Simple Arithmetic expression use of Built-in
Math Library in C.
Mixed-mode expressions
Mixing different data types in the same
expression, e.g.:
integers and floats
different types of integers
Converts to larger data type (to keep
accuracy)
char + float -> float
int - short -> int
int * double -> double
(short + long) / float -> long then float

code2_7.c
Explicit type conversion
Given:
int a, b;
float y, z;
Can do:
y = z + (float) a;
b = (int) y; // will lose fraction
Good to be explicit for readability
Test your understanding
Declarations:
int num_one;
long num_two;
float num_three;
double num_four;
double result;

What is the type for result in the expression:


result = (long)num_one + num_two + (long) num_three;

(a) int
(b) long
(c) float
(d) double
Boolean variables
Need the concept of true and false
FALSE:
Usually defined as zero (0)
TRUE:
Can be defined as one (1)
Better to say not FALSE; complement
#define FALSE 0
#define TRUE !FALSE
Boolean operators
Uses:
and: &
or: |
equals ==
not equal: !=
greater than: >
less than: <
greater than or equal: >=
less than or equal: <=
Boolean expressions
int x;
int y;
int z;

x = 4;
y = 4;

printf("x=%d y=%d\n",x,y);
z = x == y; // z set to 1 (TRUE)
printf("(x==y) Value of z is %d\n",z);
z = x != y; // z set to 0 (FALSE)
printf("(x!=y) Value of z is %d\n",z);

x = 2;
y = 4;

printf("x=%d y=%d\n",x,y);
z = x < y; // z set to 1 (TRUE)
printf("(x<y) Value of z is %d\n",z);
z = x > y; // z set to 0 (FALSE)
printf("(x>y) Value of z is %d\n",z);

code2_6.c
Simple arrays
The need to consider groups of the same data types
occurring regularly
Characters in a string
Elements in a matrix or vector
A list of students and their details
Pixels in an image
A sequence of samples from an audio signal
Dont want one variable for each element!
e.g. a0=0.23; a1=1.45; ...; a1999=0.78;
Use arrays (note most computer languages include

arrays)
Can make arrays from any data type:
int, float, double, char and etc.
Arrays
Examples:
int ages[100];
stores the ages of 100 people from 0 to 99
needs 400 bytes of memory: (100 * 4 bytes)
assignment; ages[0]=22; ages[1]=25; ...;
ages[99]=43;
unsigned char image[512][512];
stores all the elements of a monochrome image with 512
columns and 512 rows.
elements range from [0][0] to [511][511]
needs 512 * 512 = 262,144 bytes of memory
Array - Example
float student_test_mark[5];

student_test_mark[0]=85.5;
student_test_mark[1]=60.3;
student_test_mark[2]=45.1;
student_test_mark[3]=0.0;
student_test_mark[4]=99.9;
Multidimensional array addressing
Two dimensional array declaration:
int image[5][5];
Columns Rows Columns
[0][0] [0][1] [0][2] [0][3] [0][4]

[1][0] [1][1] [1][2] [1][3] [1][4]

[2][0] [2][1] [2][2] [2][3] [2][4]


Rows
[3][0] [3][1] [3][2] [3][3] [3][4]

[4][0] [4][1] [4][2] [4][3] [4][4] For speed, process all


columns first for each
row
Array definitions
Need to be defined at compile time
Need to use constants or numbers to define array sizes
Can do:
int a[5];
Cant do:
int x = 5;
int a[x];
But can do (with constant):
#define x 5

int main(void)
{
int a[x];
}
Can be initialised with a list:
int a[4] = {2, 5, 3, 8};
char name[10] = "Sue";
Arrays
Access to elements:
int ages[100];
First element:
x = ages[0];
Last element:
x = ages[99];
Use of expressions:
x = ages[i - 3];
x = ages[y * 3 + 1];
Example of array manipulation
Multiplying two vectors:
#include <stdio.h>

int main()
{
int vect_1[3] = {2,1,3}; // set values for vect_1 array
int vect_2[3] = {1,0,1}; // set values for vect_2 array
int result;

result = vect_1[0]*vect_2[0] + vect_1[1]*vect_2[1]


+vect_1[2]*vect_2[2];

printf("result = %d\n",result);

return(0);
}

code2_8.c
Example of array manipulation
Multiplying two matrices:
int mat_1[3][3];
int mat_2[3][3];
int result[3][3];

/* multiple mat_1 by mat_2 */


result[0][0] = mat_1[0][0]*mat_2[0][0]
+ mat_1[0][1] * mat_2[1][0]
+ mat_1[0][2]*mat_2[2][0];
result[0][1] = mat_1[0][0]*mat_2[0][1]
+ mat_1[0][1] * mat_2[1][1]
+ mat_1[0][2]*mat_2[2][1];
etc.
You check and work this out
Long winded - use looping to deal with this later in
the unit
Matrix Multiplication Example
Strings as arrays
One dimensional array
String: char name[15];
Reserves 15 bytes for the name
Special type of an array
Access elements of a string:
char name[50] = "Joe Blogg";
name[0] is J
End of string marker
name[6] is o
Address 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14
Contents J o e B l o g g \0
Input and output
Need to read from the keyboard and write to
the screen
Basic functions:
printf
scanf
Defined in the header file <stdio.h>
Formatted output: printf
Function provides for formatted output to the screen
Syntax:
printf ("format", var1, var2, ...);
The format includes a listing of the data types of the variables to be
output and, optionally, some text and control characters
Examples:
float a = 3.2;
int b = 3;
printf ("%f %d\n", a, b);
/* Outputs: 3.2 3 */
/* "\n" causes the cursor to jump to the next line (carriage return, line feed) */

printf ("a and b are: %f and %d \n", a, b);


/* Outputs: a and b are 3.2 and 3 */
/* "\n" causes the cursor to jump to the next line (carriage return, line feed) */
Output specifiers
%d - used to output an integer
%f - used to output a floating point number
%e - used to output a floating point number in
exponential format
%g - used to output in either e or f format
%c - used to output a single character
%s - displays a string of characters
%ld, %lf - used with d, f and etc. to handle
long variable types
printf: Dealing with floats
Special control format for floating point numbers (i.e.
numbers with decimal places).
Problem
float num = 3.2624;
How do you print num with varying decimal
places?
Example:
float num = 3.2624;
printf (num = %.2f\n", num);
/* output */
/* num = 3.26 */
printf (num = %.1f\n", num);
/* output */
/* num = 3.3 */
Formatted input: scanf
Function provides for formatted input from the keyboard
Syntax:
scanf ("format", &var1, &var2, ...);
The format includes a listing of the data types of the variables to be output and
control characters
NOTE the & is needed to tell the system where to store the input value i.e. its
address in memory
Examples:
float a;
int b;
scanf ("%f %d", &a, &b);
printf ("you entered %f and %d \n: ", a, b);

/* Inputs: 3.2 3 */
/* Outputs: you entered 3.2 and 3 */
Note
must use &
dont need \n as used in printf statements
Today we covered
Write simple C expressions
Variables and data types
Simple input and output
Some more example programs
Whats next?
Practical
Generate some programs
Deal with different variables, operators and
expressions
Lecture
Basic program design

Вам также может понравиться