This blog is under construction

Sunday, 6 May 2012

Accessing array elements

Array values can be accessed using its name and subscript.  Consider an array num of 5 elements and the user wants to access fourth element of that array. So, user can access fourth element from num array using num[3].

num[5] = {1, 2, 3, 4, 5};

num[3] contains the fourth element of the array num.
Note: array index starts from 0.

num[3] = 100;
The above statement assigns value 100 to the fourth element of the array num.

Consider the following example,
struct student {
      char name[32];
      int age, rollno;

Here, arr is an array of structures.  Structure is noting but elements of different data type grouped under a common name.  We will see more about structures in forthcoming tutorials.  Let us see how to assign values to all the elements of the array arr.

Method 1:
arr[0] = { "Ram", 10, 101};  // assigns value to the first array element

Method 2:  // assigns value to the second array element
strcpy(arr[1].name, "Raj");
arr[1].age = 10;
arr[1].rollno = 101;

Example C program to access array elements

#include <stdio.h> 
  int main() {
        int num[5], input, i;
        printf("Enter your 5 subject marks:\n");
        for (i = 0; i < 5; i++) {
                printf("Enter mark for subject%d:", i+1);
                scanf("%d", &num[i]);
        printf("Subject mark u wanna access(1-5):");
        scanf("%d", &input);
        if (input >= 0 && input <= 5)
                printf("Requested data:%d\n", num[input-1]);
                printf("You've given wrong input\n");
        return 0;

  jp@jp-VirtualBox:~/$ ./a.out
  Enter your 5 subject marks:
  Enter mark for subject1:90
  Enter mark for subject2:89
  Enter mark for subject3:77
  Enter mark for subject4:68
  Enter mark for subject5:90
  Subject mark u wanna access(1-5):4
  Requested data:68

No comments:

Post a Comment