what is a arrays

C arrays
An array is a variable that can store multiple values. For example, if you want to store 100 integers, you can create an array for it.
  1. int data[100];

How to declare an array?

dataType arrayName[arraySize];
For example,
float mark[5];
Here, we declared an array, mark, of floating-point type. And its size is 5. Meaning, it can hold 5 floating-point values.
It's important to note that the size and type of an array cannot be changed once it is declared.

Access Array Elements

You can access elements of an array by indices.
Suppose you declared an array mark as above. The first element is mark[0], the second element is mark[1] and so on.
C Array declaration

Few keynotes:

  • Arrays have 0 as the first index, not 1. In this example, mark[0] is the first element.
  • If the size of an array is n, to access the last element, the n-1 index is used. In this example, mark[4]
  • Suppose the starting address of mark[0] is 2120d. Then, the address of the mark[1] will be 2124d. Similarly, the address of mark[2] will be 2128d and so on.
    This is because the size of a float is 4 bytes.

How to initialize an array?

It is possible to initialize an array during declaration. For example,
  1. int mark[5] = {19, 10, 8, 17, 9};
You can also initialize an array like this.
  1. int mark[] = {19, 10, 8, 17, 9};
Here, we haven't specified the size. However, the compiler knows its size is 5 as we are initializing it with 5 elements.
Initialize an array in C programming
Here,
mark[0] is equal to 19
mark[1] is equal to 10
mark[2] is equal to 8
mark[3] is equal to 17
mark[4] is equal to 9

Change Value of Array elements

  1. int mark[5] = {19, 10, 8, 17, 9}
  2. // make the value of the third element to -1
  3. mark[2] = -1;
  4. // make the value of the fifth element to 0
  5. mark[4] = 0;

Input and Output Array Elements

Here's how you can take input from the user and store it in an array element.
  1. // take input and store it in the 3rd element
  2. scanf("%d", &mark[2]);
  3. // take input and store it in the ith element
  4. scanf("%d", &mark[i-1]);
  1. // print the first element of the array
  2. printf("%d", mark[0]);
  3. // print the third element of the array
  4. printf("%d", mark[2]);
  5. // print ith element of the array
  6. printf("%d", mark[i-1]);

Example 1: Array Input/Output

  1. // Program to take 5 values from the user and store them in an array
  2. // Print the elements stored in the array
  3. #include <stdio.h>
  4. int main() {
  5. int values[5];
  6. printf("Enter 5 integers: ");
  7. // taking input and storing it in an array
  8. for(int i = 0; i < 5; ++i) {
  9. scanf("%d", &values[i]);
  10. }
  11. printf("Displaying integers: ");
  12. // printing elements of an array
  13. for(int i = 0; i < 5; ++i) {
  14. printf("%d\n", values[i]);
  15. }
  16. return 0;
  17. }
Output
Enter 5 integers: 1
-3
34
0
3
Displaying integers: 1
-3
34
0
3

Post a Comment

0 Comments