C++ Creating array based on what functions were called - c++

For example lets say I have this simple code:
using namespace std;
char re = 'y';
void mult(int one, int two)
{
int mult = 1;
mult = one * two;
cout << mult << endl;
}
void add(int one, int two)
{
int add = 0;
add = one + two;
cout << add << endl;
}
void rep(int one, int two)
{
}
void ask()
{
int re;
cout << "do you want return to the menu? (1/2)" << endl;
cin >> re;
}
int main()
{
char re;
int one;
int two;
cout << "enter the number one:" << endl;
cin >> one;
cout << "enter the number two:" << endl;
cin >> two;
cout << endl;
cout << "Multiply - 1" << endl;
cout << "Add - 2" << endl;
cout << "Reprint - 3" << endl;
cout << endl;
int menu;
if (re == 'y')
{
cout << "select the function ";
cin >> menu;
switch (menu)
{
case 1:
mult(one, two);
ask();
break;
case 2:
add(one, two);
ask();
break;
case 3:
rep(one, two);
break;
default:
cout << "no such thing" << endl;
break;
}
}
else if (re != 'y')
{
}
return 0;
}
I need a way function rep to print out the answer of previously called functions.
For example if function mult was called it should print mult answer, IF mult and add were called then it should print mult and add function answers, if only add then only add.
I was thinking about creating a zero array and changing it whether function one or two was called out, and then somehow call the answers out. But no idea how to do it.

You could use a global variable.
int last_result = 0;
void mult(int a, int b)
{
last_result = a * b;
std::cout << last_result << std::endl;
}
void add(int a, int b)
{
last_result = a + b;
std::cout << last_result << std::endl;
}
void rep()
{
std::cout << "Last result: " << last_result << std::endl;
}
You could also have the mult and add functions return a result and store the result in main (and pass it to the rep function).
You could pass the last_result variable by reference to the add and mult functions.

Related

How to make a loop start from beginning in C++?

I am writing a program in C++ which takes numbers input and it adds substracts divides, and multiplies. In the code when I want the switch case statement to run infinitely until the user presses 5 to exit the program. Please help me. Whenever I am writing the while(true) it is infinitely showing the output.
#include <iostream>
using namespace std;
class SimpleCalculator
{
protected:
private:
int num1, num2;
public:
int add(int a, int b)
{
num1 = a;
num2 = b;
return a + b;
}
int diff(int a, int b)
{
num1 = a;
num2 = b;
return a - b;
}
int quo(int a, int b)
{
num1 = a;
num2 = b;
return a / b;
}
int pro(int a, int b)
{
num1 = a;
num2 = b;
return a * b;
}
};
int main()
{
int n1, n2;
cout << "Enter the value of the number 1: ";
cin >> n1;
cout << "Enter the value of the number 2: ";
cin >> n2;
SimpleCalculator o1;
int input;
cout << "Enter your number: ";
cin >> input;
while (true)
{
switch (input)
{
case 1:
cout << o1.add(n1, n2) << endl;
break;
case 2:
cout << o1.diff(n1, n2) << endl;
break;
case 3:
cout << o1.pro(n1, n2) << endl;
break;
case 4:
cout << o1.quo(n1, n2) << endl;
break;
case 5:
break;
default:
cout << "Invalid entry" << endl;
break;
}
}
return 0;
}
You have two main issues:
The user input requests must be part of the loop since you want them to be repeated at every iteration (i.e. the user needs to make a choice at every iteration).
You forgot to exit the loop in the case 5: statement.
[Optional] Your application is lacking a user menu (the user can't guess what he has to do)
Note: I would advise you to split your code into several functions so that it would be clearer to read and easier to organize.
Note 2: You don't need to use a class for such basic operations, the members are not really needed, you can directly return the result of the operation. My advice would be to define the functions as free functions inside a namespace or as static members of your class if you really want to.
Example:
First let's define the calculation functions:
int add(int a, int b) {return a+b;}
int sub(int a, int b) {return a-b;}
int pro(int a, int b) {return a*b;}
int quo(int a, int b) {return a/b;}
Then we define a function to ask for user inputs:
void ask_user_input(int & lhs, int & rhs)
{
std::cout << "Enter the first operand: ";
std::cin >> lhs;
std::cout << "Enter the second operand: ";
std::cin >> rhs;
}
Finally we define a function to display the user menu:
void display_menu()
{
std::cout << "\n--- Calculator ---\n";
std::cout << "1. Addition\n2. Substraction\n3. Multiplication\n4. Division\n5. Exit\n";
}
Bringing all things together in the main() function, it gives:
int main()
{
bool quit(false);
int choice, lhs, rhs;
while(!quit)
{
display_menu();
std::cin >> choice;
switch(choice)
{
case 1: ask_user_input(lhs, rhs);
std::cout << '\n' << lhs << " + " << rhs << " = " << add(lhs, rhs) << '\n';
break;
case 2: ask_user_input(lhs, rhs);
std::cout << '\n' << lhs << " - " << rhs << " = " << sub(lhs, rhs) << '\n';
break;
case 3: ask_user_input(lhs, rhs);
std::cout << '\n' << lhs << " * " << rhs << " = " << pro(lhs, rhs) << '\n';
break;
case 4: ask_user_input(lhs, rhs);
std::cout << '\n' << lhs << " / " << rhs << " = " << quo(lhs, rhs) << '\n';
break;
case 5: quit = true;
break;
default: std::cout << "Invalid choice, try again !\n";
break;
}
}
return 0;
}
Live example

how can i know what is the result of the non-void function without executing it

the problem that in the main body the getwhattheywant function is executing twice what I want is this
getwhattheywant execute then the user entered one then if the user entered one do the summation operation but what is happening with me that it's reasking the user to enter a number.
#include <iostream>
using namespace std;
double dothesum(int x, int y)
{
int sum = x + y;
return sum;
};
int getwhatheywant()
{
int choice;
cout << "1- for sum " << endl;
cout << "2- for quit ";
cin >> choice;
return choice;
}
void the_sum()
{
int x, y;
cout << " enter the first number " << endl;
cin >> x;
cout << " enter the second number " << endl;
cin >> y;
cout << " the sum of the two number is " << dothesum(x, y) << endl;
}
int main()
{
int;
while (getwhatheywant() != 2) {
if (getwhatheywant() == 1) {
the_sum();
}
}
return 0;
}
Change your main():
int main()
{
int whatTheyWant;
while ( (whatTheyWant = getwhatheywant()) != 2) {
if (whatTheyWant) == 1) {
the_sum();
}
}
return 0;
}
This stores the value from a single call to getwhattheywant() so you can first see if they're asking to quit, and if not, you can see what else they might want. Now, I'd write it slightly differently:
bool working = true;
while(working) {
int choice = getWhatTheyWant();
switch(choice) {
case 1: the_sum(); break;
case 2: working = false; break;
}
}

static stack function does not 1) take input of 1st element 2)recognise old element when new element is added

There is an array of nodes(a structure) and is used as a
stack.
it has 3 functions
to add new elements (push)
to delete elements(pop)
to display(display)
problems:
does not save the first input
when a new input is added, it replaces the previous node with the new input.
please help me identify where i have gone wrong
#include <iostream>
#include<conio.h>
#include<process.h>
struct node
{
int x, y;
};
int top = -1;
class stack
{
node s[30];
public:
void push();
void pop();
void display();
};
void stack::push()
{
if (top < 29)
{
cout << "enter elements" << endl;
int a, b;
cin >> a >> b;
top = top + 1;
s[top].x = a;
s[top].y = b;
}
else
{
cout << "OVERFLOW" << endl;
}
}
void stack::pop()
{
node temp;
temp = s[top];
top--;
cout << "element" << temp.x << "&" << temp.y << " has been deleted" << endl;
}
void stack::display()
{
for (int i = 0; i < top; i++)
{
cout << s[top].x << "&" << s[top].y << endl;
}
}
void main()
{
clrscr();
stack sup;
int choice = 1;
do
{
cout << "1.add" << endl << "2.delete" << endl << "3.display" << endl;
int c;
cin >> c;
switch (c)
{
case 1:
sup.push();
sup.display();
break;
case 2:
sup.pop();
sup.display();
break;
case 3:
sup.display();
break;
default:
cout << "error in switch case" << endl;
}
cout << "enter 1 to perform more operations" << endl;
cin >> choice;
} while (choice == 1);
getch();
}
You delete and recreate you stack (sup) every iteration of your loop. The declaration should be before the do.

C++ counter variable not working properly

I am writing a program that asks a user for a difficulty level then gives them multiplication questions while counting the correct answers. My issue is my counter (numCorrect) updates for false answers too and I can't understand why. Can someone tell me why?
int main()
{
int n; //difficulty level
int a, b, atimesb; // random generated numbers and multiplication
string name;
int numCorrect=0; // initilize counter to 0
int numAsked=0; // initilize counter to 0
int exitCond = 1; // loop condition continue
cout << "this program tests your multiplication skills!" << endl;
cout << "what is your name?" << endl;
getline(cin, name);
cout << " Enter a difficulty level" << endl;
cin >> n; // user input for difficulty level
while (exitCond != 0) // loop to continue asking until user ends with 0
{
MakeQuestion(n, a, b, atimesb); // calls function to make a question
UserAnswerIsCorrect(a, b, atimesb); // calls function to ask question and evaluate it
if (UserAnswerIsCorrect) // update if correct
{
numCorrect++;
}
numAsked++; // update total questions
cout << " Enter 0 to quit, 1 to go again" << endl;
cin >> exitCond; // user input for difficulty level
}
PrintScore(numCorrect, numAsked); // calls function to print score
return 0;
}
int NewRandomNumber(int n)
{
int val;
val = rand() % n + 2; // creates a number between 2 and n
return val;
}
void MakeQuestion(int n, int& a, int& b, int& atimesb)
{
a = NewRandomNumber(n);
b = NewRandomNumber(n);
atimesb = a*b;
return;
}
bool UserAnswerIsCorrect(int a, int b, int atimesb)
{
int userAns;
cout << a << "X" << b << "=" << endl;
cin >> userAns;
if (userAns == atimesb)
{
cout << "Correct!";
return true;
}
else
{
cout << "false, correct answer is:" << atimesb << endl;
return false;
}
}
void PrintScore(int numCorrect, int numAsked)
{
cout << "your score is: " << numCorrect << "/" << numAsked << " or " <<
(numCorrect / numAsked) * 100 << "%" << endl;
return;
}
UserAnswerIsCorrect(a, b, atimesb); // calls function to ask question and evaluate it
if (UserAnswerIsCorrect) // update if correct
{
numCorrect++;
}
should be
if (UserAnswerIsCorrect(a, b, atimesb)) // update if correct
{
numCorrect++;
}
You ignored the return value of UserAnswerIsCorrect in your code.
You can do this
bool corr;
corr = UserAnswerIsCorrect( a, b, atimesb);
if(corr) {
numCorrect++;
}
Although it just happened because you was ignoring the return value.
try this condition
if(UserAnswerIsCorrect == true){
....
}

How do I send inputs from multiple functions into one function in c++?

As part of a school assignment, I need to build a modular calculator with at least four modules (getData, getInteger, processData, displayData) doing add/subtract/multiply/divide/modulus operations on two integers.
I'm getting pretty stumped on putting this thing together, and I think it's largely because I'm struggling to understand how inter-function calls work (e.g. one function sending information to another function).
I've got the getInteger function getting integer input from the user, and I'm using processdata(intA, intB); to send this to the processData(int, int) function; but my getData(int) function also needs to send an integer input to processData - however processData(select) isn't valid because it doesn't have enough arguments. (I don't really understand what this means)
This is probably a bit confusing, so I've got the whole (unfinished/wip/doesn't actually work) program here:
//calculator program
//4 modules required: getData, getInteger, processData, displayData
#include <iostream> //To input/output to the display (I think)
#include <conio.h> //For getch() at end of program
using namespace std;
//prototypes
void getInteger(int, int);
void getData(int);
void processData(int, int);
void displayData(); // haven't added anything yet
int main(){
//prevents window from immediately closing
getch();
return 0;
}
void getInteger(int, int) {
int intA, intB;
cout << "Please enter integer one: " << endl;
cin >> intA;
cout << "Please enter integer two: " << endl;
cin >> intB;
processData(intA, intB); //sends info to processData function
}
void getData(int) {
int select;
cout << "Available Functions" << endl;
cout << "1. Addition (+)" << endl;
cout << "2. Subtraction (-)" << endl;
cout << "3. Multiplication (*)" << endl;
cout << "4. Division (/)" << endl;
cout << "5. Modulus (%)" << endl;
cout << "Please type your selection (1-5): " << endl;
cin >> select;
if (select > 5 || select < 1) {
cout << "Error: Out of Bounds, please re-enter your selection: " << endl;
cin >> select;
}
processData(select); //sends info to processData function
}
void processData() {
int add, sub, mul, div, mod, select, intA, intB;
switch(select) {
case 1:
select = 1; //addition
add = (intA + intB);
displayData(add); //sends info to displayData function
break;
case 2:
select = 2; //subtraction
sub = (intA - intB);
displayData(sub);
break;
case 3:
select = 3; //multiplication
mul = (intA * int B);
displayData(mul);
break;
case 4:
select = 4; //division
div = (intA / intB);
displayData(div);
break;
case 5:
select = 5; //modulus
mod = (intA % intB);
displayData(mod);
break;
default:
cout << "There's been an error :(" << endl;
}
return 0;
}
void displayData() {
}
Am I doing this all backwards? I feel like it'd be a lot easier if I could contain this in fewer functions, but it's mandatory to keep it in (at least) 4.
Your declarations and definitions are not matching with the arguments that you are passing. i.e. void processData() is in your definition, but you declare it void processData(int, int);
The traditional approach for this problem is to collect all the data needed in some way, then call the function to do the work. For your case, you'd have to figure out the select value, and then the intA and intB values [1], then pass all three into processData.
The other opption is to chain the calls together, so ask for the select value first, then pass the select to the function that reads the data, and call the processData from there.
So you would end up with something like this:
void getInteger(int select)
{
cout << "Please enter integer one: " << endl;
cin >> intA;
cout << "Please enter integer two: " << endl;
cin >> intB;
processData(select, intA, intB);
}
void processData(int select, int intA, int intB)
{
... code goes here...
}
I'm intentionally NOT writing the complete code - the way to learn programming is to DO things for yourself. Copy-n-paste is something you probably already can do.
[1] This is a bit problematic, a function can only return one thing. Since you have two different values to return, that's not going to work. An experienced programmer would either use reference-arguments, or return a structure containing both values, but my guess is that's part of what you are learning in a future lesson, so let's skip that idea.
Here is a working version of your code... Take note of the changes and also take notice to the use of pointers in getInteger(int*,int*)
Hope this helps you out!
#include <iostream> //To input/output to the display (I think)
#include <conio.h> //For getch() at end of program
using namespace std;
//prototypes
void getInteger(int*,int*);
void getData();
void processData(int, int, int);
void displayData(int); // haven't added anything yet
int main(){
getData();
return 0;
}
void getInteger(int *ptrA, int* ptrB) {
*ptrA = 0; //safety
*ptrB = 0; //safety
int tempA = 0;
int tempB = 0;
cout << "Please enter integer one: " << endl;
cin >> tempA;
cout << "Please enter integer two: " << endl;
cin >> tempB;
*ptrA = tempA;
*ptrB = tempB;
}
void getData() {
int select = 100;
while(select != 0){
cout << "Available Functions" << endl;
cout << "0. Exit program" << endl;
cout << "1. Addition (+)" << endl;
cout << "2. Subtraction (-)" << endl;
cout << "3. Multiplication (*)" << endl;
cout << "4. Division (/)" << endl;
cout << "5. Modulus (%)" << endl;
cout << "Please type your selection (1-5): " << endl;
cin >> select;
if (select > 5 && select > 0) {
cout << "Error: Out of Bounds, please re-enter your selection: " << endl;
cin >> select;
}else if(select == 0){
break;
}
int intA, intB; //these are set in the following void
getInteger(&intA, &intB);
processData(intA, intB, select); //sends info to processData function
}
}
void processData(int intA, int intB, int select) {
int add, sub, mul, div, mod;
switch(select) {
case 1:
select = 1; //addition
add = (intA + intB);
displayData(add); //sends info to displayData function
break;
case 2:
select = 2; //subtraction
sub = (intA - intB);
displayData(sub);
break;
case 3:
select = 3; //multiplication
mul = (intA * intB);
displayData(mul);
break;
case 4:
select = 4; //division
div = (intA / intB);
displayData(div);
break;
case 5:
select = 5; //modulus
mod = (intA % intB);
displayData(mod);
break;
default:
cout << "There's been an error :(" << endl;
}
// return 0; void does not return
}
void displayData(int result){
cout << "The result is: " << result << endl;
}