0% found this document useful (0 votes)
20 views23 pages

Module 4

Module 4 of CS1003 Programming in C covers arrays and strings, focusing on the definition, initialization, and manipulation of one-dimensional arrays. It explains concepts such as bounds checking, insertion, deletion, updating elements, and searching for duplicates, along with practical examples and code snippets. Additionally, it introduces sorting algorithms like bubble sort for organizing array elements.

Uploaded by

faizaan1845
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
20 views23 pages

Module 4

Module 4 of CS1003 Programming in C covers arrays and strings, focusing on the definition, initialization, and manipulation of one-dimensional arrays. It explains concepts such as bounds checking, insertion, deletion, updating elements, and searching for duplicates, along with practical examples and code snippets. Additionally, it introduces sorting algorithms like bubble sort for organizing array elements.

Uploaded by

faizaan1845
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Module 4: Programming in C – Arrays & Strings

Title
Title: CS1003 Programming in C
Module 4: Arrays & Strings
Subtitle: Part – 1: Arrays & Part – 2: Strings

Introduction to Arrays
Concept:
●​ An array is a collection of elements of the same type that are referenced by a
common name.
●​ Arrays have a fixed size defined at declaration.
●​ Elements are accessed using zero-based indices starting from 0.
●​ Arrays store homogeneous data types.
●​ All elements occupy contiguous memory locations, making access efficient.
Example:
int marks[5]; // declares an array of 5 integers

Explanation: The variable marks can store 5 integers. Each index (marks[0] to
marks[4]) corresponds to a unique memory location.

Need for Arrays


●​ Assume we have to store 1000 students marks. Without arrays, multiple
variables like StuMar0, StuMar1, ..., StuMar999 would need to be declared for
1000 student marks.
●​ Using an array int StuMar[1000]; simplifies storage and manipulation.
●​ Indexing allows easy access to each student’s marks.

Array Initialization & Indexing


●​ Arrays can be initialized fully, partially, or implicitly.
●​ Full Initialization: all elements assigned specific values.
int arr[5] = {1, 2, 3, 4, 5};

●​ Partial Initialization: some elements assigned, others set to 0.


int arr[5] = {1, 2}; // remaining elements initialized to 0

●​ Implicit initialization: occurs when array is declared without values.


int arr[5] // elements not initialized

●​ Memory Indexing Example: If arr starts at address 1000 and each int is 4bytes,
arr[3] is at 1000 + 3*4 = 1012.

Bounds Checking
Concept: - Valid indices: 0 to size-1. - Accessing outside this range causes undefined
behavior.
Example:
#include <stdio.h>​
int main() {​
int arr[5] = {10, 20, 30, 40, 50};​
for(int i = 0; i <= 5; i++) {​
printf("arr[%d] = %d\n", i, arr[i]);​
}​
return 0;​
}

●​ Explanation: The loop runs one index too far (i=5), causing an out-of-bounds
access. Always ensure indices remain within the valid bounds.

One-Dimensional Arrays – Declaration, Initialization, Traversal


Declaration & Initialization:
int arr[5] = {10, 20, 30, 40, 50};

Traversal Example:
for(int i = 0; i < 5; i++) {​
printf("%d ", arr[i]);​
}

●​ Access elements using the index: arr[0] is 10, arr[1] is 20 and so on till
arr[4] is 50.
●​ Traversal: Loop through each element to input/print/modify values.

One-Dimensional Arrays – Insertion, Deletion and Updation


Insertion Concept: Insert an element at a specific index.
●​ Shift elements from the insertion point to the right.
●​ Place the new element at the desired index.
●​ Array size must accommodate the new element.

int arr[100] = {10, 20, 30, 40, 50}; // Initial array


int n = 5; // Current size
int index = 2; // Where to insert
int value = 25; // Value to insert

To insert 25 at index 2, shift all elements from last to index one step right.​

for(i = n; i > index; i--)

arr[i] = arr[i - 1];

Now the position is free → place the new value:​



arr[2] = 25;

Increase array size (n++).

Output Array after insertion:


10 20 25 30 40 50

Deletion Concept: Delete an element at a specific index.


Shift elements after the deleted index to the left. Logical array size decreases by 1.
int arr[5] = {10, 20, 30, 40, 50};
int n = 5;
int index = 3;
for(int i = index; i < n - 1; i++) {
arr[i] = arr[i + 1]; // Shift elements left
}
n--; // reduce size
Initial Array
Index: 0 1 2 3 4
Value:10 20 30 40 50

We want to delete element at index 3 → value = 40.


Delete is done by shifting elements left:
arr[i] = arr[i+1];

The loop:
for(i = 3; i < 4; i++)

Because n = 5, n - 1 = 4, so condition is:


i = 3 → 3 < 4 → run
i = 4 → 4 < 4 → stop

So only one iteration happens.

Iteration 1
i = 3
arr[3] = arr[4];

Substitute values:
arr[3] = 50

Array becomes:
[10, 20, 30, 50, 50]

Why last element is duplicate?​


→ Because we shifted left, but the real size is now n = n–1 = 4, so we
ignore the last element.

Final Array After Deletion


After decreasing size:
n = 4
Array = [10, 20, 30, 50]

Updation Concept: Modify an element at a given index.


arr[1] = 50;

Changes the value at arr[1]. Other elements remain unaffected.


1D Array Manipulation – Linear Search (find first occurrence)
Concept: linear_search scans the array from index 0 to n-1. It returns the index of
the first match, or -1 if the key is not present.
#include <stdio.h>

int main() {
int n = 6;
int arr[] = {10, 25, 7, 30, 18, 40};
int key = 30;
int i, found = -1;

for(i = 0; i < n; i++) {


if(arr[i] == key) {
found = i;
break;
}
}

if(found != -1)
printf("Element %d found at index %d\n", key, found);
else
printf("Element %d not found\n", key);

return 0;
}

Step-wise Explanation of Iterations


Input:

n = 6
arr = [10, 25, 7, 30, 18, 40]
key = 30 //We search for 30.

Iteration-by-Iteration Trace
Iteration 1
●​ i = 0; arr[0] = 10
●​ Compare: 10 == 30 → ❌ No match; i++
Iteration 2
●​ i = 1; arr[1] = 25
●​ Compare: 25 == 30 → ❌ No match; i++
Iteration 3
●​ i = 2; arr[2] = 7
●​ Compare: 7 == 30 → ❌ No match; i++
Iteration 4
●​
●​
i = 3; arr[3] = 30
Compare: 30 == 30 → ✅ Match found
●​ found = 3
●​ break → loop stops

Result
Element 30 found at index 3

1D Arrays – Finding Duplicate Elements


Concept: Identify duplicate values in an array.
#include <stdio.h>

int main() {
int arr[100], freq[100];
int n, i, j;

printf("Enter number of elements: ");


scanf("%d", &n);

printf("Enter %d elements:\n", n);


for(i = 0; i < n; i++)
scanf("%d", &arr[i]);

for(i = 0; i < n; i++)


freq[i] = -1; // Initialize freq[] to -1

for(i = 0; i < n; i++) {


int count = 1;

for(j = i + 1; j < n; j++) {


if(arr[i] == arr[j]) {
count++; // Counting occurrences
freq[j] = 0; // Mark as already counted
}
}

if(freq[i] != 0)
freq[i] = count;
}

printf("\nDuplicate counts:\n");
for(i = 0; i < n; i++) {
if(freq[i] > 1) {
int duplicates = freq[i] - 1; // Printing duplicates count
printf("%d has %d duplicate(s)\n", arr[i], duplicates);
}
}

return 0;
}

Step-wise Explanation of Iterations:


Example input: n = 7; arr[ ] = [5, 2, 3, 5, 2, 5, 3]

Initial freq[] (after initialization to -1): freq[] = [-1,-1,-1,-1,-1,-1,-1]

Outer loop: i = 0 (element arr[0] = 5)


●​ Start: count = 1
●​ Inner loop j runs 1..6:
○​ j=1: arr[1]=2 → not equal → count stays 1
○​ j=2: arr[2]=3 → not equal
○​ j=3: arr[3]=5 → equal → count = 2; set freq[3] = 0
○​ j=4: arr[4]=2 → not equal
○​ j=5: arr[5]=5 → equal → count = 3; set freq[5] = 0
○​ j=6: arr[6]=3 → not equal
●​ After inner loop: count = 3
●​ freq[0] was -1 (not 0), so set freq[0] = 3
●​ freq now:
freq = [ 3, -1, -1, 0, -1, 0, -1 ]
Interpretation: value 5 occurs 3 times (positions 0,3,5). We marked 3 and 5 as counted
(freq 0) to avoid recounting.

i = 1 (element arr[1] = 2)
●​ Start: count = 1
●​ Inner j runs 2..6:
○​ j=2: arr[2]=3 → not equal
○​ j=3: arr[3]=5 → not equal
○​ j=4: arr[4]=2 → equal → count = 2; set freq[4] = 0
○​ j=5: arr[5]=5 → not equal
○​ j=6: arr[6]=3 → not equal
●​ After inner loop: count = 2
●​ freq[1] is -1 (not 0), so set freq[1] = 2
●​ freq now:
freq = [ 3, 2, -1, 0, 0, 0, -1 ]
Interpretation: value 2 occurs 2 times (positions 1,4).

i = 2 (element arr[2] = 3)
●​ Start: count = 1
●​ Inner j runs 3..6:
○​ j=3: arr[3]=5 → not equal
○​ j=4: arr[4]=2 → not equal
○​ j=5: arr[5]=5 → not equal
○​ j=6: arr[6]=3 → equal → count = 2; set freq[6] = 0​

●​ After inner loop: count = 2


●​ freq[2] is -1 (not 0), so set freq[2] = 2
●​ freq now:
freq = [ 3, 2, 2, 0, 0, 0, 0 ]
Interpretation: value 3 occurs 2 times (positions 2,6).

i = 3 (element arr[3] = 5)
●​ Before doing inner loop, note freq[3] == 0 (we marked this earlier when i=0)
●​ The if(freq[i] != 0) guard prevents assigning freq[3]; but the algorithm as
written still runs the inner loop for i=3 (some implementations skip if freq[i]==0 —
both are okay, but skipping is slightly more efficient).
●​ If inner loop runs:
○​ j=4..6 comparisons → no new matches (arr[4]=2, arr[5]=5 but freq[5]
already 0, arr[6]=3)
○​ count would be 1 (or more if matching), but since freq[3] == 0, we do
not overwrite it.
●​ freq remains:
freq = [ 3, 2, 2, 0, 0, 0, 0 ]
i = 4 (element arr[4] = 2)
●​ freq[4] == 0 (already counted when i=1), skip assigning.
●​ freq unchanged.​

i = 5 (element arr[5] = 5)
●​ freq[5] == 0 (already counted), skip assigning.​

i = 6 (element arr[6] = 3)
●​ freq[6] == 0 (already counted), skip assigning.​

Final freq[] array


freq = [ 3, 2, 2, 0, 0, 0, 0 ]

Printing step (the program prints only where freq[i] > 1)


●​ For i=0: arr[0] = 5, freq[0] = 3 → prints 5 has 2
duplicate(s) (printed value = freq[0] - 1)
●​ For i=1: arr[1] = 2, freq[1] = 2 → prints 2 has 1
duplicate(s)
●​ For i=2: arr[2] = 3, freq[2] = 2 → prints 3 has 1
duplicate(s)
●​ All other indices have freq 0 or 1 so nothing printed for
them.

Final Output
Duplicate counts:
5 has 2 duplicate(s)
2 has 1 duplicate(s)
3 has 1 duplicate(s)

Notes:
●​ freq[j] = 0 marks duplicate positions so the same value is not reported
multiple times.
●​ The printed number of duplicates is freq[i] - 1 because freq[i] stores
total occurrences.

1D Array Manipulation – Sorting – Bubble Sort


int arr[5] = {5, 3, 4, 1, 2};​
int n = 5;​
for(int i = 0; i < n-1; i++) {​
for(int j = 0; j < n-i-1; j++) {​
if(arr[j] > arr[j+1]) {​
int temp = arr[j];​
arr[j] = arr[j+1];​
arr[j+1] = temp;​
}​
}​
}

Sorting Order: Ascending order sorting. The algorithm compares adjacent elements and
swaps if the left element is greater than the right. After all passes, the array is arranged
from smallest to largest.
Iteration-wise Debugging: - Initial Array: [5, 3, 4, 1, 2]
Pass 1 (i = 0):
j = 0 → arr[0]=5 > arr[1]=3 → swap → [3, 5, 4, 1, 2]
j = 1 → arr[1]=5 > arr[2]=4 → swap → [3, 4, 5, 1, 2]
j = 2 → arr[2]=5 > arr[3]=1 → swap → [3, 4, 1, 2, 5]
j = 3 → arr[3]=5 > arr[4]=2 → swap → [3, 4, 1, 2, 5]
Pass 2 (i = 1):
j = 0 → arr[0]=3 < arr[1]=4 → no swap → [3, 4, 1, 2, 5]
j = 1 → arr[1]=4 > arr[2]=1 → swap → [3, 1, 4, 2, 5]
j = 2 → arr[2]=4 > arr[3]=2 → swap → [3, 1, 2, 4, 5]
Pass 3 (i = 2):
j = 0 → arr[0]=3 > arr[1]=1 → swap → [1, 3, 2, 4, 5]
j = 1 → arr[1]=3 > arr[2]=2 → swap → [1, 2, 3, 4, 5]
Pass 4 (i = 3): j = 0 → arr[0]=1 < arr[1]=2 → no swap → [1, 2, 3, 4, 5]
Sorted Array: [1, 2, 3, 4, 5]
Explanation: Outer loop (i) controls the number of passes. Inner loop (j) compares
adjacent elements. Each iteration of j shows index-based comparisons and swaps.
Largest unsorted element moves to its correct position after each pass, demonstrating
ascending bubble sort mechanics.

Passing Single Array Element to Function


Concept: Pass a single element to a function.
#include <stdio.h>​
void update(int x) {​
x = x + 10;​
}​
int main() {​
int arr[3] = {1, 2, 3};​
update(arr[1]);​
printf("arr[1] = %d", arr[1]);​
return 0;​
}

Explanation: Demonstrates call-by-value. Only a copy of the element is passed. Original


array element remains unchanged.
Passing Entire 1D Array to Function
Concept: Can modify the whole array through a function.
#include <stdio.h>​
void updateArray(int a[], int n) {​
for(int i = 0; i < n; i++) a[i] += 5;​
}​
int main() {​
int arr[3] = {1, 2, 3};​
updateArray(arr, 3);​
for(int i = 0; i < 3; i++) printf("%d ", arr[i]);​
return 0;​
}

Explanation: Arrays are passed by reference. Changes in function reflect in original


array. In the above example each element of the array is incremented by 5. Updated
array values arr[3] = {6, 7, 8}.

1D Array Manipulation – Reversing, Concatenation and Splitting


Reversing: Reverse array elements.
for(int i = 0, j = n-1; i < j; i++, j--) {​
int temp = arr[i];​
arr[i] = arr[j];​
arr[j] = temp;​
}

Idea: Swap first ↔ last, second ↔ second last … until the middle.

Example Array
arr = [10, 20, 30, 40, 50]; n = 5
Indices:
0 1 2 3 4
10 20 30 40 50

Step-by-Step Iterations
Initial:
i = 0; j = 4
Iteration 1: i = 0, j = 4
Swap arr[0] and arr[4]:
temp = 10
arr[0] = arr[4] → 50
arr[4] = temp → 10
Array becomes: [50, 20, 30, 40, 10]
Increment and decrement:

i → 1; j → 3
Iteration 2: i = 1, j = 3
Swap arr[1] and arr[3]:
temp = 20
arr[1] = arr[3] → 40
arr[3] = temp → 20
Array becomes: [50, 40, 30, 20, 10]
Update: i → 2; j → 2
i < j → FALSE
So loop ends.

Final Reversed Array: [50, 40, 30, 20, 10]

Summary of Swaps: Swap 10 ↔ 50, Swap 20 ↔ 40, Middle element (30) stays
unchanged

Concatenation: Combine two arrays.


int result[n1+n2];​
for(int i = 0; i < n1; i++) result[i] = arr1[i];​
for(int i = 0; i < n2; i++) result[n1+i] = arr2[i];

First copy elements of arr1[] to result[]. Then copy elements of arr2[]. Result[] array has
all elements of arr1[] and arr2[] sequentially.

Splitting: Divide array into two parts.


int part1[m], part2[n-m];​
for(int i = 0; i < m; i++) part1[i] = arr[i];​
for(int i = m; i < n; i++) part2[i-m] = arr[i];

First half of arr[] is copied to part1[]. Second half copied to part2[]. Demonstrates how
array can be partitioned.
2-D Arrays – Declaration, Initialization, and Traversal
Concept: 2D arrays are arrays of arrays. Each element is accessed using two indices:
row and column. Useful to represent tables, matrices, or grids.
Declaration:
int arr[2][3]; // 2 rows, 3 columns
int arr[m][n]; // m rows, n columns

Initialization:
int arr[2][3] = {{1, 2, 3}, {4, 5, 6}};

●​ Row-wise initialization.
●​ arr[0][0] = 1, arr[1][2] = 6

Traversal Example Program:


#include <stdio.h>​
int main() {​
int arr[2][3] = {{1, 2, 3}, {4, 5, 6}};​
for(int i = 0; i < 2; i++) {​
for(int j = 0; j < 3; j++) {​
printf("arr[%d][%d] = %d\n", i, j, arr[i][j]);​
}​
}​
return 0;​
}

The above code demonstrates row-major order access. Outer loop iterates over rows.
Inner loop iterates over columns. Prints each element using its row and column indices.​

Step-wise Iteration:​
i = 0 (First Row):
j = 0 → arr[0][0] = 1
j = 1 → arr[0][1] = 2
j = 2 → arr[0][2] = 3
i = 1 (Second Row):
j = 0 → arr[1][0] = 4
j = 1 → arr[1][1] = 5
j = 2 → arr[1][2] = 6

1D Array Manipulation – Reversing, Concatenation and Splitting

#include <stdio.h>
int main()
{
int r, c;
printf("Enter number of rows and columns: ");
scanf("%d%d", &r,&c); // Input number of rows and columns
int A[r][c], B[r][c], Sum[r][c];
printf("\nEnter elements of Matrix A:\n");
for(int i = 0; i < r; i++) {
for(int j = 0; j < c; j++) {
scanf("%d", &A[i][j]); // Input elements of Matrix A
}
}
printf("\nEnter elements of Matrix B:\n");
for(int i = 0; i < r; i++) {
for(int j = 0; j < c; j++) {
scanf("%d", &B[i][j]); // Input elements of Matrix B
}
}
for(int i = 0; i < r; i++) {
for(int j = 0; j < c; j++) {
Sum[i][j] = A[i][j] + B[i][j]; // Add the matrices
}
}
printf("\nResultant Matrix After Addition:\n");
for(int i = 0; i < r; i++) {
for(int j = 0; j < c; j++) {
printf("%d ", Sum[i][j]); // Display the result
}
printf("\n");
}
return 0;
}

Activity – 2D Arrays
Try it Yourself:
1.​ Write a program to add two matrices (same order) and display the result.
2.​ Write a program to calculate and display the sum of each row and each column
of a matrix.
3.​ Write a program to check whether a given square matrix is an identity matrix.
4.​ Write a program to find the largest and smallest elements in a 2D array.
5.​ Write a program to multiply two matrices and print the resulting matrix.
​ Hint: Use three nested loops:
​ Two input matrices: A of size m × n ; and B of size n × p
​ Result: Matrix C of size m × p
for(i = 0; i < m; i++)
for(j = 0; j < p; j++)
for(k = 0; k < n; k++)
C[i][j] += A[i][k] * B[k][j];

Arrays Library Functions:


Function Purpose Syntax Input Output
memcpy Copy memory block memcpy(dest, Source array, Copies n bytes
from source to src, n) destination from src to dest
destination array, size in
bytes
memmove Move memory safely memmove(dest Source array, Moves n bytes;
(handles , src, n) destination original memory
overlapping array, size correctly adjusted
memory) if overlapping
memset Initialize memory memset(ptr, Pointer, value, Sets n bytes of
with a value val, n) size memory to val
memcmp Compare two memcmp(ptr1, Two pointers, Returns 0 if equal,
memory blocks ptr2, n) size negative if ptr1 <
ptr2, positive if
ptr1 > ptr2
sizeof Get the size of array sizeof(varia Variable or Returns size in
or variable in bytes ble) array bytes
atoi Convert string to atoi(str) String Integer value
integer representing
number
atof Convert string to atof(str) String Float value
float representing
floating point
number
abs Get absolute value abs(n) Integer Absolute value
of integer
qsort Sort array qsort(base, Array pointer, Sorts array
num, size, number of according to
compar) elements, size comparison
of element, function
comparison
function
bsearch Binary search in bsearch(key, Key to search, Returns pointer to
sorted array base, num, array pointer, found element or
size, number of NULL
compar)
elements, size,
comparison
function

Part – 2: Strings
Strings as Array of Characters
Concept: Strings are sequences of characters stored in contiguous memory ending with
\0 -null character.

#include <stdio.h>​
int main() {​
char str[6] = "Geeks";​
for(int i = 0; i < 6;
i++) {​
printf("str[%d] =
%c\n", i, str[i]);​
}​
return 0;​
}

●​ The array is declared as char str[6] because the string “Geeks” has 5
characters and one extra space for the null character \0 that marks the end of
the string.
●​ Each character, including \0, occupies a unique array index.
●​ Looping through 0 to 5 prints all characters including the null terminator. This
ensures correct string handling in C.
Iteration-wise Debugging:
i = 0 → str[0] = ‘G’
i = 1 → str[1] = ‘e’
i = 2 → str[2] = ‘e’
i = 3 → str[3] = ‘k’
i = 4 → str[4] = ‘s’
i = 5 → str[5] = ‘\0’ → marks end of string

Strings Using Pointers


Concept: Strings can be accessed using pointers with pointer arithmetic.
#include <stdio.h>​
int main() {​
char *ptr = "Hello";​
int i = 0;​
while(*(ptr + i) != '\0') {​
printf("ptr[%d] = %c\n", i, *(ptr + i));​
i++;​
}​
return 0;​
}

●​ ptr points to the first character of the string.


●​ Pointer arithmetic *(ptr + i) accesses the i-th character of the string
●​ The loop continues until the null character \0 is encountered.
Iteration-wise Debugging:
i = 0 → (ptr+0) = ‘H’
i = 1 → (ptr+1) = ‘e’
i = 2 → (ptr+2) = ‘l’
i = 3 → (ptr+3) = ‘l’
i = 4 → (ptr+4) = ‘o’
i = 5 → (ptr+5) = ‘\0’ → loop ends
Demonstrates how the pointer moves through the string in memory using indices.

String Operations – Manual Implementation


Length of String:
int len = 0;​
while(str[len] != '\0') len++;

Iterations:
len=0 → str[0]=‘H’ → len++
len=1 → str[1]=‘e’ → len++
len=2 → str[2]=‘l’ → len++
len=3 → str[3]=‘l’ → len++
len=4 → str[4]=‘o’ → len++
len=5 → str[5]=‘\0’ → loop ends, string length = 5

Copy String:
for(int i = 0; str2[i] != '\0'; i++) str1[i] = str2[i];​
str1[i] = '\0';

Iterations:
i=0 → str1[0]=str2[0]=‘H’
i=1 → str1[1]=str2[1]=‘e’
i=2 → str1[2]=str2[2]=‘l’
i=3 → str1[3]=str2[3]=‘l’
i=4 → str1[4]=str2[4]=‘o’
i=5 → str1[5]=‘\0’
Concatenate Strings:
int i=0, j=0;​
while(str1[i]!='\0') i++;​
while(str2[j]!='\0') str1[i++] = str2[j++];​
str1[i]='\0';

Iterations:
i=0-4 → skip existing str1 characters
i=5, j=0 → str1[5]=str2[0]=‘H’ // Copies character in str2[j] to str1[i]
i=6, j=1 → str1[6]=str2[1]=‘e’ //ie. value of str2[0] is copied to str1[5]
i=7, j=2 → str1[7]=str2[2]=‘l’ //and so on till it encounters null value
i=8, j=3 → str1[8]=str2[3]=‘l’
i=9, j=4 → str1[9]=str2[4]=‘o’
i=10 → str1[10]=‘\0’ → concatenation complete
Compare Strings:
while (str1[i] != '\0' && str2[i] != '\0')
{
if (str1[i] != str2[i]) {
flag = 1; // strings are not equal
break;
}
i++;
}

Iterations:
i=0 → str1[0]=‘H’, str2[0]=‘H’ → equal
i=1 → str1[1]=‘e’, str2[1]=‘e’ → equal
i=2 → str1[2]=‘l’, str2[2]=‘l’ → equal
i=3 → str1[3]=‘l’, str2[3]=‘l’ → equal
i=4 → str1[4]=‘o’, str2[4]=‘o’ → equal
i=5 → str1[5]=‘\0’, str2[5]=‘\0’ → strings equal, flag=0
//If any character differs → set flag = 1 and break.

Methods to Scan (Read) Strings in C


There are 4 commonly used methods:
1. scanf() with %s
✔️ Characteristics
●​ Reads a single word only .
●​ Stops reading when it finds a space, tab, or newline.
●​ Can cause buffer overflow if input is longer than array size.​

✔️ Example
char name[20];
printf("Enter your name: ");
scanf("%s", name); // only reads first word
printf("You entered: %s", name);

Input:
Hello World

Stored:
Hello
2. scanf() using scanset (%[^\n])
✔️ Characteristics
●​ Readsentire line including spaces .​

●​ Used when you want to read sentences.​

✔️ Example
char str[50];
scanf("%[^\n]", str);
printf("You entered: %s", str);

Input:
Operating Systems Concepts

Stored:
Operating Systems Concepts

3. gets() ❌
✔️ Characteristics
(Not recommended — unsafe)
●​ Reads a full line including spaces.
●​ Does not check array size → may write beyond the buffer.
●​ Removed from the C11 standard (dangerous).​

✔️ Example
char str[50];
gets(str); // unsafe!
printf("%s", str);

Use only if teacher expects, otherwise avoid.

4. fgets() ✔️
✔️ Characteristics
(Best and safest)
●​ Reads at most (size – 1) characters.
●​ Prevents buffer overflow.
●​ Stores newline character \n also (if space available).
●​ Most recommended for safe string input.​

✔️ Example
char str[50];
fgets(str, sizeof(str), stdin);
printf("%s", str);
Methods to Print Strings in C
There are 2 main methods:
1. printf() with %s
✔️ Characteristics
●​ Most common method.​

●​ Prints a string exactly as stored.​

✔️ Example
printf("%s", str);

2. puts()
✔️ Characteristics
●​ Prints the string followed by a newline automatically.​

●​ Simple and clean.​

✔️ Example
puts(str);

Input stored:
Hello

Output:
Hello
(with newline)

Summary (Easy to Memorize)


To read strings
●​ scanf("%s", str); → single word
●​ scanf("%[^\n]", str); → full line
●​ gets(str); → full line, unsafe
●​ fgets(str, size, stdin); → full line, safe​

To print strings
●​ printf("%s", str);
●​ puts(str);
String Library Functions
Function Purpose Syntax Input Output
strlen Get string strlen(str) String Length of string
length
strcpy Copy string strcpy(dest, src) Source, Copies string
destination
strncpy Copy n chars strncpy(dest, src, Source, Copies n
n) destination, n characters
strcat Concatenate strcat(dest, src) Source, Appends src to
destination dest
strncat Concatenate n strncat(dest, src, Source, Appends n
chars n) destination, n characters
strcmp Compare strcmp(str1, str2) Two strings 0 if equal, >0/<0
strings otherwise
strncmp Compare n strncmp(str1, Two strings, n 0 if equal, else
chars str2, n) difference
strchr Find character strchr(str, ch) String, character Pointer to first
occurrence
strstr Find substring strstr(str, String, substring Pointer to first
substr) occurrence

You might also like