C++: Learning the Basics – Introduction to IF LOOP

Situation #1: User types in a number and the program displays whether it is odd or even.

Code:

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

     int num;

     cout<<"\n\t Enter number: ";             cin>>num;

     if (num%2==0) 
     { 
            cout<<"\n\t Even "; 
     } 
     else 
     { 
            cout<<"n\t\ Odd"; 
     }
}

Important notes:

  • If and else conditions have their own brackets.

 

Situation 2: User types two numbers and the program displays the largest.

#include <iostream.h> 
#include <conio.h> 
void main() 
{ 
   clrscr();
   int num1, num2;
   
   cout<<"\n\t Enter a number: ";
   cin>>num1;

   cout<<"\n\t Enter another number: ";
   cin>>num2;

   if (num1>num2)
   {
       cout<<"\n\t The largest number is "<<num1;
   }
   else
   {
       cout<<"\n\t The largest number is "<<num1;
   }
   getch;
}

Situation #3: User types in their age and the programs displays whether the person is a minor or an adult.

#include <iostream.h> 
#include <conio.h> 
void main() 
{ 
   clrscr();
   int age;
   
   cout<<"\n\t Enter age: ";
   cin>>age;
   
   if (age>18)
   {
        cout<<"\n\t Adult ";
   }
   else
   {
        cout<<"\n\t Minor ";
   }
   getch;
}

 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s