Decision Making Statement | Part-2

Check the year is leap year or not.

#include<stdio.h>
int main() {
	int year;
	printf("Enter any year: ");
	scanf("%d",&year);
	
	if(year % 100 == 0) {
		if (year % 400 == 0) {
			printf("%d is a leap year",year);
		} else {
			printf("%d is not a leap year",year);
		}
	}else {
		if(year % 4 == 0) {
			printf("%d is a leap year",year);
		} else {
			printf("%d is not a leap year",year);
		}
	}
	return 0;
}

Output

Enter any year: 1996
1996 is leap year

Enter any year: 2001
2001 is no a leap year

Enter any year: 1800
1800 is not a leap year

Program Explained

  1. You know the year which is divisible by 4 is called leap year, but what about the century? Each century is divisible by 4. but to check whether the century is a leap year or not we have to check its divisibility by 400. So the logic to check the year is a leap or not:
  2. First check the year is a century if the year is century then check its divisibility by 400. if it is fully divisible by 400 then the century is leap year otherwise not.
  3. If the year is not the century then check its divisibility with 4. if it is divided by 4 then the year is a leap or not.

Check Leap year using Logical operator

if(year%100==0 && year%400==0 || year%4==0)
	printf("%d is leap year",year);
else
	printf("%d is not leap year",year);

Program Snippet Explained

Observe the above program section, first check the year is divisible by 100 then check it is divisible by 400 then the year is a leap year.

But if the year is not a century then its divisibility is checked by 4. it is OK.

But what happens when the year is century but not a leap year, then in the above program snippet its divisibility is checked by 4. That is not ok according to leap year logic. So the above program logic is wrong.

The improvement in the above logic is to ensure that the divisibility by 4 should be checked only in the case when the year is not a century. The improved logic is given below:

if(year%100==0 && year%400==0 || year%100!=0 && year%4==0)
	printf("%d is leap year",year);
else
	printf("%d is not leap year",year);

The above given logic is perfectly OK. But one more improvement can be added that is if year is divisible by 400 then it is also divisible by 100. so no need to check the divisibility by 100.

if(year%400==0 || year%100!=0 && year%4==0)
	printf("%d is leap year",year);
else
	printf("%d is not leap year",year);

Conditional operator

?: are known as conditional operator. This is a shorthand way to deal with conditional statement. These operator are also known as ternary operator because they receive 3 arguments to work.

Syntax of Conditional operator

condition ? statement if true : statement if false;

Syntax explained

In the above given syntax first condition is evaluated and if condition is true then statement if true part is executed otherwise statement if false part is executed.

Example of Conditional operator

max = a > b ? a : b;

In the above example first a>b condition is tested if condition becomes true then a is stored in max otherwise b is stored in max.

a > b ? printf("%d",a) : printf("%d",b);

Above given program snippet shows another way to find the max of two numbers, but the statement print the max.

a > b ? max = a : max = b;

One more way to find the max of two numbers as given in the above statement. When you compile this program the compile shows and syntax error.

The reason for the error is that: enjoy the higher priority than =. The solution of the given error is given below.

a > b ? max = a : (max = b);
So this is a good way to enclose the statement in brackets to avoid the error, while using the conditional statement.
max = a > b ? (a > c ? a : c) : (b > c ? b : c);

The conditional operator can be nested this is shown in the above example. Above example is find the max of 3 numbers a,b,c and the result is stored in max. Trace out the above statement yourself.

switch/case control statement

switch-case control statement is another and fast way to deal with the conditional statement.

Syntax of switch/case statement

switch(switch variable)
{
	case constant-1:
    	statement-1;
        statement-2;
        statement-3;
        ...........;
        ...........;
    case constant-2:
    	statement-1;
        statement-2;
        statement-3;
        ...........;
        ...........;
    case constant-3:
    	statement-1;
        statement-2;
        statement-3;
        ...........;
        ...........;
        
    ...............
    ...............
    ...............
    
    default:
    	statement-1;
        statement-2;
        statement-3;
        ...........;
        ...........;

}

Syntax Explained

The switch variable is matched with each and every case-constant and if case variable value is matched with any constant all the statement written after it are executed.

One more thing is that in the place of switch variable any Integral expression can also be written.

In the above-given syntax note that case contains multiple statements but no need to enclosed in brackets.One more thing you should note that after case constant there is no semicolon(;), there is a colon(:). Don't try to change.

Program: To print the weekday

#include<stdio.h>
int main() {
	int day;
	
	printf("Enter weekday, say(0-6): ");
	scanf("%d",&day);
	
	switch(day) {
		case 0:
			printf("Sunday");
			break;
		case 1:
			printf("Monday");
			break;
		case 2:
			printf("Tuesday");
			break;
		case 3:
			printf("Wednesday");
			break;
		case 4:
			printf("Thrusday");
			break;
		case 5:
			printf("Friday");
			break;
		case 6:
			printf("Saturday");
			break;
		default:
			printf("Invalid input");
	}
	return 0;
}

Limitation of case control statement

  1. case constant can be any Integer constant,character constant. Floating point constant and string constant are not allowed.
    case 5: //ok
    case 'A': //ok
    case 5.7: //wrong
    case "abc": //wrong
    
    
  2. Only constant and constant expression are allowed as a case constant, variable and variable expression are not allowed.
    case 5: // ok
    case 5+9: // ok
    case x: // wrong
    case x+y+5: // wrong
    
    
  3. Duplicate case constants or expressions are not allowed enclosing in same switch statement block.
    case 5: //ok
    case 3+2: // wrong, duplicate of above case 
    case 'A': // ok
    case 65: // wrong, duplicate of above case because A's ascii is 65
    
    
  4. Range is not allowed in the case constant.
    case ch>=65 && ch<=90: //wrong,ch is checked against range 65 to 90. but variable expression is not allowed here.
    case 65-90: // wrong, Interpreted as 65-90(65 minus 90).
    case >=65 && <=90: //wrong, because >=,<= are binary operator.
    
    
Note: switch,case,default,break are the keywords. break and default are optional.

Program: To print the days in a month

#include<stdio.h>
int main() {
	int m,y;
	
	printf("Enter any month, say(1-12): ");
	scanf("%d",&m);
	
	switch(m) {
		case 1:
		case 3:
		case 5:
		case 7:
		case 8:
		case 10:
		case 12:
			printf("31 days");
			break;
		case 4:
		case 6:
		case 9:
		case 11:
			printf("30 days");
			break;
		case 2:
			printf("Enter the year: ");
			scanf("%d",&y);
			if(y%400 == 0 || y%100 != 0 && y%4 == 0) {
				printf("29 days");
			} else {
				printf("28 days");
			}
		break;
		default:
			printf("Invalid input");
	}
	
}

Output

Enter any month,say(1-12): 2
Enter the year: 1998
28 days

Enter any month,say(1-12): 7
31 days

Program: Create a simple calculator

/*create a calculator*/
#include<stdio.h>
#include<math.h>

int main() {
 	int a,b;
 	char ch;
 	
	printf("Enter any choice,say(+,-,*,/,%%,^): ");
	scanf("%c",&ch);	
 
 	printf("Enter any two numbers: ");
 	scanf("%d%d",&a,&b);	
 	
	switch(ch)
 	{
 		case '+':
			printf("Total= %d",a+b);
			break;
 		case '-':
 			printf("Sub= %d",a-b);
 			break;
 		case '*':
 			printf("Multiplication= %d",a*b);	
 			break;
 		case '/':
 			if(b!=0)
 				printf("Division= %.2f",(float)a/b);
 			else
				printf("Error! Divide by zero");
 			break;
 		case '%':
 			if(b!=0)
 				printf("Remainder= %d",a%b);
 			else
 				printf("Error! Div by zero");
 			break;
 		case '^':
 			printf("%d raised to power %d=%d",a,b,(int)(pow(a,b)));
 			break;
 		default:
 			printf("Invalid Input.");
 		}
 	return 0;
}

Output

Enter any choice,say(+,-,*,/,%,^): *
Enter any two numbers: 4 8
Multiplication= 32

Program Explained

  1. In the printf("Enter any choice,say(+,-,*,/,%%,^): ");, look at the double % sign. % sign can't be printed on screen because compiler think it the start of format specifier. To print % on output screen use the double % sign.
  2. To calculate the power caret(^) sign is used for the notation.It is not an operator in c but many other language used it for the power.
  3. The next think that you should observe, printf("%d raised to power %d=%d",a,b,(int)(pow(a,b))); statement. In this statement pow() function is used to calculate the power. This function return the output in double. To convert the output into int. The typecasting is done.
Previous Back to C Programming index Next

Comments

Popular posts from this blog

String in golang

Inline V/S Block Level Element

Arrays in C Language

Data Types in Go language

Printing in C programming

Variable Naming & Scope of Variable

Escape Sequence | Formatted Printing | Interview Questions

Floating point Data types in Go lang

Overview of Go lang

Literals in Java