Array and String PDF
Array and String PDF
UNDERSTANDING
ARRAYS AND STRINGS IN C PROGRAMMING LANGUAGE
• Imagine an Arrays as a large chunk of memory divided into smaller block of memory and each block
is capable of storing a data value of some type.
Syntax:
Data_type Array_name[number_of_Elements];
C provides:
1D (One-dimensional) Arrays – Like a simple list of values.
2D (Two-dimensional) Arrays – Like a matrix or a table.
Multi-dimensional Arrays – Arrays of arrays (3D, 4D, etc.).
Example: Without Arrays:
Imagine you want to store 5 numbers. Without an array, you need to create separate variables like this:
✅ Code Example:
#include <stdio.h>
int main ()
{
int num1 = 10, num2 = 20, num3 = 30, num4 = 40, num5 = 50;
printf ("Numbers: %d, %d, %d, %d, %d\n", num1, num2, num3, num4, num5);
return 0;
}
This approach is not efficient if you have many numbers.
✅ Code Example:
#include <stdio.h>
int main ()
{
int numbers [5] = {10, 20, 30, 40, 50}; // Declaring and initializing an array
for (int i = 0; i < 5; i++)
{
printf ("Number at index %d: %d\n", i, numbers[i]); // Accessing elements
}
return 0;
}
1. Fixed-Length Arrays
• A Fixed-Length Array has a size that is known at compile-time and cannot be changed during
program execution.
Key Features:
Size is fixed at compile time (e.g., int arr[5];)
Stored in stack memory
Fast execution (memory is allocated once)
Cannot be resized dynamically
✅ Code Example:
#include <stdio.h>
int main ()
{
int arr[5] = {10, 20, 30, 40, 50}; // Fixed size array
// Printing elements
for (int i = 0; i < 5; i++)
{
printf ("%d ", arr[i]);
}
return 0;
}
Memory Representation:
Index 0 1 2 3 4
Value 10 20 30 40 50
How to Initialize:
1. Default Initialization (Uninitialized)
If an array is declared without an initializer, its values are garbage (random memory values) in local scope.
However, global and static arrays are initialized to zero by default.
Example:
#include <stdio.h>
int main ()
{
int arr[5]; // Not initialized, contains garbage values
for (int i = 0; i < 5; i++)
{
printf("%d ", arr[i]); // Output: Garbage values
}
return 0;
}
2. Explicit Initialization
• We can explicitly initialize the array elements.
• int arr[5] = {1, 2, 3, 4, 5}; // Initializing with specific values
Example:
#include <stdio.h>
int main()
{
int arr[5] = {1, 2, 3, 4, 5}; // Explicit initialization
for (int i = 0; i < 5; i++)
{
printf("%d ", arr[i]); // Output: 1 2 3 4 5
}
return 0;
}
Output:
Array after insertion: 10 20 25 30 40 50
3. Deletion (Removing an Element from an Array)
Deletion removes an element and shifts the remaining elements leftward.
Example: Deleting an Element at a Specific Index
#include <stdio.h>
int main()
{
int arr[5] = {10, 20, 30, 40, 50};
int pos = 2; // Delete the element at index 2 (30)
for (int i = pos; i < 4; i++) // Shifting elements left
{
arr[i] = arr[i + 1];
}
printf("Array after deletion: "); // Printing the updated array (one less element)
for (int i = 0; i < 4; i++)
{
// Size reduced by 1
printf("%d ", arr[i]);
}
return 0;
}
Output:
Array after deletion: 10 20 40 50
Operation Description
C1 C2 C3
R1 1 2 3
C1 C2 C3
R2 4 5 6
Here,
• Row 1: {1, 2, 3}
• Row 2: {4, 5, 6}
Initializing a 2D Array in C
Method 1: Row-by-Row Initialization
int matrix[2][3] =
{
{1, 2, 3},
{4, 5, 6}
};
Method 2: Single-Line Initialization
int matrix[2][3] = {1, 2, 3, 4, 5, 6};
(Elements are automatically placed row-wise.)
Initializing a 3D Array in C
int cube[2][2][3] =
{
{ {1, 2, 3}, {4, 5, 6} },
{ {7, 8, 9}, {10, 11, 12} }
};
Each {} represents a row in a layer.
Layer 1:
789
10 11 12
Summary
Final Takeaways
2D Arrays → Like a table (Rows × Columns)
3D Arrays → Like a stack of tables (Layers × Rows × Columns)
Access elements using [index] notation
Nested loops help print multi-dimensional arrays
Understanding Strings in C
Basics of String literals:
Definition: String literal (or String Constant) is a sequence of characters enclosed with double quotes.
For Example:
“Hello everyone”
%s is a placeholder:
int main()
{
Printf(“%s”,”Earth”); // double quotes are important to mention
}
Storing string literals:
String literals are stored as array of characters.
E a r t h \0
1000
Null Character
Indicates the end of the string
Total 6 bytes of read only memory is allocated to the string literal.
• ‘\0’ Character must not be confused with ‘0’ character. Both have different ASCII codes. ‘\0’ has the
code 0 while ‘0’ has the code 48.
• In C, Compiler treats a string literal as a Pointer to the first character.
E a r t h \0
1000
• So to the printf or scanf, we are passing pointer to the first character of a string literal.
• Both printf and scanf functions expects a character pointer (char *) as an argument.
• Passing “ Earth ” is equivalent to passing the pointer to letter ‘E’.
• Writing string literal is equivalent to writing the pointer to the first character of the string literal.
• Ptr contains the address of the first character of the string literal
“Hello”[1] is equivalent to pointer to ‘H’[1]
H e l l o \0
1000 1001 1002 1003 1004 1005
Pointer to ‘H’[1] = *(pointer to ‘H’ + 1)
Pointer to ‘H’[1] = *(1000 + 1) = *(1001) = ‘e’
Point to be Noted: string literal cannot be modified. It causes undefined behaviour.
char *ptr = “Hello”;
*ptr = ‘M’; Not Allowed
* String literals are also known as string constants. They have been allocated a read only memory. So we
cannot alter them.
* But character pointer itself has been allocated read write memory. So, the same pointer can pointer to
some other string literal.
String literal VS Character constant:
String literal and character constants are not same.
“H” not equal to ‘H’
Note: Always make the array one character longer than the string. If length of the string is 5 characters
long then don’t forget to make extra room for NULL character. Failing to do the same may cause
unpredictable results when program is executed as some C libraries assume the strings are Null terminated.
Initializing a string variable:
Example: char s[6] = “Hello”;
s
H e l l o \0
Although, it seems like “Hello” in the above example is a string literal but it is not. When a String is assigned
to a character array, then this character array is treated like other of arrays. We can modify its characters.
It seems like:
Char s[6] = “Hello”;
Char s[6] = { ‘H’, ‘e’, ‘l’, ‘l’, ‘o’, ’\0’}; * They both are equal
Recall: We cannot modify a string literal, but we can modify a char array.
1. Printing a String
We use printf to display strings.
#include <stdio.h>
int main()
{
char name[] = "Vamsi";
printf("My name is %s", name);
return 0;
}
Output:
My name is Vamsi
#include <stdio.h>
int main() {
char name[20]; // Max 20 characters
printf("Enter your name: ");
scanf("%s", name);
printf("Hello, %s!", name);
return 0;
}
Problem: scanf stops at a space (e.g., "Vamsi Krishna" → only "Vamsi" is stored).
Solution: Use gets() or fgets()
#include <stdio.h>
int main() {
char name[50];
printf("Enter your full name: ");
fgets(name, 50, stdin); // Reads the full line
printf("Hello, %s!", name);
return 0;
}
Output:
Length of word: 8
#include <stdio.h>
#include <string.h>
int main()
{
char str1[] = "Hello";
char str2[20];
strcpy(str2, str1); // Copy str1 into str2
printf("Copied string: %s", str2);
return 0;
}
Output:
Copied string: Hello
#include <stdio.h>
#include <string.h>
int main()
{
char first[20] = "Hello";
char second[] = " World";
strcat(first, second); // Appends second to first
printf("After concatenation: %s", first);
return 0;
}
Output:
After concatenation: Hello World
#include <stdio.h>
#include <string.h>
int main()
{
char str1[] = "Vamsi";
char str2[] = "Krishna";
if (strcmp(str1, str2) == 0)
{
printf("Strings are equal");
} else
{
printf("Strings are different");
}
return 0;
}
Output:
Strings are different
Each row (3 rows) stores a separate string of max 19 characters (+1 for \0)
Fixed size (cannot store more characters dynamically)
Method 2: Using an Array of Character Pointers (char *)
#include <stdio.h>
// Function to print an array of string pointers
void printStrings(char *arr[], int size)
{
for (int i = 0; i < size; i++) {
printf("%s\n", arr[i]);
}
}
int main()
{
char *names[] = {"Vamsi", "Krishna", "Vaka"};
printStrings(names, 3); // Pass array of pointers
return 0;
}
Output:
Vamsi
Krishna
Vaka
#include <stdio.h>
int main()
{
char name[20];
printf("Enter your name: ");
gets(name); // Reads input (NO SIZE LIMIT)
printf("Hello, %s", name);
return 0;
}
If user enters more than 20 characters, it overwrites memory, causing a crash.
Solution: Use fgets()
Example:
#include <stdio.h>
int main()
{
char name[20];
printf("Enter your name: ");
fgets(name, 20, stdin); // Reads at most 19 chars + `\0`
printf("Hello, %s", name);
return 0;
}
Advantage: Prevents buffer overflow
Note: It stores \n (newline) at the end of input, so you may need to remove it manually.
Removing \n from fgets() input:
Creating a Custom Input and Output Functions Using getchar() and putchar():
1 What is getchar() in C?
getchar() is a standard library function in stdio.h that reads a single character from the user.
It waits for user input and returns the ASCII value of the entered character.
Example: Using getchar()
#include <stdio.h>
int main()
{
char ch;
printf("Enter a character: ");
ch = getchar(); // Read a single character
printf("You entered: %c\n", ch);
return 0;
}
Input: A
Output:
Enter a character: A
You entered: A
Note: getchar() only reads one character at a time.
2️ What is putchar() in C?
putchar() is used to print a single character to the output screen.
It takes a character or a variable as input.
Example: Using putchar()
#include <stdio.h>
int main()
{
char ch = 'B';
putchar(ch); // Prints 'B'
putchar('\n'); // New line
return 0;
}
Output:
B
Note: putchar() is useful when printing characters one by one.
#include <stdio.h>
// Custom input function
int custom_input (char str[], int max_length)
{
int i = 0;
char ch;
while ((ch = getchar()) != '\n' && i < max_length - 1)
{
// Read until Enter is pressed
str[i++] = ch;
}
str[i] = '\0'; // Null-terminate the string
return i;
}
int main()
{
char name[50];
printf("Enter your name: ");
custom_input(name, 50); // Call custom input function
printf("Hello, ");
puts(name); // Print using puts()
return 0;
}
Input: Vamsi Krishna
Output:
Enter your name: Vamsi Krishna
Hello, Vamsi Krishna
How it works?
• Reads characters one by one using getchar()
• Stops when Enter (\n) is pressed
• Stores characters in the array
• Adds \0 at the end to make it a valid string
#include <stdio.h>
// Custom output function
int custom_output(char str[])
{
int i = 0;
while (str[i] != '\0') { // Print until null character
putchar(str[i]);
i++;
}
putchar('\n'); // New line
return i;
}
int main()
{
char message[] = "Hello, Vamsi!";
custom_output(message); // Call custom output function
return 0;
}
Output:
Hello, Vamsi!
How it works?
• Loops through the string
• Prints characters one by one using putchar()
• Stops when \0 is reached
• Prints a new line (\n) at the end