back


The Basic Nature of an IF STATEMENT

One of the most fundamental concepts in programming is the IF ELSE STATEMENT.
In C++ you write one like this:


	if(some condition)
           {
	     Do Something;
	    }
	else
	    {
	     Do Something Else;
            }
	


Let's say you created an INT variable named age by typing:

int age; You could write a simple program like this:

	cout<<"How old are you?";
	cin>>age;
	if(age<21)
	   {
 	     cout<<"Can I see your ID?";
            }
	 else
	    {
	      cout<<"How can I help you today?";
	     }


Tons of programs are based on simple IF ELSE statements.

The basic mathematical symbols apply: <,>,<=,>=,in addition C++ uses || to mean "or" and "&&" to mean "and."

You have to be careful about your use of parenthesis.
For example if you had a question where you wanted the user to be at least 21 and have worked five years or be at least 30, you would write your IF statement like this:

	if((age>=21 && YearsOnJob>=5)||(age>30))
		{
		  cout<<"Something...";
		}
	else
		{
		  cout<<"Something else...";
		}

Assignment: You are writing a program to see if someone can retire. The criteria is as follows. The user can retire if any of the following conditions are met:

  • they are over the age of 65
  • they are over 60 and they have over 30 years of service
  • they are over 55 and they have over 35 years of service
Start by declaring the following int variables:
  • age
  • YearsOfService