Home C++ Tutorial C++ Program to Find the Length of a String without Using Function

C++ Program to Find the Length of a String without Using Function

by Adarsh Pal
25 minutes read

In this article, you’ll learn about how to make C++ Program to calculate the length of string without using function. To do so we will iterate each character of the string through a for loop and increase the count until null(‘\0’) is not encountered .

Program to calculate the length of string without using function

  • Initialize the variable.
  • Accept the string.
  • Initiate a for loop.
  • Increase the count on every iteration. 
  • Terminate the loop when null(‘\0’).
  • Print length.
// C++ program to find length of a string without using function
#include <iostream>
using namespace std;
int main()
{
char s[100];
int i;
cout << "\nEnter a string: ";
gets(s);
for(i = 0; s[i] != '\0'; ++i);
cout << "Length of string : " << i;
cout << endl;
return 0;
}

Output

Enter a string: Hello, Welcome to Impactmillions
Length of string : 32

Program to find the length of a string using pointers

  • Initialize a variable ‘str’ , ‘length’.
  • call the function string_length and pass str as parameter store this in length.
  • in the function loop over the string and Terminate the loop when null(‘\0’).
  • Print length.
// C++ program to find length of a string using pointers
#include <iostream>
using namespace std;

int string_length(char* p) {
    int count = 0;
    while (*p != '\0') {
        count++;
        p++;
    }
    return count;
}

int main() {
    char str[50];
    int length;
    cout << "Enter any string : ";
    gets(str);
    length = string_length(str);
    cout << "The length of the given string : " << length;
    cout << endl;
    return 0;
}

Output

Enter any string : Hello, Welcome to Imapctmillions
The length of the given string : 32

Thank you for reading, If you have reached so far, please like the article, It will encourage me to write more such articles. Do share your valuable suggestions, I appreciate your honest feedback!

related posts

Leave a Comment