I broke up the parts to see what was wrong, but I couldn't figure it out.
I think the main issue is with case 1, because case 2 and 3 work fine without it. But then if I take out case 2 and 3, such that 1 is the only one left, it works perfectly fine.
#include <iostream>
usingnamespace std;
int power (int a,int b) {
int c=a;
while (1 < b) {
a*=c;
b--;
}
return a;
}
void swap (int a, int b) {
int swap=a;
a=b;
b=swap;
return;
}
int sum (int* a, int b) {
int total=0;
for (int i=0; b>i; i++) {total+=*(a+i);}
return total;
}
int main () {
cout << "Do you want to find the total (hit number 1), find the power (hit number 2) or switch numbers (hit number 3)?";
int v,r;
cin >> v;
switch (v) {
case 1:
cout << "How many numbers do you want to add?";
cin >> r;
int* a=newint [r];
for (int i=0; r>i; i++) {cout << "Enter number: ";
cin >> *(a+i);}
cout << sum(a,r);
delete a;
break;
case 2:
char choice;
while (choice='y') {
cout << "Enter 2 numbers: ";
int x,y;
cin >> x >> y;
cout << x << " to the power of " << y << " is " << power(x,y) <<endl;
cout << "Do you want to compute again? Hit y if yes, enter anything else for no" << endl;
cin >> choice; }
break;
case 3:
cout << "Enter two numbers: ";
int first, second;
cin >> first >> second;
swap (first,second);
cout << "It is done.";
break;
default:
cout << "I didn't get that, please re-enter 1, 2 or 3";
cin >> v;
}
system ("pause");
}
Strictly speaking the cases can be used without the curly braces however it is not recommended because if any variables are declared in the case then that variable remains for the rest of the switch statement, so if you're not careful this can cause problems...
Some compilers may complain at this whereas others may let it slip right through.
Does your swap function work? It's a void function with the arguments assigned to local variables, so it won't change the value of any variable in the main() program. The args really need to be pointers or references in this case.
There is no output to show that the numbers have been swapped.
Your for loops seem to be the reverse of the normal convention.
for (int i=0; b>i; i++)
Try this form instead:
for (int i=0; i < b; i++)
Rather than use pointer arithmetic for your dynamic array, use the [] operator - it's easier & clearer.
The power function could be written more clearly IMO.
Hopefully these points are useful and help you out a bit.
EDIT: In most cases a break is used once just one solution is found so more often then not there isn't a problem because break will tell switch to stop looking for any further matches, otherwise chances are that you'll get caught in the default catch.
However it's always considered "good practice" to wrap the cases up in there own scope blocks