Call us at 0700-922-6559 or Click here

Write a program to Find the Length of a String.

Below is the program to find the length of a string with explanation.

#include <stdio.h>

int main() {

    char s[] = “Programming is fun”;

    int i;

    for (i = 0; s[i] != ‘\0’; ++i);   

    printf(“Length of the string: %d”, i);

    return 0;

}

Output-

Length of the string: 18

Below is the step-by-step explanation of the program.

  1. We start by including the standard input/output library with the #include <stdio.h> statement.
  2. We then define the main() function, which is the starting point of any C program.
  3. We declare a character array called s and initialize it with the string “Programming is fun” with the statement char s[] = "Programming is fun";. This array s holds the characters of the string we want to find the length of.
  4. We declare an integer variable i which will be used to iterate over the characters of the string s.
  5. We start a for loop with the statement for (i = 0; s[i] != '\0'; ++i);. This loop will iterate over each character in the s array starting from the first character with the index 0. It will continue to loop until it reaches the null character '\0', which indicates the end of the string.
  6. The loop condition s[i] != '\0' checks if the current character is not equal to the null character. If it is not equal, the loop body is executed. Otherwise, the loop terminates.
  7. In each iteration of the loop, we increment the value of i by 1 with the statement ++i. This means we move to the next character in the array s.
  8. When the loop terminates, i will hold the number of characters in the string s.
  9. Finally, we print the length of the string with the statement printf("Length of the string: %d", i);. The %d format specifier tells printf() to print an integer value, which we provide with the variable i.
  10. We end the program by returning 0 from the main() function with the statement return 0;.

Once you have written the code, you can compile and run it using a C compiler, such as GCC, on your computer. The program will then display output on the screen when executed.

For more information about C programming join our course of C programming.

Leave a Reply

Your email address will not be published. Required fields are marked *