w3resource

C Exercises: Calculate the length of the string

C Pointer: Exercise-10 with Solution

Write a program in C to calculate the length of a string using a pointer.

Visual Presentation:

C Exercises: Pictorial: Calculate the length of the string.

Sample Solution:

C Code:

#include <stdio.h>

// Function to calculate the length of the string
int calculateLength(char*); // Function prototype

int main() 
{
   char str1[25];
   int l;

   printf("\n\n Pointer : Calculate the length of the string :\n"); 
   printf("---------------------------------------------------\n");

   printf(" Input a string : ");
   fgets(str1, sizeof str1, stdin); // Input the string from the user

   l = calculateLength(str1); // Get the length of the input string
   printf(" The length of the given string %s is : %d ", str1, l-1); // Display the length of the string
   printf("\n\n");
}

// Function to calculate the length of the string
int calculateLength(char* ch) // Takes a pointer to the first character of the string
{
   int ctr = 0;

   while (*ch != '\0') // Loop until the null character '\0' is found
   {
      ctr++; // Increment the counter for each character encountered
      ch++; // Move to the next character in the string
   }

   return ctr; // Return the total count of characters (excluding the null character)
}

Sample Output:

 Pointer : Calculate the length of the string :                                                               
---------------------------------------------------                                                           
 Input a string : w3resource                                                                                  
 The length of the given string w3resource                                                                    
 is : 10

Flowchart:

Flowchart: Calculate the length of the string

C Programming Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Write a program in C to find the largest element using Dynamic Memory Allocation.
Next: Write a program in C to swap elements using call by reference.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://w3resource.com/c-programming-exercises/pointer/c-pointer-exercise-10.php