Data Structure
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 }
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
Arrays …
48 88 34 23 96
per[0]
per[1]
per[2]
per[3]
Similar elements could be
◦
All ints
◦
All floats
◦
All chars
Array of characters is called ‘string’
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 2
ndexample
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 } ;
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
main () {
int arr[MAX]={0}, i, sum=0;
printf("Please input 10 integer values.\n");
for(i=0; i<MAX; i++) { scanf("%d", &arr[i]); }
for (i=0; i<MAX; i++) { sum += arr[i];
}
printf("The sum is %d.", sum); return 0;
}
Example #1:
Sum of
Array of Integers
Sets maximum size of an array Sets all 10 element values to zero
Stores 10 integer inputs from the keyboard
Sums all10 integers from arr[ ]
Please input 10 integer values. 1 2 3 4 5 6 7 8 9 10
#include <stdio.h> #define MAX 10
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]); }
for (i=0; i<MAX; i++) { arrDup[i]= arr[i];
}
for(i=0; i<MAX; i++) { printf("%4d", arrDup[i]); } return 0; }
Example #2:
Duplicating Arrays
Please input 10 integer values. 1 2 3 4 5 6 7 8 9 10
An array storing the same integer values of arr [ ]
1 2 3 4 5 6 7 8 9 10
arr[0] = 1 arr[1] = 2 …
arr[8] = 9 arr[9] = 10
arrDup[0] = 1 arrDup[1] = 2
#include <stdio.h> #define MAX 10
main () {
int arr[MAX]={0}, i, searchVal, found=0; printf("Please input 10 integer values.\n");
for(i=0; i<MAX; i++) { scanf("%d", &arr[i]); }
printf("What value to be searched? "); scanf("%d", &searchVal);
for (i=0; i<MAX; i++) { if (searchVal == arr[i]) { found=1; break; } }
if(found) printf("\nThe value is in the array."); else printf("\nThe value is not in the array."); return 0;
}
Example #3:
Finding
Values in an Array
Please input 10 integer values. 1 2 3 4 5 6 7 8 9 10
What value to be searched? 2
arr[0] = 1 arr[1] = 2 …
arr[8] = 9 arr[9] = 10
match with 2?
No Yes
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
Programming Exercise (2)
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
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
Write a program with a function that adds all digits
of an integer number.
Example:
Number =94356
Sum = 27
Requirement:
int sumOfDigits(int num) { … }
Next:
#include <stdio.h>
#define SIZE 9
swap (int *a, int *b)
{
int t ;
t = *a ;
*a = *b ;
*b = t ;
}
Passing Array Elements to a Function
int main () {
int i, a[SIZE]={[2]=34,
[5]=11, [8]=-13, [7]= 8};
for (i=0; i<SIZE;i++)
printf("%d\n",a[i]);
for (i=0;i<SIZE/2;i++) {
swap(&a[i],&a[SIZE-1-i]);
}
printf("\nReverse
Order.\n");
for (i=0; i<SIZE;i++)
printf("%d\n",a[i]);
return 1;
}
Pg 195
Address of the array at index is submitted to the function –
Create a function that searches a number in the array and returns the
first location of the number
int searchN(int arr[], int s, int n) {...}
Example:
array = {0, 13, 4, 11, 9, 4, 2, 58, 1}
search number = 4
location at = 3
array = {0, 13, 4, 11, 9, 4, 2, 58, 1}
search number = 2
location at = 7
Passing an Entire Array to a Function
#include <stdio.h> #define SIZE 9
swap (int *a, int *b) { int t ;
t = *a ; *a = *b ; *b = t ; }
reverse (int a[], int s) { int i=0;
for (i=0;i<SIZE/2;i++) { swap(&a[i],&a[SIZE-1-i]);
} }
int main () {
int i, a[SIZE]={[2]=34, [5]=11, [8]=-13, [7]= 8};
for (i=0; i<SIZE;i++) printf("%d\n",a[i]);
printf("\nReverse Order.\n"); reverse(a,SIZE);
for (i=0; i<SIZE;i++) printf("%d\n",a[i]); return 1;
}
Address of the array is submitted to the function –
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])))
Code to Example: Computing Interest
Constant Arrays
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
Array may have N-Dimensions
Example:
◦
int m[5][9];
//creates 2D Array [row][column]
Multi-Dimensional Array
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
Initializing a Multidimensional Array
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: