"if... else" and "loops"?? What am I missing?

Pages: 12
Alright so I have to create a simple calculator and need to include the following features:
- an "if... else" or "switch" structure
- Display of an invalid operation, divisor, and modulus
- a properly constructed "loop"

I've spent a couple hours on it but I'm making progress (very slowly)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
    
// ALGORITHM

// Define variables and calculations
// 
// Welcome User to Calculator
// Prompt user to enter first number
       // - If invalid, prompt user to re-enter first number
       // - If valid, move to function selection
// Prompt user to select mathmatical function
       // - If invalid, prompt user to re-enter functions
       // - If valid, move to second number selection
// Prompt user to enter second number
       // - If invalid, prompt user to re-enter first number
       // - If valid, move to function selection
// Calculate equation
// Display equation
// Prompt user to perform another calculation (loop)
// Prompt user to exit calculator using EOF input


#include <iostream>
#include <iomanip>
#include <cmath>

using namespace std;

int main()
{
  
// Define Variables & Calculations
char function;
double m,n;
double sum (m + n);
double difference (m - n);
double product (m * n);
double quotient ( m / n);

// Welcome user

   cout  <<  "Hi and Welcome to the Calculator.\n"  << endl;

// Prompt user to enter first number

   cout  <<  "Please enter the first number and press Enter:   \n"  <<  endl;
   cin  >>  m; 
   
   
// Prompt user to enter mathmatical function

   cout  <<  "Please enter mathmatical function and press Enter" 
     "(ex. '+' , '-' , '*' , '/' , '%'):  \n"  <<  endl;
   cin  >>  function;
   

// Prompt user to enter second number

   cout  << "Please enter second number and press Enter:   \n"  <<  endl;
   cin  >>  n;
   
   
// Compute calculation

if (m + n)
       
       cout  <<  "The answer to your problem is " <<  sum   <<  endl;
       
else if (m - n)
       
       cout  <<  "The answer to your problem is " <<  difference   <<  endl;
      
else if (m * n)
       
       cout  <<  "The answer to your problem is " <<  product   <<  endl;
       
else if (m / n)
       
       cout  <<  "The answer to your problem is " <<  quotient   <<  endl;              


       system ("pause");
       return 0;
}     


The math on this keeps giving me a answer in scientific notation format.
"5 + 5 = 4.05359e-307"

So I need to display a invalid operation. Here's what I have so far but it's not working.

1
2
3
4
5
6
7
8
    cout  <<  "Please enter the function (+,-,*,/,%) :   \n"  << endl;
    cin  >>  function;
    
    if (function == '+', '-', '*', '/', '%');
      
    
    else (function != '+', '-', '*', '/', '%');
    cout << "Invalid function! Please try again.\n"  << endl;


Do I need to define "+", "-", etc, in the "char function" command?

I would appreciate any feedback.

Thanks
Your answer variables are all going to be garbage. You declare m and n, but give them no values, then use them to calculate 'sum', etc. So those values are also garbage.

Your if statements are meaningless. The first says, "if m + n doesn't equal 0 print the value of sum". The others are similarly flawed.
I don't want to sound discouraging, but it's all wrong. Your assumptions about how the language works are way off. They are valid (most of them, anyway), so it's not all lost. A hypothetical language could conceivably work like this. This one doesn't.
I find lines 34-37 troubling. I get the feeling you were trying to do something very specific, but I would rather not say what.

You should scrap lines 34-37 and 64-78.
Start by implementing one operation at a time and verifying that it works, then, and only then, start adding the other ones.
A small hint: you can't separate checking the 'function' variable and deciding which operation to perform*.
Another one: In the code you posted, you're not performing any calculations on useful data.



* Well, you can, but it's more work.
Ok, 3 things to get you moving along. First, line 64 if (m + n), This means take m, add it to n, and branch based on if it's true of false. c++ defines any non 0 value as true. This means no matter what you enter, it will go to the first if statement (unless it adds up to 0). What you should have there is if(function == '+')

The second issue is on line 34-37, those are function prototypes, but you never actually define what the function does. That means you are getting undefined behavior, and the number it is returning will be some archaic result of how your compiler chooses to implement that. The function should look more like: double sum(double value1, double value2){return value1+value2}. Functions are also typically global. These are really simple calculations, so it may be wise to not have them as functions at all, and just do the calculations as you are using cout.

The third is how to get it to loop, you will need to put everything between lines 43 and 79 in a while loop, and have a variable such as doAnotherCalculation, and ask the user after you do 1 calculation if they want to do another.


Edit: Actually, I'm not entirely sure why lines 34 and 66 don't issue a compiler error. He's doesnt define what types m and n are in the function prototype (or does it come over because he declared m and n as variables?), and on line 66 he calls sum without the () to show it's a function.
Last edited on
i'm a little bit surprised about the functions declarations, i thought maybe there's something i didn't know yet (another syntax that i probably don't know yet till now, but after helios' explanations i'm relived that i didn't miss anything :) )

the functions should be written

1
2
3
double sum (double n, double m) {return (m + n);}
double difference (double n, double m) {return (n - m);}
//and so forth... 


oh yeah, you don't have to include the <cmath> (and <iomanip> probably)
Last edited on
Intrexa wrote:
The second issue is on line 34-37, those are function prototypes
No they aren't. The constructors of those variable are called. Equivalent to
1
2
double sum = (m + n);
double difference = (m - n);
(Which doesn't make sense here)

You don't need functions:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
bool retry;
do
{
retry = false;
...
if (function == '+')
       
       cout  <<  "The answer to your problem is " <<  (m + n)   <<  endl;
       
else if (function == '-')
       
       cout  <<  "The answer to your problem is " <<  (m - n) << endl;
...
else
{
    retry = true;
    cout  <<  "Please enter the function (+,-,*,/,%) :   \n"  << endl;
}
 // You may ask ther user here if he wants to do it again (if not retry is already true)
}
while(retry);

Lines 34-37 aren't function declarations, so that's why you haven't seen them before.
They're equivalent to double sum = m + n; etc.
Edit: ah, that was directed at chipp and Intrexa.

But they were probably supposed to be function declarations. However, lambda functions are declared with different syntax in C++:
1
2
auto sum=[](double m,double n) {return m+n;};
cout << sum(m,n) << endl;

or as originally intended:

1
2
auto sum=std::bind([](double a,double b) {return a+b;},std::ref(m),std::ref(n));
cout << sum() << endl;


The above uses C++0x features, though. While current compilers support them already, they're not part of the current standard yet.
Last edited on
retry is not true, right? it is true if the "function" is not being inputed properly. am i right?
Last edited on
You can create retry, with do while loop.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
char again;

do {
......
.......
..........
..........
............


cout<<"Do you want to retry? Y for Yes, N for No!"<<endl;
cin>>again;

}

while (again == 'Y' || again == 'y');

I appreciate the feedback (the good and the bad)... I've went back to the drawing board and have made some progress. I'm still having trouble with a few things though:

#1- I can get it to display the proper error message when attempting to divide/modulus by "0".

#2- After it display the error message for dividing/modulus by "0" how can I get it to restart the sequence and have the user enter the calculation again?

# 3- I can't figure why my loop is not working correctly. The program is terminating when i need it to prompt the user " Would you like to enter another calculation?"

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82

#include <iostream>

using namespace std;

int main()
{
  
// Define Variables
char function;
char redo;
int m,n;


// Welcome user

   cout  <<  "Hi and welcome to the Calculator.\n"  << endl;

// Prompt user to enter calculation


do
{
   cout  <<  "Please enter the equation you would like to solve:   \n"  <<  endl;
   cin  >>  m  >>  function >> n;
   
      
// Compute calculation
if (!cin.eof())
{
if (function == '+')
       
       cout  <<  "The answer to  "  << m  <<  "  "  << function  <<  "  "  << n  <<  "   "  
       <<  "is:   "<<  m + n  <<  endl;
       
else if (function == '-')
       
       cout  <<  "The answer to  "  << m  <<  "  "  << function  <<  "  "  << n  <<  "   "  
       <<  "is:   "<<  m - n  <<  endl;
      
else if (function == '*')
       
       cout  <<  "The answer to  "  << m  <<  "  "  << function  <<  "  "  << n  <<  "   "  
       <<  "is:   "<<  m * n  <<  endl;
       
else if (function == '/')
     {
     if (n == 0)
     cout << "Cannot divide by 0.  Please re-enter."  << endl;
     }
           
       cout  <<  "The answer to  "  << m  <<  "  "  << function  <<  "  "  << n  <<  "   "  
       <<  "is:   "<<  m / n  <<  endl;   
         
       
else if (function == '%')

  {
     if (n == 0)
     cout << "Cannot modulus by 0.  Please re-enter."  << endl;
     }
       
       cout  <<  "The answer to  "  << m  <<  "  "  << function  <<  "  "  << n  <<  "   "  
       <<  "is:   "<<  m % n  <<  endl;
       
else
       cout  << "Invalid function!   Please re-enter equation:   \n"  <<    endl;
}                   
       
       cout <<  "Would you like to enter another calculation? (Y/N) :   "  <<  endl;
       cin >> redo;
       
       while ( redo == 'y' || 'Y')
       
       while (!cin.eof());
       
       
       system ("pause");
       return 0;
}     

you forgot and misplaced the closing bracket ('}') dude... in here:
1
2
3
4
5
6
7
8
9
10
if (n == 0)
     cout << "Cannot modulus by 0.  Please re-enter."  << endl;
     }
       
       cout  <<  "The answer to  "  << m  <<  "  "  << function  <<  "  "  << n  <<  "   "  
       <<  "is:   "<<  m % n  <<  endl;
       
else
       cout  << "Invalid function!   Please re-enter equation:   \n"  <<    endl;
}                   


should be:

1
2
3
4
5
6
7
8
9
if (n == 0)
     cout << "Cannot modulus by 0.  Please re-enter."  << endl;
     }
       
       cout  <<  "The answer to  "  << m  <<  "  "  << function  <<  "  "  << n  <<  "   "  
       <<  "is:   "<<  m % n  <<  endl;
} //here, the sign of the end of your "if"     
else
       cout  << "Invalid function!   Please re-enter equation:   \n"  <<    endl;


and then:
1
2
3
4
cout <<  "Would you like to enter another calculation? (Y/N) :   "  <<  endl;
       cin >> redo;
       
       while ( redo == 'y' || 'Y')


should be:
1
2
3
cout <<  "Would you like to enter another calculation? (Y/N) :   "  <<  endl;
       cin >> redo;
} /* here, the sign of the end of your "do" */while ( redo == 'y' || 'Y');


btw, what for cin.eof ? i don't really know what it does... (haven't learn it yet -_-!)

append: system("PAUSE"); //not lowercase
Last edited on
cin.eof() checks if an end-of-file character has been read by the standard input stream. Run a program with it* and enter ^Z (Ctrl-Z) in Windows, or ^D in unix.

*
1
2
3
4
5
6
7
8
9
10
11
12
#include <iostream>
#include <string>

using namespace std;

int main() {
   string input;
   cout << "Enter data. Type ^Z (Windows) or ^D (Unix) to quit." << endl;
   while( !cin.eof() )
      getline( cin, input ); //read a line of text from standard input
   return 0;
}
For lines 66 and 82 I keep getting the following errors when I try to compile:

66: expected primary-expression before "else"
66: expected ";" before else
82: expected 'while' at end of input
82: expected '(' at end of input
82: expected primary-expression at end of input
82: expected ')' at end of input
82: expected ';' at end of input
82: expected '}' at end of input

Is their something obvious I am missing?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
#include <iostream>

using namespace std;

int main()
{
  
// Define Variables
   char function;
   char redo;
   int m,n;

   do
   {
// Welcome user

   cout  <<  "Hi and welcome to the Calculator.\n"  << endl;

// Prompt user to enter calculation


     
   {
   cout  <<  "Please enter the equation you would like to solve:   \n"  <<  endl;
   cin  >>  m  >>  function >> n;
   
   if (!cin.eof())
   {  
// Compute calculation
           if (function == '+')
// Try and remove "  "  once compiled 
      
              cout  <<  "The answer to  "  << m  <<  "  "  << function  <<  "  "  << n  <<  "   "  
                  <<  "is:   "<<  m + n  <<  endl;
       
           if (function == '-')
       
              cout  <<  "The answer to  "  << m  <<  "  "  << function  <<  "  "  << n  <<  "   "  
              <<  "is:   "<<  m - n  <<  endl;
      
           if (function == '*')
               
               cout  <<  "The answer to  "  << m  <<  "  "  << function  <<  "  "  << n  <<  "   "  
               <<  "is:   "<<  m * n  <<  endl;
       
           if (function == '/')

              cout  <<  "The answer to  "  << m  <<  "  "  << function  <<  "  "  << n  <<  "   "  
              <<  "is:   "<<  m / n  <<  endl; 
           
           
           else if (n == 0)
              cout << "You cannot divide by 0.  Please re-enter calculation."  << endl;
                 
           
           if (function == '%');
              
     
              else if (n == 0)
                   cout << "Cannot modulus by 0.  Please re-enter."  << endl;
                   
                   
              cout  <<  "The answer to  "  << m  <<  "  "  << function  <<  "  "  << n  <<  "   "  
              <<  "is:   "<<  m % n  <<  endl;
       
           else if
              cout  << "Invalid function!   Please re-enter equation:   \n"  <<    endl;
}       
            
//       
//       cout <<  "Would you like to enter another calculation? (Y/N) :   "  <<  endl;
//       cin >> redo;
//       
//       while ( redo == 'y' || 'Y')
//       
       } 
       while (!cin.eof());
       
       
       system ("pause");
       return 0;
} 



line 63. Put lines 60-65 in brackets {}. An if statement only executes the next single instruction, between the if statements on line 59 and 66 there are 2 instructions, so that the compiler thinks it is done with the if/else if block, so on line 66 it sees that else if as an entirely new line of if statements.

Edit: As for the second part, where it is having an issue with line 82, that is extremely straight forward, and is telling you exactly what is wrong and what it is expecting. On line 13 you have a do statement that doesn't line up with the ending while statement.
Last edited on
When you say "line up" do you mean in terms of spacing or something else like bracketing?
When I said line up, I meant in terms of just having a matching while statement. A do while looks like"
1
2
3
do{
//stuff
}while(condition);


You are missing line 3 of that.

Edit: Further looking, line 77 is still inside the do brackets, put a } in front of while on line 77. You didn't match your brackets.

Edit2: Instead of that, you should probably just remove the bracket on line 23, it serves no point, and is the reason your brackets aren't matching.
Last edited on
Thanks man... I really appreciate the help and that was huge.

I still can't figure why my loop is not working correctly? I need it to prompt the user to continue to enter calculations until "ctrl + z" are entered to end the program.

Secondly, my error message when a user attempts to divide by "0" is working correctly (line 53). The program divides by "0", returns 0 and then fails.
if (function == '%'); //semicolon? this is not a function dude
you shouldn't do this...

and why you put so much "if" without pair it with "else if", dude? maybe this will help:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
//i use to code this when i was a beginner
//(but now it still a beginner -_-!)
#include <iostream>
#include <conio.h>
using namespace std;

double calc_this (double n, char f, double m) {
	switch (f) {
		case '+': {
			return (n + m);
			break;
				  }

		case '-': {
			return (n - m);
			break;
				  }

		case '/': {
			if (n == 0 || m == 0) {
				cout << "cannot divide by zero!!" << endl;
				break;
			}
			return (n / m);
			break;
				  }

		case '*': {
			return (n * m);
			break;
				  }

		default:
			break;
	}
}
int main () {
	double n, m, result;
	char function, choi;
	do {
		cout << "calculation (y / n): ";
		cin >> choi;
		if (choi == 'y' || choi == 'Y') {
			cout << "enter your calculation (sum, multiply, subtraction, division):" << endl;
			cin >> n >> function >> m;
		}			
	} while (choi == 'y' || choi == 'Y');
	getch();
	return 0;
}


oh yeah, you want it in ifs right? you can change the cases with ifs

append: be sure to learn what's the code does. might it help. any other wanna contribute? :D
Last edited on
Chipp, I appreciate your help but I'm only more confused with your code. I've only been coding in C++ for 3 weeks. The goal of this assignment is for me to use "if...else" statement's. I've reworked it and I think I'm 90% of the way there. I'm just running into the following issues:

1. The "else" statement in line 92 displays all the time even when a simple and valid equation is entered.

2. My professor said "The test for a zero divisor or mod should immediately follow the function test and not be an else if." When I do this it doesn't compile. I've tried putting the "if" statements in braces directly under their respective equations with no luck.

3. When I divide by "0" it doesn't return an answer and the program crashes. I need it to return "Cannot divide by 0" (lines 77).

4. When I try and modulus by "0" it returns "Cannot divide by 0" (line 77) and also "Cannot modulus by 0" (line 89). Why is that?




1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
// Simple Calculator ALGORITHM

// Do Loop
// Define variables 
// Welcome User to Calculator
// Prompt user to enter first number
       // - If invalid, prompt user to re-enter first number
       // - If valid, move to function selection
// Prompt user to select mathmatical function
       // - If invalid, prompt user to re-enter functions
       // - If valid, move to second number selection
// Prompt user to enter second number
       // - If invalid, prompt user to re-enter first number
       // - If valid, move to function selection
// Calculate equation
// Display equation
// Prompt user to perform another calculation (loop)
// Prompt user to exit calculator using EOF input


#include <iostream>

using namespace std;

int main()
{
  
// Define Variables
   char function;
   char redo;
   int m,n;

  
   
// Welcome user

   cout  <<  "Hi and welcome to the Calculator.\n"  << endl;

// Prompt user to enter calculation

  do
   {
   
   cout  <<  "Please enter the equation you would like to solve:   \n"  <<  endl  
   << endl;
   cin  >>  m  >>  function >> n;
   
   
     
// Compute calculation

           if (function == '+')

              cout  <<  "The answer to  "  << m  <<  "  "  << function  <<  "  "  << n  <<  "   "  
                  <<  "is:   "<<  m + n  <<  endl;
       
           else if (function == '-')
       
              cout  <<  "The answer to  "  << m  <<  "  "  << function  <<  "  "  << n  <<  "   "  
              <<  "is:   "<<  m - n  <<  endl;
      
           
           else if (function == '*')
               
               cout  <<  "The answer to  "  << m  <<  "  "  << function  <<  "  "  << n  <<  "   "  
               <<  "is:   "<<  m * n  <<  endl;
       
           
           else if (function == '/')
                   
           
              cout  <<  "The answer to  "  << m  <<  "  "  << function  <<  "  "  << n  <<  "   "  
              <<  "is:   "<<  m / n  <<  endl; 
           
          if (n == 0)
            
              cout << "You cannot divide by 0.  Please re-enter calculation."  << endl; 
            
                   
           
           else if (function == '%')                  
                   
                   
                 cout  <<  "The answer to  "  << m  <<  "  "  << function  <<  "  "  << n  <<  "   "  
                   <<  "is:   "<<  m % n  <<  endl;
              
                 if (n == 0)
              
                   cout << "Cannot modulus by 0.  Please re-enter."  << endl;
                         
                         
            else  
              cout  << "Invalid function!   Please re-enter equation.   \n"  <<    endl;
       
           
     
       } 
       while (!cin.eof());
       
       
       system ("pause");
       return 0;
}     
I've made a similar calculator (it takes multiple numbers and parens however, but it's still the same idea) if you want me to post the source. I used a switch statement for parsing the string. Also you have a ton of extra white space in there, I can barely read that program, its almost twice as many lines as it could be.

As for your code, you want to put the checks for whether the user entered 0 before you output the answer or your program is going to crash. Also even if the user does enter 0 you're not doing anything about, and whenever you divide by zero on a computer the program crashes, so try using exit(1) or return 0.

The reason the else on line 92 keeps getting displayed is because you left out your curly braces on line 81 so the else on line 92 is an else to the if statement on line 87. This means it will be displayed whenever the user doesn't enter 0 when they're dividing. Just give your else if statement curly braces and you'll be good.
Last edited on
Pages: 12