Single Dimensional Arrays in C can be initialized in the following way:
Method 1:
int rollnum[6]={5,3,32,9,2,10};
By this way, you specify the size of the array and initialize the values.
Method 2:
int rollnum[]={5,3,32,9,2,10};
You can even assign values to the array, without initializing the size of the array.
Method 3:
int rollnum[5]; int i; for( i=0;i<5;i++ ) { rollnum[i] = i; }
You can initialize the arrays this way too.
Accessing Array Elements
In C programming, you can access and operate arrays like variables in C. To access i'th element in the array you need to write as <array name>[i-1]. Since the array index starts from 0.
For example:
scanf("%d",&rollNum[3]); /* statement to insert value in the forth element of array rollNum[]. */ scanf("%d",&rollNum[i]); /* Statement to insert value in (i+1)th element of array rollNum[]. */ /* Because, the first element of array is rollNum[0], second is rollNum[1], ith is rollNum[i-1] and (i+1)th is rollNum[i]. */ printf("%d",rollNum[0]); /* statement to print first element of an array. */ printf("%d",rollNum[i]); /* statement to print (i+1)th element of an array. */
One thing you should remember is that, when you have declared roll_Number[6] array of size 6, your valid access to the array is only from 0 to 5. If you try to access any invalid index like 8, 10 etc. compiler do not throw any error, it will be throw a runtime error. Usually a program crash due to invalid memory manipulation i.e. it would cause a segmentation fault.
No comments:
Post a Comment