C++ program on determining triangle - c++

I need help with the following code that requires me to:
Declare 3 double type variables, each representing one of three sides of a triangle.
Prompt the user to input a value for the first side, then
Set the user’s input to the variable you created representing the first side of the triangle.
Repeat the last 2 steps twice more, once for each of the remaining 2 sides of the triangle.
Use a series of nested if / else statements to determine if the triangle having side-lengths as set by the user is an EQUILATERAL, ISOSCELES, or SCALENE triangle.
[Note: look to the Wikipedia page on ‘triangle’ for definitions of these three types of triangles.]
Print the resulting triangle type to the console.
Ensure your Triangle detector works by running it 5 times as in the example above. You may use the same values as in the example.
I currently have:
//lab eleven program code on triangles
#include <iostream.h>
main()
{
//variables
float aside, bside, cside;
//enter side a
cout<<"enter the length of side a "<<endl;
cin>>aside;
//enter side b
cout<<"enter the length of side b "<<endl;
cin>>bside;
//enter side c
cout<<"enter the length of side c "<<endl;
cin>>cside;
// all sides equal
if(aside==bside && bside==cside)
cout << "Equilateral triangle\n";
// at least 2 sides equal
else if(aside==bside || aside==cside || bside==cside)
cout << "Isosceles triangle\n";
// no sides equal
else
cout << "Scalene triangle\n";
}
But I need help with the if and else if statements to determine the type triangle. Our professor has not covered this topic in class.
We use the program Ch 6.3 on Windows.

if(a==b && b==c) // all sides equal
cout << "Equilateral triangle\n";
else if(a==b || a==c || b==c) // at least 2 sides equal
cout << "Isosceles triangle\n";
else // no sides equal
cout << "Scalene triangle\n";

As your professor suggested, you should look at:
http://en.wikipedia.org/wiki/Triangle#Types_of_triangles
You should also look at:
http://www.teacherschoice.com.au/maths_library/trigonometry/solve_trig_sss.htm
Algorithm:
Solve for all angles, a1, a2, a3 (see the article above)
If you can't find a solution:
Output "Error: Not a valid triangle"
Else:
If (a1 == a2) && (a2 == a3):
Output "EQUILATERAL" and stop
If (a1 == a2) || (a2 == a3) || (a1 == a3):
Output "ISOSCELES" and stop
Output "SCALENE" and stop
Also note: Be careful about "equality" with floating point (float/double) values (such as angles). If you are doing such a comparison, you should usually use this instead:
abs(x - y) < epsilon
Where epsilon is a "sufficiently small value".

The logic falls out neatly from the definition of these different types of triangles, which as the professor notes, is information readily obtained from Wikipedia. It just involves a simple comparison of side lengths; you don't have to go as far as angles. But I'll give you some help with the "not a triangle" condition. Don't be afraid to put on your math hat here and go wandering in, a little logic isn't a bad thing for a poli sci student to endure every now and then. :-)
For the sides to make a proper triangle, for each pair of sides (I'll call them f and g), they must add up to greater than the third side's length (I'll call it h). If you're dealing with equilateral triangles, you automatically know this condition is met (why?). If you're dealing with isosceles or scalene triangles, you technically only need to check the smaller two sides against the largest side, and if it's true for them, it's true for the other two cases as well (why?). However, it may be just as convenient for you to check all three cases.
Looking at why this inequality has to hold: if the sum of two sides was exactly equal to the third side's length, you'd have a "degenerate" triangle where sides f and g could only lay on top of h! If they added up to less, the two sides could connect to the endpoints of h but then would never meet at a third point! You can test this yourself by cutting lengths of string or strips of paper and trying it out.
Three other things to think about:
In C++, double and float are not the same thing. One has less precision than the other. Make sure you use the one the professor asks for.
Checking to make sure the sides are non-negative is a great idea. You could probably reasonably rule out lengths of 0 as well, to eliminate the possibility of degenerate triangles that just look like line segments or points.
When comparing floating-point numbers, you should always be careful to consider whether a strict equality is going to get you what you want. For checking the equilateral/isosceles/scalene conditions, you're fine because the user is directly entering in the floating-point numbers and you're not manipulating them, so there's no chance for you to introduce error. But when checking the "not a triangle" condition, it's relatively easy to set up a situation where adding the two sides rounds off (because of the vicissitudes of floating-point arithmetic in the CPU) to something that's very close to, but not quite exactly, the third side. In those cases, if you want to catch degenerate triangles, what you usually do is pick an "epsilon" value (some very small value relative to the numbers you're dealing with) that represents the maximum amount of roundoff you're willing to tolerate. You then check whether the sum of f and g is somewhere between h - epsilon and h + epsilon – or put another way, whether the absolute value of f + g - h is less than or equal to epsilon. If it is, you claim that f + g = h (as best as you can tell) and deal with the degenerate case.

To complete this program you will need the following:
Make sure input is valid. In this case, input must be greater than 0. You could catch your input using a loop like
while (invar <= 0)
{
cout<<"Enter length"<<endl;
cin>>invar;
if (invar <= 0)
{
cout<<"invalid input"<<endl;
}
}
I am not sure if this is proper c++ syntax, I haven't used it in about 8 years.
you can do this for all 3 inputs. I would probably make a function to determine the triangle using 3 input variables and 1 return variable. The following is pseudo-code
if (a + b <= c) or (a + c <= b) or (b + c <= a)
{
return "you don't have a triangle."
}
else
{
if (a == b) or (a == c) or (b == c)
{
if (a == b and b == c)
{
return "equilateral"
}
return "isosceles"
}
return "scalene"
}
return -1

#include<stdio.h>
#include<ctype.h>
#include<conio.h>
#include<math.h>
int main()
{
float Side1,Side2,Side3;
float Flag1,Flag2,Sum_of_sq1,Sum_of_sq2,Sum_of_sq3;
clrscr();
printf("Enter Three Sides Side1 Side2 Side3 :");
scanf("%f %f %f", &Side1 , &Side2 , &Side3);
Flag1=(Side1==Side2)?(Side2==Side3?1:0):((Side2==Side3)?0:-1);
if(Flag1==0)
{ printf("Triangle is Isoceles\n");
}
if (Flag1==1)
{ printf("Equilateral Triangle");
}
Sum_of_sq1=pow(Side1,2)+pow(Side2,2);
Sum_of_sq2=pow(Side1,2)+pow(Side3,2);
Sum_of_sq3=pow(Side2,2)+pow(Side3,2);
if (sqrt(Sum_of_sq1)==Side3 ||sqrt(Sum_of_sq2)==Side2 || sqrt(Sum_of_sq3)==Side1)
printf("The Triangle is Right Angled Triangle");
getch();
return(0);
}

#include<iostream>
using namespace std;
//create a class
class Triangle {
//declare three sides for the triangle
double side1;
double side2;
double side3;
public:
//constructor to initialize the data members
Triangle(double s1, double s2, double s3) {
side1 = s1;
side2 = s2;
side3 = s3;
}
void triangleType() {
//all sides equal
if((side1 == side2)&&(side2 == side3))
cout << "It is an Equilateral Triangle" << endl;
//at least two sides are equal
else if((side1 == side2) || (side2 == side3) || (side1 == side3))
cout << "It is an Isosceles Triangle" << endl;
//all are different
else
cout << "It is a Scalene Triangle" << endl;
}
};
int main() {
//local variable
double a_side, b_side, c_side;
//taking the user inputs
cout << "Enter the three sides of a triangle: " << endl;
cin >> a_side >> b_side >> c_side;
Triangle t1(a_side, b_side, c_side); //create an object of Triangle
t1.triangleType(); //call the function
return 0;
}

Related

Determining a valid DNA sequence using recursion

I've been stuck on this problem that I need to solve for a school assignment a quite a while now, over a week and I still don't have any idea of what to do.
DNA forms the building blocks of our genetic sequence. DNA is made up of two chains of nucleotides. Each nucleotide is one of four possibilities:
A - Adenine
T - Thymine
C - Cytosine
G - Guanine
When combined in the DNA Sequence, A and T can bind and C and G can bind. Other combinations are not valid.
For this assignment, you are going to ask the user for two sequences, then return the number of valid pairs by comparing corresponding positions in the sequence. In other words, you will look at the first character in each. If these are an A & T or a C & G, it s a valid pair. You will then move on to the second pair. You can ignore any invalid characters, but you should not assume that the length of the sequences are equal.
I'm not sure how to go about making a recursion statement that would help this assignment. I'm not sure how I would go about finding the base case for this problem and making a function using recursion that gets back to the base case.
#include "util.h"
using namespace std;
int valid(string first, string second)
{
int valid_pairs;
return valid_pairs;
}
int main()
{
string first;
string second;
cout << "Please enter the first sequence: ";
cin >> first;
cout << "Please enter the second sequence: ";
cin >> second;
cout << "Valid pairs: " << valid(first, second) << endl;
return 0;
}
Recursion is mostly a matter of writing down the possible situations and doing The Right Thing for each one in turn.
In your case, those possibilities are
At least one of the strings is empty (in which case there are no pairs at all)
first[0] and second[0] make a valid pair
first[0] and second[0] don't make a valid pair
Since you know that valid(first.substr(1), second.substr(1)) is going to be the number of valid pairs without the two initial characters, you can now write down the solution.
Doing that left as an exercise.
(First writing the function bool is_valid(char c1, char c2)that determines whether two characters make a valid pair will simplify this function.)

How to make my CodeChef solution code faster?

I am a beginner currently in first semester. I have been practising on Code Chef and am stuck at this problem. They are asking to reduce the execution time of my code. The problem goes as follows:
Meliodas and Ban are fighting over chocolates. Meliodas has X chocolates, while Ban has Y. Whoever has lesser number of chocolates eats as many chocolates as he has from the other's collection. This eatfest war continues till either they have the same number of chocolates, or at least one of them is left with no chocolates.
Can you help Elizabeth predict the total no of chocolates they'll be left with at the end of their war?
Input:
First line will contain T, number of testcases. Then the testcases follow.
Each testcase contains of a single line of input, which contains two integers X,Y, the no of chocolates Meliodas and Ban have, respectively.
Output:
For each testcase, output in a single line the no of chocolates that remain after Ban and Meliodas stop fighting.
Sample Input:
3
5 3
10 10
4 8
Sample Output:
2
20
8
My code is as follows:
#include <iostream>
using namespace std;
int main()
{
unsigned int t,B,M;
cin>>t;
while(t--)
{
cin>>M>>B;
if(B==M)
{
cout<<B+M<<endl;
}
else
{
for(int i=1;B!=M;i++)
{
if(B>M)
B=B-M;
else
M=M-B;
}
cout<<M+B<<endl;
}
}
return 0;
}
Assuming that Band Mare different from 0, this algorithm corresponds to one version of the Euclidean algorithm. Therefore, you can simply:
std::cout << 2 * std::gcd(B, M) << "\n";
If at least one of the quantity is equal to 0, then just print B + M.
After realizing that your code was correct, I wondered where could be any algorithmic improvement. And I realized that eating as many chocolate from the peer as one has was in fact close to a modulo operation. If both number are close, a minus operation could be slightly faster than a modulo one, but if one number is high, while the other is 1, you immediately get it instead of looping a great number of times...
The key to prevent stupid errors is to realize that if a modulo is 0, that means that the high number is a multiple of the small one and we must stop immediately writing twice the lower value.
And care should be taken that if one of the initial counts are 0, the total number will never change.
So the outer loop should become:
if(B==M || B == 0 || M == 0)
{
cout<<B+M<<"\0";
}
else {
for (;;) {
if (M < B) {
B = B % M;
if (B == 0) {
cout << M * 2 << '\n';
break;
}
}
else {
M = M % B;
if (M == 0) {
cout << B * 2 << '\n';
break;
}
}
}
}
...
Note: no infinite loop is possible here because a modulo ensures that for example is M > B > 0' after M = M % Byou will haveB > M >= 0and as the case== 0` is explicitely handled the number of loops cannot be higher than the lower number.

Branching statements doesn't work? Giving me a negative answer when it's supposed to be positive

This is a class assignment that I can't seem to figure out. The assignment tells us to prompt a user for 2 numbers, those numbers each represent the radius of 2 separate circles. We are then supposed to find the difference between the areas of these circles by subtracting the smaller area from the larger.
I have been fine up to that part, sometimes it works other times it doesn't, but I have been testing it with the numbers 3 and 4, which gives me the areas of 9.42477 and 12.56632 respectively. But the difference keeps coming out as -3.14... and none of the answers are supposed to be negative if you're subtracting the smaller number from the larger number.
#include <stdio.h>
double areaOfCircle(double radius)
{
return radius * 3.14159;
}
int main()
{
double Num1;
double Num2;
printf("Type in a number: ");
scanf("%lf", &Num1);
printf("Type in a second number: ");
scanf("%lf", &Num2);
double areaOfCircle1 = areaOfCircle(Num1);
double areaOfCircle2 = areaOfCircle(Num2);
double areadifference = 0;
// this is where youre supposed to subtract
// the area of the smaller circle form the area of the
//larger circle, but I keep getting a negative number
// when using the numbers 3 (Num1) and 4 (Num 2)
// should a;ways be a postive number or 0.
if (areaOfCircle1 < areaOfCircle2)
{
areadifference = areaOfCircle2 - areaOfCircle1;
}
else (areaOfCircle1 > areaOfCircle2)
{
areadifference = areaOfCircle1 - areaOfCircle2;
}
printf("The difference between the areas is: %lf\n", areadifference);
return 0;
}
Your area calculation is wrong, area of circle is pir^2, but you have pir. And if you had checked what your area values came out as you would have seen that.

How to deal with overlapping values in c++?

I'm currently trying to solve a programming problem that involves different ranges of values that overlap. The task is to accept input, in E-notation, and that is where the overlap of range inevitably occurs.
I have 2 ranges that overlap at 1E-11. 1E-11 and lower and 1E-11 and higher
The output would be 1E-11 is either x or it is y. Programmatically i would solve it like this:
(X_MIN would be 1E-11 and X_MAX 1E-8)
(Y_MAX would be 1E-11 and Y_MIN 1E-13)
(lengthOfRange <= X_MIN) && (lengthOfRange >= Y_MAX) ?
cout << "This value entered indicates that it is x\n" :
cout << "It is y";
Expressed this way if i input IE-11 it shows me "This value entered indicates ..." but will never show me it is y (understandably - overlap!)
The other way around would be expressing it this way:
(lengthOfRange <= X_MIN) && (lengthOfRange != Y_MAX) ?
cout << "This value entered indicates that it is x\n" :
cout << "It is y";
The output would always be "... It is y ..." (Same difference - overlap!) There is no other determining factor that would tell range is x or y coming in to play there as of right now.
...
if (lengthOfRange <= X_MIN) && (lengthOfRange == Y_MAX)
{
cout << "The input indicates that it could be either x or y\n";
}
...
Even if i were to solve the problem in a way such as defining the range with different values, would in the end lead to the very same problem. I COULD define MIN and MAX as constants in lengthOfFrequency, which is totally different, bit then i would have to say: lengthOfFrequency = 1E-11; and voila same problem once again. 1 input 2 ranges that are technically different, getting the same one and only correct value in E-notation.
Is there a way around this without involving to simply say input is either x || y? Which it is technically of course, and if it were to be solved physically there are ways of telling it apart that 1E-11 is not 1E-11 though it is. (I hope i make sense here). But, again, ... is there such way, and how would i go about writing it? (Not asking for code specifically though it would be highly welcome, just a pointer in the right direction.) Or should i rather go with saying input is either x || y?
Thanks in advance for any answer!
**Minimum Complete Code:**
#include <iostream>
using std::cout;
using std::cin;
int main()
{
/* Constants for ranges, min and max */
const double X_RAYS_MIN = 1E-13,
X_RAYS_MAX = 1E-11,
Y_RAYS_MIN = 1E-11,
Y_RAYS_MAX = 1E-8,
Z_RAYS_MIN = 1E-7,
Z_RAYS_MAX = 3.8E-7;
double lengthOfRange;
/* Test output and validation */
cout << "Enter value in scientifc notation: ";
cin >> lengthOfRange;
/* X_RAYS_MIN < is 1E-14, 1E-15, 1E-16 etc. > 1E-12, 1E-11 etc.. */
if (lengthOfRange >= X_RAYS_MIN && lengthOfRange <= X_RAYS_MAX)
{
cout << "X_RAYS\n";
}
else if (lengthOfRange >= Y_RAYS_MIN && lengthOfRange <= Y_RAYS_MAX)
{
cout << "Y_RAYS\n";
}
system("pause");
return 0;
}
Output is: 1E-10 is Y_RAYS, 1E-9 is Y_RAYS, 1E-11 X_RAYS, 1E-12 X_RAYS
Somehow i found the solution for my problem myself without going any roundabout ways ... By hovering over the 1E-13:
X_RAYS_MIN = 1E-13
VS showed me 1.(numberofzeros)3E-13, and guess what ... if instead the input for 1E-11 is 2E-11, the output for X_RAYS becomes Y_RAYS ... so the problem "magically" solved itself ... lucky me i guess ... :)

If-else statement in c++

i have a problem with the next question, i need to solve it by using if/else, i wrote the code but i don't know if it's the solve of the question or not:
Write a program in which the user enters the coordinates of the black pawns (a, b) on the chessboard.
The program must determine whether the pawn may move to get to one field (c, d):
1. In the ordinary move;
2. When it "hit" piece or pawn opponent.
Note: Black pawn move on the board from the bottom up.
char CoordinY;
int CoordinX;
if (CoordinY > 'b' && CoordinX <= 1 && CoordinX>8)
{
cout << "Error . . . \n";
}
else
{
if (CoordinX >= 2 && CoordinX <= 8 && CoordinY == 'a' || CoordinY == 'b'*)
{
// arbitrary move:
cout << "will not get to the field (c, d) in the ordinary move.\n";
// when it "hits" enemy's figure or pawn
cout << "will not get to the field (c, d) when ше hit a figure or pawn opponent.\n";
}
else if (CoordinX>1 && CoordinX < 8 && CoordinY == 'b')
{
// arbitrary move
cout << "will not get to the field (c, d) in the ordinary move.\n";
// when it "hits" enemy's figure or pawn
cout << "will not get to the field (c, d) when it hit a figure or pawn opponent.\n";
}
In the answer I assume the following classic chess board and the fact that I am moving white pawn:
It is important because in your problem definition, blacks are moving bottom up, which is incorrect.
In my example, I will use the following variables:
char a, c; int b, d; // E2 - E4 is: a = 'e', b = 2, c = 'e', d = 4.
Arbitrary move
Where can a pawn go with an arbitrary move in chess?
One step ahead
Two steps ahead if it is standing at row 2
So, in general, a pawn at (a; b) can move to (c; d), if they stand in the same row (a == c) AND if it is one step ahead or two steps ahead for b equal to 2.
So, let's implement it:
if (a == c && (d - b == 1 || (d - b == 2 && b == 2)))
cout << "Abitrary move: YES";
} else {
cout << "Arbitrary move: NO";
}
Attack
A pawn can move with an attack if only an enemy is standing in the next row, one cell to the left or to the right:
if ((c == a + 1 || c == a - 1) && (d - b == 1))
cout << "Attack: YES";
} else {
cout << "Attack: NO";
}
Note that this solution is not working for the case which is called en passant (is it more well-known as "битое поле" or "взятие на проходе" in Russian).
This is a solution in pseudocode:
if (d == b - 1) // destination is one square up
if (c == a) // pawn is on a square in the same column as destination
return true; // yes, pawn can move forwards to destination
if (c == a - 1 || c == a + 1) // destination is one square to left or right
return true; // yes, pawn can take a white pawn to move to destination
end if
return false
First we do the check which is true for both cases... is the destination only one step in front (note that in chess pawns can also move two squares on their first turn, but you didn't request that solution so I haven't added it)?
Next we check if the move is either straight ahead, or diagonal.
You might want to check that a,b c,d are all valid chess coordinates to start with, which would prevent illegal moves being marked as ok.
Edit: also I'm assuming that the bottom of the board has a larger 'y' coordinate than the top. If the coordinates are reversed you would check for b + 1 in the first conditional.