I would like to have my entire program to repeat a single time without user input. How could I do this with both main and foo? I know how to repeat a program when there is just main but not when there are two functions.
int foo()
{
int a,
b,
c,
d;
cout << "Please enter three numbers: " << endl;
cin >> a;
cin >> b;
cin >> c;
d = a + b + c;
return d;
}
int main()
{
int Sum = foo();
cout << "Your sum of these numbers is: " << Sum << "\n" << endl;
return 0;
}
#include <iostream>
using std::cout;
using std::cin;
using std::endl;
int foo()
{
int a,
b,
c,
d;
cout << "Please enter three numbers: " << endl;
cin >> a;
cin >> b;
cin >> c;
d = a + b + c;
return d;
}
int main()
{
bool first_run = true;
while (first_run) {
int Sum = foo();
cout << "Your sum of these numbers is: " << Sum << "\n" << endl;
first_run = false;
}
int Sum = foo();
cout << "Your sum of these numbers is: " << Sum << "\n" << endl;
return 0;
}
Its exactly what I needed. However I dont understand how this works. Do you mind explaining to me whats going on in line 25 - 29? How does it know to go back up and run foo again?
while (first_run) {
int Sum = foo();
cout << "Your sum of these numbers is: " << Sum << "\n" << endl;
first_run = false;
}
in other words
1 2 3 4 5 6
this = true;
while (this = true)
{
run this code.
then set this = false.
}
so it sets "first_run" to true.
while loop works while "this" is true
then once while loops executes it sets "this" to false...
then it does not run again.
Its exactly what I needed. However I dont understand how this works. Do you mind explaining to me whats going on in line 25 - 29? How does it know to go back up and run foo again?
The code in question is a loop which only runs once. It is a bit of obfuscation.
The main is equivalent to:
1 2 3 4 5 6 7 8 9 10 11
int main()
{
int Sum = foo();
cout << "Your sum of these numbers is: " << Sum << "\n" << endl;
int Sum = foo();
cout << "Your sum of these numbers is: " << Sum << "\n" << endl;
}
Something more useful might be:
1 2 3 4 5 6 7 8 9
int main()
{
constunsigned times_to_execute = 2 ;
for (unsigned i=0; i<times_to_execute; ++i)
{
int sum = foo();
cout << "Your sum is: " << sum << '\n';
}
}