Array definition and declaration


Array definition and declaration

Arrays are a sort of data structure that may store a definite number of items of the same type in a logical order. Although an array is used to store data, it is often more convenient to think of it as a collection of similar-type variables.

You create a single array variable named numbers and use numbers[0], numbers[1],..., numbers[99] to represent individual variables instead of individual variables like number0, number1,..., and number99. In an array, an index is used to retrieve a specific element.

Declaring Arrays

In C, a programmer declares an array by specifying the type of components and the number of elements required by the array as follows:
arrayName [ arraySize ] type;

A single-dimensional array is what this is termed. arraySize must be a positive integer constant, and type can be any acceptable C data type. Use the expression double balance[10] to declare a 10-element array of type double named balance.

Declaring Arrays

  • Array variables are defined similarly to data type variables, with the difference that each array dimension's variable name is preceded by one pair of square [ ] brackets.
  • The size of rows, columns, and other elements of uninitialized arrays must be specified within square brackets.
  • When defining arrays in C, the dimensions must be positive integral constants or constant expressions.
  • Variables can be used as long as they have a positive value when the array is declared, but dimensions must still be positive integers in C99. (When the array is defined, space is only allocated once.) The array does not change in size if the variable used to define it changes later.

Examples:

#include<stdio.h> #include<conio.h> void main() { int marks [10],i,n,sum; sum=0; printf("enter number of student "); scanf("%d",&n); for(i=0;i<n;i++) { printf("enter marks of student %d",i); scanaf("%d",&marks[i]); sum=sum+marks[i]; } print("sum=%d",sum); } getch();

output:

enter number of student 3 enter marks of student0 8 enter marks of student1 7 enter marks of student2 5 sum = 20