ECE DEPARTMENT : NOTICE BOARD

ADVISORY TO STUDENTS (Answer to "Sir, College is there today ?")

Quote :
"If egg is broken by outside force, life ends. If broken by inside force, life begins. Great things always begin from inside force, trust yourself."

Batchwise blogs: -2008 | 2009 | 2010 | 2011 | 2012

Internal Marks Sem-II : | 2011 | 2010 | 2009 |

Intro | Case 1 | Case 2 | Case 3 | Case 4 | Case 5 |

Previous Posts

Saturday, July 10, 2010

Today's C Program

What's wrong with the following program ?


#include "stdio.h"
/*computes the length of a string*
*
* Parameters
*
* string - - The string whose length we want.
*
*Returns
* the length of the string
*
*/

int length(char string[])
{
   int index ; /* index into the string */
      /*
       * Loop until we reach the end of string character
       */
          for (index = 0; string[index] != '\0'; ++index)
                /* do nothing */
          return (index);
}

int main ( )
{
char line[100] ; /* Input line from user */
        while (1) {
             printf("Enter line :");
             fgets(line, sizeof(line), stdin);
  printf("Length (including newline) is : %d\n", length(line));
        }
}



1 comment:

  1. Ans:in this program an infinite while loop is used in main() function which executes infinite no of times.
    inside this infinite loop the user is prompted to enter a string through the fgets() function which takes the string coming through the standard input stream in this case keyboard.

    now supposing that the user has entered the string "Hello World!" when we press enter the fgets function appends '\n' character at the end of the string and after that null character '\0' in the string. now this is passed to the function length() in which a for loop is used to count the length of the string in a variable called index.
    but every time u enter a string however long it might be it will return length as 0(zero) why??????????
    bcuz the return statement is placed immediately after the for loop so each time the loop is true it(return statement) is executed so for the first time through the loop with the value of index being zero the condition in loop is true hence the return statement is executed which returns zero to its caller which in this case is main()and takes the control back to the main() function.the value returned zero is printed by printf()! hence the op.

    the problem lies in the for loop of the function length here the for loop should be written like this:

    for(index=0;string[index]!='\0';++index)
    ;/*do nothing */

    return (index);

    whenever we want to do nothing till some loop is true we should use null statement ; which on execution does nothing!!!!

    ReplyDelete