1
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#define SIZE 19

int main() 
{
    char name[SIZE];
    int x;
    int i;

    printf("Enter your name: ");

    scanf("%s", &name);

    for (i = 1; name[i] != '\0'; i++);
        printf("Are you sure your name is: ");

    for (x = i - 1; x >= 0; x--)
        printf("%c", name[x]);
}

On line 9 why do we need to have a semicolon there after the For statement? Without the semicolon the program prints "Are you sure your name is: Are you sure your name is: ".

EDIT: People don't like duplicate questions so here I am making it different - What do you think is the problem, why isn't it working???? [SOLVED]

  • Nope. That's a bug. – evaitl Jul 22 '16 at 19:36
  • Not clear what it is you expect. However, you don't need a semi-colon after the for; by removing the semi-colon, you print your message twice because the NULL character is at the third element (in the case you describe) of your array. What is it you want to accomplish? – clarasoft-it Jul 22 '16 at 19:39
  • 2
    It is not a bug. It is used to calculate the string length into `i`. – Eugene Sh. Jul 22 '16 at 19:41
  • Yes, it's clearly intentional. Indentation just is wrong and it would be a lot cleaner with a while loop and nobody would wonder if it is a bug or not. – Sami Kuhmonen Jul 22 '16 at 19:44
  • Oh... Yeah my bad. The loop is supposed to be empty yet I assumed the printf after it goes together. I guess I could have also done the for loop but left the {} braces empty. –  Jul 22 '16 at 20:14

1 Answers1

3

The line

for (i = 1; name[i] != '\0'; i++);

Is looping until name[i] is a null terminator. At this point the counter i will have the length of the string name, which is used in the next code lines. The only problem with the code is the indentation of the next line, which is misleading to think it is the part of the loop.

Eugene Sh.
  • 17,802
  • 8
  • 40
  • 61
  • "The only problem with the code is the indentation of the next line" -- well, that and the fact that there's no reason not to use strlen() and make this whole thing a lot more clear... – nephtes Jul 22 '16 at 19:45
  • @nephtes That's for sure. But I'll leave it for code review. – Eugene Sh. Jul 22 '16 at 19:45
  • Yup, the print statement after the loop is not supposed to be like that... lol. Thanks Eugene! –  Jul 22 '16 at 20:16