0% found this document useful (0 votes)
2 views22 pages

Array and String Notes by Me

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)
2 views22 pages

Array and String Notes by Me

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

​What is an Array?


​ n​​array​​is a​​collection of similar data items​​stored in​​continuous (side-by-side) memory​
A
​locations​​.​

​What is Declaration of Array?​


​Declaration of array means​​telling 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
​To​​access​​(get or use) any value from the array, we use an​​index​​.​

​What is an Index?​
​Index means​​position number​​of each element in the​​array.​

​👉​​Important:​

​●​ ​Index​​always 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 becomes​​4​​automatically.​

​What does dynamic initialization mean?​


​ ynamic array initialization means giving values to an array while the program is​
D
​running.​

​●​ ​Values are​​not fixed in advance​

​●​ ​You can​​ask the user​​to enter the values​

​●​ ​Size can be​​decided at runtime​​(in some languages)​

​Input Data into Array​


I​nputting data into an array​​means​​taking values from​​the user and storing them into the​
​array​​.​
​●​ ​Instead of giving values in the code (like static initialization), we​​ask the user​​at runtime.​

​●​ ​Useful when​​we 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 initialization​​means​​giving​​values to an array while the program​
R
​is running​​, instead of giving them at the time of​​declaration.​

​●​ ​Values are​​not known in advance​

​●​ ​User or program decides the values​​at 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 the​​index​​to quickly access any element.​


marks[2]​​gives the 3rd element.​
​○​ ​Example:​​

​3.​ ​Efficient memory use​

​○​ A
​ ll elements are stored in​​continuous memory locations​​,​​so it’s faster to​
​access.​

​4.​ ​Easy to use with loops​

​○​ ​Can process all elements using a​​for 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 size​​cannot be changed​​(unless​​using 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 cause​​errors or garbage​​values​​.​

​5.​ ​Insertion and Deletion are costly​

​○​ ​Adding or removing elements in the middle requires​​shifting many elements​​.​

​Types of Arrays​
​ rrays can store​​multiple values​​in an organized way.​
A
​They are classified based on​​number of dimensions​​(rows, columns, etc.)​

​One-Dimensional Array (1D / Single Array)​


​●​ ​Stores​​a single row of elements​

​●​ ​Looks like a​​list or row of boxes​

​●​ ​Accessed using​​one 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)​


​●​ ​Stores​​data in rows and columns​

​●​ ​Looks like a​​table or matrix​

[row][column]​
​●​ ​Accessed using​​two 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 in​​3 or more dimensions​

​●​ ​Think of it as​​a cube or multiple tables stacked​

[i][j][k]​
​●​ ​Accessed using​​multiple 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​
I​nitializing a two-dimensional array means assigning values to its elements at the time of​
​declaration.​

​●​ ​You give values to​​rows and columns​​in a​​tabular form​​.​

​●​ ​Can initialize​​all elements​​or​​some elements​​(rest default to 0 in C).​

​Methods of Initializing 2D Arrays​


​1️⃣ Row-wise Initialization (Most Common Method)​
{ }​
​●​ ​Values are given​​row by row​​inside​​

​●​ ​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 in​​one pair of braces​

​●​ ​Values are stored​​row by row automatically​

​Example:​

int matrix[2][3] = {1, 2, 3, 4, 5, 6};​


​●​ ​Same as row-wise initialization​

​3️⃣ Partial Initialization​


​●​ ​Initialize​​some elements​​, rest will​​default 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?​
​A​​matrix​​is a​​rectangular arrangement of numbers​​in​​rows and columns​​.​

​●​ ​Stored in​​2D arrays​​in C.​

​●​ ​Example of 2×3 matrix:​

1
​ 2 3​
4
​ 5 6​

​Matrix Operations Using Arrays​


​We can perform many operations on matrices using​​2D​​arrays​​, like:​

​1.​ ​Addition of matrices​

​2.​ ​Subtraction of matrices​

​3.​ ​Multiplication of matrices​

​Matrix Addition​
​●​ ​Add​​corresponding elements​​of two matrices.​

​●​ ​Only possible if​​both 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​
​●​ ​Subtract​​corresponding elements​​.​

C[i][j] = A[i][j] - B[i][j];​


​Matrix Multiplication​
​●​ ​Multiply​​row of first matrix​​with​​column of second​​matrix​

​●​ ​Only possible if​​columns 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?​
​A​​string​​is a​​sequence of characters​​stored together.​

​●​ ​Think of it as a​​word, sentence, or any text​​.​

'\0'​
​●​ I​n C, strings are stored as​​arrays of characters​​ending​​with 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 counts​​letters + 1 for '\0​

​1️⃣ Reading a String​


​●​​Reading means​​taking input from the user​​and​
​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 at​​space​​,​​tab​​, or​​enter​

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 means​​displaying 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 in​​character arrays​

​2.​​Use​​scanf​​for single word input​

​3.​​Use​​fgets​​for full line input (includes spaces)​

​4.​​Use​​printf("%s", str)​​to display the string​


strstr()​
​What is​​ ​?​
strstr()​​function is used to​​find a​
​●​​The​​
​substring​​inside a string.​

​●​​It​​returns the address of the first occurrence​


​of the substring in the main string.​

​●​​If the substring is​​not found​​, it returns​​NULL​​.​

​⭐ Simple Definition​
strstr(mainString, subString)​​searches​

subString​​inside​​
f​ or​​ mainString​​and 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​


str2​​in​​
​ str1​​or​​
NULL​​if 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​


You might also like