Contact Learn C
Copy Program Share Program

Program 40:To know the length of a string without using string functions

Program 40:
 
#include<stdio.h>
main()
{
 char str[100];
 int i,len=0;
 printf("Enter a string to know the length\n");
 scanf("%s",&str);
 for(i=0;str[i]!='\0';i++)
 {
  len++;
 }
 printf("The length of %s is %d\n",str,len);
}
Explanation:
  1. This program starts with initializing :
    • str[100] → To store string with length of 100 which means it can store 100 letters
    • i →Used as helping variable
    • len→ To store length of given string and is initilized to zero.
  2. printf("Enter a string to know the length\n");
     scanf("%s",&str);
    takes the string from user
  3. for(i=0;str[i]!='\0';i++)
     {
      len++;
     }
    When ever you enter a string,compiler will add \0 at the end of the string.This is not visible to us.So if you enter "helloworld" which is interpreted as "helloworld\0" where \0 is single letter indicates the end of the string.
  4. Lets take a small example of string "he"
    • Iteration 1:i=0,and str[0] is 'h' and it is not \0 which means for loop is executed
      • now len will be incremented by 1 so len=1
      • i will be incremented by 1 and i=1
    • Iteration 2:i=1,and str[1] is 'e' and it is not \0 which means for loop is executed
      • now len will be incremented by 1 so len=2
    • Iteration 3:i=2,and str[2] is '\0' so for loop is terminated
  5. printf("The length of %s is %d\n",str,len);
    Finally len is printed.Which is len=2

  Output:

To know the length of a string without using string functions

Download App and Learn when ever you want

Get it on PlayStore
Get it on Amazon App Store
Get it on Aptoide