Sei sulla pagina 1di 38

Type Constructors :

Arrays and Functions

Array

A group of contiguous memory locations used to


store a series of related values
Individual elements of an array are accessed via
an integer index: array[index]
Element indices start at 0: array[0] is the first
element
Common graphical representations of an array
[0]
[1]
[2]
[3]
[0][1] [2][3] [4][5]

[17] [18][19]

[18]
[19]

Arrays are the oldest form of composite data structure,


first found in FORTRAN (FORmula TRANslator, 1955),
the first high-level programming language, designed by
IBM for number-crunching and still in use today:
FORTRAN is a hardy weed

Array Declarations
Arrays contain a fixed number of variables of
identical type
Array declaration and allocation are separate
operations
Declaration examples:
int[ ] counts;
double[ ] scores;
String[ ] studentNames;

Array Allocation
Arrays are allocated using operator
~Arrays are special in Java

The syntax is:


new type[size];
Examples:

counts = new int[10];


scores = new double[15];
studentNames = new String[10];

Array Organization
0

counts

Each box is an int variable


The numbers on top are each variables
subscript or index
An array of size 10 has subscripts 0 to 9

Array Subscripts
Arrays can contain any one type of value
(either primitive values or references)
Subscripts are used to access specific array
values
Examples:
counts[0] // first variable in counts
counts[1] // second variable in counts
counts[9] // last variable in counts
counts[10] // error trying to access
// variable outside counts

Expressions as Subscripts
Array subscripts do not have to be constants
Array subscripts do need to be integer
expressions that evaluate to valid subscript
values for the current array allocation
Examples:
counts[i]
counts[2*i]
counts[I/2]

Array Initialization
Arrays can be initialized by giving a list of
their elements
If your list contains n elements the
subscripts will range from 0 to n 1
You do not need to allocate the array
explicitly after it is initialized
Example:
int [] primes =
{2, 3, 5, 7, 11, 13, 17, 19, 23, 29};

Initializing an Array of Strings


final Sring[ ] NAME = {
Sunday, Monday, Tuesday,
Wednesday, Thursday, Friday,
Saturday};
// procedure that prints the day of week
public void printName (int day,
OutputBox out) {
out.print(NAME[day 1]);
}

Aliases
It is possible to have two different variables refer to
the same array
When this happens these variables are called
aliases
Creating aliases is not a good programming
practice
Example of how it can happen:
int [ ] A, B;

B = new int [10];


A = B;

Passing Arrays to
Functions

The array is passed


as an array of unspecified size (int
array[ ])
OR
as a pointer (int *array)
Changes to the array within the function affect
the
original array

Array Programming Language


The fundamental idea behind array programming is
that operations apply at once to an entire set of
values.
The basis behind array programming and thinking is
to find and exploit the properties of data where
individual elements are similar and/or adjacent.
Array programming primitives concisely express
broad ideas about data manipulation.

Functions

"the concept of function is probably the single


most important idea in mathematics" and "the
idea of function is inherent in many parts of
today's algebra and geometry programs

-Lisa Sheehy

A function is a group of statements that is executed when it is


called from some point of the program
type name ( parameter1, parameter2, ...) { statements }
where:
type is the data type specifier of the data returned by the function.
name is the identifier by which it will be possible to call the
function.
parameters (as many as needed): Each parameter consists of a data
type specifier followed by an identifier, like any regular variable
declaration (for example: int x) and which acts within the function
as a regular local variable. They allow to pass arguments to the
function when it is called. The different parameters are separated
by commas.
statements is the function's body. It is a block of statements
surrounded by braces { }.

// function example #include <iostream>


int addition (int a, int b)
{
int r;
r=a+b;
return (r);
}
int main ()
{ int z;
z = addition (5,3);
cout << "The result is " << z;
return 0;
}

main function begins by declaring the variable z of type


int. Right after that, we see a call to a function called
addition. Paying attention we will be able to see the
similarity between the structure of the call to the
function and the declaration of the function itself some
code lines..

The parameters and arguments have a clear


correspondence. Within the main function we
called to addition passing two values: 5 and 3,
that correspond to the int a and int b parameters
declared for function addition.

Function-level
programming

-refers to one of the two contrasting programming paradigms


identified by John Backus in his work on programs as
mathematical objects, the other being value-level
programming.
-In the function-level style of programming, a program is built
directly from programs that are given at the outset, by combining
them with program-forming operations or functional

References
An Introduction to Computer Science Using Java (2nd Edition)
by S.N. Kamin, D. Mickunas, E. Reingold
Dick Pountain. Functional Programming Comes of Age. BYTE.
COM (August 1994). Retrieved on August 31, 2006.

POINTER & RECURSIVE


TYPES
-James Roldan L. Lopez

POINTER

programming language data type whose value


refers directly to (or points to) another value
stored elsewhere in the computer memory using its
address.
Memory
Address

Contents
1000 1004
1001
1002
1003
1004

* Pointers are addresses

POINTER VARIABLES

a variable that holds a pointer.

Declaration:

type * name

Where:
type defines the type of pointer variable
name pointer variable name

POINTER OPERATORS

& (ampersand) and * (asterisk)

1) & - a unary operator that returns the memory


address of its operand.
Ex:
assume: count = 100, and uses the memory
location 2000 to store its value.
m = &count;

/* m receives the address of count, m = 2000 */

POINTER OPERATORS
2) * - a unary operator that returns the value of
the variable located at the address that follows.
Ex.
m contains the memory address of the variable
count.
q = *m;

/* q receives the value at address m, q = 100 */

SAMPLE PROGRAM
#include<stdio.h>
main(void)
{
int count, q;
int *m;
count = 100; /* count is assigned to 100 */
m = &count; /*m receives counts address */
q = *m; /*q is assigned counts value indirectly
printf(%d, q); /* prints 100 */
return 0;
}

through m*/

POINTER EXPRESSIONS
Pointer Assignments
Pointer Arithmetic

POINTER ASSIGNMENTS

A pointer may be used on the right-hand side of assignment


statements to assign its value to another pointer.
Ex.
#include<stdio.h>
main(void)
{
int x;
int *p1, *p2;
p1 = &x;
p2 = p1;
/*p1 and p2 will have the same value*/
printf(%p %p, p1, p2);
return 0;
}

POINTER ARITHMETIC
1)
2)

Addition
Subtraction

Ex. Let p1 & p2 be a pointer to an integer with a current value of


2000, and assume that integers are 2 bytes long. After the
expression
p1++;

p2--;

p1 = 2002,

p2 = 1998

* Each time a pointer is incremented or decremented, it points to the


memory location of the next/previous element of its base type.

POINTER ARITHMETIC
In the case of pointers to characters this appears
as normal arithmetic.
All other pointers inc/dec by the length of the
data type they point to.
Ex.
Assume 1-byte characters, 2-byte integers:
-when a char pointer is incremented, its
value increases by 1.
-when an int pointer is incremented, its
value increases by 2.

POINTER ARITHMETIC
char *ch = 3000;
int *i = 3000;
ch

3000

ch+1

3001

ch+2

3002

ch+3

3003

ch+4

3004

ch+5

3005

}i
}
}

i+1
i+2

All pointer arithmetic is done relative to the base type of the pointer
so that the pointer is always pointing to another element of the base type

TURBO CS DYNAMIC ALLOCATION


FUNCTIONS
Once compiled, all C programs organize the computers memory into
four regions which holds program code, global data, the stack and
the heap.
Heap is an area of free memory that is managed by Cs dynamic
allocation functions malloc() and free().

malloc() a function that allocates memory and returns a pointer


to the start: void *malloc(size_t num_bytes);
free()- returns previously allocated memory to the heap for possible
reuse: void free(void *p)
Ex.
char *p;
p = malloc(25);
Evaluation: p points to the first of 25 bytes of free memory, no type
cast is used,

POINTERS & ARRAYS

Two Methods of Accessing an Array Element


1) Array
2) Pointer

Ex.
char str[80], *p1;
p1 = str;

/* p1 is set to the address of the 1st array element in


str */

Assume to access the 5th element using pointer & array:


str[ 4 ]
*(p1 + 4)
*Pointer arithmetic can be faster than array-indexing.

POINTERS
Provide the means by which functions can modify
their calling arguments
To support dynamic allocation system
To improved the efficiency of certain routines
To support certain data structures such as linked
list and binary trees.

RECURSION
A method of defining functions in which the function being
defined is applied within its own definition. The term is also used
more generally to describe a process of repeating objects in a selfsimilar way.
Ex.
/* Compute the factorial of a number */
factr(int n) /* recursive */
{ int answer;
if(n==1) return (1);
answer = factr(n-1) *n;
return(answer);
}
Evaluation:
- factr() is called w/ an argument of 1, the function returns 1;
otherwise it returns the product of factr(n-1)*n.

ADVANTAGE OF RECURSIVE
FUNCTION

To create versions of several algorithms that are


clearer and simpler than their iterative
equivalents.
Ex. quicksort, mergesort, etc.

END

Reference:

Wikipedia.com

Schildt, Herbert. Turbo C/C++: The Complete Reference, 2 nd Ed. McGrawHill, 1992.

Potrebbero piacerti anche