Lecture V
Lecture V
Arrays in C
Arrays
a set of similar data types, called array. This Lecture describes how
arrays can be created and manipulated in C.
What are Arrays
For understanding the arrays properly, let us consider the following
program:
main( )
int x ;
x=5;
x = 10 ;
}
No doubt, this program will print the value of x as 10. Why so?
Because when a value 10 is assigned to x, the earlier value of x, i.e.
5, is lost. Thus, ordinary variables (the ones which we have used so
far) are capable of holding only one value at a time (as in the above
example). However, there are situations in which we would want to
store more than one value at a time in a single variable.
Definition!
int main()
{
int a[5]={5,10,20,30,40};
int i;
for(i=0;i<=4;i++)
printf("%d\n",a[i]);
system("pause");
return 0;
}
Defining Arrays
Example:
int marks[30] ;
Here, int specifies the type of the variable, just as it does with
ordinary variables and the word marks specifies the name of the
variable. The [30] however is new. The number 30 tells how many
elements of the type int will be in our array. This number is often
called the ‘dimension’ of size of the array. The bracket ( [ ] ) tells the
compiler that we are dealing with an array.
Accessing Elements of an Array
}
More on Arrays
#include <stdio.h>
#define SIZE 30
int main( )
{
int a[SIZE]={12,23,14,15,16,17,18,19,20,22};
int i;
int sum=0;
for(i=0;i<SIZE;i++)
{
sum=sum+a[i];
}
}
Example
int main( )
{
int a[100]={12,23,14,15,16,17,18,19,20,22};
int i;
int sum=0;
for(i=0;i<100;i++)
{
sum=sum+a[i];
}
system("pause");
return 0;
}
Example
Suppose we have an array num[ ] = { 24, 34, 12, 44, 56, 17 }. The
following figure shows how this array is located in memory.
main( )
{
int num[ ] = { 24, 34, 12, 44, 56, 17 } ;
int i ;
for ( i = 0 ; i <= 5 ; i++ )
{
printf ( "\nelement no. %d ", i ) ;
printf ( "Address = %u", &num[i] ) ;
}}
Two Dimensional Arrays
There are two parts to the program—in the first part through a for
loop we read in the values of roll no. and marks, whereas, in second
part through another for loop we print out these values.
int stud[4][2] = {
{ 1234, 56 },
{ 1212, 33 },
{ 1434, 80 },
{ 1312, 78 }
};
or