C Program to find the length of the string

For a better understanding, we always recommend you to learn the basic topics of C programming listed below:

What is the length of a string?

In this C program, we are counting the number of characters in a given string to find out and display the string length. The length of a string means the number of characters in that string. For example, consider a string 'powerful', the number of characters in that s=string is 8.

Using this c program, we find out the length of a string, which means we need to find out the number of characters in the string. We need to count the number of characters in the string using a 'for loop' finally, we display the output as the value of the counter. We declare an array to store the string and accept the user string into that array. Then we start the for loop to count the number of string characters and display the output. The steps are:

  • Take a string as input and store this in an Array.
  • Count the number of characters in the Array using for loop and store the result in a variable.
  • Print the variable as the output.

Here the program uses For loop to find the number of characters.

What is the syntax of for loop?


 for(initialization Statement; testExpression; updateStatement)
     {
           // code
      }

Here initialization statement is executed only once. Then test expression is evaluated. If the test expression is true, the code inside for loop is executed and update the term. The process continues until the test expression becomes false. But if the test expression is wrong, the code inside For loop is terminated.

ALGORITHM

STEP 1: Include the header files to use the built-in functions in the C program.

STEP 2: Declare the character Array String.

STEP 3: Declare the integer variable I, length.

STEP 4: Set length=0.

STEP 5: Accept a String from the user using the gets() function.

STEP 6: Set i=0.

STEP 6: By using a for loop with the condition string[i] != '\0' increment length by 1.

STEP 7: Increment 'i' by 1, and repeat step 6.

STEP 8: Display the length of the String as length using printf.

C Source Code

                                          #include <stdio.h>

void main() {
  char string[50];
  int i, length = 0;
  printf("Enter a string\n");
  gets(string);
  for (i = 0; string[i] != '\0'; i++) /*keep going through each */ {
    /*character of the string */
    length++; /*till its end */
  }
  printf("The length of a string is the number of characters in it\n");
  printf("So, the length of %s =%d\n", string, length);
}
                                      

OUTPUT

Enter a string

hello
The length of a string is the number of characters in it
So, the length of hello = 5

RUN2

Enter a string
E-Commerce is hot now
The length of a string is the number of characters in it
So, the length of E-Commerce is hot now =21