Print Substring of a Given String Without Using Any String Function and Loop in C
Last Updated :
23 Jul, 2025
In C, a substring is a part of a string. Generally, we use string libary functions or loops to extract the substring from a string and then print it. But in this article, we will learn how to print the substring without using any string function or loops.
The simplest method for printing a substring of a string is by using recursion. Let's take a look at an example:
C
#include <stdio.h>
void printSS(char* s, int left, int right) {
// Finding the length
int n = right - left + 1;
// Printing using width specifier for string
printf("%.*s", n, s + left);
}
int main() {
char s[] = "Geeks for Geeks";
// Printing the substring "for"
printSS(s, 6, 8);
return 0;
}
Explanation: In this program, printSS() takes starting(left) and ending(right) index of the substring as parameters. It then prints the character at left index in one recursive call and move left index towards right index can call itself again. It does this until left is greater than right index.
If the recursive method is also restricted, then we can use the pointer arithmetic with print width specifier inside the printf() function to print the substring.
Using Pointer Arithmetic
Find the length of the string by calculating the difference between the starting and ending indexes. Then use print width specifier in printf() function print the given length starting from the first character of the string using pointer arithmetic. Let's take a look and an example:
C
#include <stdio.h>
void printSS(char *s, int l, int r) {
// Base case
if (l > r) {
return;
}
// Print character at s[l]
printf("%c", s[l]);
// Move pointer to the right and call again
printSS(s, l + 1, r);
}
int main() {
char s[] = "Geeks for Geeks";
// Printing the substring "for"
printSS(s, 6, 8);
return 0;
}
Explanation: In this program, the substring "for" is printed by calling the printSS function with its starting and ending index. The expression s + left moves the pointer to the starting position of the substring, and %.*s ensures that only the specified number of characters (3 in this case) are printed.
Explore
C Basics
Arrays & Strings
Pointers and Structures
Memory Management
File & Error Handling
Advanced Concepts