0
#include <stdio.h> #include <stdlib.h> int main(){ int f,x,s,y,t,l,year,sum; f=year/1000; x=year%1000; s=x/100; y=x%100; t=y/10; l=y%10; sum=f+s+t+l; printf("Enter a Year:"); scanf("%d",&year); if (year%4==0){ printf("Leap,%d",sum); } else if (year%400==0){ printf("Leap,%d",sum); } else if (year%100==0){ printf("Regular,%d",sum); } else {printf("Regular,%d",sum);} return 0; } 

Obejective: Input a 4 digit year using stdin (scanf). Display whether it is a leap year or not. If it is a leap year, display - Leap,sum of digits of year. If not a leap year, display - Regular,sum of digits of year.

Its giving correct output for leap year but not the sum of the digits

2
  • Well, you're calculating the sum BEFORE you read the year from the user. You have to do it after. Commented Dec 22, 2020 at 17:40
  • The PC starts at the beginning of main() and evaluates one statement after the other. (Simply speaking, startup routine, signals, interrupts, multithreading, stack unwinding .... ignored). Ignoring the return value of scanf() is a programming error. Commented Dec 22, 2020 at 17:51

2 Answers 2

3

Expressions in C are not formulas that automatically take effect when the associated variables change. They work on the current value of the variables in question at that point in the program.

You need to move the digit calculation to after you read the value of year.

printf("Enter a Year:"); scanf("%d",&year); f=year/1000; x=year%1000; s=x/100; y=x%100; t=y/10; l=y%10; sum=f+s+t+l; 

Also, you'll want to take another look at how you do the leap year calculation. Try 1900, 1999, 2000, and 2004 as test values.

Sign up to request clarification or add additional context in comments.

1 Comment

Not checking the return value of scanf() is a error.
1

Your actual question was answered by @dbush, however, your leap year criteria are also not quite right. Your first if branch will always execute when year % 4 == 0 regardless of whether year % 100 == 0. So what you really want there is

if(year % 4 == 0 && (year % 100 != 0 || year % 400 == 0)) { // leap year ... } else { // no leap year ... } 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.