,

Practice Program







  • Program of Calculating length of string.
  • Solution:
    void main()
    {
        char s[20];
        int length;
    
        //taking string as input from the user.
        printf("Enter the string: ");
        gets(s);
    
    
        for(length = 0 ;s[length] != '\0'; length++);
        {
            //till backslash character does not occurs this loop will iterate.
                //as length variable is increasing at every iteration.
                //as for loop will complete its iteration then we will get the length of string.
        } //value in length variable is nothing but length of the string.
    
    
             printf("Length of string is %d",length);
    
    }
    

    Output1
    Enter the string: programmerdouts

    Length of string is 15.

    Output2
    Enter the string: programmer

    Length of string is 10.

    Output3
    Enter the string: Hello

    Length of string is 5.







    defining a function 'give_lenght' which will return length of string 

    int give_lenght(char s[])
    {    int length;
        for(length = 0; s[length]!='\0'; length++)
        {
                //till backslash character does not occurs this loop will iterate.
                //as length variable is increasing at every iteration.
                //as for loop will complete its iteration then we will get the length of string.
        } //value in length variable is nothing but length of the string.
             //returning length variable.
    return length;
    }
    

    Using above define function 'give_lenght()':
    void main()
    {
        int lenght;
    
        lenght = give_lenght("Programmerdouts");
        printf("Length of the string is %d",lenght);
    }
    

    Output1
    Length of the string is 15

    Using above define function 'give_lenght()':
    void main()
    {
        int lenght;
    
        lenght = give_lenght("Code");
        printf("Length of the string is %d",lenght);
    }
    

    Output2
    Length of the string is 4

    Using above define function 'give_lenght()':
    void main()
    {
        int lenght;
    
        lenght = give_lenght("Computer");
        printf("Length of the string is %d",lenght);
    }
    

    Output3
    Length of the string is 8