Page 46 - Modular_V2.0_C++_Flikpbook
P. 46

THE IF…ELSE STATEMENT

                  The if…else statement is used in programming to make decisions. If the condition is True, the
                  program runs the if block. If it is False, the program runs the else block instead. This helps the
                  program choose between two actions based on the condition.

                  The syntax of the if…else statement is given below:

                       if(condition)
                                                                                     Test Expression
                       {
                                                                                                                False
                       Statement 1;
                                                                                           True
                       }
                                                                                       Body of if         Body of else
                       else
                       {
                       Statement 2;                                                  Statement just
                                                                                     below if...else
                       }
                  Some examples of valid if…else statement are:

                  •  if(num1 > num2)
                          cout<< num1 << " is greater than " << num2;
                    else
                          cout<< num2 << " is greater than " << num1;
                  •  if((gender == 'M') || (gender == 'm'))
                          cout<< "You are a male.";
                    else

                          cout<< "You are a female.";
                  Program 2: To show the pass/fail status of a student.

                  #include<iostream.h>
                  #include<conio.h>
                  void main()
                  {
                      clrscr();
                      int marks;

                      cout<< "Enter your total marks: ";
                      cin>> marks;                                           DOSBox 0.74, Cpu speed: max 100% cycles, Frames
                      if(marks > 200)                                     Enter your total marks: 250
                      {                                                   Pass

                          cout<< "Pass";
                      }                                                      DOSBox 0.74, Cpu speed: max 100% cycles, Frames
                      else                                                Enter your total marks: 200
                       {                                                  Fail
                          cout<< "Fail";


                   44
                          Touchpad MODULAR (Ver. 2.0)
   41   42   43   44   45   46   47   48   49   50   51