C Arrays: Unit Ix

You might also like

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 13

1st Semester | SY 2020 – 2021

UNIT IX

C ARRAYS

I. Module Overview

A fixed number of data items which are stored contiguously and the elements
can be accessed by an index. It is also a finite ordered collection of homogenous
elements.

Thus, the following are the characteristics of an array:


 Finite. There is a specific number of elements in the array.
 Ordered. All the elements of the array are arranged so that there is
first, second, third and so on.
 Homogenous. All the elements in the array must be of the same
type(e.g all integers, all characters, all floating point).

This module will discuss how to use Arrays in C program.


II. Desired Learning Outcome

At the end of this topic, the students should be able to:


1. Identify the parts of an Array syntax
2. Apply and use Arrays in C program

III. Take off/Motivation

The instructor/professor will discuss some real-life scenarios where we can


apply arrays.
IV. Content Focus

Arrays a kind of data structure that can store a fixed-size sequential


collection of elements of the same type. An array is used to store a collection of
data, but it is often more useful to think of an array as a collection of variables of
the same type.

Instead of declaring individual variables, such as number0, number1, ..., and


number99, you declare one array variable such as numbers and use numbers[0],
numbers[1], and ..., numbers[99] to represent individual variables. A specific
element in an array is accessed by an index.

All arrays consist of contiguous memory locations. The lowest address


corresponds to the first element and the highest address to the last element.

123
1st Semester | SY 2020 – 2021

Declaring Arrays

To declare an array in C, a programmer specifies the type of the elements


and the number of elements required by an array as follows –

type arrayName [ arraySize ];

This is called a single-dimensional array. The arraySize must be an integer


constant greater than zero and type can be any valid C data type. For example,
to declare a 10-element array called balance of type double, use this statement –

double balance[10];

Here balance is a variable array which is sufficient to hold up to 10 double


numbers.

Initializing Arrays

You can initialize an array in C either one by one or using a single statement
as follows –

double balance[5] = {1000.0, 2.0, 3.4, 7.0, 50.0};

The number of values between braces { } cannot be larger than the number
of elements that we declare for the array between square brackets [ ].

If you omit the size of the array, an array just big enough to hold the
initialization is created. Therefore, if you write –

double balance[] = {1000.0, 2.0, 3.4, 7.0, 50.0};

You will create exactly the same array as you did in the previous example.
Following is an example to assign a single element of the array –

balance[4] = 50.0;

The above statement assigns the 5th element in the array with a value of
50.0. All arrays have 0 as the index of their first element which is also called the
base index and the last index of an array will be total size of the array minus 1.
Shown below is the pictorial representation of the array we discussed above −

Accessing Array Elements

124
1st Semester | SY 2020 – 2021

An element is accessed by indexing the array name. This is done by placing


the index of the element within square brackets after the name of the array. For
example –
double salary = balance[9];

The above statement will take the 10th element from the array and assign
the value to salary variable. The following example Shows how to use all the
three above mentioned concepts viz. declaration, assignment, and accessing
arrays –

#include <stdio.h>
int main()
{
int avg = 0;
int sum =0;
int x=0;

/* Array- declaration – length 4*/


int num[4];

/* We are using a for loop to traverse through the array


* while storing the entered values in the array
*/
for (x=0; x<4;x++)
{
printf("Enter number %d \n", (x+1));
scanf("%d", &num[x]);
}
for (x=0; x<4;x++)
{
sum = sum+num[x];
}

avg = sum/4;
printf("Average of entered number is: %d", avg);
return 0;
}

When the above code is compiled and executed, it produces the following
result –
Enter number 1
10
Enter number 2
10
Enter number 3
20
Enter number 4
40
Average of entered number is: 20

125
1st Semester | SY 2020 – 2021

Lets discuss the important parts of the above program:

Input data into the array

Here we are iterating the array from 0 to 3 because the size of the array is


4. Inside the loop we are displaying a message to the user to enter the
values. All the input values are stored in the corresponding array elements
using scanf function.

for (x=0; x<4;x++)


{
printf("Enter number %d \n", (x+1));
scanf("%d", &num[x]);
}

Reading out data from an array

Suppose, if we want to display the elements of the array then we can use
the for loop in C like this.

for (x=0; x<4;x++)


{
printf("num[%d]\n", num[x]);
}

Various ways to initialize an array

In the above example, we have just declared the array and later we
initialized it with the values input by user. However you can also initialize
the array during declaration like this:

int arr[5] = {1, 2, 3, 4 ,5};


OR (both are same)

int arr[] = {1, 2, 3, 4, 5};


Un-initialized array always contain garbage values.

126
1st Semester | SY 2020 – 2021

Arrays in Detail

Arrays are important to C and should need a lot more attention. The
following important concepts related to array should be clear to a C programmer

Sr.No. Concept & Description

1 Multi-dimensional arrays

C supports multidimensional arrays. The simplest form of the


multidimensional array is the two-dimensional array.

2 Passing arrays to functions


You can pass to the function a pointer to an array by specifying
the array's name without an index.

3 Return array from a function


C allows a function to return an array.

4 Pointer to an array
You can generate a pointer to the first element of an array by
simply specifying the array name, without any index.

127
1st Semester | SY 2020 – 2021

Two dimensional (2D) arrays in C programming with example

An array of arrays is known as 2D array. The two dimensional (2D) array in C
programming is also known as matrix. A matrix can be represented as a table of rows
and columns. Before we discuss more about two Dimensional array lets have a look at
the following C program.

Simple Two dimensional(2D) Array Example


For now don’t worry how to initialize a two dimensional array, we will discuss that part
later. This program demonstrates how to store the elements entered by user in a 2d
array and how to display the elements of a two dimensional array.

#include<stdio.h>
int main(){
/* 2D array declaration*/
int disp[2][3];
/*Counter variables for the loop*/
int i, j;
for(i=0; i<2; i++) {
for(j=0;j<3;j++) {
printf("Enter value for disp[%d][%d]:", i, j);
scanf("%d", &disp[i][j]);
}
}
//Displaying array elements
printf("Two Dimensional array elements:\n");
for(i=0; i<2; i++) {
for(j=0;j<3;j++) {
printf("%d ", disp[i][j]);
if(j==2){
printf("\n");
}
}
}
return 0;
}
Output:

Enter value for disp[0][0]:1


Enter value for disp[0][1]:2
Enter value for disp[0][2]:3
Enter value for disp[1][0]:4
Enter value for disp[1][1]:5
Enter value for disp[1][2]:6
Two Dimensional array elements:
123
456
Initialization of 2D Array
There are two ways to initialize a two Dimensional arrays during declaration.

128
1st Semester | SY 2020 – 2021

int disp[2][4] = {
{10, 11, 12, 13},
{14, 15, 16, 17}
};
OR

int disp[2][4] = { 10, 11, 12, 13, 14, 15, 16, 17};
Although both the above declarations are valid, I recommend you to use the first method
as it is more readable, because you can visualize the rows and columns of 2d array in
this method.

Things that you must consider while initializing a 2D array

We already know, when we initialize a normal array (or you can say one dimensional
array) during declaration, we need not to specify the size of it. However that’s not the
case with 2D array, you must always specify the second dimension even if you are
specifying elements during the declaration. Let’s understand this with the help of few
examples –

/* Valid declaration*/
int abc[2][2] = {1, 2, 3 ,4 } 
/* Valid declaration*/
int abc[][2] = {1, 2, 3 ,4 } 
/* Invalid declaration – you must specify second dimension*/
int abc[][] = {1, 2, 3 ,4 }  
/* Invalid because of the same reason  mentioned above*/
int abc[2][] = {1, 2, 3 ,4 }
How to store user input data into 2D array
We can calculate how many elements a two dimensional array can have by using this
formula:
The array arr[n1][n2] can have n1*n2 elements. The array that we have in the example
below is having the dimensions 5 and 4. These dimensions are known as subscripts. So
this array has first subscript value as 5 and second subscript value as 4.
So the array abc[5][4] can have 5*4 = 20 elements.

To store the elements entered by user we are using two for loops, one of them is a
nested loop. The outer loop runs from 0 to the (first subscript -1) and the inner for loops
runs from 0 to the (second subscript -1). This way the the order in which user enters the
elements would be abc[0][0], abc[0][1], abc[0][2]…so on.

#include<stdio.h>
int main(){
/* 2D array declaration*/
int abc[5][4];
/*Counter variables for the loop*/
int i, j;
for(i=0; i<5; i++) {
for(j=0;j<4;j++) {

129
1st Semester | SY 2020 – 2021

printf("Enter value for abc[%d][%d]:", i, j);


scanf("%d", &abc[i][j]);
}
}
return 0;
}
In above example, I have a 2D array abc of integer type. Conceptually you can visualize
the above array like this:

Passing Arrays as Function Arguments in C


If you want to pass a single-dimension array as an argument in a function, you would
have to declare a formal parameter in one of following three ways and all three
declaration methods produce similar results because each tells the compiler that an
integer pointer is going to be received. Similarly, you can pass multi-dimensional arrays
as formal parameters.
Way-1
Formal parameters as a pointer −

void myFunction(int *param) {


.
.
.
}
Way-2
Formal parameters as a sized array −

130
1st Semester | SY 2020 – 2021

void myFunction(int param[10]) {


.
.
.
}
Way-3
Formal parameters as an unsized array −

void myFunction(int param[]) {


.
.
.
}
Example
Now, consider the following function, which takes an array as an argument along with
another argument and based on the passed arguments, it returns the average of the
numbers passed through the array as follows −
double getAverage(int arr[], int size) {

int i;
double avg;
double sum = 0;

for (i = 0; i < size; ++i) {


sum += arr[i];
}

avg = sum / size;

return avg;
}

Now, let us call the above function as follows −


#include <stdio.h>

/* function declaration */
double getAverage(int arr[], int size);

int main () {

/* an int array with 5 elements */


int balance[5] = {1000, 2, 3, 17, 50};
double avg;

/* pass pointer to the array as an argument */


avg = getAverage( balance, 5 ) ;

131
1st Semester | SY 2020 – 2021

/* output the returned value */


printf( "Average value is: %f ", avg );

return 0;
}

When the above code is compiled together and executed, it produces the
following result −
Average value is: 214.400000
As you can see, the length of the array doesn't matter as far as the function is
concerned because C performs no bounds checking for formal parameters.

Instruction: The students will write a C program for the following problems:

1. C program to store elements in an array and print it.


Sample Output:
Input 10 elements in the array:
element - 0: 1
element - 1: 1
element - 2: 2
.......
Elements in array are: 1 1 2 3 4 5 6 7 8 9

2. Write a program in C to read n number of values in an array and display it in


reverse order.
Sample Output:
Input the number of elements to store in the array :3
Input 3 number of elements in the array:
element - 0: 2
element - 1: 5
element - 2: 7
The values store into the array are: 2 5 7
The values store into the array in reverse are: 7 5 2
3. Write a program in C to find the sum of all elements of the array.
Sample Output:
Input the number of elements to be stored in the array :3
Input 3 elements in the array:
element - 0: 2
element - 1: 5
element - 2: 8
Sum of all elements stored in the array is: 15

4. Write a program in C to find the maximum and minimum element in an array.

132
1st Semester | SY 2020 – 2021

Sample Output:
Input the number of elements to be stored in the array :3
Input 3 elements in the array:
element - 0: 45
element - 1: 25
element - 2: 21
Maximum element is: 45
Minimum element is: 21

5. Write a program in C to sort elements of the array in descending order.


Sample Output:
Input the size of array: 3
Input 3 elements in the array:
element - 0: 5
element - 1: 9
element - 2: 1
Elements of the array in sorted descending order:
9 5 1

Rubric for Assessment to be used for creating C programs (for review with
the students to be handled):

Criteria Exemplary Good Satisfactory Unsatisfactor


(91 - 100%) (81 - 90%) (71 - 80%) y
(70 - 61%)

Deliver  Accomplishe  Accomplishe  Accomplishe  Accomplishe


y d between d between d between d between
91-100% of 81 - 90% of 71 - 80% of 71 - 80% of
the required the required the required the required
output output output output
 Output  Output  Output  Output
submitted submitted submitted submitted
is delivered is delivered is delivered is delivered
on or on or on the next a week or
before the before the meeting more after
deadline deadline after the the
and but some deadline deadline
followed of the and some and
properly submission of the submission
the guidelines submission guidelines
submission were not guidelines were not
guidelines. followed. were not followed.
followed.

V. Self-Check

MULTIPLE CHOICE.

133
1st Semester | SY 2020 – 2021

Instruction: The students will be required to answer the following questions.


Only letter will be chosen and written in the space provided before the number.

_______1. Which of the following correctly declares an array?


a. int anarray[10];
b. int anarray;
c. anarray{10};
d. array anarray[10];
_______2. What is the index number of the last element of an array with 29
elements?
a. 29
b. 28
c. 0
d. Programmer-defined
_______3. Which of the following is a two-dimensional array?
a. array anarray[20][20];
b. int anarray[20][20];
c. int array[20, 20];
d. char array[20];
_______4. Which of the following correctly accesses the seventh element
stored in foo, an array with 100 elements?
a. foo[6];
b. foo[7];
c. foo(7);
d. foo;
_______5. What are the legal indexes for the array ar, given the following
declaration: int ar[] = {2, 4, 6, 8 }
a. 0, 1, 2, 3
b. 1, 2, 3, 4
c. 2, 4, 6, 8
d. 0, 2, 4. 6
_______6. For which of the following applications is an array NOT suitable:
a. Holding the scores on twelve midterms exams of a class.
b. Holding the name, social security number, age, and income of
one individual.
c. Holding the temperature readings taken every hour throughout a
day.
d. Holding the total sales a store made in each of twelve months.
_______7. The first element in array is numbered(index).
a. 0
b. 1
c. -1
d. none of them
_______8. int marks[30]; What the number 30 tells us?
a. int data type size

134
1st Semester | SY 2020 – 2021

b. number of elements in marks array


c. maximum value that we can store in marks
d. none of them
_______9. Which one is correct syntax for entering 30 at 10th position of an
array
a. marks[10] = 30
b. marks[9] = 29
c. marks[9] = 30
d. marks[10] = 29
_______10. double num [7]; what is the name of this array?
a. seven
b. double
c. has no name
d. num
_______11. Can an entire array be printed out at once?
a. yes
b. no
_______12. What is the correct way to initialize values in an array?
a. my_array [5] = (5,3,4,2,7);
b. my_array [5] = {5;3;4;2;7};
c. my_array [5] = {5,3,4,2,7};
d. my_array [5] = [5,3,4,2,7];
_______13. What do arrays do?
a. hold addresses
b. hold values under a single name
c. hold one value
d. hold libraries
_______14. How is an array declared?
a. my_array |5|;
b. my_array [5];
c. my_array (5);
d. my_array {5};
_______15. For which of the following applications is an array NOT suitable:
a. Holding the scores on twelve midterms exams of a class.
b. Holding the name, social security number, age, and income of
one individual.
c. Holding the temperature readings taken every hour throughout a
day.
d. Holding the total sales a store made in each of twelve months.

REFERENCES
https://www.tutorialspoint.com/cprogramming/c_arrays.htm

135

You might also like