Using a conditional statement, we output the season. Below are the months with numbers:
12, 1, and 2 – winter,
3, 4, and 5 – spring,
6, 7, and 8 – summer,
9, 10, and 11 – autumn.
Algorithm Implementation
Read the input data.
scanf("%d",&n);Output the answer.
if ((n == 12) || (n == 1) || (n == 2))
printf("Winter\n");
else if ((n >= 3) && (n <= 5))
printf("Spring\n");
else if ((n >= 6) && (n <= 8))
printf("Summer\n");
else
printf("Autumn\n");Algorithm Implementation – Optimal
Reduce the number of conditions.
#include <stdio.h>
int n;
int main(void)
{
scanf("%d",&n);
if ((n == 12) || (n == 1) || (n == 2)) printf("Winter\n");
else if (n <= 5) printf("Spring\n");
else if (n <= 8) printf("Summer\n");
else printf("Autumn\n");
return 0;
}Algorithm Implementation – switch
#include <stdio.h>
int n;
int main(void)
{
scanf("%d", &n);
switch (n)
{
case 1:
case 2:
case 12:
puts("Winter");
break;
case 3:
case 4:
case 5:
puts("Spring");
break;
case 6:
case 7:
case 8:
puts("Summer");
break;
default:
puts("Autumn");
}
return 0;
}Java Implementation
import java.util.*;
public class Main
{
public static void main(String[] args)
{
Scanner con = new Scanner(System.in);
int n = con.nextInt();
if ((n == 12) || (n == 1) || (n == 2))
System.out.println("Winter");
else if ((n >= 3) && (n <= 5))
System.out.println("Spring");
else if ((n >= 6) && (n <= 8))
System.out.println("Summer");
else
System.out.println("Autumn");
}
}Java Implementation – switch
import java.util.*;
public class Main
{
public static void main(String[] args)
{
Scanner con = new Scanner(System.in);
int n = con.nextInt();
switch (n)
{
case 1:
case 2:
case 12:
System.out.println("Winter");
break;
case 3:
case 4:
case 5:
System.out.println("Spring");
break;
case 6:
case 7:
case 8:
System.out.println("Summer");
break;
default:
System.out.println("Autumn");
}
con.close();
}
}