Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Arrays in C': Shashidhar G Koolagudi CSE, NITK, Surathkal

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 26

Arrays

in ‘C’
Shashidhar G Koolagudi
CSE, NITK, Surathkal
Introduction
In C language, arrays  are referred to as structured data
types.
An array is defined as 
Finite ordered collection of homogenous data, stored in
contiguous memory locations.
Examples:
• List of Employee or Student names,
• Marks of students,
• List of numbers or characters etc.
Declaration of Arrays
• Like any other variable, arrays must be declared before they are used.
General form of array declaration is,
• data-type variable-name[size];
• int arr[10];

Here int is the data type, arr is the name of the array and 10 is the size of array. It means array arr can only contain 10 elements
of int type.
Index of an array starts from 0 to size-1 i.e first element of arr array will be stored at arr[0] address and the last element will
occupy arr[9].

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];

Accessing of Array elements:

You can use array subscript (or index) to access any element stored in array. Subscript starts with 0, which means arr[0] represents the first element in the array
arr.
In general arr[n-1] can be used to access nth element of an array. where n is any integer number.
Initialization of an Array
After an array is declared it must be initialized. Otherwise, it will
contain garbage value(any random value). An array can be initialized at
either compile time or at runtime.
Compile time initialization of array elements is same as
ordinary variable initialization. The general form of initialization of array
is,
data-type array-name[size] = { list of values };
Here are a few examples
int marks[4]={ 67, 87, 56, 77 }; // integer array initialization
float area[5]={ 23.4, 6.8, 5.5 }; // float array initialization
int marks[4]={ 67, 87, 56, 77, 59 }; // Compile time error
Different initializations during declaration
Memory status in a system after array is initialized.
int val[7];
Name of an array always contains the address of the first element of an array, It is also the same as the address of the element val[0].

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.
double balance[] = {1000.0, 2.0, 3.4, 7.0, 50.0};
Small programme
#include<stdio.h>
void main()
{ int i; int arr[] = {2, 3, 4};
// Compile time array initialization
for(i = 0 ; i < 3 ; i++)
{ printf("%d\t",arr[i]); }
}
Runtime Array initialization
An array can also be initialized at runtime using  scanf()  function.
This approach is usually used for initializing large arrays, or to initialize arrays with user specified values.
Example,
#include<stdio.h>
void main()
{ int arr[4]; int i, j;
printf("Enter array element");
for(i = 0; i < 4; i++)
{ scanf("%d", &arr[i]); //Run time array initialization }
for(j = 0; j < 4; j++)
{ printf("%d\n", arr[j]);
} }
What does this programme do?

#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]; /*sum+=num[x];*/
}
avg = sum/4;
printf("Average of entered numbers is: %d", avg);
return 0;
}
Another simple programme
#include <stdio.h>
int main ()
{
int n[ 10 ]; /* n is an array of 10 integers */
int i,j; /* initialize elements of array n to 0 */
for ( i = 0; i < 10; i++ )
{
n[ i ] = i + 100; /* set element at location i to i + 100 */
} /* output each array element's value */
for (j = 0; j < 10; j++ )
{ printf("Element[%d] = %d\n", j, n[j] );
}
return 0;
}
Programme to reverse the list
#include <stdio.h>
void main()
{
int i,n,a[100];
printf("\n\nRead n number of values in an array and display it in reverse order:\n");
printf("------------------------------------------------------------------------\n");
printf("Input the number of elements to store in the array :");
scanf("%d",&n);
printf("Input %d number of elements in the array :\n",n);
for(i=0;i<n;i++)
{
printf("element - %d : ",i);
scanf("%d",&a[i]);
}
printf("\nThe values store into the array are : \n");
for(i=0;i<n;i++)
{
printf("% 5d",a[i]);
}
printf("\n\nThe values store into the array in reverse are :\n");
for(i=n-1;i>=0;i--)
{
printf("% 5d",a[i]);
}
printf("\n\n");
}
Flow of execution
Programme to separate out even and odd numbers in two arrays
#include <stdio.h>
void main()
{
int arr1[10], arr2[10], arr3[10];
int i,j=0,k=0,n;

printf("\n\nSeparate odd and even integers in separate arrays:\n");


printf("------------------------------------------------------\n");
printf("Input the number of elements to be stored in the array :");
scanf("%d",&n);
printf("Input %d elements in the array :\n",n);
for(i=0;i<n;i++)
{
printf("element - %d : ",i); scanf("%d",&arr1[i]); }
for(i=0;i<n;i++)
{
if (arr1[i]%2 == 0)
{ arr2[j] = arr1[i]; j++; }
else
{ arr3[k] = arr1[i]; k++; }
}
printf("\nThe Even elements are : \n");
for(i=0;i<j;i++) { printf("%d ",arr2[i]);
}
printf("\nThe Odd elements are :\n");
for(i=0;i<k;i++) { printf("%d ", arr3[i]); }

printf("\n\n");
}
Flow Chart
Programme to count the frequency of each element in the array
main()
{
int arr1[100], fr1[100];
int n, i, j, ctr;
printf("\n\nCount frequency of each element of an array:\n");
printf("------------------------------------------------\n");
printf("Input the number of elements to be stored in the array :");
scanf("%d",&n);
printf("Input %d elements in the array :\n",n);
for(i=0;i<n;i++)
{
printf("element - %d : ",i);
scanf("%d",&arr1[i]);
fr1[i] = -1;
}
for(i=0; i<n; i++)
{
ctr = 1;
for(j=i+1; j<n; j++)
{
if(arr1[i]==arr1[j])
{
ctr++; fr1[j] = 0;
}

if(fr1[i]!=0)
{
fr1[i] = ctr;
}
}
printf("\nThe frequency of all elements of array : \n");
for(i=0; i<n; i++)
{
Programme- Bubble sorting

#include <stdio.h>
int main()
{
  int array[100], n, i, j, swap;
  printf("Enter number of elements\n");
  scanf("%d", &n);
  printf("Enter %d integers\n", n);
  for (i = 0; i < n; i++)
    scanf("%d", &array[i]);
  for (i = 0 ; i < n - 1; i++)
  {
    for (j = 0 ; j < n - i - 1; j++)
    {
      if (array[j] > array[j+1]) /* For decreasing order use '<' instead of '>' */
      {
        swap       = array[j];
        array[j]   = array[j+1];
        array[j+1] = swap;
      }
    }
  }

  printf("Sorted list in ascending order:\n");


  for (i = 0; i < n; i++)
     printf("%d\n", array[i]);
  return 0;
}
Accessing array elements using address of memory locations

#include <stdio.h>
int main ()
{ /* an array with 5 elements */
double balance[5] = {1000.0, 2.0, 3.4, 17.0, 50.0};
double *p; int i; p = balance; /* output each array element's value */
printf("value of p is %d and balance is %d\n\n", p, balance);
printf( "Array values using Normal approach\n");
for ( i = 0; i < 5; i++ )
{ printf(" %f is stored in : %dth location \n", balance{i}, i+1 ); }

printf( "Array values using Address\n");


for ( i = 0; i < 5; i++ )
{ printf("*(p + %d) : %f\n", i, *(p + i) ); }
printf( "Array values using balance as address\n");
for ( i = 0; i < 5; i++ )
{ printf("*(balance + %d) : %f\n", i, *(balance + i) ); }
return 0;
}
Yet another programme

#include <stdio.h>
int main ()
{ /* an array with 5 elements */
int marks[5], i;
printf( "Enter 5 array elements\n");
for ( i = 0; i < 5; i++ )
scanf("%d", &marks[i]);
printf("Printing array elements using normal and address approach\n\n");
for ( i = 0; i < 5; i++ )
printf("%d is stored in the address %d\n", marks[i], marks+i);
/*Add 5 to each element of teh array marks*/
printf("Array elements after adding 5 to each element\n");
for ( i = 0; i < 5; i++ )
*(marks+i)=*(marks+i)+5;
for ( i = 0; i < 5; i++ )
printf("%d is stored in the address %d\n", marks[i], marks+i);
return 0;
}
Output

Enter 5 array elements


1
2
3
4
5
Printing array elements using normal and address approach

1 is stored in the address 6487552


2 is stored in the address 6487556
3 is stored in the address 6487560
4 is stored in the address 6487564
5 is stored in the address 6487568
Array elements after adding 5 to each element
6 is stored in the address 6487552
7 is stored in the address 6487556
8 is stored in the address 6487560
9 is stored in the address 6487564
10 is stored in the address 6487568
Programme to print the array in the reverse using address
#include <stdio.h>
void main()
{ int n, i, arr1[15]; int *pt;
printf("\n\n Pointer : Print the elements of an array in reverse order :\n");
printf("----------------------------------------------------------------\n");
printf(" Input the number of elements to store in the array (max 15) : ");
scanf("%d",&n);
pt = &arr1[0]; // pt stores the address of base array arr1
printf(" Input %d number of elements in the array : \n",n);
for(i=0;i<n;i++)
{ printf(" element - %d : ",i+1);
scanf("%d",pt);//accept the address of the value pt++;
}
pt = &arr1[n - 1];
printf("\n The elements of array in reverse order are :");
for (i = n; i > 0; i--)
{ printf("\n element - %d : %d ", i, *pt);
pt--;
}
printf("\n\n");
}
Two Dimensional
Arrays
Matrix representation in C
However, Actual representation of elements
in the memory (RAM)is as follows
Matrix initialization
#include <stdio.h>
int main()
{ int abc[5][4] ={ {0,1,2,3}, {4,5,6,7},{8,9,10,11}, {12,13,14,15},{16,17,18,19} };

for (int i=0; i<=4; i++)


{
printf("%d ",abc[i]);
}
for (i=0; i<=4; i++)
{
for (j=0;j<4;++j)
printf("%d \t",abc[i][j]);
printf("\n");
}
return 0;
}
Output:
• 6487488
• 6487504
• 6487520
• 6487536
• 6487552
•0 1 2 3
•4 5 6 7
•8 9 10 11
• 12 13 14 15
• 16 17 18 19
• #include
#include
#include
• int main()
{
int m, n, c, d, first[10][10], second[10][10], sum[10][10];
clrscr();
printf(“Enter the number of rows and columns of Array(2D)\n”);
scanf(“%d%d”, &m, &n);
printf(“Enter the elements of first Array\n”);
• for (c = 0; c < m; c++)
for (d = 0; d < n; d++)
scanf("%d", &first[c][d]);
• printf("Enter the elements of second Array\n");
• for (c = 0; c < m; c++)
for (d = 0 ; d < n; d++)
scanf("%d", &second[c][d]);
• printf("Sum of Arrays:-\n");
• for (c = 0; c < m; c++) {
for (d = 0 ; d < n; d++) {
sum[c][d] = first[c][d] + second[c][d];
printf("%d\t", sum[c][d]);
}
printf("\n");
}

You might also like