0

Link to the Problem - LuckyFour

The code works fine on my own system, but while submitting shows wrong answer?

#include <stdio.h>
void main()
{
    int t, n, count;
    scanf("%d", &t);
    while(t--)
    {
        count=0;
        scanf("\n%d",&n);
        while(n>0)
        {
            if(n%10==4)
            {
                count++;
            }
            n=n/10;
        }
        printf("\n%d", count);
    }
}
Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
sanchit
  • 41
  • 1
  • 8

3 Answers3

1

I think you must write outputs in end.

and also use "%d\n" instead of "\n%d"

first change these lines and check:

scanf("\n%d",&n);

to

scanf("%d",&n);

and

printf("%d\n", count); // instead of \n%d

if dont work save results in an array and print they in another "while"

morteza ataiy
  • 541
  • 4
  • 12
  • It worked. By changing `int main(void)` and adding `return 0;` Also, with this `printf("%d\n", count);` Can you tell me what actually went wrong? – sanchit Aug 26 '18 at 11:59
  • 1
    The primary problem was probably that your output didn't end with a newline. Print lines so that they end with newlines; only add newlines at the front when you want blank lines. – Jonathan Leffler Aug 26 '18 at 22:54
1

Avoid using whitespace (space, newline) in scanf. Please see an earlier thread on this topic Using “\n” in scanf() in C

Ravi S
  • 139
  • 3
0

As an example of how I'd avoid conversion: (also added some error checking and an actual return value for main which I like to have, as do Unix-like OS'es...)

#include <stdio.h>
#include <stdlib.h>

static size_t count_char_in_line(const char *l, size_t len, char c){
    size_t res=0;
    while(len>0){ 
        if (*(l++) == c) res++; 
        len--;
    }
    return res;
}

int main(void){

size_t nr_of_expected_lines=0;
ssize_t nr_read;
size_t line_length;
char *line = NULL;
int ret=0;

if (-1 != ( nr_read = getline(&line, &line_length, stdin))){
    if (1 != sscanf(line, "%zu", &nr_of_expected_lines)){
        fprintf(stderr, "not a number on the first line..\n");
        ret=1;
        goto cleanup;
    }
} else {
    fprintf(stderr, "premature end of stdin..\n");
    ret=2;
    goto cleanup;
}
while (nr_of_expected_lines > 0 && (-1 != (nr_read = getline(&line, &line_length,stdin)))){
    if (nr_read > 1){
        size_t count=count_char_in_line(line, nr_read-1, '4');
        fprintf(stdout, "%zu\n", count);
        nr_of_expected_lines--;
    } else {
        fprintf(stderr, "empty line error\n");
        ret= 3;
        break;
    }
}  

cleanup:
free(line);
return ret;

}

Henno Brandsma
  • 2,116
  • 11
  • 12