C Tutorial menu

C Arrays and Strings

An array holds many values of the same type in one variable. In C, a string is simply an array of characters.

Creating an Array

Example

c
int marks[5] = {72, 88, 65, 91, 79};
  • int is the type of every item
  • 5 is the number of items
  • Items are reached by index, starting at 0

Example

c
#include <stdio.h>

int main(void) {
  int marks[5] = {72, 88, 65, 91, 79};
  printf("First: %d\n", marks[0]);
  printf("Last: %d\n", marks[4]);

  marks[2] = 70;   // change an item
  printf("Third: %d\n", marks[2]);
  return 0;
}
Output
First: 72
Last: 91
Third: 70

C does not check array limits. Reading marks[5] or marks[10] will not stop with a clear error; it reads random memory. Always stay between 0 and size - 1.

Looping Through an Array

Example

c
#include <stdio.h>

int main(void) {
  int sales[] = {1200, 950, 1800, 700};
  int count = sizeof(sales) / sizeof(sales[0]);
  int total = 0;

  for (int i = 0; i < count; i++) {
    total += sales[i];
  }
  printf("Days: %d\n", count);
  printf("Total sales: Rs %d\n", total);
  return 0;
}
Output
Days: 4
Total sales: Rs 4650

sizeof(sales) is the size of the whole array in bytes. Dividing by the size of one item gives the number of items.

Two-Dimensional Arrays

Example

c
int table[2][3] = {
  {1, 2, 3},
  {4, 5, 6}
};
printf("%d\n", table[1][0]);   // prints 4

Strings in C

A string is an array of char that ends with a special null character '\0'. When you write text in double quotes, C adds the '\0' for you.

Example

c
#include <stdio.h>

int main(void) {
  char name[] = "Ayesha";
  printf("Hello, %s!\n", name);
  printf("First letter: %c\n", name[0]);
  return 0;
}
Output
Hello, Ayesha!
First letter: A

The word "Ayesha" has 6 letters, but the array uses 7 bytes because of the hidden '\0' at the end.

String Functions

Include <string.h> to use these helpers:

FunctionWhat it does
strlen(s)Length of the string (without '\0')
strcpy(dest, src)Copies src into dest
strcat(dest, src)Adds src to the end of dest
strcmp(a, b)Returns 0 if the strings are equal

Example

c
#include <stdio.h>
#include <string.h>

int main(void) {
  char city[20] = "Karachi";
  char full[40];

  strcpy(full, city);
  strcat(full, ", Pakistan");

  printf("%s\n", full);
  printf("Length: %zu\n", strlen(full));
  printf("Same? %d\n", strcmp(city, "Karachi") == 0);
  return 0;
}
Output
Karachi, Pakistan
Length: 17
Same? 1

Make sure the destination array is big enough for the result, or you will overwrite memory.

Reading a Line of Text

scanf("%s", ...) stops at the first space. To read a full line, use fgets:

Example

c
char fullName[50];
fgets(fullName, sizeof(fullName), stdin);

Exercise

Exercise

What character marks the end of every C string?

Learn C with a teacher

Join the Python Programming course at Workownix, online or in Orangi Town, Karachi, and get a certificate.

See the course Ask on WhatsApp