-1

I'm using turbo C++ to compile the program. The program is

 main()

 {

    char inp1[21],inp2[21];

    int nsame=0,i=0,l1,l2;

    clrscr();

    gets(inp1);

    gets(inp2);

    l1=strlen(inp1);

    l2=strlen(inp2);

    if(l1==l2)
    {

        for(;inp1[i]!='\0',inp2[i]!='\0',inp1[i]==inp2[i];i++)
        {
            nsame++;
        }
    }
    if(nsame==l1)
    {
        puts("Same");
    }
    else
    {
        puts("Not the same");
    }
    getch();

}

The for loop above runs an extra time so the nsame is greater than the correct value by 1. So the program's output is correct if an extra nsame--; is added.

SKD
  • 464
  • 1
  • 4
  • 16
Htnamus
  • 56
  • 11

1 Answers1

4

The conditional in the for statement is not right. You have:

for(; inp1[i]!='\0', inp2[i]!='\0', inp1[i]==inp2[i]; i++)

You have three comma separated expressions. The first two are evaluated and discarded. Their values are not used in the test. Only the value of the last expression is used to determine when to terminate the loop.

You need to use:

for(; inp1[i]!='\0' && inp2[i]!='\0' && inp1[i]==inp2[i]; i++)

Suggestion for improvement:

You can remove one of the first two expressions and your program will work.

for(; inp1[i]!='\0' && inp1[i]==inp2[i]; i++)
R Sahu
  • 204,454
  • 14
  • 159
  • 270