MODULE 2 : PROGRAMMING IN C
Arrays in C – Definition, Initialization, and Accessing
What is an Array?
An array is a collection of multiple values of the same data type, stored in continuous memory
locations.
• It allows you to use one variable name to store and access multiple values.
• Each value in an array is called an element.
• Each element is accessed using an index (starting from 0).
Types of Arrays
1. Single-Dimensional Array (1D Array)
• Stores data in a linear or one-row format.
• Example: To store 5 numbers:
• int marks[5]; // Declaration
2. Multi-Dimensional Array (Mostly 2D)
• Used to store data in rows and columns (like a table or matrix).
• Example:
• int matrix[3][3]; // 3 rows and 3 columns
Initialization of Arrays
1. Single-Dimensional Array Initialization
int a[5] = {10, 20, 30, 40, 50}; // initializes all 5 values
You can also initialize like this:
int a[] = {10, 20, 30}; // compiler counts the size
2. Multi-Dimensional Array Initialization
int b[2][2] = {
{1, 2},
{3, 4}
};
Accessing Elements of Arrays
1. Accessing 1D Array Elements
Use the index number:
int a[3] = {10, 20, 30};
printf("%d", a[0]); // prints 10
2. Accessing 2D Array Elements
Use row and column indices:
int b[2][2] = {{1, 2}, {3, 4}};
printf("%d", b[1][0]); // prints 3
Example: Simple Program Using 1D Array
#include <stdio.h>
int main() {
int i, a[3] = {10, 20, 30};
for(i = 0; i < 3; i++) {
printf("%d ", a[i]);
return 0;
}
Example: Simple Program Using 2D Array
#include <stdio.h>
int main() {
int i, j, a[2][2] = {{1, 2}, {3, 4}};
for(i = 0; i < 2; i++) {
for(j = 0; j < 2; j++) {
printf("%d ", a[i][j]);
printf("\n");
return 0;
Develop Programs Using Single and Multi-Dimensional Arrays
1. Single-Dimensional Array Program
Objective: Store and print 5 numbers using an array.
Program:
#include <stdio.h>
int main() {
int i;
int numbers[5] = {10, 20, 30, 40, 50};
for(i = 0; i < 5; i++) {
printf("Element at index %d = %d\n", i, numbers[i]);
}
return 0;
Explanation:
• int numbers[5]: Declares an array of size 5.
• {10, 20, 30, 40, 50}: Initializes the array elements.
• for(i = 0; i < 5; i++): Loops through the array using index.
• numbers[i]: Accesses each element by index and prints it.
2. Multi-Dimensional (2D) Array Program
Objective: Store and display a 2×2 matrix (2 rows and 2 columns)
Program:
#include <stdio.h>
int main() {
int i, j;
int matrix[2][2] = {
{1, 2},
{3, 4}
};
for(i = 0; i < 2; i++) {
for(j = 0; j < 2; j++) {
printf("Element at [%d][%d] = %d\n", i, j, matrix[i][j]);
} }
return 0;
Explanation:
• int matrix[2][2]: Declares a 2x2 array.
• { {1, 2}, {3, 4} }: Initializes values in row and column format.
• Two for loops:
o Outer loop for rows
o Inner loop for columns
• matrix[i][j]: Accesses each element using row and column index.
Divide and Conquer Method in Solving Problems
What is Divide and Conquer?
Divide and Conquer is a problem-solving technique in programming where:
1. Divide – The problem is broken into smaller sub-problems.
2. Conquer – Each sub-problem is solved individually (often using recursion).
3. Combine – The results of the sub-problems are combined to get the final solution.
Steps of Divide and Conquer:
Step Description
Divide Split the main problem into smaller parts
Conquer Solve each part (usually recursively)
Combine Merge the results to solve the original problem
Real-life Example:
Imagine cutting a pizza into slices to make it easier to eat.
• You divide it (slices), eat (solve) each slice, and together it's the full pizza eaten
(combined result).
Common Examples in C Programming:
1. Binary Search
2. Merge Sort
3. Quick Sort
Example: Binary Search (using Divide and Conquer)
int binarySearch(int arr[], int low, int high, int key) {
if (low <= high) {
int mid = (low + high) / 2;
if (arr[mid] == key)
return mid;
else if (key < arr[mid])
return binarySearch(arr, low, mid - 1, key);
else
return binarySearch(arr, mid + 1, high, key);
return -1; // Not found
Explanation:
• Divide the array into half using mid.
• Conquer by checking whether the key is on the left or right.
• Combine is implicit, as the result (index) is returned once the correct element is found.
Advantages of Divide and Conquer:
• Efficient for large problems
• Reduces time complexity (e.g., Binary Search = O(log n))
• Uses recursion to break problems into manageable parts
Searching and Sorting Programs with Explanations
1. Linear Search
Program:
#include <stdio.h>
int main() {
int a[5] = {10, 20, 30, 40, 50}; // array of 5 elements
int key = 30, i, found = 0;
for(i = 0; i < 5; i++) {
if(a[i] == key) { // check if current element matches the key
printf("Found at index %d\n", i); // print position
found = 1; // mark as found
break; // exit the loop
if(!found)
printf("Not found\n"); // if not found, print message
return 0;
Explanation:
• The array a has 5 elements.
• The program looks for key = 30 using a loop.
• Each element is checked one by one.
• If it matches the key, its index is printed.
• If not found after the loop, it prints "Not found".
2. Binary Search
Program:
#include <stdio.h>
int main() {
int a[5] = {10, 20, 30, 40, 50}; // must be sorted
int key = 30, low = 0, high = 4, mid;
while(low <= high) {
mid = (low + high) / 2; // find middle index
if(a[mid] == key) {
printf("Found at index %d\n", mid);
return 0;
} else if(key < a[mid]) {
high = mid - 1; // search in left half
} else {
low = mid + 1; // search in right half
}
printf("Not found\n");
return 0;
Explanation:
• The array is already sorted (important for binary search).
• It finds the middle element and checks if it's equal to the key.
• If the key is less, search left; if greater, search right.
• This continues until the key is found or the search ends.
Selection Sort
Program:
#include <stdio.h>
int main() {
int a[5] = {30, 10, 50, 20, 40}; // Unsorted array
int i, j, temp;
for(i = 0; i < 5; i++) {
for(j = i + 1; j < 5; j++) {
if(a[j] < a[i]) {
// Swap a[i] and a[j]
temp = a[i];
a[i] = a[j];
a[j] = temp;
printf("Sorted array: ");
for(i = 0; i < 5; i++) {
printf("%d ", a[i]);
return 0;
What this Program Does:
• It sorts the array {30, 10, 50, 20, 40} in ascending order using a simple sorting technique.
Step-by-Step Explanation
Initial Array:
a[5] = {30, 10, 50, 20, 40}
Outer Loop: for(i = 0; i < 5; i++)
• This loop goes through each element one by one.
• It assumes that the current element (a[i]) is the smallest, and tries to find a smaller
element in the rest of the array.
Inner Loop: for(j = i + 1; j < 5; j++)
• This loop compares a[i] with every next element a[j].
• If it finds a[j] < a[i], it swaps the values.
Swapping:
temp = a[i];
a[i] = a[j];
a[j] = temp;
• This swaps two values in the array.
How the Array Changes (Step by Step):
Step 1:
• Compare 30 with 10 → Swap
→ {10, 30, 50, 20, 40}
Step 2:
• Compare 30 with 20 → Swap
→ {10, 20, 50, 30, 40}
Step 3:
• Compare 50 with 30 → Swap
→ {10, 20, 30, 50, 40}
Step 4:
• Compare 50 with 40 → Swap
→ {10, 20, 30, 40, 50}
Final Sorted Array:
Sorted array: 10 20 30 40 50
Output:
Sorted array: 10 20 30 40 50
Summary of Logic:
Part Meaning
Outer loop i Picks one element at a time
Inner loop j Compares it with the rest of the elements
Swap Happens if a smaller number is found
Result Array gets sorted in ascending order
QUICKSORT
What is Quick Sort?
• Quick Sort is a fast way to sort numbers.
• It uses a method called “Divide and Conquer.”
• The idea is to:
1. Pick one number as a pivot.
2. Put smaller numbers on the left, and bigger numbers on the right.
3. Do the same thing again and again (recursively) on both sides until everything is
sorted.
Let’s Understand with a Simple Example
Array:
a = {40, 10, 30, 20}
➤ Step 1: Choose Pivot
Let’s take the first element as pivot:
pivot = 40
➤ Step 2: Arrange elements
Put all numbers less than 40 on the left, greater on the right:
New order: {10, 30, 20, 40}
Now, pivot 40 is in its correct place.
➤ Step 3: Repeat on Left Side {10, 30, 20}
• Pivot = 10
• All elements > 10, so move them to the right
New order: {10, 30, 20}
Now 10 is in its correct place.
➤ Step 4: Repeat on {30, 20}
• Pivot = 30
• 20 < 30, so swap
New order: {20, 30}
Final Sorted Array:
{10, 20, 30, 40}
Simple Quick Sort Program in C
#include <stdio.h>
void quickSort(int a[], int low, int high) {
if (low < high) {
int i = low, j = high, pivot = a[low], temp;
while (i < j) {
while (a[i] <= pivot && i < high) i++;
while (a[j] > pivot) j--;
if (i < j) {
temp = a[i];
a[i] = a[j];
a[j] = temp;
// Place pivot in correct position
a[low] = a[j];
a[j] = pivot;
// Sort left and right parts
quickSort(a, low, j - 1);
quickSort(a, j + 1, high);
int main() {
int a[4] = {40, 10, 30, 20};
int i;
quickSort(a, 0, 3); // 0 to 3 = 4 elements
printf("Sorted array: ");
for(i = 0; i < 4; i++) {
printf("%d ", a[i]);
return 0;
Output:
Sorted array: 10 20 30 40
Simple Points to Remember
Step Description
Pick a pivot
Put smaller on left, larger on right
Place pivot in its correct place
Repeat the steps on left and right parts (recursion)
Result: Array is sorted
Representation of Strings in C
What is a String in C?
• A string is a group of characters.
• In C, a string is stored in a character array.
• A null character \0 is added at the end of the string to mark its end.
Example:
char name[] = "JISAM";
This is stored in memory as:
| 'J' | 'I' | 'S' | 'A' | 'M' | '\0' |
Ways to Declare Strings in C:
1. Using Double Quotes (String Literal):
char name[] = "HELLO";
2. Using Character Array:
char name[] = {'H', 'E', 'L', 'L', 'O', '\0'};
String Input and Output
Input Using scanf:
char name[20];
scanf("%s", name); // Reads a single word only
Output Using printf:
printf("%s", name); // Prints the string
Note:
• scanf() stops reading input at a space.
• To read a full sentence, use gets() (old) or fgets() (recommended).
String Header File
• To use string functions, include:
#include <string.h>
Common String Functions:
Function Purpose
strlen(s) Finds the length of string s
strcpy(s1, s2) Copies string s2 into s1
strcat(s1, s2) Appends s2 to the end of s1
strcmp(s1, s2) Compares two strings
strstr(s, "word") Finds "word" in string s
Example Program:
#include <stdio.h>
#include <string.h>
int main() {
char name[20] = "JISAM";
printf("Name: %s\n", name);
printf("Length: %d\n", strlen(name)); // Output: 5
return 0;
Summary
• A string is a character array ending with '\0'.
• Can be declared with quotes or with characters.
• Use #include <string.h> for built-in string functions.
C Programs to Perform Different String Operations
1. Find the Length of a String
#include <stdio.h>
#include <string.h>
int main() {
char str[20] = "Hello";
int length = strlen(str);
printf("Length = %d\n", length);
return 0;
Explanation:
• strlen() function returns how many characters are in the string (excluding \0).
2. Copy One String to Another
#include <stdio.h>
#include <string.h>
int main() {
char str1[20] = "JISAM";
char str2[20];
strcpy(str2, str1);
printf("Copied string: %s\n", str2);
return 0;
Explanation:
• strcpy(destination, source) copies contents of str1 to str2.
3. Concatenate (Join) Two Strings
#include <stdio.h>
#include <string.h>
int main() {
char str1[20] = "Hello ";
char str2[10] = "World";
strcat(str1, str2);
printf("Concatenated string: %s\n", str1);
return 0;
Explanation:
• strcat() joins str2 at the end of str1.
4. Compare Two Strings
#include <stdio.h>
#include <string.h>
int main() {
char str1[20] = "Apple";
char str2[20] = "Apple";
if(strcmp(str1, str2) == 0)
printf("Strings are equal\n");
else
printf("Strings are not equal\n");
return 0;
Explanation:
• strcmp() returns 0 if both strings are the same.
5. Reverse a String (Without Built-in Function)
#include <stdio.h>
#include <string.h>
int main() {
char str[20] = "JISAM";
int i, len = strlen(str);
printf("Reversed string: ");
for(i = len - 1; i >= 0; i--) {
printf("%c", str[i]);
return 0;
Explanation:
• This loop prints the string from the last character to the first.
6. Count Vowels in a String
#include <stdio.h>
#include <string.h>
int main() {
char str[100] = "Hello World";
int i, count = 0;
for(i = 0; str[i] != '\0'; i++) {
if(str[i]=='a'||str[i]=='e'||str[i]=='i'||str[i]=='o'||str[i]=='u' ||
str[i]=='A'||str[i]=='E'||str[i]=='I'||str[i]=='O'||str[i]=='U')
count++;
printf("Number of vowels = %d\n", count);
return 0;
}
Explanation:
• This loop checks each character and counts if it is a vowel.
Passing Arrays to a Function – Very Simple Note
What does it mean?
• When we give an array to a function, we are sending it so the function can use or
change the array.
Why do we pass arrays?
• To print array elements
• To change values inside the array
• To do calculations like sum, average, etc.
Key Point:
We don’t send the full array — we only send its starting address (just the name of the array).
So any changes made inside the function will also happen in the original array.
Example 1: Just Print the Array
#include <stdio.h>
// Function to print array
void show(int arr[], int size) {
for(int i = 0; i < size; i++) {
printf("%d ", arr[i]);
}
}
int main() {
int a[3] = {10, 20, 30};
show(a, 3); // We send array to function
return 0;
What happens?
• The function show() gets the array a[] and prints each number.
Example 2: Change Array Values
#include <stdio.h>
// Function to double each value
void change(int arr[], int size) {
for(int i = 0; i < size; i++) {
arr[i] = arr[i] * 2;
int main() {
int a[3] = {1, 2, 3};
change(a, 3); // Send array to function
// Print changed values
for(int i = 0; i < 3; i++) {
printf("%d ", a[i]);
return 0;
What happens?
• The function change() doubles every value in the array.
• Since the array is passed by reference, the original array is also changed.
Simple Summary Table
Concept Meaning
Arrays are passed by Reference (address)
Function receives The address of array
Can we change array in function? Yes
Do we need to send size? Yes, always send size too