-1

I found the question in CodeChef which asks us to write a program to calculate the sum of the first and last digit of a number N(1 ≤ N ≤ 1000000) for T test cases(1 ≤ T ≤ 1000)(Here's the full problem definition https://www.codechef.com/problems/FLOW004/). I pass the sample input but when submitting gives me the wrong answer. How should I approach to debug my code. Please refer to the below code which gave the wrong answer, as in how one should identify different kinds of inputs using which one can try to detect the error.

#include <stdio.h>
#include <math.h>

int main(void) {
    int t, n, last_term, first_term;
    scanf("%d", &t);
    while(t--)
    {
        scanf("%d", &n);
        last_term = n % 10;
        while(abs(n) > 10)
        {
            n = n / 10;
        }
        first_term = n;
        printf("%d\n", abs(first_term) + abs(last_term));
    }
    return 0;
}
Arimee
  • 7
  • 3
  • 1
    C and C++ are different language. Would you mind choosing one? – MikeCAT Jan 29 '21 at 12:26
  • Doesn't work https://godbolt.org/z/1j4E5n – Marek R Jan 29 '21 at 12:38
  • 1
    "How should I approach to debug my code" - write your own tests. Why rely on blackbox testing only when you can write your own tests? And: [What is a debugger and how can it help me diagnose problems?](https://stackoverflow.com/questions/25385173/what-is-a-debugger-and-how-can-it-help-me-diagnose-problems) – 463035818_is_not_an_ai Jan 29 '21 at 12:39

1 Answers1

2

The condition abs(n) > 10 looks wrong.

It should be abs(n) >= 10 or abs(n) > 9 to loop until the number becomes one-digit long.

MikeCAT
  • 73,922
  • 11
  • 45
  • 70
  • Thank you so much for clarifying this very minute mistake. I invested more focus on edge case inputs rather than clearly reading my code. – Arimee Jan 30 '21 at 14:05