Saturday, February 7, 2015

How to Read and Write Single Dimensional Array in C Language

6:18 PMSaturday, February 7, 2015
In Computer Programming, it is very easy to read or write variables by following some of the syntaxex listed in the rules. While programming in C, as discussed in earlier article, single dimensional array have such a simple declaration, initialization and now read and write syntax.

Consider the declaration shown below:

int arr[5];

Here, 5 memory locations are reserved and each item in the memory location can be accessed by specifying the index as: arr[0] through arr[4], we can access 5 data items. What, if there are n no. of items to be stored in the array.
Note: In general, using arr[0] through arr[n-1] we can access n data items of an array.

The n data items are read from the keyboard using the scanf() function as shown below:

scanf("%d", &arr[0]);
scanf("%d", &arr[1]);
scanf("%d", &arr[2]);

scanf("%d", &arr[n-1]);

In general syntax of scanf("%d", &arr[i]) i may be valued as 0, 1, 2, 3, ……., n-1. So, in C language, if we want to read n data items from the keyboard, the following looping statement can be used:

for(i=0; i<n; i++)

Similarly, to display n data items stored in the array, replace scanf() by printf() statement as shown below:

for(i=0; i<n; i++)

Now, write a small C program to read n elements from the keyboard and to display those same n elements on to the screen.

  int n, i, arr[10];
  printf("Enter the value of n:");
  printf("Enter n elements here:\n");
  for(i=0; i<n; i++)
       printf("The entered elements are :%d\n", arr[i]);

The above program, when run, will show the following output screen:

How to Read and Write Single Dimensional Array in C: Computer Programming

Protected by Copyscape Online Copyright Protection Software


Post a Comment

Toggle Footer