If Else Structure in C/C++

If Else Structure in C/C++

example if else structure c c++

If else structure comes under selection looping structure. When a programmer wants compiler to select one of the two alternatives available, programmer can use if else structure. We can also use if statement without else statement. If else structure reduces the length of the code. It is an alternative to switch case. Let’s see an example of if else structure in C/C++.

Example – Write algorithm and program to compare two numbers using if else structure.

1. Algorithm

1. START
2. PRINT "ENTER TWO NUMBERS:"
3. READ a,b
4. IF a>b THEN
        PRINT "FIRST NUMBER IS GREATER"
   ELSE
        PRINT "SECOND NUMBER IS GREATER"
   [END OF IF]
5. STOP

2. Code

C code

//compare two nos in C++
#include <stdio.h>

int main()
{
  int a,b;
  printf("\n Enter 2 nos:");
  scanf("%d%d",&a,&b);

  if(a > b)
  {
    printf("\n First no is greater");
  }
  else
  {
    printf("\n Second no is greater");
  }

  return 0;

}

C++ code

//compare two nos in C++
#include <iostream>

using namespace std;

int main()
{
  int a,b;
  cout<<"\n Enter 2 nos:";
  cin>>a>>b;

  if(a > b)
  {
    cout<<"\n First no is greater";
  }
  else
  {
    cout<<"\n Second no is greater";
  }

  return 0;

}

3. Output

output for If Else Structure example C C++
output for If Else Structure example C C++

4. Program Parts

1. #include is a pre-processor directive. It is used to include header files.
2. stdio/iostream is header file which has certain commands that c/c++ supports. E.g. return, main, etc.
3. .h is an extension for header file.
4. int is data type. It indicates that the program returns a value.
5. main() is main function that indicates the compiler that the user written programs starts from here.
6. printf/cout is the keyword use to print a message.
7. scanf/cin is the keyword use to store values in variables.
8. return statement is use to return a value. If any error occurs the program will return 0.

5. Explanation

At first compiler will check header files. If required header files are present then the compiler will enter main function. First, two variables are declared a and b on integer data type. The compiler then asks user to enter two numbers. Now if condition is checked. If the condition is true i.e. a is greater than b then “First number is greater is printed”. Else compiler will print “Second number is greater”. And finally program execution will terminate.

Conclusion

So this was the example of if else structure in C/C++. There are many other possible ways to find greatest number. If you know any of them do tell us in the comment section below. Hope you liked it. If yes then please do share it with your friends and programming buddies. Also tell us what other programs you would like us to post.

For more such content follow us on instagram. Visit again!

ErrorFreeProgram.

3 COMMENTS

Leave a Reply

Your email address will not be published. Required fields are marked *