Nested if Loops and Resetting User Input

Hi, relatively new to C++, so if my code is absolute crap, it's probably just because of that. I'm trying to make a program to solve the Pythagorean Theorem for my Geometry teacher as a Win32 App on VS Community 2015 in visual C++. Here is my code:

#include "stdafx.h"
#include <iostream>
#include <math.h>
#include <conio.h>
#include <Windows.h>
#include <stdlib.h>

using namespace std;

int main()
{

int x;
int y;

y = 1;

if (y != 0) {

cout << "\n\n\nThis program will solve the Pythagorean Theorem for you:)\n\n\n\nPlease enter the number for the part of the triangle you wish to solve for...\n Leg Hypotenuse Exit Program\n [1] [2] [3]\n";

cin >> x;

if
(x = 1) {

system("cls");

float a;
float b;
float c;

cout << "\n\nEnter the length of the given leg of the triangle\n";
cin >> b;
system("cls");

cout << "\n\nEnter the length of the hypotenuse\n";
cin >> c;

a = sqrt(pow(c, 2) - pow(b, 2));

cout << "\n\nThe non-given leg has a length of " << a;
Sleep(5000);

}

else {
system("cls");

float a;
float b;
float c;

cout << "\n\nEnter the length of the first leg of the triangle\n";
cin >> a;
system("cls");

cout << "\n\nEnter the length of the second leg of the triangle\n";
cin >> b;

c = sqrt(pow(a, 2) + pow(b, 2));

cout << "\n\nThe hypotenuse has a length of " << c;
Sleep(5000);

}

}

return 0;
}

What I want the program to do is go back to the "menu" that's directly inside of the first if loop after the program outputs the solution to the equation, and I want to clear the user input so I can input a new variable and solve for a new set of parameters on a triangle.
Could you put [code] tags around your code and format it? It would make review easier.
One way is to use a while loop inside main.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
bool running = true;

while (running)
{
// show the menu
// get the input
switch (input)
{
   case 1:
     //hand case 1
     break;
   case 2:
     //handle case 1
     break;
   case 3:
     running= false;
     break;
}


alternatively you can use if else if you haven't learned about switch statement.
• You should never reset user input by clear all text on screen, it may clear important information from last program. If the users want to clear their console, they will do it. Also note that effect of system("cls") is really depend on system.

• Why the Sleep(500)?

• Besides put code tags, you can use reformat document (Ctrl+k,Ctrl+d) in visual studio to format your code.

===solution===

• A solution is use while(true){if(condition){break;}}

• If there are nested loop/switch around if(condition) you may consider use goto to break out, set condition variable in while loop, or just return in this case.

Last edited on
Topic archived. No new replies allowed.