Title: C for Java Programmers
 1C for Java Programmers
  2Last Lecture
- Last Lecture we had a look at 
 - Single Dimensional Arrays 
 - Multi Dimensional Arrays 
 - First Mention of Pointers 
 - C-Style Strings 
 - The Null Terminator 
 - String Manipulation 
 
  3Todays Lecture
- This lecture we will be looking at 
 - The ? command 
 - Structs 
 - Typedef Command 
 - Functions 
 - Unfortunately theres no pictures of Bjarney 
today.  - Nonetheless Bjarney is with us in spirit. 
 -  
 
  4The ? Operator
- You can use the ? operator to replace if-else 
statements  - However both the if and else parts must be part 
of the single expression  not another statement.  - The ? is called a ternary operator because it 
requires three operands.  - Just like regular expressions in perl, this is 
the main contributor for making C/C unreadable 
  5? operators General Form 
-  Exp1 ? Exp2  Exp3 
 - The value of a ? expression is determined as 
follows  - Exp1 is evaluated. 
 - If it is true Exp2 is evaluated and becomes the 
value of the entire ? expression  - If Exp1 is false, Exp3 is evaluated and then that 
value becomes the value of the ? expression. 
  6Example
-  y  x 9 ? 100  200 
 - This can be basically translated from Creek to 
mean  - If x is greater than nine, then assign 100 to y, 
and if x is not greater than 9 assign 200 to y.  - The point to note is that when using the ? 
operator, is that it will ultimately evaluate an 
expression - the following statement alone would 
do nothing   -  x 9 ? 100  200
 
  7When should you use it?
- Only use this operator when it is the right 
situation!  - The following statement shows how you might use 
the operator to return the square of a value i, 
but still preserving its sign  -  isquare  i0 ? ii  -(ii) 
 - However the next bit of code which returns a 
certain prime number dependent on i, would be 
better written and much easier to understand for 
any reader using a switch statement  - n  i1?1i2?3i3?5i4?711 
 
  8? evaluate expressions
- You can use any valid expressions after the ? 
such as  - int magic  10 
 - int guess  17 
 - if (guess  magic) cout Blaine 
 - else guess magic ? cout low
 
In this code fragment, having guessed wrong we 
use the ? operator to help us display on screen 
whether the guess was too high or too low. 
 9Expressions in Conditionals
- It can be confusing that that you are allowed to 
use any valid expression to control the if or the 
? operator.You are not restricted to expressions 
which use relational operators (as you are in 
basic or pascal)  - You can use any expression that resolves to a 
true (zero) or false (non-zero) value. For 
example  - if (b) cout 
 - else cout muppet 
 
  10Structures
- A structure is a collection of related data 
identified as a single storage unit.  - Each element in a structure is called a data 
member.  - After it has been declared, an instance of that 
structure can be created for use in your program.  - It is almost an unwritten law in Computer Science 
lectures that any examples of structures must, 
and I mean must, be boring. Im talking about 
stuff like address books or bus timetables. 
  11Jims Chauvinistic Struct
- struct vital_Statistics 
 -  
 -  char modelsName50 
 -  char hairColour20 
 -  long int age 
 -  int nrOfPublications 
 
Here our struct has two char arrays and 4 ints, 
but we could have used any data types, including 
other structs. 
 12And the code would be
- vital_statistics jordan 
 - strcpy( jordan.modelsName, Jordan) 
 - strcpy( jordan.hairColour, Brunette) 
 - jordan.age  24 
 - jordan.nrOfPubs  33
 
Note the use of the dot operator, sometimes 
called the direct membership operator.
integers and other fundamental types can be 
directly accessed. For the char arrays we use the 
strcpy function. 
 13You can have lots of instances
- Once you have defined the struct you can create 
as many instance as you want  - vital_Statistics brad 
 - strcpy( brad.modelsName, Brad Pitt) 
 - strcpy( brad.hairColour, Blonde-ish) 
 - brad.nrOfPubs  13 
 
Example for the girls so I dont get in trouble. 
 14Quick Initialisation
- Similar to the way you can initialise arrays when 
they are declared, you can also instantiate an 
object and supply all of its members at once  -  vital_Statistics anotherPerson   
 -  whoever, 
 -  ginger, 
 -  87 
 -  
 
You have to remember what order your data 
elements were declared 
 15Whats happening in memory?
modelsName (50 Bytes) 
hairColour (20 Bytes)
age (32 Bytes) 
nrOfPubs(16 Bytes) 
 16Manipulating Structures
- Accessing Structure Members  
 -  cout 
 - Assigning to Structure Members 
 -  jordan.age  24 
 - Assigning whole structures 
 -  vital_Statistics a,b 
 -  a.age  24 
 -  b  a 
 
Assigning one struct to the other. 
 17Arrays of Structures
- Perhaps the most common use of structures is in 
arrays of structures. To declare an array of 
structures, you must first define a structure, 
and then declare an array variable of that type  - vital_Statistics topTrumps52 
 - To access the structs variables simply index the 
the structure name as you would with a normal 
array  -  someString  topTrumps7.name 
 
  18Complex Structures
- Members of structures can either be of type 
 -  simple or compound 
 - Code fragment Example of a struct with compound 
members  -  struct phone_book  
 -  char address50 
 -  int number 
 -  vital_statistics info 
 -   
 
Any of the built in data types such as an integer 
or a character
Arrays of these fundamentals, or other structures 
themselves. 
 19Structs  the origin of Classes
- Structures are part of the C-subset and were 
inherited in C from the C Language.  - But C Structs are very closely related to C 
Classes.  - In C the role of a structure was expanded, 
allowing you to have both private and public 
variables and even methods. Its only difference 
from a class is that by default all members of a 
struct are public.  - Struct and Classes are so similar why keep 
structs at all?  - Tradition, but also because it allows the 
definition of a class to be free to evolve. 
Furthermore it allows C to remain compatible 
with C. 
  20User Defined Types
- You can define a new data type name using the 
keyword typedef.  - It doesnt actually create a new type, but rather 
defines a new name for one.  - General Form typedef type newName 
 - Example typedef float balance 
 
  21FUNCTIONS
- Functions are the fundamentals of Procedural 
Programming. C is a language of this type.  - Before OO this was how everything was written. 
 - In many instances this is how things are still 
written.  - Functions are the building blocks of C and C
 
  22Learning Progression 
 23General Form
- Functions compartmentalise a repetitive task. 
 - General Form is  
 - returnType functionName (parameter list) 
 - Example  
 -  float bowel(int i, char c)   
 
Functions can return any type of data except an 
array. This one returns a float.
body
name of the function
parameters 
 24Example  An Addition Function
- include 
 - int foo(int a, int b)  
 -  int r 
 -  rab 
 -  return (r) 
 -  
 -  
 - int main ()  
 -  int z 
 -  z  foo(5,3) 
 -  cout 
 -  
 
Our function foo, that sums numbers
statement that calls the function and puts it 
into z. 
 25Formal Parameters
- If a function takes in arguments as in the above 
example you must declare variables for them to go 
in.  -  int foo(int a, int b) 
 -  z  foo( 5, 3) 
 - Even if you declare these the same name as those 
used in your main program, they are not the same 
variables. 
  26Sending Parameters
- You can pass variables into a function by two 
methods - value or by reference.  - When you pass a variable by value into a 
function, the variable passed in is only changed 
locally within the function. Essentially it is 
copied across.  - Passing by reference makes global changes to a 
variable passed in. To pass by reference we use 
the address operator  when we receive the 
argument. 
  27Passing by Value
-  void cube(int x) 
 -   
 -  x  xxx 
 -  cout 
 -   
 -  
 -  // MAIN PROGRAM 
  -  int main() 
 -   
 -  int number  3 
 -  cube(number) 
 -  cout 
 -   
 - OUTPUT  The answer is 27 and the number is 3
 
  28Passing by Reference
-  void cube(int  x) 
 -   
 -  x  xxx 
 -  cout 
 -   
 -  
 -  // MAIN PROGRAM 
  -  int main() 
 -   
 -  int number  3 
 -  cube(number) 
 -  cout 
 -   
 - OUTPUT  The answer is 27 and the number is 
27 
  29Scoping
- As you know scope rules govern whether a piece of 
code knows about or has access to another piece 
of code or data.  - Each function is a discrete piece of code  
everything inside it is essentially hidden from 
the rest of the program.  - So Variables defined within the function are 
local to it.  - The function can only see its own data  apart 
from any global variables that you use. Strive 
against global variables however. 
  30Having Arrays as Parameters
- We discussed arrays last lecture and I mentioned 
that sending arrays to functions was not 
straightforward.  - Passing arrays is an exception to the normal 
send-by-value parameter passing.  - There are several ways of passing arrays to 
functions but in each case we only pass the 
arrays address. This is very similar what we just 
considered when we were passing variables by 
reference.  - Because of this we are not sending a copy - any 
changes in the function will affect our original 
array! 
  313 methods for passing Arrays
- void foo1 (int x10) //sized array 
 -  
 -   
 -  
 - void foo2 (int x) //unsized array 
 -  
 -   
 -  
 - void foo3 (int x) //pointer 
 -  
 -   
 
Here we take in an address and use x to remember 
it as an array with 10 elements
but the length of the array doesnt matter as 
far as C is concerned
final method uses a pointer. 
 32Passing Multidimensional Arrays
- Be careful when sending multi-dimensional arrays 
to functions  
void mal (int x45)    int 
main()  int hipHip333  mal(hipHip)  
For a multi-dimension array we must declare all 
but the first of the dimensions 
 33The main function
- A C program must have a main function of some 
form, to act as an entry point.  - N.B. This is a function and not a method. 
 - In Java everything is a class  not so in C. 
 - main is a function like any other function, and 
acts in exactly the same way 
  34Arguments to main()
- Just as other functions can take arguments, so 
can your main function.  - Generally you pass information into the main via 
command line arguments, that follow the programs 
name when you are executing it.  - There are two special built in arguments  argv 
and argc, that are used to receive information 
from the command line.  - argc  holds the number of arguments entered 
 - argv  is an array of these arguments themselves
 
  35Example of command line info
- int main (int argc, char argv) 
 -  
 -  if (argc!2)  
 -  cout 
 -   
 -  cout 
 -  
 
check on the number of arguments 
statement that ouputs the info to the screen.
example of use if we had compiled the code as 
myProgram. 
 36Return Statement
- The return statement can be used to leave a 
function at any point  - It is essentially a jump statement (like break 
and continue) because it jumps back to the point 
in your program where the function was called.  - A return statement may or may not have a value 
associated with it.  - However if your definition indicated that it 
would send back a value, any return statement 
must send back a value of that type. 
  37multiple returns
- a function may contain several return statements. 
For example, here is some code for a function 
that checks the sign of any integer passed into 
it  
int completeDys(int number)  if (numberreturn 1 if (number0) return 1 return 0 
If true returns to the main program before 
reaching the next statement 
 38So what does main() return?
- You dont have to use a return statement  the 
block of code will return itself when it hits its 
final curly bracket.  - When you use the command in the main function it 
returns an integer to the calling process, which 
is generally the operating system.  - If you dont send a return from main() what 
happens is technically undefined. Better safe 
than sorry and always put it in.  - The Exit(0) statement is very similar to return. 
 
  39Function Prototypes
- Until now, we have defined the functions before 
the first appearance of a call to it, leaving the 
function main for the end.  - If you try to repeat some of the examples of 
functions described until now but placing the 
function main before any other function that is 
called from within it, you will most likely 
obtain an error.  - The reason is that to be able to call to a 
function it must have been declared previously - 
it must be known.  
  40Prototyping functions
- We can avoid this by prototyping functions. 
 - This consists of making a previous shorter 
declaration of the complete definition, so that 
the compiler can know the arguments and the 
return type needed.  -  
 -  returnType functionName (parameter types) 
 
ends with a semicolon
It is enough to list the parameter types alone if 
you wish
Almost identical to a function header, except it 
has no code body and 
 41Example of Prototyping
- include 
 - void odd (int a) 
 - void even (int a) 
 - int main ()  
 -  int i 
 -  cout 
 -  cin i 
 -  odd (i) 
 -  
 - void odd (int a)  
 -  if ((a2)!0) cout 
 -  else even (a) 
 -  
 
prototypes 
 42Recursion
- Functions can, and often do, call other 
functions.  - Recursivity is the property that functions have 
to be called by themselves.  - Recursion is the process of defining something in 
terms of itself, sometimes called circular 
definition.  - Recursion is useful for all sorts of tasks  
examples are certain sorting methods or to 
calculate the factorial of a number.  
  43Example  Factorial Calculator
- include 
 - long factorial (long a)  
 -  if (a 1) return (a  factorial (a-1)) 
 -  else return (1) 
 -  
 - int main () 
 -  
 -  long l 
 -  cout 
 -  cin l 
 -  cout 
 -  return 0 
 -  
 
A Recursive function, calling itself, but 
stopping when a reaches 1 
 44Being recursive
- Most recursive routines dont significantly 
reduce code size or improve memory utilisation.  - Recursive routines may also run slower because of 
the repeated function calls, or could eventually 
cause the stack to potentially overrun.  - However recursive solutions can be very elegant 
and they lend themselves to certain problems 
especially well (in AI for example).  - They also tend to make you feel pretty damn 
clever.  
  45Exercise of the day
- Rewrite the step in your 3N1 program using the ? 
operator.  - Incorporate the 3N1 algorithm into a function 
T(t,n,s), accepting a table t, a dimension n and 
a seed s as parameters. The function should fill 
t with the first n numbers in the 3N1 row 
starting from s and return the number of steps 
until a loop is detected.  - Put the table t and the dimension n into a 
structure and use it as a parameter for the 
function. Should it be passed by value or by 
reference? Experiment with both. 
  46C Extras
- There are quite a few difference in what a 
function in C is capable of in comparison to 
functions in C.  - Function Overloading 
 - Default Parameters 
 - Class Member Functions 
 - Inline Functions 
 - Well look at these next lecture