Transcript Lecture 6

Chapter 7
One-Dimensional Arrays
C Programming for Scientists &
Engineers with Applications
by Reddy & Ziegler
Numeric Arrays
1-D Arrays and Printing Array Elements



An array is a data structure in C
A grouping of like-type data
Topics




Definition of arrays
Characteristics of an array
Using #define directive to define array size
Printing array elements
1-D Arrays

What is a one-dimension array and how do we
declare it?
element_type array_name [number_of_elements];



element_type specifies the type of the array’s elements
array_name is the name of the array
number_of_elements specifies the max number of
elements that can be stored in the array.
1-D Arrays

int a[2];
declares
the name of the array is a
the type of array elements is int
the dimension is 1 (with one pair of brackets [])
the number of elements or size is 2
1-D Arrays

How to name an array?




Array names are classified as identifiers.
c[15], f3_rack[4] (legal identifiers)
12abc[15], y4#[23] (illegal identifiers)
How to distinguish between a 1-D, 2-D, or 3-D
arrays?



int a[2];
int b[2][3];
int c[2][3][2];
1-D Array

What is the first index (also called subscript) of an
array in C?


In C, by default, the first index or subscript is 0.
int a[2];



Since C begins at 0, a[0] and a[1] are used in the
program body.
We should not use a[2] in the program body.
With a[2], the program may execute completely and
give answers (which very likely will be wrong).
1-D Array

How to print an array element using printf?


Treat an array element like we treat a single variable
printf(“a[0] = %3d, a[1] = %3d”, a[0], a[1]);
printf(“b[3] = %8.2f, b[6] = %8.2f”, b[3], b[6]);
What types of variables can be used for array
indices?


Integer type variables such as int
char with their modifiers signed, unsigned, short, and
long

/* Program for Lesson 6_1 */






#define N 10
void main(void)
{
int a[2];
double b[N];



a[0]=11;
a[1]=22;



b[3]=777.7;
b[6]=888.8;






printf("a[0] = %3d, a[1] = %3d\n", a[0],a[1]);
printf("b[3] = %8.2lf, b[6] = %8.2lf \n", b[3],b[6]);
printf("b[2] = %lf\n", b[2]);
The results make no sense.
printf("a[3] = %d\n", a[3]);
}
Array Initialization

Topics



Methods for initializing array elements in declarations
Initialing array elements using scanf
Initialing array elements using assignment statements
in loops
Initialization
What are two ways to initialize the elements of a
1-D array in a declaration?

1.
type name [number_of_elements] = {value_0, …, value_n}


2.
int a[3] = {11, 22};
a[0] = 11, a[1] = 22, and a[3] = 0.
type name [] = {value_0, …, value_n}



int b[] = {44, 55, 66};
Advantages: unnecessary to change the number of elements
values and count the number of array elements
Disadvantages: may lead to out-of-range errors
Initialization

How else to initialize an array?


Use a read function, such as scanf
 double x[2];
 scanf(“%lf %lf”, &x[0], &x[1]);
Use an assignment statement
 double y[10];
 for (i=0; i<10; i++)
 {

y[i] = i*100.0;
 }
Initialization


Would the declaration “int b[2]={44, 55, 66}”
have caused an error in C?
Yes! Since b has only 2 elements, we listed three.
Although C will not detect out-of-range errors
with arrays, it will detect this error.
One-Dimensional Arrays



The simple built-in data types of the C language int, float, double, and char - are not sufficient to
represent complex data such as lists, tables,
vectors, and matrices.
A one-dimensional array is a data type derived
from the basic built-in data types.
In scientific and engineering computations, there
are vectors, matrices, and determinants.


The flight path of a space shuttle, projectile or
orbiters, as well as pressure measurements under
the sea floor, are all recorded and stored as lists
using one-dimensional arrays.
Operations such as sorting and searching require
an entire list of data to be stored in memory. This
is accomplished by storing the data in a onedimensional array.
7.1 One-Dimensional Arrays



Subscripts and Subscripted Variables
Declaration of Arrays
Initialization of Arrays
array




An array is a named sequence of memory locations
that is used to store data of a homogeneous data type.
Each of the named memory locations is called an
element of the array.
The elements of an array are identified by a subscript
or an index.
Here are some practical applications: altitude, depth,
pressure, velocity, and temperature measurements
may be stored in one-dimensional arrays.
Subscripts and Subscripted
Variables
Declaration of Arrays
Initialization of Arrays
7.2
Input of One-Dimensional Arrays

Array Input


The input of data to a one-dimensional array may use
indexing, or may use array pointers or dynamic
pointers which will be presented in Chapter 10.
Input of Parallel Arrays
Array Input
Input of Parallel Arrays
7.3
Output of One-Dimensional Arrays

Array Output


Output may be displayed on a monitor, printed using a
printer, or written to an output data file.
Output of Parallel Arrays
Array Output
Output of Parallel Arrays
Manipulation of Arrays



Arithmetic, relational, and logical operations can
be performed on array elements.
An array can be added to another array and the
result can be stored in a third.
All these operations are performed element-byelement using for loops.
7.4 Manipulation of Arrays


Array Assignment
Array Arithmetic
Array Assignment
Array Arithmetic
Passing Arrays to Functions




Arrays can be passed to functions as though they
were single variables; but rather than being a set of
values, an array name is an address constant.
An entire array is effectively passed by using the
array name as an argument, which passes the address
of the array.
If an array is passed element-by-element as single
variables, the elements may be passed by value or
explicitly by pointer.
It is a normal practice to pass arrays by name into
input functions, thus the input values from the
function are passed back to the storage allocated in
the calling function.
7.5 Passing Arrays to Functions


Passing Fixed-Sized Arrays
Passing Array Elements
Functions and 1-D Arrays

Topics




Passing individual array elements to functions
Passing entire arrays to functions
Passing entire arrays to functions with a restriction
Illustrate how values and address of array elements are
passed
Function Call

How to pass a single array element to a function?




We treat a single element like a simple variable.
If we want to change the value of the array element in
the function, we use the “address of” operator, &,
before the array element in the function call.
If we want to pass element without having it changed in
the function, we simple put the array element in the
parameter list.
function1(&a[5], a[8]);
Function Prototype



When receiving an address, we must use a pointer
variable (indicated in the declaration by *).
When receiving a value, we use a simple variable.
void function1(int *d, int e);
function1(&a[5], a[8]);
Address passed to
pointer variable
Value passed to
simple variable
void function1(int *d, int e)
*d = 100 + e;
Function Call and Prototype

How to pass the ability to access an entire 1-D
array to a function?




Pass the address of the first element of the array
With the address of the first element, C can internally
calculate the address of any element in the array.
The address of the first element of an array is indicated
by the array name with no brackets following it.
&c[0] and c are equivalent.
Function Call and Prototype

function2(c, 5)


Pass the address of the first element of the array c[ ] to
function2, which gives function2 the ability to modify
the array c[ ].
The prototype for the function must indicate that
it is receiving an address.

Use * in the declaration


void function2 (double *b, int num_elem);
Use brackets [ ]

void function2 (double b[ ], int num_elem);
Function Call and Prototype
function2(c, 5)
Address of the
first element passed
to pointer variable
indicated with brackets
Number of array elements
passed as a simple variable
void function2 (double b[ ], int num_elem);
Function Definition

Within a function that has received an array’s
address, how to work with the array?

Must be cognizant of the number of elements that the
array contains.


void function2 (double b[ ], int num_elem)
void function2 (double b[5])
This is correct –
A separate parameter is used to
transfer the number of elements.
This is incorrect –
It does not indicate that
b[ ] has only five elements.
Passing Fixed-Sized Arrays
Output of an Array in a Function
Manipulation of Arrays in a Function
Passing Array Elements
Sample Programs







Reynolds Numbers
Stress and Strain
Standard Deviation
Maximum and Minimum Values
Sorting
Searching
Inventory of an Engineering Sales Company
Bubble Sort

What concept underlines a bubble sort?

Want to sort the 1-D array, b[4] = {33, 44, 11, 22}, in
ascending order.





First compare b[0] and b[1]; if b[0] > b[1], swap the values;
otherwise, no rearrangement.
Perform the same action for b[1] and b[2].
Continue this with the last pair, b[2] and b[3].
This concludes the first round.
The largest element, 44, bubbles down and stops in the last
element of the array.
Bubble Sort

Bubble sort





Round 1
Round 2
Round 3
Round 4
b[3] is the largest of the four values
b[2] is the largest of the three values
b[1] is the larger of the two values
b[0] is automatically the smallest
Swapping the values of array elements
temp = b[1];
b[1] = b[2];
b[2] = temp;
copy the value of b[1] into temp
copy the value of b[2] into b[1]
copy the value of temp into b[2]


#include <math.h>
#include <stdio.h>




























#define START 0
#define END 4
#define SIZE 10
Beginning and ending of
portion of array to be sorted
void main(void)
{
int i, j, k, b[SIZE], c[SIZE], d[SIZE];
int temp, max, wheremax=END-1, min, wheremin=START;
int a[END]={33,44,11,22};
/************************************************
** INITIALIZE ARRAYS b, c, AND d
************************************************/
for (i=START; i<END ;i++) b[i]=c[i]=d[i]=a[i];
/************************************************
** BUBBLE SORT
************************************************/
for (i=START;i <END;i++)
Each time through loop is
{
one round for the bubble sort
for (j=START; j <END-i-1;j++)
{
if (b[j] > b[j+1] )
The swap is performed
{
temp=b[j+1];
b[j+1]=b[j] ;
b[j]=temp;
}
}
}
Exchange Maximum Sort

Exchange maximum sort





Assign the last array element to the variable max.
Compare max with the rest of the array elements; if the
max is smaller than any array element, then replace
max and use the variable wheremax to relocate the
new maximum. Continue the process until the max in
the array is found.
Put the found max at the last element of the array. This
completes the first round.
Eliminate the last element from the search group.
Repeat steps 2, 3, and 4 until the array is in ascending
order.

















/*******************************************
** EXCHANGE MAXIMUM SORT
*******************************************/
for (i = END-1; i >= START; i--)
Each time through loop is
{
one round for the exchange
maximum sort
max = c[i];
for (j = i; j >= START; j--)
Compare max with the rest of the array
{
elements; if the max is smaller than any
if (max <= c[j])
array element, then replace max and use
the variable wheremax to relocate the
{
new maximum. Put the found max at the
max = c[j];
last element of the array. Eliminate the la
wheremax = j;
element from the search group
}
}
c[wheremax] = c[i];
The swap is performed
c[i] = max;
}
Exchange Minimum Sort

Exchange Minimum Sort



Similar to the Exchange Maximum Sort
Finds the min value and puts it in the first loation
In ascending order

















/********************************************
** EXCHANGE MINIMUM SORT
********************************************/
for (i=START;i <END;i++)
{
min=d[i];
for (j=i;j <END;j++)
{
if (min >= d[j])
{
min=d[j];
wheremin=j;
}
}
d[wheremin]=d[i];
d[i]=min;
}