In this blog post, you will see some programming examples related to the if-else statement (including if, if…else, and nested if..else).
C if…else Statement:
if and if-else in C is a selection statement that is used to select statements depending on the value of a controlling expression.
Syntax:
if ( controlling expression )
statement;
In the above scenario, the statement will only be executed if the controlling expression is non-zero.
Let’s consider an example code.
if ( expression ) statement1 ; else statement2;
In the above scenario, the statement1 will only be executed if the expression is non-zero. if the expression is zero, then statement2 will be executed.
To understand mentioned C programs, you should have knowledge of the following C programming topics:
- if statement in C.
- if-else statements.
- Storage class in C.
- Operator Precedence And Associativity In C.
Example-1: C program to find the greatest number among three numbers
#include <stdio.h> int main(void) { int a, b, c; printf(" Enter the number1 = "); scanf("%d", &a); printf("\n Enter the number2 = "); scanf("%d", &b); printf("\n Enter the number3 = "); scanf("%d", &c); if (a > b) { if (a > c) { printf("\n Greatest number = %d \n",a); } else { printf("\n Greatest number = %d \n",c); } } else if (b > c) { printf("\n Greatest number = %d \n",b); } else { printf("\n Greatest number = %d \n",c); } return 0; }
Output:
Example-2: C program to find out whether a given year is a leap year or not:
An algorithm to check leap year
Algorithm: IF year MODULER 400 IS 0 THEN leap year ELSE IF year MODULER 100 IS 0 THEN not_leap_year ELSE IF year MODULER 4 IS 0 THEN leap_year ELSE not_leap_year
Example code,
#include <stdio.h> int IsLeapYear(int year) { // Function to check leap year. if (year % 4 != 0) return 0; if (year % 100 != 0) return 1; return (year % 400) == 0; } int main() { unsigned int uiYear=0; printf("Enter the year:"); scanf("%u",&uiYear); (IsLeapYear(uiYear)? printf("Leap Year."): printf("Not Leap Year.")); return 0; }
Output:
Enter the year:2016
Leap Year.
For more detail, you can see this article, check leap year
Example-3: C program to convert temperature from Fahrenheit to Celsius and Celsius to Fahrenheit
The basic formula to convert Fahrenheit and Celsius to each other.
Celsius to Fahrenheit: (°C × 9/5) + 32 = °F
Fahrenheit to Celsius: (°F − 32) x 5/9 = °C
#include <stdio.h> int main() { float fh,cl; char ch; printf("\n\n Press c to convert temperature from Fahrenheit to Celsius."); printf("\n\n Press f to convert temperature from Celsius to Fahrenheit."); printf("\n\n Enter your choice (c, f): "); scanf("%c",&ch); if((ch =='c') ||(ch =='C')) { printf("\n\nEnter temperature in Fahrenheit: "); scanf("%f",&fh); cl= (fh - 32) / 1.8; printf("\n\nTemperature in Celsius: %.2f\n\n",cl); } else if((ch =='f') ||(ch =='F')) { printf("\n\nEnter temperature in Celsius: "); scanf("%f",&cl); fh= (cl*1.8)+32; printf("\n\nTemperature in Fahrenheit: %.2f\n\n",fh); } else { printf("\n\nInvalid Choice !!!\n\n"); } return 0; }
Output:
Example-4: C program to check the sign of a given number
The MSB bit of a number defines their sign. If the MSB bit is set, the number will be negative.
#include <stdio.h> int main() { int sign = 0; int data = 0; printf("\n\n Enter the number = "); scanf("%d",&data); //Get the number sign = (data > 0) - (data < 0); // check the sign of the number if(sign == 1) { printf("\n\n Enter number is a positve number\n"); } else if(sign == -1) { printf("\n\n Enter number is a negative number\n"); } else { printf("\n\n Enter number is zero\n"); } return 0; }
Output:
Example-5: Check whether a given number is even or odd
If a number is divided by 2, it means it is an even number. We can also check number is even or odd to check LSB bit. If LSB bit of a number is set that means it is an odd number otherwise even.
Using modular division:
#include <stdio.h> int main(void) { int data; //variable to store data /*Get input from the user*/ printf("\n Enter any number: = "); scanf("%d", &data); /* If number is divisible by 2 then it is a even number */ if((data % 2) == 0) { printf("\n Number is Even.\n\n"); } else { printf("\n Number is Odd.\n\n"); } return 0; }
Output:
Check LSB bit:
#include <stdio.h> int main(void) { int data; //variable to store data /*Get input from the user*/ printf("\n Enter any number: = "); scanf("%d", &data); /* Check LSB bit of the number */ if(data & 1) { printf("\n Number is Odd.\n\n"); } else { printf("\n Number is Even.\n\n"); } return 0; }
Example-6: Check whether the triangle is equilateral, scalene, or isosceles
Before writing the program, we should know the properties of isosceles, equilateral, and scalene triangles.
Isosceles triangle: In geometry, an isosceles triangle is a triangle that has two sides of equal length.
Equilateral triangle: In geometry, an equilateral triangle is a triangle in which all three sides are equal.
Scalene triangle: A scalene triangle is a triangle that has three unequal sides.
#include <stdio.h> int main(void) { int triSide1, triSide2, triSide3; /* Get sides of a triangle from the user */ printf("\n Enter first side of triangle: = "); scanf("%d", &triSide1); printf("\n Enter second side of triangle: = "); scanf("%d",&triSide2); printf("\n Enter third side of triangle: = "); scanf("%d",&triSide3); if((triSide1==triSide2) && (triSide2==triSide3)) { /* If all sides are equal, then Equilateral triangle*/ printf("\n Equilateral triangle.\n\n"); } else if((triSide1==triSide2) || (triSide1==triSide3) || (triSide2==triSide3)) { /* If two sides are equal, then Isosceles triangle*/ printf("\n Isosceles triangle.\n\n"); } else { /* If none sides are equal, then Scalene triangle*/ printf("\n Scalene triangle.\n\n"); } return 0; }
Output:
There are several courses that you may have come across during your search for learning the C language. Our team of experts has carefully analyzed some courses for you. You can check the courses, Trial of some courses is free.
- The C Programming Language in Action (Free Trial Available).
- C Programming For Beginners – Master the C Language.
- Advanced C Programming: Pointers.
Example-7: C program to check whether a character is an alphabet or not
An input character is an alphabet if it lies in between a-z or A-Z.
#include <stdio.h> int main(void) { char cData; //character variable /*Get value from the user*/ printf("Enter any character: "); scanf("%c", &cData); //check range for alphabate if((cData >= 'a' && cData <= 'z') || (cData >= 'A' && cData <= 'Z')) { printf("\n It is an aplhabate.\n\n"); } else { printf("\n It is not an aplhabate.\n\n"); } return 0; }
Using the ASCII value, we can also check the alphabet character.
#include <stdio.h> int main(void) { char cData; //character variable /*Get value from the user*/ printf("\n Enter any character: "); scanf("%c", &cData); //check range for alphabate if((cData >= 97 && cData <= 122) || (cData >= 65 && cData <= 90)) { printf("\n It is an aplhabate.\n\n"); } else { printf("\n It is not an aplhabate.\n\n"); } return 0; }
Output:
Example-8: C program to check vowel or consonant
There are 5 vowels in English alphabets, these are a, e, i, o, u. These vowels can be in uppercase or lowercase.
#include <stdio.h> int main() { char cData; /* Get inpur from the user*/ printf("\n Enter any character: "); scanf("%c", &cData); //check alphabate if((cData >= 'a' && cData <= 'z') || (cData >= 'A' && cData <= 'Z')) { // check for vowel if(cData=='a' || cData=='e' || cData=='i' || cData=='o' || cData=='u' || cData=='A' || cData=='E' || cData=='I' || cData=='O' || cData=='U') { printf("\n It is an vowel.\n\n"); } else { printf("\n It is a consonant.\n\n"); } } else { printf("\n It is not an vowel nor consonant.\n\n"); } return 0; }
Output:
Example-9: Program to print a number of days in a month
#include <stdio.h> //Range of year #define MAX_YR 9999 #define MIN_YR 1900 // Function to check leap year. //Function returns 1 if leap year int IsLeapYear(int year) { return (((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0)); } // returns 1 if given date is valid. int numberDays(int month,int year) { //check range of year if (year> MAX_YR || year < MIN_YR) return 0; //check range of month if (month< 1 || month > 12) return 0; //Handle feb days in leap year if (month == 2) { if (IsLeapYear(year)) return (29); else return (28); } else if (month == 4 || month == 6 || //handle months which has only 30 days month == 9 || month== 11) return (30); return 31; } int main(void) { int year = 0; //variable to store year int month = 0;//variable to store month int ret = 0; printf("\n Enter the year: = "); scanf("%d",&year); printf("\n Enter the month: = "); scanf("%d",&month); //check number of days ret = numberDays(month,year); if(0 == ret) { printf("\n Enter valid month and year"); return 0; } printf("\n Number of days = %d",ret); return 0; }
Output:
Example-10: C program to check whether the triangle is valid or not if angles are given
The angle property of the triangle says that the sum of all three angles should be equal to 180.
#include <stdio.h> int main(void) { int angle1, angle2, angle3, sum; //variable to store angles // Get three angles of triangle from the user printf("\n Enter 1 angles of triangle: = "); scanf("%d", &angle1); printf("\n Enter 2 angles of triangle: = "); scanf("%d", &angle2); printf("\n Enter 3 angles of triangle: = "); scanf("%d", &angle3); //Calculate sum of angles sum = angle1 + angle2 + angle3; //check sum of three angles if(sum == 180 && angle1 != 0 && angle2 != 0 && angle3 != 0) { printf("\n Valid Triangle.\n\n"); } else { printf("\n Not valid Triangle.\n\n"); } return 0; }
Output:
Example-11: C program to check whether the triangle is valid or not if sides are given
A triangle is valid if the sum of its two sides is greater than the third side.
Let’s say that a, b, c is the sides of the triangle. So it must satisfy the below criteria :
- a + b > c
- a + c > b
- b + c > a
#include <stdio.h> int main(void) { int a, b, c, sum; //variable to store angles // Get three sides of triangle from the user printf("\n Enter 1 side of triangle: = "); scanf("%d", &a); printf("\n Enter 2 side of triangle: = "); scanf("%d", &b); printf("\n Enter 3 side of triangle: = "); scanf("%d", &c); //check validity of triangle if((a + b > c) && (a + c > b) && (b + c > a)) { printf("\n Valid triangle.\n\n"); } else { printf("\n Not valid triangle.\n\n"); } return 0; }
Output:
Example-12: C program to check whether a number is a prime number or not
A prime number is a positive natural number, whose value is greater than 1 and has only two factors 1 and the number itself. In other words, the prime number is only divided by itself and 1. Any positive natural number that is not a prime number is called a composite number.
For example,
2,3,5,7,11..
In the above example, 2 is the (smallest) prime number because it has only two factors 1 and 2.
Note: 1 is not a prime or composite number and 2 is the only even prime number.
An algorithm to check prime number using the division method
START
1 → Take the number n
2 → Divide the number n with (2, n-1) or (2, n/2) or (2, sqrt(n)).
3 → if the number n is divisible by any number between (2, n-1) or (2, n/2) or (2, sqrt(n)) then it is not prime.
4 → If it is not divisible by any number between (2, n-1) or (2, n/2) or (2, sqrt(n)) then it is a prime number
STOP
#include <stdio.h> #include <math.h> #define PRIME_NUMBER 1 int IsPrimeNumber(int iNumber) { int iLoop = 0; int iPrimeFlag = 1; int iLimit = sqrt(iNumber); // calculate of square root n if(iNumber <= 1) { iPrimeFlag = 0; } else { for(iLoop = 2; iLoop <= iLimit; iLoop++) { if((iNumber % iLoop) == 0) // Check prime number { iPrimeFlag = 0; break; } } } return iPrimeFlag; } int main(int argc, char *argv[]) { int iRetValue = 0; int iNumber = 0; printf("Enter the number : "); scanf("%d",&iNumber); iRetValue = IsPrimeNumber(iNumber); if (iRetValue == PRIME_NUMBER) printf("\n\n%d is prime number..\n\n", iNumber); else printf("\n\n%d is not a prime number..\n\n", iNumber); return 0; }
Output:
Example-13: C program to enter student marks and find percentage and grade
A college has the following rules for the grading system:
1. Below 25 – F
2. 25 to 45 – E
3. 45 to 50 – D
4. 50 to 60 – C
5. 60 to 80 – B
6. Above 80 – A
Ask the user to enter the mark of 5 subjects and print the corresponding grade.
#include <stdio.h> int main(void) { float subMark[5]= {0}; float per = 0.0; int i = 0; float sum = 0.0; /* Get subject Marks from user */ for(i=0 ; i <5; i++) { printf("\n Enter subject %d marks: ",i); scanf("%f",&subMark[i]); //check validty of marks if(subMark[i]> 100) { printf("\n Enter valid number ! \n"); i--; } else sum += subMark[i]; } /* total marks */ printf("\n total marks = %f\n", sum); /* Calculate percentage */ per = (sum / 500.0)*100; printf("\n Percentage = %.2f\n", per); /*Grade according to the percentage */ if(per >= 80) { printf("\n Grade A"); } else if(per >= 60) { printf("\n Grade B"); } else if(per >= 50) { printf("Grade C"); } else if(per >= 45) { printf("\n Grade D"); } else if(per >= 25) { printf("\n Grade E"); } else { printf("\n Grade F"); } return 0; }
Check MCQ on the if-else statement, Click to Check
Recommended Articles for you:
- How to use if condition.
- C language character set.
- Elements of C Language.
- Data type in C language.
- Online programming tools.
- Operators with Precedence and Associativity.
- How to pass an array as a parameter?
- Memory Layout, you should know .
- File handling, In a few hours.
- Replacing nested switches with the multi-dimensional array
- How to access a two-dimensional array using pointers?
- Brief Introduction of switch case.
- 100 C interview Questions.
- Function pointer, a detailed guide.
- How to use the structure of function pointer in c language?
- Function pointer in structure.
- Pointer Arithmetic operation.
- Brief Introduction of void pointer.