L-06: Arrays, Strings

Arrays in C Programming #


What is an Array? #

  • An array is a collection of elements of the same data type stored in contiguous memory locations.
  • Each element is accessed using an index.
  • In C, array indices start from 0.

Syntax:

data_type array_name[size];

Example: Declaring Arrays #

int marks[5];           // Array of 5 integers
float prices[10];       // Array of 10 floats
char name[20];          // Array of 20 characters

Memory is allocated contiguously.

marks[0], marks[1], … marks[4]

code


Example: Input from user #

#include <stdio.h>

int main() {
    int arr[5];
    for (int i = 0; i < 5; i++) {
        printf("Enter element %d: ", i+1);
        scanf("%d", &arr[i]);
    }

    printf("You entered: ");
    for (int i = 0; i < 5; i++) {
        printf("%d ", arr[i]);
    }
    return 0;
}

Example: Sum of elements #

#include <stdio.h>

int main() {
    int arr[5] = {2, 4, 6, 8, 10};
    int sum = 0;

    for (int i = 0; i < 5; i++) {
        sum += arr[i];
    }

    printf("Sum = %d\n", sum);
    return 0;
}

Example: Find duplicates in an array #

#include <stdio.h>

int main() {
    int marks[5] = {90, 85, 88, 92, 88};
    for (int i = 0; i < 5; i++) {
      for(int j = i + 1; j < 5; j++) {
        if (marks[i] == marks[j]) {
          printf("Found duplicate number %d in %d, %d positions\n", marks[i], i, j);
          return 0;
        }
      }
    }
    printf("No duplicates\n");
    return 0;
}

Step by Step Execution #

Exercise #

Print all duplicates in the array (previous program stopped at the first time duplicate is found). Only if no duplicates are found, print “No duplicates”.


Strings in C Programming #


What is a String? #

  • A string in C is an array of characters ending with a special character '\0' (null terminator).
  • Unlike some other languages, C does not have a built-in string type — they are handled using character arrays.

Syntax:

char str[size];

Declaring and Initializing Strings #

char name[20] = "Alice";

Other Ways

char name[] = "Alice";        // Size auto-determined
char name[6] = {'A','l','i','c','e','\0'};

Input and Output of Strings #

#include <stdio.h>

int main() {
    char name[50];

    printf("Enter your name: ");
    scanf("%s", name);   // Reads until space

    printf("Hello %s!\n", name);
    return 0;
}

Example Problem: Count Vowels in a String #


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

  int main() {
      char str[100] = "Hello World!";
      int count = 0;

      for(int i=0; str[i] != '\0'; i++) {
          char c = str[i];
          if(c=='a'||c=='e'||c=='i'||c=='o'||c=='u'||
            c=='A'||c=='E'||c=='I'||c=='O'||c=='U') {
              count++;
          }
      }
      printf("Number of vowels = %d\n", count);
      return 0;
  }

Next Class #

  • String Library
  • Multidimensional Arrays