0% found this document useful (0 votes)
2 views

Array and String PDF

This document provides a comprehensive overview of arrays and strings in the C programming language, detailing their definitions, types, and operations. It covers one-dimensional and two-dimensional arrays, including fixed-length and variable-length arrays, along with examples of initialization, traversal, insertion, deletion, searching, updating, sorting, and merging. The document serves as a guide for understanding how to effectively utilize arrays in C programming.

Uploaded by

Sachin C V Sachi
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Array and String PDF

This document provides a comprehensive overview of arrays and strings in the C programming language, detailing their definitions, types, and operations. It covers one-dimensional and two-dimensional arrays, including fixed-length and variable-length arrays, along with examples of initialization, traversal, insertion, deletion, searching, updating, sorting, and merging. The document serves as a guide for understanding how to effectively utilize arrays in C programming.

Uploaded by

Sachin C V Sachi
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 24

FEBRUARY 10, 2025

UNDERSTANDING
ARRAYS AND STRINGS IN C PROGRAMMING LANGUAGE

VAMSI KRISHNA VAKA


What is an Array?
• An array is a collection of variables of the same data type stored in continuous memory locations.
Instead of creating separate variables, an array helps to store multiple values using a single name.
• An array is a Data structure containing a number of data values (all of which are same type)
What is Data Structure?
• Data structure is a format for organizing and storing data. Also, each data structure is designed to
organize data to suit a specific purpose.
For example: Array is a data structure which you can visualize as follows:
5 6 34 24 67 12 56 88 4 32
Index - 0 1 2 3 4 5 6 7 8 9

• 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.

Example: Using an Array


Instead, we use an array to store these numbers and Accessing Array Elements- (1D)

✅ 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;
}

In the above example, an array of Integers can be declared as:


Int Numbers[5] = {10,20,30,40,50};
Numbers
10 20 30 40 50
Index - 0 1 2 3 4
• Compiler will allocate a contiguous block of memory of size = 5*sizeof(int).
• The length of an array can be specified by any POSITIVE INTEGER constant expression.
Accessing Elements from 1D Arrays.
To Access an array elements, just write:
• Array_name[index];
Accessing the first element of an array: Numbers[0]
Accessing the second element of any array: Numbers[1]

C Provides two types of arrays:


➢ Fixed – Length array
➢ Variable – Length array

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

Example: Fixed-Length Array

✅ 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

Limitations of Fixed-Length Arrays:


Cannot change size at runtime.
Wastes memory if not fully utilized.
Not flexible for dynamic data handling.

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;
}

3. Partial Initialization (Remaining Elements Set to Zero)


• If we initialize only a few elements, the rest are set to zero.
• int arr[5] = {10, 20}; // Remaining elements will be 0
Example:
#include <stdio.h>
int main()
{
int arr[5] = {10, 20}; // Only first two elements initialized
for (int i = 0; i < 5; i++)
{
printf("%d ", arr[i]); // Output: 10 20 0 0 0
}
return 0;
}

4. Automatic Size Deduction


• The compiler automatically determines the array size if we initialize it directly.
• int arr[] = {5, 10, 15, 20}; // Size is automatically 4
Example:
#include <stdio.h>
int main()
{
int arr[] = {5, 10, 15, 20}; // Compiler determines size (4)
for (int i = 0; i < 4; i++)
{
printf("%d ", arr[i]); // Output: 5 10 15 20
}
return 0;
}

2. Variable-Length Arrays (VLA)


• A Variable-Length Array (VLA) is an array whose size is determined at runtime.
Key Features:
Introduced in C99 standard
Size is determined at runtime
Allocated on the stack (not heap)
More memory-efficient than fixed-length arrays
Example: Variable-Length Array (VLA)
#include <stdio.h>
int main()
{
int n;
printf("Enter array size: ");
scanf("%d", &n); // User decides array size at runtime
int arr[n]; // Variable-Length Array
for (int i = 0; i < n; i++) // Assigning values
{
arr[i] = (i + 1) * 10;
}
printf("Array elements: "); // Printing values
for (int i = 0; i < n; i++)
{
printf("%d ", arr[i]);
}
return 0;
}
Output Example (User Input: 4)
Enter array size: 4
Array elements: 10 20 30 40
Limitations of VLAs:
Only works in C99 and later (not supported in C90 or older versions).
Consumes stack memory, which is limited.
Cannot use sizeof(arr) to get the size because the array is runtime-dependent.

2. Variable-Length Arrays (VLA) Initialization


* Since VLAs do not support compile-time initialization, they must be initialized at runtime.
2.1 User Input Initialization (Runtime)
Example:
#include <stdio.h>
int main()
{
int n;
printf("Enter array size: ");
scanf("%d", &n); // User decides size
int arr[n]; // VLA
for (int i = 0; i < n; i++) // Initializing the array at runtime
{
arr[i] = (i + 1) * 10; // Assigning values dynamically
}
printf("Array elements: "); // Printing values
for (int i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
return 0;
}
Output (User Inputs 4)
Enter array size: 4
Array elements: 10 20 30 40

2.2 Initialization Using Loops


* Since direct initialization like int arr[n] = {1,2,3}; is not allowed in VLAs, we use loops.
Example:
#include <stdio.h>
int main() {
int n;
printf("Enter array size: ");
scanf("%d", &n);
int arr[n];
for (int i = 0; i < n; i++) // Assigning values
{
arr[i] = i * 5; // Initializing dynamically
}
for (int i = 0; i < n; i++) // Printing values
{
printf("%d ", arr[i]);
}
return 0;
}

Basic Operations on Arrays in C


Arrays are used to store multiple values in a single variable. Several operations can be performed on arrays,
including:
1. Traversal (Accessing Elements) : Print all the Array elements one by one.
2. Insertion (Adding Elements) : Adds an element at the given index.
3. Deletion (Removing Elements) : Deletes an element at the given index.
4. Search (Finding an Element) : Searches an element using the given index or by the value.
5. Update (Modifying Elements) : changing the value of an element at a specific index.
6. Sorting (Arranging Elements) : Arranging in an order.
7. Merging (Combining Arrays) : combining elements from two arrays into a new array.

1. Traversal (Accessing Elements)


Traversal means visiting each element of an array one by one.
Example: Traversing an Array
#include <stdio.h>
int main()
{
int arr[5] = {10, 20, 30, 40, 50}; // Fixed-length array
printf("Array elements: ");
for (int i = 0; i < 5; i++)
{
printf("%d ", arr[i]); // Accessing each element
}
return 0;
}
Output:
Array elements: 10 20 30 40 50

2. Insertion (Adding Elements to an Array)


Insertion means adding an element at a specific position.
• In a fixed-size array, inserting a new element shifts the later elements.
• In a dynamic array, new memory can be allocated.
Example: Insert an Element at a Specific Position
#include <stdio.h>
int main()
{
int arr[6] = {10, 20, 30, 40, 50}; // Size 6 but only 5 elements used
int pos = 2, new_value = 25; // Insert at index 2
for (int i = 5; i > pos; i--) // Shifting elements to the right
{
arr[i] = arr[i - 1];
}
arr[pos] = new_value; // Inserting new element
printf("Array after insertion: "); // Printing updated array
for (int i = 0; i < 6; i++)
{
printf("%d ", arr[i]);
}
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

4. Search (Finding an Element in an Array)


Searching finds the index of an element in the array.
Example: Linear Search
#include <stdio.h>
int main()
{
int arr[5] = {10, 20, 30, 40, 50};
int key = 30, found = 0;
for (int i = 0; i < 5; i++)
{
if (arr[i] == key) {
printf("Element %d found at index %d\n", key, i);
found = 1;
break;
}
}
if (!found)
{
printf("Element not found\n");
}
return 0;
}
Output:
Element 30 found at index 2

5. Update (Modifying an Element in an Array)


Updating means changing the value of an element at a specific index.
Example: Updating an Element
#include <stdio.h>
int main()
{
int arr[5] = {10, 20, 30, 40, 50};
int pos = 2, new_value = 99;
arr[pos] = new_value; // Updating element at index 2
// Printing updated array
printf("Array after update: ");
for (int i = 0; i < 5; i++)
{
printf("%d ", arr[i]);
}
return 0;
}
Output:
Array after update: 10 20 99 40 50

6. Sorting (Arranging Elements in Order)


Sorting arranges elements in ascending or descending order.
Example: Bubble Sort (Ascending Order)
#include <stdio.h>
void bubbleSort(int arr[], int n)
{
for (int i = 0; i < n - 1; i++)
{
for (int j = 0; j < n - i - 1; j++)
{
if (arr[j] > arr[j + 1])
{
// Swap if greater
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
}
int main()
{
int arr[5] = {50, 10, 40, 20, 30};
bubbleSort(arr, 5); // Sorting the 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

7. Merging (Combining Two Arrays into One)


Merging means combining elements from two arrays into a new array.
Example: Merging Two Arrays
#include <stdio.h>
int main()
{
int arr1[3] = {1, 2, 3};
int arr2[3] = {4, 5, 6};
int merged[6];
// Copy elements from arr1
for (int i = 0; i < 3; i++) {
merged[i] = arr1[i];
}
// Copy elements from arr2
for (int i = 0; i < 3; i++) {
merged[i + 3] = arr2[i];
}
// Printing merged array
printf("Merged array: ");
for (int i = 0; i < 6; i++)
{
printf("%d ", merged[i]);
}
return 0;
}
Output:
Merged array: 1 2 3 4 5 6

Summary of Array Operations

Operation Description

Traversal Accessing each element in the array.

Insertion Adding a new element at a specific index.

Deletion Removing an element from a specific index.

Search Finding an element's index (linear or binary search).

Update Modifying an element at a given index.

Sorting Arranging elements in ascending or descending order.

Merging Combining two arrays into a single array.

2. Two-Dimensional (2D) Arrays


A 2D array is like a table or a chessboard.
It consists of rows and columns.
Example: A 2D Matrix
Imagine a 2×3 table:

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}

How to Declare a 2D Array in C


We declare a 2D array using:
data_type array_name[rows][columns];
Example:
int matrix[2][3]; // 2 rows, 3 columns

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.)

Accessing Elements of a 2D Array


Each element is accessed using row index and column index.
int value = matrix[1][2]; // Accessing element in row 1, column 2
Indexes start from 0.
Example:
matrix[0][0] = 1; // First row, first column
matrix[1][2] = 6; // Second row, third column

Example: Printing a 2D Array


#include <stdio.h>
int main()
{
int matrix[2][3] = { {1, 2, 3}, {4, 5, 6} };
printf("2D Array (Matrix):\n");
for (int i = 0; i < 2; i++)
{
// Row loop
for (int j = 0; j < 3; j++)
{
// Column loop
printf("%d ", matrix[i][j]); // Print each element
}
printf("\n"); // New line for next row
}
return 0;
}
Output:
2D Array (Matrix):
123
456

2️ Multi-Dimensional Arrays (3D and Beyond)


A 3D array is like a collection of 2D tables, stacked on top of each other.
Example: A 3D Array
Think of a Rubik’s cube or layers of a cake.
If a 2D array is a table, a 3D array is a stack of tables.
Example: 2×2×3 Matrix (2 Layers, 2 Rows, 3 Columns)
Layer 1:
1 2 3
4 5 6
Layer 2:
7 8 9
10 11 12

How to Declare a 3D Array in C


We declare a 3D array as:
data_type array_name[depth][rows][columns];
Example:
int cube[2][2][3]; // 2 layers, 2 rows, 3 columns

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.

Accessing Elements in a 3D Array


Each element is accessed using:
array_name[layer][row][column];
Example:
int num = cube[1][0][2]; // Layer 1, Row 0, Column 2️ → Value: 9

Example: Printing a 3D Array


#include <stdio.h>
int main()
{
int cube[2][2][3] =
{
{ {1, 2, 3}, {4, 5, 6} },
{ {7, 8, 9}, {10, 11, 12} }
};
// Printing elements
for (int i = 0; i < 2; i++)
{
printf("Layer %d:\n", i);
for (int j = 0; j < 2; j++)
{
for (int k = 0; k < 3; k++)
{
printf("%d ", cube[i][j][k]);
}
printf("\n"); // New row
}
printf("\n"); // Space between layers
}
return 0;
}
Output:
Layer 0:
123
456

Layer 1:
789
10 11 12
Summary

Array Type Shape Example

1D Array List {10, 20, 30}

2D Array Table (Rows × Columns) {{1, 2}, {3, 4}}

3D Array Cube (Layers × Rows × Columns) {{{1,2}, {3,4}}, {{5,6}, {7,8}}}

Real-life Uses of Multi-Dimensional Arrays


• 2D Arrays → Spreadsheets, Chessboards, Image Processing
• 3D Arrays → 3D Graphics, Rubik’s Cube, Weather Data

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’.

Assigning String literal to a pointer:

Char *ptr = “Hello”

• 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’

Represented by a pointer Represented by an integer (ASCII code: 72)


To a character ‘H’

Declaring a string variable:


• A string variable is a one-dimensional array of character that is capable of holding a
string at a time.
For example: char s[6];

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

2. Taking String Input from the User


Using scanf:

#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;
}

4️ String Functions in C (String.h Library)


To use built-in functions, we include:
#include <string.h>
Function Purpose
strlen(str) Finds length of string
strcpy(dest, src) Copies src into dest
strcat(str1, str2) Appends str2 to str1
strcmp(str1, str2) Compares two strings
strrev(str) Reverses a string (Not in standard C)

Example 1: Find String Length


#include <stdio.h>
#include <string.h>
int main()
{
char word[] = "Embedded";
printf("Length of word: %d", strlen(word));
return 0;
}

Output:
Length of word: 8

Example 2: Copy One String into Another

#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

Example 3: Concatenating (Joining) Strings

#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

Example 4: Comparing Strings

#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

Example 5: Reversing a String (Using Loop)


#include <stdio.h>
#include <string.h>
int main()
{
char str[] = "C Programming";
int len = strlen(str);
printf("Reversed String: ");
for (int i = len - 1; i >= 0; i--)
{
printf("%c", str[i]); // Print from last index
}
return 0;
}
Output:
Reversed String: gnimmargorP C

5. Array of Strings (Multiple Strings)

* What is an Array of Strings?


An array of strings in C is a 2D character array where each row represents a separate string.
It is useful for storing multiple strings (like names, commands, or messages).

1 Declaring an Array of Strings


There are two ways to declare an array of strings in C:
Method 1: Using a 2D Character Array

char names[3][20] = {"Vamsi", "Krishna", "Vaka"};

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 *)

char *names[] = {"Vamsi", "Krishna", "Vaka"};

Each element is a pointer to a string literal


More flexible (can store longer strings dynamically)

2️ Example: Printing an Array of Strings


#include <stdio.h>
int main()
{
char names[3][20] = {"Vamsi", "Krishna", "Vaka"};
for (int i = 0; i < 3; i++)
{
printf("%s\n", names[i]); // Print each string
}
return 0;
}
Output:
Vamsi
Krishna
Vaka

3 Passing an Array of Strings to a Function


When passing an array of strings to a function, you can use:
• A 2D character array
• An array of pointers (char * array)

Method 1: Passing a 2D Character Array


#include <stdio.h>
// Function to print an array of strings
void printStrings(char arr[][20], int size)
{
for (int i = 0; i < size; i++) {
printf("%s\n", arr[i]);
}
}
int main()
{
char names[3][20] = {"Vamsi", "Krishna", "Vaka"};
printStrings(names, 3); // Pass 2D array
return 0;
}
Output:
Vamsi
Krishna
Vaka

Each row of the 2D array represents a string


Limitation: Cannot modify string size dynamically.

Method 2: Passing an Array of Pointers (char *arr[])

#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

More flexible (can store longer strings dynamically)


Efficient memory usage

Summary of Array of Strings in C


Method Declaration Example Usage
2D Character Array char arr[3][20] char names[3][20] = {"A", "B", "C"}; Fixed size, easy to use
Array of Pointers (char *) char *arr[] char *names[] = {"A", "B", "C"}; More flexible, efficient

Alternatives to printf() and scanf() for Strings in C


In C programming, printf() and scanf() are commonly used for input and output operations. However, there
are alternative functions that provide more flexibility and safety, especially for handling strings.

1 Alternatives to printf() (for Output)


Function Purpose
puts(str) Prints a string followed by a new line
fputs(str, stream) Prints a string to a file or console
sprintf(buffer, format, ...) Stores formatted output in a string
snprintf(buffer, size, format, ...) Safe version of sprintf() with buffer size limit

Using puts() (Simpler Alternative to printf() for Strings)


Doesn't require format specifier (%s)
Automatically adds a newline (\n)
Example:
#include <stdio.h>
int main()
{
char name[] = "Vamsi Krishna";
puts(name); // Prints with a new line
return 0;
}
Output:
Vamsi Krishna
Drawback: Cannot format the output like printf("%s is %d years old", name, age);
Using fputs() (Print String to Console or File)

Doesn't add a newline automatically


Safer than printf() because it avoids format string attacks
Example (Print to Console):
#include <stdio.h>
int main()
{
char message[] = "Hello, Embedded Systems!";
fputs(message, stdout); // Prints to console
return 0;
}
Output:
Hello, Embedded Systems!
Drawback: No automatic newline. Use \n manually.

Using sprintf() (Store Output in a String Instead of Printing)

Works like printf(), but stores the result in a string


Useful when building formatted messages dynamically
Example:
#include <stdio.h>
int main()
{
char buffer[50]; // Buffer to store formatted string
int age = 22;

sprintf(buffer, "Vamsi Krishna is %d years old", age);


puts(buffer); // Print formatted string
return 0;
}
Output:
Vamsi Krishna is 22 years old
Risk: sprintf() doesn’t check buffer size, can cause buffer overflow.

Using snprintf() (Safer Alternative to sprintf())


Prevents buffer overflow by limiting output size
More secure than sprintf()
Example:
#include <stdio.h>
int main()
{
char buffer[20]; // Small buffer
snprintf(buffer, sizeof(buffer), "Name: %s", "Vamsi Krishna");
puts(buffer); // Ensures it does not exceed buffer size
return 0;
}
Output:
Name: Vamsi Krish
The output is truncated because the buffer is small.

2️ Alternatives to scanf() (for Input)


Function Purpose
gets(str) Reads an entire line ( Unsafe)
Function Purpose
fgets(str, size, stream) Safe version of gets()
sscanf(str, format, ...) Reads formatted input from a string
Creating own input function using
Getchar()

Using gets() (Unsafe, Should NOT Be Used)


Why unsafe? It doesn't check buffer size, leading to buffer overflow.
Example (DO NOT USE in modern C programming):

#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()

Using fgets() (Safe Alternative to gets())


Limits input size to prevent buffer overflow
Reads the entire line including spaces

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:

name[strcspn(name, "\n")] = '\0'; // Removes newline

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.

3 Creating Our Own scanf() Alternative Using getchar()


We will create a function called custom_input() that reads a full string from user input, character by
character, until Enter (\n) is pressed.

Custom Input Function: custom_input()

#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

4️ Creating Our Own printf() Alternative Using putchar()


We will create a function called custom_output() that prints a string character by character using
putchar().

Custom Output Function: custom_output()

#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

You might also like