Arrays and Strings in C Programming

What is an Array?

Know more in Detail

An array is a collection of variables of the same type that are stored in contiguous memory locations. Think of it as a row of boxes, each box holding one value, and all boxes being of the same kind (type).

Arrays help you store and manage multiple values using a single variable name with an index to access each value.

Key Terms:

Example: Declaring and Using an Integer Array

int numbers[5] = {10, 20, 30, 40, 50};
printf("%d\n", numbers[2]);  // Outputs 30

Here, numbers is an array of 5 integers. We access the 3rd element using numbers[2] because indexes start at 0.


What is a String in C?

Know more in Detail

A string is a sequence of characters stored as an array of char elements in C. It is terminated with a special character called the null character represented as '\0'.

This null character marks the end of the string so functions know where the string stops.

Key Terms:

Example: Declaring and Printing a String

char name[] = "Rahul";
printf("%s\n", name);  // Outputs Rahul

Here, name is a character array holding the characters 'K', 'a', 'p', 'i', 'l', and '\0' (end marker).


How to Work with Arrays and Strings?

Example: Looping through an Array

int i;
int numbers[5] = {10, 20, 30, 40, 50};
for (i = 0; i < 5; i++) {
    printf("Element %d: %d\n", i, numbers[i]);
}

Common Operations with Strings


Practice Assignments

  1. Declare an integer array of size 10, initialize it with values, and print all elements.
  2. Write a program that reads a string from the user and prints its length using strlen().
  3. Write a program to reverse a string entered by the user.
  4. Write a program to concatenate two strings using strcat().

Further Reading