Tuesday, 3 January 2012

One Dimensional Arrays

Declaration of One Dimensional Arrays:
Syntax: data_type array_name[width];
Example: int roll[8];
In our example, int specifies the type if the variable, roll specifies the name of the variable and the value in bracket [8] is new for newbie. 
The bracket ([ ]) tells compiler that it is an array and number mention in the bracket specifies that how many elements (values in any array is called elements) it can store. This number is called dimension of array.
So, with respect to our example we have declared an array of integer type and named it “roll” which can store roll numbers of 8 students
C Array Assignment and Initialization:
We can initialize and assign values to the arrays in the same way as we do with variable. We can assign value to an array at the time of declaration or during runtime. Let’s look at each approach.
Syntax: data_type array_name[size]={list of values};
int arr[5]={1,2,3,4,5};
int arr[]={1,2,3,4,5};
In our above array example we have declared an integer array and named it “arr” which can hold 5 elements, we are also initializing arrays in the same time. 
Both statements in our example are valid method to declare and initialize single dimension array. 
In our first example we mention the size (5) of an array and assigned it values in curly brace, separating element’s value by comma (,). 
But in second example we left the size field blank but we provided its element’s value. When we only give element values without providing size of an array then C compiler automatically assumes its size from given element values.
There is one more method to initialize array C programming; in this method we can assign values to individual element of an array.
void main()
int arr[5],i;
printf("Value in array arr[0] : %d\n",arr[0]);
printf("Value in array arr[1] : %d\n",arr[1]);
printf("Value in array arr[2] : %d\n",arr[2]);
printf("Value in array arr[3] : %d\n",arr[3]);
printf("Value in array arr[4] : %d\n",arr[4]);
    printf("Value in array arr[%d] : %d\n",i,arr[i]);

1 comment:

  1. Appreciation for nice Updates, I found something new and folks can get useful info about BEST ONLINE TRAINING


host gator coupon