Reputation: 1
#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
Upvotes: 0
Views: 60
Reputation: 156
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 ...
}
Upvotes: 1
Reputation: 225117
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.
Upvotes: 3