Friday, December 28, 2012

More examples on if-else statements in C++

In my previous post I gave a clear idea about control structures and their usage in C++. In this post I thought to explain some better examples on these control structures.

our target 1:-
Let the user enter a character out of o,b,y, g and display Ammonia for o , Carbon Monoxide for b, Hydrogen for y, oxygen for g. If the user enters any other character other than the given set of characters  display a proper error message. Finally display a good buy message. Also accepts the letters that user enters both in uppercase and lowercase. e.g:- display Ammonia for both o and O.

You may decide that you must use conditional statements to achieve this simple task. Let's see which of them can  be used to give the best solution

using if-else statements

#include<iostream>
using namespace std;
int main()
{
char ch;                                                                              //declare a variable to get user input

cout<<"Input the first letter of the colour of the gas:"; //display message to let the user input
cin>>ch;                                                                             //get the user input to the ch variable

if(ch=='o' ||ch=='O')                                                          //if it is o or O 
cout<<"Ammonia"<<endl;                                              //display Ammonia

if(ch=='b' || ch=='B')                                                          //if it is b or B 
cout<<"Carbon Monoxide"<<endl;                                //display Carbon Monoxide

if(ch=='y' || ch=='Y')                                                          //if it is y or Y
cout<<"Hydrogen"<<endl;                                              //display Hydrogen

if(ch=='g' || ch=='G')                                                         //if it is g or G
cout<<"Oxygen"<<endl;                                                 //display Oxygen

else
cout<<"Invalid character entered,please try again"<<endl;  //else display error message

cout<<"Glad to be of service!"<<endl;                                   //display good buy message

return 0;
}

using if-elseif blocks

#include<iostream>
using namespace std;
int main()
{
char ch;                                                                              //declare a variable to get user input

cout<<"Input the first letter of the colour of the gas:"; //display message to let the user input
cin>>ch;                                                                             //get the user input to the ch variable

if(ch=='o' ||ch=='O')                                                          //if it is o or O 
cout<<"Ammonia"<<endl;                                              //display Ammonia

else if(ch=='b' || ch=='B')                                                  //else if it is b or B 
cout<<"Carbon Monoxide"<<endl;                                //display Carbon Monoxide

else if(ch=='y' || ch=='Y')                                                  //else if it is y or Y
cout<<"Hydrogen"<<endl;                                              //display Hydrogen

else if(ch=='g' || ch=='G')                                                 //else if it is g or G
cout<<"Oxygen"<<endl;                                                 //display Oxygen

else
cout<<"Invalid character entered,please try again"<<endl;  //else display error message

cout<<"Glad to be of service!"<<endl;                                   //display good buy message

return 0;
}

you can examine that both of the above programs work in the same way.

our target 2:-

  1. let the user enter three values for a , b and c
  2. calculate x1 and x2 using the following formulas 


x1=(-b+sqrt(pow(b,2)-4.0*a*c))/(2.0*a)
x2=(-b-sqrt(pow(b,2)-4.0*a*c))/(2.0*a)

   3. If x1 and x2 has logical errors in calculations such as divide by zero or equal to zero, display proper      error messages before calculations (before the running program shows you error messages, you handle them)

    4.Finally, display the value of a, b,c along with the values obtained for x1 and x2

First of all, you have to notice that both the formulas need functions that are available in cmath thus you need to include cmath library to the program.
Next point on how you are going to handle the logical errors. Actually when seeing the formulas you can see that two things may go wrong in calculation

  1. If the denominator becomes zero, then there would be a division by zero error ( since the answer is infinity)
  2. if the value inside the square root (in the numerator) will be a negative number, then the answer will not be a number
to handle the division by zero issue, you can clearly see that the value of a is the only thing to focus. If a is zero, then the denominator will be zero for sure. So, simply check whether the user enters a zero value for a or not.

Now we'll see how the numerator can be a value that is not a number. of course, if b^2 - 4ac results in a negative value, then the square root of it wont be a number. So, if we can check that b^2 < 4ac, then we can  track the error. 

observe the below code.



#include<iostream>
#include<cmath>
using namespace std;
int main()
{
double a,b,c,x1,x2;

cout<<"Enter a value for a :";
cin>>a;

cout<<"Enter a value for b :";
cin>>b;

cout<<"Enter a value for c :";
cin>>c;

x1=(-b+sqrt(pow(b,2)-4.0*a*c))/(2.0*a);
x2=(-b-sqrt(pow(b,2)-4.0*a*c))/(2.0*a);

cout<<"If a= "<<a<<" ,b= "<<b<<" ,c= "<<c<<" then x1= "<<x1<<"and x2= "<<x2<<endl;

return 0;

}

note that in the above code, i have not checked for the logical errors that we have discussed above. I just wanted to show you how the program reacts when they are unhanded by the programmer. Now, we know if we enter a=10, b=5 and c=35, the program should give an error because b^2 is less than 4ac so that it wont be a number. Check the running terminal as shown below










Note that the program is giving -nan  for both x1and x2. -nan means the reslut is not a number.

Now if i enter a=0 and any values for other two, then also my program should show error results like shown below.






Here note that x2 has resulted in -inf   which means the answer is infinity since there is a division by zero.
Finally observe the output if the user enters proper inputs for a, b and c






As you have already understood we should not expect the users of a program to enter correct inputs as always thus we have to do error handling as much as possible. Do you think every user understands the real meaning of -nan and -inf ? No, they are not supposed to understand them either but it's our responsibility to display messages to users in a way that they can understand.

Now see the below code and observe how I have added a couple of code with if-else blocks to handle this simple issue.


#include<iostream>
#include<cmath>
using namespace std;
int main()
{
double a,b,c,x1,x2;

cout<<"Enter a value for a :";
cin>>a;

cout<<"Enter a value for b :";
cin>>b;

cout<<"Enter a value for c :";
cin>>c;

if((2*a)==0)
cout<<"Error! The answer is infinite, Please Retry!"<<endl;

else if((b*b)<(4.0*a*c))
cout<<"Error! The answer is not a Number, Please Try again"<<endl;

else
{
x1=(-b+sqrt(pow(b,2)-4.0*a*c))/(2.0*a);
x2=(-b-sqrt(pow(b,2)-4.0*a*c))/(2.0*a);


cout<<"If a= "<<a<<" ,b= "<<b<<" ,c= "<<c<<" then x1= "<<x1<<"and x2= "<<x2<<endl;
}
return 0;

}
















I'll be posting you a more practical example on multiple selective structure -switch statements in my next blog.











No comments:

Post a Comment