Arrays:
In this tutorial, we are going to talk about arrays.C programming language provides a data structure called the array.An array lets you declare and work with a collection of values of the same type.
Let’s say you want to declare 5 integers. With the knowledge from the last few tutorials you would do something like this:
int a,b,c,d,e;
now you want to declare 1000 variables of same type.Are you ready to type thousand variables like above?it will take more time , thats why array introduced in C,So we can easily declare our 5 variable like this.
int a[5];
Array classified into two categories.
Single Dimensional ArrayMulti-Dimensional Array.
Column0 Column1 Column2
Row0 a[0][0] a[0][1] a[0][2]
Row1 a[1][0] a[1][1] a[1][2]
Declaration:
syntax:
data_type variable_name[array_size];
This type of array is called as single dimensional array.
Array size should be an integer,and greater than zero.
Initializing Arrays:
You can declare an array one by one or in a statement.
int age[3];
age[0] = 10;
age[1] = 20;
age[2] = 30;
(OR)
int age[3] = {10,20,30}; // the number of values inside the {,} can not be greater than array size declared with in [].
(OR)
int age[] = {10,20,30};
program:
#include <stdio.h>
int main ()
{
int age[ 5 ]; /* age is an array of 5 integers */
int i,j;
/* initialize age */
for ( i = 0; i < 5; i++ )
{
age[ i ] = i + 10;
}
/* output each array element's value */
for (j = 0; j < 5; j++ )
{
printf("age[%d] = %d\n", j, age[j] );
}
return 0;
}
output:
age[0] = 10
age[1] = 11
age[2] = 12
age[3] = 13
age[4] = 14
Multi-Dimensional Array:
C programming allows multi-Dimensional array,
syntax:
data_type variable_name[size1][size2]......[size_n];
To understand easily lets take Two Dimensional array.It can be illustrated in matrix.
Declaration:
int a[2][3]; // 2 rows 3 columns
Initialization:
int a[2][3] = { 0,1,2 /* row 1*/
3,4,5} /* row 2*/
program:
#include<stdio.h>
int main()
{
int a[2][2], i , j;
for (i = 0; i < 2; i++)
{
for ( j = 0; j < 2; j++)
{
a[i][j] = i+j;
printf("a[%d][%d] = %d \n", i, j, a[i][j]);
}
}
return 0;
}
output:
a[0][0] = 0;
a[0][1] = 1;
a[1][0] = 1;
a[1][1] = 2;
Passing Arrays as Function Arguments:
We can pass arrays as arguments in function as follows.
void myFunction(int param[])
{
.
.
}
program:
#include <stdio.h>
/* function declaration */
int getTotal(int arr[], int size);
int main ()
{
/* an int array with 5 elements */
int values[5] = {10, 2, 3, 5, 50};
int sum;
/* pass pointer to the array as an argument */
sum = getTotal(values,5 ) ;
/* output the returned value */
printf( "Total value is: %f ", sum );
return 0;
}
int getTotal(int arr[], int size)
{
int i;
int sum;
for (i = 0; i < size; ++i)
{
sum += arr[i];
}
return sum;
}
0 comments:
Post a Comment