# Small program using "if" and some variables assistance.

Show 80 post(s) from this thread on one page
Page 1 of 3 123 Last
• 01-20-2012
Pielord
Small program using "if" and some variables assistance.
First off: HI! :D Been lurking on here for a while now and decided to join at last. Love the site btw.

Anyway, I started the tutorial a day or two ago and took a shot at my first program. The goal is that I will be able to pick a shape and then input various measurements and the program will then take these and work out area, volume, etc using what equations I add.

My little program so far looks like this:
Code:

``` #include <iostream> using namespace std; int main() {     int shape;     float PI = 3.141592654;     float radius;     float length;     float height;     float diameter;     float width;     float area;     float volume;     float base;   cout << "Please choose a shape by typing its corresponding value and pushing enter:\n1-circle\n2-square\n3-triangle\n";   cin >> shape;   cin.get();   if ( shape==1 ) {   cout << "Type in the radius\n"; //circle   cin >> radius;   float area=(radius + radius) * PI;   cout << "Area: ";   cout << area;   cout << "cm squared";   cin.get();   }   else if ( shape==2 )  {   cout << "square\nVolume:\nArea:\n"; //square   }   else if ( shape==3) {   cout << "Type in the perpendicular height\n"; //triangle   cin >> height;   cout << "\n";   cout << "Type in the length of the base\n";   cin >> base;   float area=0.5*(base*height);   cout << "Area: ";   cout << area;   cout << "cm squared\n";   cin.get();   }   else {   cout << "Unrecognised shape";   }   cin.get(); }```
I've just added a little bit of content here and there to test everything and after it works well I can obviously tweak it.
My first problem is that I cannot loop the program block. For example if someone inputs a shape that isn't supported and the cout "Unregistered shape" is prompted, I want the program to then reset back to the start of the main() rather than having to restart the whole program window again.
My other problem is that at the start when the user is prompted to pick a shape, I had to use a number to represent each variable instead of being able to just allow the input "circle" (for example) which would activate the next line of corresponding coding. I have read about strings and i tried the #include strings but I still can't get it to see the circle as a 1 or something which I can use in the "if" section.
(sorry that this is so long-winded, after reading the warnings prior to entering the message board section i'm terrified of under explaining myself thus invoking the wrath of the pro c++ pplz who are fed up with this kind of thing...I really have been looking things up and cannot come up with a solution, also skimmed ahead in the tutorial since i'm only on loops/functions and didn't find what I needed)
My final problem will arise after I figure out the looping program problem because the area, etc "float" variables will have been made to = something, will that mess up the next equations?
Thank you in advance. (Everyone seems to say that, sry if its presumptuous)
• 01-20-2012
hk_mp5kpdw
Quote:

Originally Posted by Pielord
My first problem is that I cannot loop the program block. For example if someone inputs a shape that isn't supported and the cout "Unregistered shape" is prompted, I want the program to then reset back to the start of the main() rather than having to restart the whole program window again.

So implement a loop around your code starting just before you ask the user for the shape and encompasing your if/else-if/else logic. Probably a do-while loop would work well here.

Quote:

My other problem is that at the start when the user is prompted to pick a shape, I had to use a number to represent each variable instead of being able to just allow the input "circle" (for example) which would activate the next line of corresponding coding. I have read about strings and i tried the #include strings but I still can't get it to see the circle as a 1 or something which I can use in the "if" section.
Show your code where you tried to use strings. We'll help you out. Should be relatively straight forward.

Quote:

My final problem will arise after I figure out the looping program problem because the area, etc "float" variables will have been made to = something, will that mess up the next equations?
Huh??? I don't get what you're asking here? I have noticed you are creating extra variables within your if/else-f blocks that seem to override the ones in main. You probably don't need those.

Code:

```  if ( shape==1 ) {   cout << "Type in the radius\n"; //circle   cin >> radius;   float area=(radius + radius) * PI;   cout << "Area: ";   cout << area;   cout << "cm squared";   cin.get();   }```
That's not how you calculate the area of a circle. You are calculating PI * 2R instead of PI*R2.
• 01-20-2012
Pielord
I have to say I am flabbergasted as to how fast that reply was (In a good way ;p) and I facepalmed a handprint onto my forehead when I saw the basic geometry mistake, ty for pointing that out lol. I was looking into some other 3D shape examples and scrapped them after trying the coding because I couldn't figure out how to add the superscript/power/exponent part, so I assumed I couldn't do it on codeblocks or something. Could you please tell me how you did that?
I'll look into loop section again and remake my strings code section ASAP, also I think I see what you mean by the redundant variables I repeated in a way and i'll look into that too, if so then my third question is null anyway. TY!

EDIT: (Yay the loop worked. Thanks (again)! No idea why I hadn't implemented it before, I knew about it but I just didn't seem to click)
• 01-20-2012
hk_mp5kpdw
The superscript is just for the purpose of the post, you don't put superscript in actual code to indicate raising something to a specific exponent. In actual code, raising something to a power can be done with the pow function.

Code:

`area = PI * pow(radius,2.0);`
...or for this particular case it's easy enough for you to just multiply radius by itself:

Code:

`area = PI * radius * radius;`
• 01-20-2012
Pielord
Here's the tweaked program:

Code:

``` #include <iostream> using namespace std; int main() {     char circle[7];     char square[7];     char triangle[9];     int shape;     int x;     float PI = 3.141592654;     float radius;     float length;     float height;     float area;     float base;     do {   cout << "Name a shape you want the area for:\n";   cin.getline ( circle, 7 );   cin.getline ( square, 7 );   cin.getline ( triangle 9 );   if ( circle) {   cout << "Type in the radius\n"; //circle   cin >> radius;   float area=radius * radius * PI; //special thanks to hk_mp5kpdw here xD   cout << "Area: ";   cout << area;   cout << "cm squared\n";   cin.get();   }   else if ( square )  {   cout << "Type in the length of a side\n"; //square   cin >> length;   float area=length*length;   cout << "Area: ";   cout << area;   cout << "cm squared\n";   cin.get();   }   else if ( triangle) {   cout << "Type in the perpendicular height\n"; //triangle   cin >> height;   cout << "\n";   cout << "Type in the length of the base\n";   cin >> base;   float area=0.5*(base*height);   cout << "Area: ";   cout << area;   cout << "cm squared\n";   cin.get();   }   else {   cout << "Unrecognised shape\n";   }   } while ( x=1 );   cin.get(); }```
The string works if I only use it for "circle" but not when I try to use it for all of the options.
(P.S: I can't seem to get the blasted code tag to work)

EDIT: Oh dear, after checking the build messages and stuff I noticed that I'd forgotten a little comma after triangle. the program runs after it was fixed but it makes me push enter an irritating amount of times and always prompts for the circle area no matter what I type, sometimes i even cause an infinite looping of the first cout spamming my screen. :/
• 01-20-2012
hk_mp5kpdw
Code:

```char circle[7]; char square[7]; char triangle[9]; ... if ( circle) {   ... } else if ( square )  {     ... } else if ( triangle) {     ... } else {     ... }```
if statements work by checking the condition being tested for true/false. In this language "true" means any non-zero value and "false" means 0. In the above context, the variable circle is evaluated to true in the if test because the variable name by itself is taken to be the address of the character array in memory and that address is not going to be 0... ever. You will never execute any code other than what's in the first if-block no matter what you type.

My recommendation would be to use a string object to get the shape (a single value, not three) from the user and then compare:
Code:

```#include <string> ... string shape; ... cout << "Please enter a shape: "; cin >> shape; ... if( shape == "circle" ) {   // Do circle stuff } else if (shape == "square" ) {   // Do square stuff } else if ( shape == "triangle" ) {   // Do triangle stuff } else {   // Display error message }```

Code:

```int x; ... } while ( x=1 );```
Beware the difference between = (assignment) and == (equality). If you mean the first case, your loop is effectively an infinite loop. The variable x will be assigned the value of 1, the expression will test as 1 (non-zero therefore true) and the loop will continue executing forever. If you mean the latter case, you need to initialize x before you compare it with something or you'd be testing against an uninitialized variable. Eventually you're probably going to want to exit the loop.
• 01-21-2012
Pielord
For the umpteenth time ty! Not only for providing a solution but for helping me understand my mistakes. Everything works now :D

On a side note, is it possible to implement sin, cos and tan into a codeblocks program?
• 01-21-2012
grumpy
Quote:

Originally Posted by Pielord
On a side note, is it possible to implement sin, cos and tan into a codeblocks program?

Why would you want to?

sin(), cos(), and tan() are declared in the standard header, <cmath> within namespace std. Just bear in mind that the argument of each function is measured in radians, not degrees.

Rather than defining PI as a constant like you have done (the precision might be insufficient, depending on what floating point types your system supports) you might want to compute it. For example, as 4.0*atan(1.0). There are various techniques to avoid doing such a calculation repeatedly, if needed.
• 01-21-2012
Pielord
Thanks for the detailed answer! I'm only in my final year of high school and my AS maths class hasn't covered rad yet ;( (its next in the syllabus though) so I guess I'll have to wait and see with that section. Great to know its possible though.

I have absolutely no idea what 4.0*atan(1.0) is but I think its above my pay-grade to learn atm o.o

If I just add that as the PI float variable will it just add accuracy to the latter formulas?
• 01-21-2012
grumpy
Quote:

Originally Posted by Pielord
Thanks for the detailed answer! I'm only in my final year of high school and my AS maths class hasn't covered rad yet ;( (its next in the syllabus though) so I guess I'll have to wait and see with that section. Great to know its possible though.

Put it this way: an angle of 180 degrees is equal to pi radians. Essentially measuring angle based on distance traveled on the corresponding arc of a circle divided by radius of that circle. You know that the circumference of a circle is 2*pi*radius. That corresponds to 360 degrees being 2pi radians.
Quote:

Originally Posted by Pielord
I have absolutely no idea what 4.0*atan(1.0) is but I think its above my pay-grade to learn atm o.o

atan() is the C/C++ function for computing arc-tangent. tan() computes the tangent of an angle. atan(x) computes an angle such that tan(angle) is x and angle is between -pi and pi.

Quote:

Originally Posted by Pielord
If I just add that as the PI float variable will it just add accuracy to the latter formulas?

It will give you pi to the accuracy supported by your floating point type (float in your case). The potential trade-off is that it may be a function call which does a calculation run-time, which can be less efficient at run-time than using a compile-time constant. That is the reason for my previous comment about there being techniques to avoid doing the calculation repeatedly. [Note, also, that some compilers will happily optimise out the calculation, since 4.0 and 1.0 are literals (compile-time constants for want of a better description), and atan(1.0) always gives the same result .... which is pi/4).
• 01-21-2012
Pielord
Quote:

Originally Posted by grumpy
Put it this way: an angle of 180 degrees is equal to pi radians. Essentially measuring angle based on distance traveled on the corresponding arc of a circle divided by radius of that circle. You know that the circumference of a circle is 2*pi*radius. That corresponds to 360 degrees being 2pi radians.

Although I think I see what a radian is now in comparison with the circle example, I still can't seem to equate it with degrees if I'm to try convert the radian answer given by my program into the familiar degrees I can work with. Does this mean that 360 (in deg)=2pi (in rad)?

Atm my program looks like this:
Code:

``` #include <iostream> #include <string> //just added everything incase... #include <math.h> #include <cmath>                                 //Because I'm forgetful: using namespace std;            //sin = opp./hyp. cos = adj./hyp. tan = opp./adj.                                 //cosine rule = a^2=b^2+c^2- 2bccosA int main() {     float a;     float b;     float c;     float A;     float B;     float C;     string hyp;     string side1;     string side2;     string angle;     cout << "Which side is the hypotenuse?\n";     cin >> hyp;     if ( hyp=="a") {     cout << "Which side do you have?\n";     cin >> side1;     if ( side1=="a" ) {     cout << "Type in side a's length.\n";              //only have one path to test with so far     cin >> a;                                          //it prompts me through a-a-length-b-length-B-answer     cout << "Which other side do you have?\n";     cin >> side2;     if ( side2=="b" ) {     cout << "Type in side b's length.\n";     cin >> b;     }     }     }     cout << "Which angle do you need?\n";     cin >> angle;     if ( angle=="B" ) {     float B=sin(b/a);     cout << B;     } }```
The triangle example I have in my head is:
...|\B
...| .\
c | ...\a
...|_.. .\
A |_|_ _\C
......b
lower case=sides
upper case=angles
(sry about the random dots, the message kept squishing my triangle to make it save space text-wise)

So I ran the program with A as my right angle, a as 5(hypotenuse aswell) and b as 4, it then prompted me and I chose B as my needed angle which meant it would use sin because of opposite over hypotenuse. My problem is that I need second function sin to get the actual angle, although i can use this sin for working out lengths wen i try that section (though I'm not too sure wat the degree sign will be o.o) and if I do get the angle at last, I don't think I can make it into the same answer i get on my calculator (sin^-1(4/5) = 53 degrees) instead of radians.
• 01-21-2012
Elysia
It's a matter of simple conversion. Say that we have a number x = pi. Now we want to make a function, f, such that when x = pi, it returns 180.
We could make write it as

f(x) = (def) x / pi * 180 = 180x/pi = x*(180/pi)

With this, we have scaled out number, so that whenever x = pi, it returns 180. So 2*pi = 360, and so on.
So we see that by simply multiplying x by 180/pi, we can convert radians into degrees.

Also think about that your way of going about this calculation is a waste of code and time, since you have to create code paths for every possible case the user can enter information. You should try generalizing it. Come up with an algorithm, then code it.
• 01-21-2012
Pielord
Tnx the radiant/degree part works great! makes sense too.
As for the rest...uhm, I feel alot more stupid now than I did before looking up algorithms and the associated coding on the site. Its like hieroglyphs . o.0
So let me get this straight: it's possible to take every variable (a,b,c,A,B,C etc) and to place them into some sort of database, with all the formulas in another, and then to input what I have and/or what i need, which will then, using and algorithm on the program, automatically pull out the formula and matching variables to work out the sum? I rly want to figure this out but i'm slowly developing a brain tumor checking the advanced stuff in the tutorial. Could I bother someone for names? Just for a push in the right direction, like if I need to use arrays or binary trees, or if I'm totally in over my head and should scrap it and try something else?
Btw about the comment concerning my terrible indentation, can I fix that with functions to make it neater or do you mean I'm just using my current codes incorrectly/inefficiently?
• 01-21-2012
Elysia
I mean you have insufficient whitespace. Google indentation.
As for the rest ... there is no "working" algorithm for this problem. We're talking about a program structure here.
But I mean, you could ask for the length of all the sides first (the user could enter 0 if a side length is unknown), and from there ask what angle you want to know (or just output all of them which can be calculated). It would be vastly simpler than your current approach. With some programming tricks, you could get that down to a few lines of code.
• 01-22-2012
Pielord
Quote:

Originally Posted by Elysia
I mean you have insufficient whitespace. Google indentation.

Oh, been looking it up and there seem to be numerous different styles involved, any you would recommend or doesn't it really matter as long as I follow something?

It seems that the triangle trig project might be a bit hard to implement the structure idea considering how new it is to me, since I would have to use the variables hyp, opp and adj and then have them each rearranged according to which angle/side is needed before the calculation part even begins...
Could I instead try merge this shortcut that bypasses the whole inefficient if problem with another project entirely that has some similarities in what it requires? I've been using the long method of true/false prompting to try make use of the equations of motion in physics. the variables are final velocity(v), initial velocity(u), acceleration(a), time taken(t) and displacement(s) used in 4-5 equations as follows:
v=U+at
s=0.5(u+v)*t
s=ut+0.5(a)(t)^2
v^2=u^2+2as
(there's another but I don't need it)

In common questions associated with these formulas enough information is given to use at least one formula which only has one unknown and then get the rest from there (which is generally unnecessary as you will be able to take out what you need from the first one completed using manipulation). So with this structured program concept can I input whichever variables I have and then create a program that that works like...an AND operator I guess...because the formula's generally only have one or two variables different from the last as you look through them (since they're all derived from one another) so I can say "if this and that variable are available and I need v, run formula 1 and output v, etc.
Sorry this is really clumsily explained and completely redundant to ppl familiar with it.
This is a snippet from my attempt to run through every possible variable combination using if statements and the formulas:
Code:

``` cout << "Which variable do you need?\n";     cin >> variable;     if ( variable=="v") {     cout << "Type in the initial velocity.\n";     cin >> u;     cout << "Type in the acceleration\n";     cin >> a;     cout << "Do you have time taken(t) or displacement(s)?\n";     cin >> answer1;     if ( answer1=="t" ) {     cout << "Type in the time taken.\n";     cin >> t;     float v=u+a*t;     cout << "Velocity = ";     cout << v;     cout << " m/s\n";     cin.get();     }     else if ( answer1=="s" ) {     cout << "Type in the displacement.\n";     cin >> s;     float v=sqrt(u*u+2*a*s);     cout << "Velocity = ";     cout << v;     cout << "m/s\n";     cin.get();```
And this was my experimentation with structures in the triangle program attempt2:
Code:

``` structureA triangle;     trig *tri;     structureA.hyp;     structureA.adj;     structureA.opp;     cout << "Please input the triangle's sides in relation to the unknown angle.\nhyp:\n";     cin >> hyp,     cout << "adj:\n";     cin >> adj;     cout << "opp:\n";     cin >> opp;```

These are mostly to show I AM doing something and getting nowhere slowly, I do want to figure it out but I'm kinda at a loss.
Any help would be appreciated, also PLEASE tell me if the program I want to make is just a bit too advanced for someone a few days into this stuff - I dun wanna get half way only to run in an unsolvable issue o.o
Thanks.
Show 80 post(s) from this thread on one page
Page 1 of 3 123 Last