Problem Solving using C Language

0 of 85 lessons complete (0%)

Arrays

Program: Array

1. Basic Array Initialization and Traversal

#include <stdio.h>

int main() {
  int arr[5] = {10, 20, 30, 40, 50}; // Initialization of array
  
  // Traversing and printing array elements
  printf("Array elements:\n");
  for(int i = 0; i < 5; i++) {
    printf("%d ", arr[i]);
  }

  return 0;
}

2. Sum of All Elements in an Array

This program calculates the sum of all the elements in an array.

#include <stdio.h>

int main() {
  int arr[6] = {5, 8, 12, 3, 7, 10};
  int sum = 0;
  
  // Calculate sum
  for(int i = 0; i < 6; i++) {
    sum += arr[i];
  }
  
  printf("Sum of array elements: %d\n", sum);
  
  return 0;
}

3. Find Maximum and Minimum Element in an Array

#include <stdio.h>

int main() {
  int arr[6] = {12, 5, 7, 89, 34, 21};
  int max = arr[0];
  int min = arr[0];
  
  for(int i = 1; i < 6; i++) {
    if(arr[i] > max) {
      max = arr[i];
    }
    if(arr[i] < min) {
      min = arr[i];
    }
  }
  
  printf("Maximum: %d\n", max);
  printf("Minimum: %d\n", min);
  
  return 0;
}

4. Reversing an Array

This program reverses the elements of an array.

#include <stdio.h>

int main() {
  int arr[5] = {10, 20, 30, 40, 50};
  int temp;

  // Reversing the array
  for(int i = 0; i < 5 / 2; i++) {
    temp = arr[i];
    arr[i] = arr[5 - i - 1];
    arr[5 - i - 1] = temp;
  }

  printf("Reversed array:\n");
  for(int i = 0; i < 5; i++) {
    printf("%d ", arr[i]);
  }

  return 0;
}

5. Sorting an Array in Ascending Order

#include <stdio.h>

int main() {
  int arr[5] = {64, 34, 25, 12, 22};
  int n = 5, temp;
  
  // Bubble sort algorithm
  for(int i = 0; i < n-1; i++) {
    for(int j = 0; j < n-i-1; j++) {
      if(arr[j] > arr[j+1]) {
        temp = arr[j];
        arr[j] = arr[j+1];
        arr[j+1] = temp;
      }
    }
  }
  
  printf("Sorted array: \n");
  for(int i = 0; i < n; i++) {
    printf("%d ", arr[i]);
  }
  
  return 0;
}

Programs to Practice

  • Create an array to store and print student grades.
  • Write a program to find the largest number in an array.
  • Implement a program that takes user input to fill an array and then displays it.
  • Array Input and Output: Write a program to take input for an array from the user and print the array elements.
  • Array Sum and Average: Calculate the sum and average of the elements in an array.
  • Find Largest and Smallest Element: Find the maximum and minimum element in an array.
  • Count Even and Odd Numbers: Write a program to count the number of even and odd elements in an array.
  • Linear Search: Implement a linear search algorithm to find a given element in an array.