Showing posts with label Arrays. Show all posts
Showing posts with label Arrays. Show all posts

Tuesday, 12 February 2013

C Programming: Arrays

An array is a series of elements of the same type placed in contiguous memory locations that can be individually referenced by adding an index to a unique identifier.
An array is a data structure of multiple elements with the same data type. Array elements are accessed using subscript. The valid range of subscript is 0 to size -1.
One Dimensional Array
A list of items can be given one variable name using only one subscript and such a variable is called a single-subscripted variable or a one-dimensional array. In C, single-subscripted variable xi can be expressed as,  x[1], x[2], x[3], x[4],…….,x[n]. The subscript can begin with number 0. For example if you want to represent a set of five numbers, say(35,40,20,57,19,45) by an array variable number, then you may declare the variable number as follows
int number[6];
and the computer reserves five storage locations as shown below:
number[0]
number[1]
number[2]
number[3]
number[4]
number[5]
The values to the array elements can be assigned as follows:
number[0] = 35
number[1] = 40
number[2] = 20
number[3] = 57
number[4] = 19
number[5] = 45
Declaration of One-Dimensional Array
type variable-name[size];

The type specifies the type of element that will be contained in the array, such as int, char etc. and size indicates the maximum number of elements that can be stored inside the array for example.     float matrix[50];

The example of One Dimensional Array is given in Next Post

Calculating the maximum and minimum element of Array in C

This program illustrates the concept of One-Dimensional Array.  In this program some elements are taken in array and maximum and minimum element are found  out. Complete source code and Output is given here..

Source Code


?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
//finding the maximum and minimum element of array
#include<stdio.h>
int findmax(int array[], int n){
    int i, maximum;
    maximum = array[0];
    for(i = 0; i < n; i++){
        if(maximum < array[i])
            maximum = array[i];
    }
    return maximum;
}
int findmin(int array[], int n){
    int i, minimum;
    minimum = array[0];
    for(i = 0; i < n; i++){
        if(minimum > array[i])
            minimum = array[i];
    }
    return minimum;
}
int main(){
    int array[10]; //array declaration of maximum size 10
    int max,min,n,i;
    printf("Enter the no of element: ");
    scanf("%d",&n);
    printf("Enter the array: ");
    for(i = 0; i < n; i++){
        scanf("%d",&array[i]);
    }
    max = findmax(array, n);
    min = findmin(array, n);
    printf("\nThe maximum element is %d", max);
    printf("\nThe minimum element is %d\n\n", min);
    return 0;
}
Output

array