A four-digit number ABCD is called Lucky if $$A + B = C + D$$.

Write a program that asks the user to enter a four-digit number n and prints whether n is a Lucky number or not.

Example:

  • The number 3719 is a Lucky number since 3 + 7 = 1 + 9
  • The number 3521 is not a Lucky number since (3 + 5) != (2 + 1).

Difficulty level
Video recording
This exercise is mostly suitable for students
#include <stdio.h>

int main()
{
    int X, digit1, digit2,digit3,digit4;
    printf("Enter a 4 digit integer: ");
    scanf("%d",&X);
    
    digit1=X/1000;
    digit2=(X-digit1*1000)/100;
    digit3=(X-digit1*1000 - digit2*100)/10;
    digit4=X%10;
    
    if(digit1+digit2==digit3+digit4)
        printf("The number %d is a Lucky number since %d + %d = %d + %d\n",X, digit1, digit2,digit3,digit4);
    else
       printf("The number %d is not a Lucky number since %d + %d != %d + %d\n",X, digit1, digit2,digit3,digit4);

    return 0;
}

Back to the list of exercises
Looking for a more challenging exercise, try this one !!
Implementation of 3 stacks within a single array