nzheard50 - 1 year ago 90
C Question

# Hi, I am trying to write a program that shows whether a year is a leap or not and if it is what the sum of its digits is

I understand the line of code that is used to determine if something is a leap year or not and I've seen the line of code to determine the sum of numbers but I don't know how to combine the two. When I run it I get an error saying

``````In function "main":
error. "else" without a previous "if"
error. "else" without a previous "if"
``````

Code:

``````#include <stdio.h>
int main()
{
int year,sum=0,r;

printf("Enter a year to check if it is a leap year\n");
scanf("%d", &year);
if ( year%400 == 0)
for(;year!=0;year=year/10){
r=year%10;
sum=sum+r;
}
printf("%d is a leap year and the sum is %d.\n", year,sum);
else if ( year%100 == 0)
printf("%d is not a leap year.\n", year);
else if ( year%4 == 0 )
for(;year!=0;year=year/10){
r=year%10;
sum=sum+r;
}
printf("%d is a leap year and the sum is %d.\n", year,sum);
else
printf("%d is not a leap year.\n", year);
return 0;
}
``````

Couple of problems in your code-

Problem no. 1 -

"if" statements in your program contain multiple statements but you have not enclosed them in {}.

Problem no. 2 -

You are modifying the value of "year" variable and printing it if the year found as a leap year. So, the value of year will always be printed as 0. Take the backup of variable "year" value and then do your steps to calculate the sum and in the printf print the backup value.

``````#include <stdio.h>

int main()
{

int year,sum=0,r;
int year_val;

printf("Enter a year to check if it is a leap year\n");
scanf("%d", &year);
year_val = year;

if ( year%400 == 0) {
for(;year!=0;year=year/10){
r=year%10;
sum=sum+r;
}
printf("%d is a leap year and the sum is %d.\n", year_val,sum);
} else if ( year%100 == 0)
printf("%d is not a leap year.\n", year);
else if ( year%4 == 0 ) {
for(;year!=0;year=year/10){
r=year%10;
sum=sum+r;
}
printf("%d is a leap year and the sum is %d.\n", year_val,sum);
} else
printf("%d is not a leap year.\n", year);
return 0;
}
``````
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download