What is an Array?
narrayis acollection of similar data itemsstored incontinuous (side-by-side) memory
A
locations.
What is Declaration of Array?
Declaration of array meanstelling the compiler:
● what type of data the array will store
● how many values it can hold
● what name you want to give the array
• Syntax: type arrayName [ arraySize ];
• Example:
int group[10];
float height[50];
char name[15];
How to Access Elements of an Array
hen you create an array, it stores many values.
W
Toaccess(get or use) any value from the array, we use anindex.
What is an Index?
Index meansposition numberof each element in thearray.
👉Important:
● Indexalways starts from 0
● Last index =size – 1
Example:
int marks[4] = {50, 60, 70, 80};
Indexes are:
● marks[0] → 50
● marks[1] → 60
● marks[2] → 70
● marks[3] → 80
Syntax to Access an Element
arrayName[index]
Examples:
marks[0];
// gives 50
marks[2];
// gives 70
Summary (Very Simple)
●
Arrays store many values
●
Each value has an
index
●
Index starts from
0
●
Use arrayName[index] to access any element
What does Initialization mean?
Initialization of an array means storing values in the array when it is declared.
Example (Very Simple)
int marks[4] = {50, 60, 70, 80};
Empty Initialization (All zero)
If you give only one zero:
int a[5] = {0};
What does static initialization mean?
tatic array initialization means giving values to the array at the time of declaration,
S
before the program starts running.
Initialization Without Size
You can skip size also:
int num[] = {2, 4, 6, 8};
Then size becomes4automatically.
What does dynamic initialization mean?
ynamic array initialization means giving values to an array while the program is
D
running.
● Values arenot fixed in advance
● You canask the userto enter the values
● Size can bedecided at runtime(in some languages)
Input Data into Array
Inputting data into an arraymeanstaking values fromthe user and storing them into the
array.
● Instead of giving values in the code (like static initialization), weask the userat runtime.
● Useful whenwe don’t know the values in advance.
Reading Data from an Array
eading data from an array means accessing the values stored in the array to use or
R
display them.
● You don’t change the value, just look at it or print it.
● Use the index of the element to read it.
untime Array initialization /Dynamic initialization of
R
array
untime (dynamic) array initializationmeansgivingvalues to an array while the program
R
is running, instead of giving them at the time ofdeclaration.
● Values arenot known in advance
● User or program decides the valuesat runtime
● Size can sometimes be decided during execution
Advantages of Arrays
1. Easy to store multiple values
○ One variable can hold many values of the same type.
int marks[5];stores 5 marks in one array.
○ Example:
2. Easy to access elements
○ Use theindexto quickly access any element.
marks[2]gives the 3rd element.
○ Example:
3. Efficient memory use
○ A
ll elements are stored incontinuous memory locations,so it’s faster to
access.
4. Easy to use with loops
○ Can process all elements using afor or while loop.
5. Helps organize data
○ Keeps related data together instead of using multiple separate variables.
Disadvantages of Arrays
1. Fixed size (in static arrays)
○ O
nce declared, the sizecannot be changed(unlessusing dynamic arrays in
some languages).
2. Same type only
○ Can store only one data type (all int, all float, etc.).
3. Wasted memory
○ If size is declared too big, extra memory is wasted.
4. No built-in bounds checking (in C/C++)
○ Accessing invalid index may causeerrors or garbagevalues.
5. Insertion and Deletion are costly
○ Adding or removing elements in the middle requiresshifting many elements.
Types of Arrays
rrays can storemultiple valuesin an organized way.
A
They are classified based onnumber of dimensions(rows, columns, etc.)
One-Dimensional Array (1D / Single Array)
● Storesa single row of elements
● Looks like alist or row of boxes
● Accessed usingone index
Syntax:
int marks[5] = {50, 60, 70, 80, 90};
Memory View (1D):
Index: 0
1 2 3 4
Value:50
60 70 80 90
Two-Dimensional Array (2D Array)
● Storesdata in rows and columns
● Looks like atable or matrix
[row][column]
● Accessed usingtwo indices:
Declaration Syntax in C
dataType arrayName[rows][columns];
Where:
●
dataType→ type of data (int, float, char, etc.)
●
arrayName→ name of the array
●
rows→ number of rows
●
columns→ number of columns
Syntax:
int matrix[2][3] = {
{1, 2, 3},
{4, 5, 6}
};
Memory View (2D):
Row\Col
0 1 2
0
1 2 3
1
4 5 6
●
matrix[0][2]→ 3
●
matrix[1][0]→ 4
Multidimensional Array (3D or more)
● Stores data in3 or more dimensions
● Think of it asa cube or multiple tables stacked
[i][j][k]
● Accessed usingmultiple indices:
Example (3D Array):
●
int box[2][2][3] = {
● {
● {1,2,3},
● {4,5,6}
● },
● {
● {7,8,9},
● {10,11,12}
● }
●
};
●
box[0][1][2]→ 6
●
box[1][0][1]→ 8
Initializing Two – Dimensional Arrays
Definition
Initializing a two-dimensional array means assigning values to its elements at the time of
declaration.
● You give values torows and columnsin atabular form.
● Can initializeall elementsorsome elements(rest default to 0 in C).
Methods of Initializing 2D Arrays
1️⃣ Row-wise Initialization (Most Common Method)
{ }
● Values are givenrow by rowinside
● Each row is enclosed in{ }
Syntax:
dataType arrayName[rows][columns] = {
{row1 values},
{row2 values},
...
};
Example:
int matrix[2][3] = {
{1, 2, 3},
{4, 5, 6}
};
●
matrix[0][0]→ 1
●
matrix[1][2]→ 6
Single Braces Initialization (Flattened Method)
● All elements can also be listed inone pair of braces
● Values are storedrow by row automatically
Example:
int matrix[2][3] = {1, 2, 3, 4, 5, 6};
● Same as row-wise initialization
3️⃣ Partial Initialization
● Initializesome elements, rest willdefault to 0
Example:
int matrix[2][3] = {
{1, 2},
// 3rd element in first row = 0
{4}
// 2nd and 3rd elements in second row = 0
};
Memory Layout:
matrix[0][0] = 1
matrix[0][1] = 2 matrix[0][2] = 0
matrix[1][0] = 4
matrix[1][1] = 0 matrix[1][2] = 0
Sorting operation using array
Simple Definition
Sorting an array is the process of rearranging its elements in a desired order.
● Ascending order:smallest → largest
● Descending order:largest → smallest
#include <stdio.h>
int main() {
int arr[5] = {50, 20, 40, 10, 30};
int temp;
// sorting using simple method (bubble sort)
for(int i = 0; i < 5-1; i++) {
for(int j = i+1; j < 5; j++) {
if(arr[i] > arr[j]) { // swap if arr[i] > arr[j]
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}
// print sorted array
printf("Sorted Array: ");
for(int i = 0; i < 5; i++) {
printf("%d ", arr[i]);
}
return 0;
}
OUTPUT:
Sorted Array: 10 20 30 40 50
Matrix operation using array
What is a Matrix?
Amatrixis arectangular arrangement of numbersinrows and columns.
● Stored in2D arraysin C.
● Example of 2×3 matrix:
1
2 3
4
5 6
Matrix Operations Using Arrays
We can perform many operations on matrices using2Darrays, like:
1. Addition of matrices
2. Subtraction of matrices
3. Multiplication of matrices
Matrix Addition
● Addcorresponding elementsof two matrices.
● Only possible ifboth matrices have the same size.
Example (2×2):
include <stdio.h>
#
int main() {
int A[2][2] = {{1,2},{3,4}};
int B[2][2] = {{5,6},{7,8}};
int C[2][2];
// Addition
for(int i=0;i<2;i++){
for(int j=0;j<2;j++){
C[i][j] = A[i][j] + B[i][j];
}
}
// Print result
printf("Sum of matrices:\n");
for(int i=0;i<2;i++){
for(int j=0;j<2;j++){
printf("%d ", C[i][j]);
}
printf("\n");
}
return 0;
}
Output:
6 8
10 12
Matrix Subtraction
● Subtractcorresponding elements.
C[i][j] = A[i][j] - B[i][j];
Matrix Multiplication
● Multiplyrow of first matrixwithcolumn of secondmatrix
● Only possible ifcolumns of first = rows of second
Formula:
C[i][j] = sum of (A[i][k] * B[k][j]) for k=0 to n-1
Part-2: String
What is a String?
Astringis asequence of charactersstored together.
● Think of it as aword, sentence, or any text.
'\0'
● In C, strings are stored asarrays of charactersendingwith a special character
(null character) to mark the end.
Simple Definition
A string is a collection of characters treated as a single data item.
Examples of Strings
char name[10] = "Anuj";
// stores characters 'A','n','u','j','\0'
char city[] = "Delhi";
// size automatically set to 6 (5 letters +
'\0')
Common String Operations
scanf("%s", str);
1. Read a string:
printf("%s", str);
2. Print a string:
strlen(str);
3. Find length:
strcpy(dest, src);
4. Copy string:
strcat(str1, str2);
5. Concatenate strings:
6.
Convert to Uppercase:
for(int i=0; str[i]!='\0'; i++)
str[i]=toupper(str[i]);
7.
Convert to Lowercase:
for(int i=0; str[i]!='\0'; i++)
str[i]=tolower(str[i]);
Declaration of String in C
1️⃣ Using char array
char str[10];
// declares a string that can hold up to 9
characters + '\0'
2️⃣ Declaration with Initialization
char name[] = "Anuj";
// size
automatically 5 (4 letters + '\0')
●Here,size is optional
●Compiler countsletters + 1 for '\0
1️⃣ Reading a String
●Reading meanstaking input from the userand
storing it in a string variable.
Methods to Read a String
scanf()
a) Using
char str[20];
scanf("%s", str);
// reads a single
word (stops at space)
●Limitation: stops reading atspace,tab, orenter
gets()(older method, not safe, avoid in
) Using
b
modern C)
char str[50];
gets(str);
// reads a line
including spaces
fgets()(safe and recommended)
c) Using
char str[50];
fgets(str, 50, stdin);
// reads a
line including spaces
⭐ 2️⃣ Writing (Printing) a String
●Writing meansdisplaying the string on the
screen
Example:
char str[] = "Hello";
printf("%s", str);
// prints Hello
%s→ used to print a string
●
⭐ Key Points
1.Strings are stored incharacter arrays
2.Usescanffor single word input
3.Usefgetsfor full line input (includes spaces)
4.Useprintf("%s", str)to display the string
strstr()
What is ?
strstr()function is used tofind a
●The
substringinside a string.
●Itreturns the address of the first occurrence
of the substring in the main string.
●If the substring isnot found, it returnsNULL.
⭐ Simple Definition
strstr(mainString, subString)searches
subStringinside
f or mainStringand returns
the pointer to the first match.
⭐ Syntax
#include <string.h>
char *strstr(const char *str1, const
char *str2);
str1→ main string
●
str2→ substring to search for
●
●Return value:pointer to first occurrence of
str2in
str1or
NULLif not found
⭐ Example
#include <stdio.h>
#include <string.h>
int main() {
char str1[] = "Hello World";
char str2[] = "World";
char *ptr = strstr(str1, str2);
// search for "World" in "Hello
World"
if(ptr != NULL) {
printf("Substring found:
%s\n", ptr); // prints "World"
} else {
printf("Substring not
found\n");
}
return 0;
}
Output:
Substring found: World