Sie sind auf Seite 1von 43

Topic: Arrays

Duration: 2 hr
Prepared by: MBJ Ortuyo
 To be able to define arrays
 To familiarize array initialization
 To perform bounds checking in arrays
 To apply passing array elements to a function
 To apply passing an entire array to a function
 To be able to apply 2-dimensional array
 To illustrate memory map of a 2-dimensional array
 To use pointers to an array
 To familiarize and apply array of pointers
 To be able to apply 3-dimensional array
 To be able to apply n-dimensional arrays in problem
solving
Scalar variables – capable of holding a single data
item.
Aggregate variables – stores collections of values.

Two kinds of aggregate variables:


- Array and Structure

The C language provides a capability that enables


the user to design a set of similar data types,
called Array.
Suppose we wish to arrange the percentage marks
obtained by 100 students in ascending order.
In such a case we have two options to store these
marks in memory:

(a) Construct 100 variables (scalar) to store percentage


marks obtained by 100 different students, i.e. each
variable containing one student’s marks.
(b) Construct one variable (an aggregate called array or
subscripted variable) capable of storing or holding all
the hundred values.

The second is better, for it is much easier to handle 1


variable than with 100 different variables.
Definition:
◦ Is a collective name given to a group of similar
quantities/elements

Example:
◦ Representing marks obtained by five students

per = { 48, 88, 34, 23, 96 } 48 88 34 23 96


per[0] per[2] per[4]
per[1] per[3]
accessing the numbers in the group is through its
position/location starting from 0, say,

accessing 88 would refer to per [1], and accessing 23 to per


[3], … per [i] to refer to any location i

where the per is the subscripted variable (array), whereas i is its


subscript/index
 Similar elements could be
◦ All ints
◦ All floats
◦ All chars

Array of characters is called ‘string’


◦ All ints
main( )
{
int avg, sum = 0 ;
int i ;
int marks[30] ; /* array declaration */
for ( i = 0 ; i <= 29 ; i++ )
{
printf ( "\nEnter marks " );
scanf ( "%d", &marks[i] ); /* store data in array */
}
for ( i = 0 ; i <= 29 ; i++ )
sum = sum + marks[i] ; /* read data from an array*/

avg = sum / 30 ;
printf ( "\nAverage marks = %d", avg ) ;
}
 Purpose:
◦ To let the compiler
 know what kind of array, and
 how large an array we want

 Syntax:
data_type array_name [ integer_size ];

Example:
int marks [30] ;
 Done with subscript, the number in the
brackets following the array name
◦ The number specifies the element’s position in the
array
◦ All elements are numbered starting at 0 to size-1
◦ Use of a variable like i to refer to various elements
of the array

Example:
marks[i]
 Example:
for ( i = 0 ; i <= 29 ; i++ )
{
printf ( "\nEnter marks " );
scanf ( "%d", &marks[i] );
}

Program flow:
The for loop causes the process of asking for and receiving a
student’s marks from the user to be repeated 30 times. The first
time through the loop, i has a value 0, so the scanf( ) function will
cause the value typed to be stored in the array element marks[0], the
first element of the array. This process will be repeated until i
becomes 29. This is last time through the loop, which is a good
thing, because there is no array element like marks[30].
 Example:
for ( i = 0 ; i <= 29 ; i++ )
sum = sum + marks[i] ;

Program flow:
The for loop is much the same, but now the body of the loop
causes each student’s marks to be added to a running total stored in
a variable called sum. When all the marks have been added up, the
result is divided by 30, the number of students, to get the average.
 Example:
int num[6] = { 2, 4, 12, 5, 45, 5 } ;
int n[ ] = { 2, 4, 12, 5, 45, 5 } ;
float press[ ] = { 12.3, 34.2 -23.4, -11.3 } ;

Note:

(a) Till the array elements are not given any specific
values, they are supposed to contain garbage
values.
(b) If the array is initialized where it is declared,
mentioning the dimension of the array is optional as
in the 2nd example above
 If initializer is shorter than array

int num[6] = { 2, 4, 12 } ;
/* initial value of a is 2, 4, 12 , 0, 0, 0 */

 Initializing array to all zeros

int num[6] = { 0 } ;
/* initial value of a is 0, 0, 0, 0, 0, 0 */

 Designated initializers
int num[6] = { [2]=12, [4]=45 } ;
/* initial value of a is 0, 0, 12, 0, 45, 0 */
int n[ ] = { [2]=12, [4]=45 } ;
/* this will force the array to have size of 5 */
Consider the following array declaration:

int arr [8];

For a 32-bit system, each integer element gets 2 bytes each,


thus, making it 16 bytes get immediately reserved in
memory.

Since the array has not been initialized, all 8 values present
in it would be garbage values.
In C there is no check to see if the subscript used for an array
exceeds the size of the array.

Data entered with a subscript exceeding the array size will simply
be placed in memory outside the array; probably on top of other
data, or on the program itself.

This will lead to unpredictable results, to say the least, and there
will be no error message to warn you that you are going beyond
the array size.

In some cases the computer may just hang.

Thus, to see to it that we do not reach beyond the array size is


entirely the programmer’s botheration and not the compiler’s.
#include <stdio.h>
#define MAX 10
Sets all 10 element values to zero
main () { Sets maximum size of an array
int arr[MAX]={0}, i, sum=0;
printf("Please input 10 integer values.\n");

for(i=0; i<MAX; i++) { Stores 10 integer inputs from the keyboard


scanf("%d", &arr[i]);
}
for (i=0; i<MAX; i++) { Sums all10 integers from arr[ ]
sum += arr[i];
}
printf("The sum is %d.", sum);
return 0; Please input 10 integer values.
} 1 2 3 4 5 6 7 8 9 10
The sum is 55.
#include <stdio.h>
#define MAX 10
An array storing the same integer
values of arr [ ]
main () {
int arr[MAX]={0}, arrDup[MAX]={0}, i, sum=0;
printf("Please input 10 integer values.\n");
for(i=0; i<MAX; i++) { scanf("%d", &arr[i]); }

arr[0] =1 arrDup[0] = 1
for (i=0; i<MAX; i++) { arr[1] =2 arrDup[1] = 2
arrDup[i]= arr[i]; …
} arr[8] =9 arrDup[8] = 9
for(i=0; i<MAX; i++) { arr[9] = 10 arrDup[9] = 10
printf("%4d", arrDup[i]);
} Please input 10 integer values.
return 0; 1 2 3 4 5 6 7 8 9 10
} 1 2 3 4 5 6 7 8 9 10
#include <stdio.h>
#define MAX 10

main () {
match with 2?
int arr[MAX]={0}, i, searchVal, found=0;
printf("Please input 10 integer values.\n"); arr[0] =1 No
for(i=0; i<MAX; i++) { scanf("%d", &arr[i]); } arr[1] =2 Yes

arr[8] =9
printf("What value to be searched? "); arr[9] = 10
scanf("%d", &searchVal);
Please input 10 integer values.
for (i=0; i<MAX; i++) { 1 2 3 4 5 6 7 8 9 10
if (searchVal == arr[i]) { What value to be searched? 2
found=1; break; } The value is in the array.
}
if(found) printf("\nThe value is in the array.");
else printf("\nThe value is not in the array.");
return 0;
}
 Next: Programming Exercise
Problem Definition:

Create a program that will accommodate


at most 10 entries from the user. During
execution the user will be inputting values of
at most 10. The program will then sort the
values and displays the sorted list.
Write a program that prints a table showing the
value of $100 invested at different rates of interest over
a period of years. The user will enter an interest rate
and the number of years the money will be invested.
The table will show the next four higher rates –
assuming that interest is compounded once a year.
Here’s what the session would look like:

Enter interest rate: 6%


Enter number of years: 5
Years 6% 7% 8% 9% 10%
1 106.00 107.00 108.00 109.00 110.00
2 112.36 114.49 116.64 118.81 121.00
3 119.10 122.50 125.97 129.50 133.10
4 126.25 131.08 136.05 141.16 146.41
5 133.82 140.26 146.03 153.86 161.05
Construct a flowchart (6 pts) for the program
defined below:

The program prompts the user to enter a


series of numbers, then writes the numbers
in reverse order:

Implement afterwards your solution (4 pts).


Write a program that will check an integer
value if it has repeating digit.

Example:
Number =54342
Repeated Digit
 Next:
Passing of Array Elements to Function
Passing an Entire Array to Function
#include <stdio.h> int main () {
#define SIZE 9 int i, a[SIZE]={[2]=34,
[5]=11, [8]=-13, [7]= 8};
swap (int *a, int *b) for (i=0; i<SIZE;i++)
{ printf("%d\n",a[i]);
int t ; for (i=0;i<SIZE/2;i++) {
t = *a ; swap(&a[i],&a[SIZE-1-i]);
*a = *b ; }
*b = t ; printf("\nReverse
} Order.\n");
Address of the array at for (i=0; i<SIZE;i++)
index is submitted to printf("%d\n",a[i]);
the function – uses
pass-by-reference return 1;
}
Pg 195
#include <stdio.h> int main () {
#define SIZE 9 int i, a[SIZE]={[2]=34,
[5]=11, [8]=-13, [7]= 8};
swap (int *a, int *b) {
for (i=0; i<SIZE;i++)
int t ;
t = *a ; printf("%d\n",a[i]);
*a = *b ; printf("\nReverse Order.\n");
*b = t ; reverse(a,SIZE);
} for (i=0; i<SIZE;i++)
reverse (int a[], int s) {
int i=0; printf("%d\n",a[i]);
for (i=0;i<SIZE/2;i++) { return 1;
swap(&a[i],&a[SIZE- }
1-i]);
} Address of the array is
} submitted to the
function – uses pass-by-
reference
 Can determine the size of an array in bytes
◦ Example: If a is an array of 10 integers, then
sizeof(a) is 20 (assuming each integer type
requires 2 bytes)

 Can measure the size of an array element


◦ Example: sizeof(a)/sizeof(a[0])

 Example use:
for(i=0; i<(int)(sizeof(a)/sizeof(a[0])); i++)
a[i]=0;
sizeof(a)/sizeof(a[0])

OR
Defining if with macro

#define SIZE
((int)(sizeof(a)/sizeof(a[0])))

for(i=0; i<SIZE; i++)


a[i]=0;
 Array declared as constant should not be modified
by the program

 Advantages:
 It documents that the program won’t change
the array
 Helps the compiler catch errors, by informing
it that we don’t intend to modify the array

 It is not limited to arrays; it works with any


variable
 Array may have N-Dimensions
 Example:
◦ int m[5][9]; //creates 2D Array [row][column]
column

row
 Setting Dimensions
and initializers

 Array is filled w/ 0 if
initializer is not
enough; last 2 rows
has values of 0
 Array is filled w/ 0 if
initializer inner list
isn’t long enough to
fill a row

 Omitting inner
braces

 Index [0][0] and [1][1] are initialized, the


rest are given with default zero
 Next: Programming Exercise
The prototypical Internet newbie is a fellow named B1FF,
who has a unique way of writing messages, Here’s a
typical B1FF communiqué:

H3Y DUD3, C 15 R34LLY C00L!!!!!!!!!!

Write a “B1FF filter” that reads a message entered by the


user and translates it into B1FF-speak:

Enter message: Hey dude, C is really cool


In B1FF-speak: H3Y DUD3, C 15 R1LLY C00L!!!!!!!!!!

Your program should convert the message to upper-case


letters, substitute digits for certain letters (A->4, B->8, E-
>3, I->1, O->0, S->5), and then append 10 or so
exclamation marks.
Problem Definition:

Write a C code that


performs
multiplication of
two vectors. The
procedure is as
follows:
Problem Definition:

Write a C code that performs addition of two vectors. The


procedure is as follows:
Problem Definition:

Write a C code that performs subtraction of two vectors. The


procedure is as follows:
Problem Definition:

Write a C code that


performs inverse of a
vector. The procedure
is as follows:
Problem Definition:

Write a C code that


performs the transpose
of a vector. The
procedure is as follows:

Das könnte Ihnen auch gefallen