ONE-DIMENSIONAL ARRAYS
ONE-DIMENSIONAL ARRAYS
In C, single-subscripted variable xi can be
expressed as x[0], x[1], x[2], .............. x[n-1]
The subscript begins with number 0.
That is x[0] is allowed. For example, if we want to represent
a set of five numbers, say (35, 40, 20, 57, 19) by an array variable number,
then we may declare the variable number as follows int number[5];
and the computer reserves five storage locations and
afterwards numbers are inserted as shown below:
35 number[0]
40 number[1]20 number[2]
57 number[3]
19 number[4]
Like any other variable, arrays must be declared before they are used. The general form of array declaration is
type variable-name[size];
The type specifies the type of element that will be contained in the array, such as int, float, or char and the size indicates the maximum number of elements that can be stored inside the array. For example,
float height[50];
int group[10];
The C language treats character strings simply as array of characters. The size in a character string represents the maximum number of characters that the string can hold. For instance,
char name[10];
declares the name as a character array (string) variable that can hold a maximum of 10 characters. Suppose we read the following string constant into the string variable name.
“WELL DONE”
Initialization of Arrays:
We can initialize the elements of arrays in the same way as the ordinaryvariables when they are declared. The general form of initialization of arrays is:
static type array-name[size] = {list of values};
The values in the list are separated by commas. For example, the statement
static int number[3] = {0, 0, 0};
will declare the variable number as an array of size 3 and will assign zero to each element. If the number of values in the list is less than the number of elements, then only that many elements will be initialized. The remaining
elements will be set to zero automatically. For instance,
static float total[5] = {0.0, 15.75, -10};
#include<conio.h>
main()
{
int arr[6]={67,78,89,65,69,75},i;
//clrscr();
for(i=0;i<6;i++)
printf("%3d",arr[i]);
return 0;
}
/* A program is to calculate the sum of a array */
main()
{
int arr[6],i,sum=0;
clrscr();
printf("enter the elements into an array :");
for(i=0;i<6;i++)
scanf("%d",&arr[i]);
for(i=0;i<6;i++)
sum=sum+arr[i];
printf("\n total marks = %d ",sum);
getch();
}
Comments
Post a Comment