Skip to main content

if else statement, sample programs and programs to try

If else statement
It is a decision making statement in C programming language which allows the program to test for oneor more condition(boolean value) and execute set of statements depends on the condition.The statement in the if block is executed if the condition is evaluated to be true.If the condition is false the statements in the else block will be executed.
Syntax:
if  ( condition)
 {
    statements in if block
 }
else
{
 statements in else block
}
  


Note: in C zero and null values are treated as false any other non zero or non null values are true.
the else part is optional.
example :
#include<stdio.h> 
int main() 
int num;
printf("Enter a number \n");
scanf("%d",&num);
if(num<10) 
    { printf("The value is less than 10"); } 
else 
    { printf("The value is greater than 10"); } 
return 0; 
}
if else if statement
An if statement can be followed by an optional else if...else statement, which is very useful to test various conditions using single if...else if statement.


When using if...else if..else statements, there are few points to keep in mind −
  • An if can have zero or one else's and it must come after any else if's.
  • An if can have zero to many else if's and they must come before the else.
  • Once an else if succeeds, none of the remaining else if's or else's will be tested.
Syntax

The syntax of an if...else if...else statement in C programming language is −
if(boolean_expression 1) 
    { /* Executes when the boolean expression 1 is true */ } 
else if( boolean_expression 2) 
    { /* Executes when the boolean expression 2 is true */ } 
else if( boolean_expression 3) 
    { /* Executes when the boolean expression 3 is true */ } 
else 
    { /* executes when the none of the above condition is true */ }

Note: Multiple condition can also be tested using logical operators AND (&&) OR (||) and NOT (!)

Example:
#include<stdio.h>
int main()
{
int marks;
printf("Enter marks\n");
scanf("%d",&marks);

if(marks>75)
        printf("First class"); }

else if(marks>65)
        { printf("Second class"); }
else if(marks>55)

        { printf("Third class"); }
else

    { printf("Fourth class"); }
return 0;
}

Nested if else statement


It is always legal in C programming to nest if-else statements, which means you can use one if or else if statement inside another if or else if statement(s).

Syntax

The syntax for a nested if statement is as follows −
if( boolean_expression 1) 
    { /* Executes when the boolean expression 1 is true */
             if(boolean_expression 2) 
                    { /* Executes when the boolean expression 2 is true */ }
             else
                     { /* Executes when the boolean expression 2 is false */ }
  }
else
{
   /* Executes when the boolean expression 1 is false */
  }
 Example:
 #include<stdio.h> 
int main() 
{ int num;
 printf("Enter a number\n");
scanf("%d",&num);
if(num<10) 
{      if(num==1) 
        { printf("The value is:%d\n",num); }
     else 
        { printf("The value is greater than 1"); } 
 } 
else 
    { printf("The value is greater than 10"); } 
 return 0; 
}

Summary
  • Decision making or branching statements are used to select one path based on the result of the evaluated expression.
  • It is also called as control statements because it controls the flow of execution of a program.
  • 'C' provides if, if-else constructs for decision-making statements.
  • We can also nest if-else within one another when multiple paths have to be tested.
  • The else-if ladder is used when we have to check various ways based upon the result of the expression.

Sample Programs

Check whether the given number is even or odd.

#include <stdio.h>
main()
{
long int n;
system("clear");
printf("Enter the number\n");
scanf("%ld",&n);
if(n%2==0)
  {
  printf("the number is even\n");
  }
else
  {
  printf("the number is odd\n");
  }
}
Check whether the given character is vowel or not
#include <stdio.h>
main()
{
char c;
system("clear");
printf("Enter a character\n");
scanf("%c",&c);
if(c=='a' || c=='e' || c=='i' || c=='o'||c=='u')
  {
  printf("vowel character\n");
  }
else
  {
  printf("not vowel\n");
  }
 }
 Read length of 3 sides and check whether it forms a triangle.
#include <stdio.h>
main()
{
int a,b,c;
system("clear");
printf("Enter three sides \n");
scanf("%d%d%d",&a,&b,&c);
if(a+b>c && b+c >a && a+c >b)
  {
  printf("the sides will form a triangle\n");
  }
else
  {
  printf("cannot form a triangle\n");
  }
}
check the quadrant of given point
#include <stdio.h>
main()
{
int x,y;
system("clear");
printf("Enter the point\n");
scanf("%d%d",&x,&y);
if(x>0 && y>0)
  {
  printf("first qudrant\n");
  }
else if ( x<0 && y>0 )
  {
  printf("second qudrant\n");
  }
 else if (x<0 && y<0 )
  {
   printf("third qudrant\n");
   }
 else if ( x>0 && y <0 )
 {
   printf("fourth quadrant\n");
 }
else
    {
   printf("the point is at origin\n");
     }
}

biggest of 3 numbers
#include <stdio.h>
main()
{
int a,b,c;
system("clear");
printf("Enter three numbers\n");
scanf("%d%d%d",&a,&b,&c);
if(a>b && a>c)
 { printf("biggest=%d\n",a);}
else if(b >a && b >c)
  {printf("biggest=%d\n",b);}
else
  {printf("biggest=%d\n",c);}
}
 
Roots of a quadratic equation/
The standard form of a quadratic equation is:

ax^2 + bx + c = 0, where
a, b and c are real numbers and
a != 0

The term b^2-4ac is known as the discriminant of a quadratic equation. It tells the nature of the roots.

    If the discriminant is greater than 0, the roots are real and different.
    root1=(-b+sqrt(discriminant))/(2*a) root2=(-b-sqrt(discriminant))/(2*a)

    If the discriminant is equal to 0, the roots are real and equal.
    root1=-b/(2*a) root2=-b/(2*a)

    If the discriminant is less than 0, the roots are complex and different.
    realpart=-b/(2*a) imagpart=sqrt(-discriment)/(2*a)
    root1=realpart+imagpart i  root2= realpart+ imagpart i
*/
#include <math.h>
#include <stdio.h>
int main() {
    double a, b, c, discriminant, root1, root2, realPart, imagPart;
    printf("Enter coefficients a, b and c: ");
    scanf("%lf %lf %lf", &a, &b, &c);

    discriminant = b * b - 4 * a * c;

    // condition for real and different roots
    if (discriminant > 0) {
        root1 = (-b + sqrt(discriminant)) / (2 * a);
        root2 = (-b - sqrt(discriminant)) / (2 * a);
        printf("root1 = %.2lf and root2 = %.2lf\n", root1, root2);
    }

    // condition for real and equal roots
    else if (discriminant == 0) {
        root1 = root2 = -b / (2 * a);
        printf("root1 = root2 = %.2lf;\n", root1);
    }

    // if roots are not real
    else {
        realPart = -b / (2 * a);
        imagPart = sqrt(-discriminant) / (2 * a);
        printf("root1 = %.2lf+%.2lfi and root2 = %.2f-%.2fi\n", realPart, 
         imagPart,           realPart, imagPart);
    }

    return 0;


Try the following program using if else
1)Compare two numbers( a==b , a>b or b>a)
2)Check whether the given number is even or odd.
3)Find the biggest of 3 numbers(use if else if)
4)Read internal marks( out of 50) and external mark( out of 100) and print passed /failed in internal or external or failed in both.( use KTU criteria..45% for pass)
5)Check whether the given number is zero, positive or negative.
6)Find the roots of a quadratic equation ( ax^2+bx+c)Test the program using the following sets of data:
a  b  c
2 6 l
3 3 0
1 3 1
0 12 -3
3 6 3
2 -4 3
7)Read length of 3 sides and check whether it forms a triangle.
(All you have to do is use the Triangle Inequality Theorem, which states that the sum of two side lengths of a triangle is always greater than the third side. If this is true for all three combinations of added side lengths, then you will have a triangle.)
8)Check the type of a triangle after reading the three sides ( scalene, isosceles, equilateral)
9) Check the type of a triangle after reading the three vertices ( scalene, isosceles, equilateral)

Note:
From the vertices length of the sides can be computed using the distance formulae.
A scalene triangle is a triangle that has three unequal sides.
An isosceles has two equal sides and two equal angles.
An equilateral triangle is a triangle with all three sides of equal length and also has three equal 60 degree angles.

10) Read a mark ( out of 100) and print the corresponding grade.
Percentage Range Grade
>=90 O
>=85 and <90 A+
>= 80 and <85 A
> =70 and <80 B+
> =60 and <70 B
> =50 and <60 C
>=45 and <50 P
<45 F
11) An Employee's total weekly pay equals the hourly wage multiplied by the total hours worked plus any overtime pay.Overtime pay equals the total overtime hours multiplied by 1.5 times the hourly wage.More than 40 hours/week of working time is considered to be overtime.

Write a C Program that takes as inputs hourly wage and total hours worked in the week and displays an employee's total weekly pay.
12)Check whether a given year is Leap Year or not. A year is leap year if following conditions are satisfied
    1) Year is multiple of 400
    2) Year is multiple of 4 and not multiple of 100.
13)Write a program to check the quadrant of a given point(x,y).
14)Write a program to get the absolute value of number without using the abs() function
15)Write a program that accepts the length of three sides of a triangle as input and determine whether or not the triangle is a right triangle
16)Given three points (x1,y1 ) ,(x2,y2) and (x3,y3), check whether they form a triangle.
17.Check whether the given character is upper case or lower case.
18.Check whether a number is divisible by 3 and 5.Program must produce the following output ( use if else if)
  output: divisible by 3 and 5
               divisible by 3 only
               divisible by 5 only
               not divisible by 3 and 5
19.Find the biggest of 3 numbers ( use nested if)
20.Read the age and print the following ( use nested if)
age <18 Minor
age >=18 and age <45 eligible for vaccine in the second phase
age >=45 senior ..eligible for vaccine in the first phase.
        


Comments

  1. I'll talk aboutData Types in C Language with examples in this article. What C data types are, what they look like, and when and how to utilize them . Data types are declarations for variables. This determines the type and size of data associated with variables. In this tutorial, you will learn about basic data types such as int, float, char, etc. in C programming.

    ReplyDelete
  2. To carry out actions based on a given circumstance, anif-else statement in C  is utilized. This Scaler Topics article explains how to implement the decision-making process in C using if-else statements. C if else statement - An if statement can be followed by an optional else statement, which executes when the Boolean expression is false.

    ReplyDelete

Post a Comment

Popular posts from this blog

KTU Mandatory C programs for Laboratory and Solutions

LIST OF LAB EXPERIMENTS 1. Familiarization of Hardware Components of a Computer 2. Familiarization of Linux environment – Programming in C with Linux 3. Familiarization of console I/O and operators in C     i) Display “Hello World”     ii) Read two numbers, add them and display their sum     iii) Read the radius of a circle, calculate its area and display it 4. Evaluate the arithmetic expression ((a -b / c * d + e) * (f +g))   and display its solution. Read the values of the variables from the user through console 5. Read 3 integer values, find the largest among them. 6. Read a Natural Number and check whether the number is prime or not 7. Read a Natural Number and check whether the number is Armstrong or not 8. Read n integers, store them in an array and find their sum and average 9. Read n integers, store them in an array and search for an element in the    array using an algorithm for Linear Search 10.Read n integers, store them in an array and sort the elements in t

PROGRAMMING IN C KTU EST 102 THEORY AND LAB NOTES

PROGRAMMING IN C  KTU  EST 102  THEORY AND LAB   COMMON FOR ALL BRANCHES About Me Syllabus Theory Syllabus Lab Model Question Paper EST 102 Programmin in C University Question Papers  and evaluation scheme   EST 102 Programming in C  Introduction( Lab) Introduction to C programming Linux History and GNU How to create a bootable ubuntu USB stick Installing  Linux Install Linux within  Windows Virtual Box and WSL Linux Basic Features and Architecture Basic Linux Commands Beginning C Programming Compiling C programs using gcc in Linux Debugging C program using gdb Module 1: Basics of computer hardware and software          Module-1 Reading Material Basics of Computer Architecture Hardware and Software System Software and Application Software  Programming Languages ( High level, Low level and Machine Language) and Translators ( Compiler, Interpreter, Assembler) Algorithm, Flowcharts and Pseudo code Program Development Structured Programming Basics of hardware ( video) Know about Motherboar

Arrays in C-single and multi dimensional arrays- list and matrix

An array is a collection of data items, all of the same type, accessed using a common name. A one-dimensional array is like a list(vector); A two dimensional array is like a table(matrix). We can have more dimensions. Always, Contiguous (adjacent) memory locations are used to store array elements in memory. Elements of the array can be randomly accessed since we can calculate the address of each element of the array with the given base address and the size of the data element. Declaring  Single Dimensional Arrays Array variables are declared identically to variables of their data type, except that the variable name is followed by one pair of square [ ] brackets for mentioning dimension of the array.  Dimensions used when declaring arrays in C must be positive integral constants or constant expressions.  In C99, dimensions must still be positive integers, but variables can be used, so long as the variable has a positive value at the time the array is declared. ( Space is allo