-
Simple question...
I would like to know what to include in my programs so that they go back to the start of the program once its done so you can start again.
example code:
#include <iostream.h>
#include <stdio.h>
int main()
{
int number1 = 0;
cout << "Enter a number";
cin >> number1;
int number2;
cout << "Enter another number";
cin >> number2;
int total;
total = (number1) + (number2);
cout << "Total is:";
cout << total;
return 0;
}
What would you add to this example code to make it so that the program goes back to the beginning after it gives you the answer?
Thanks
-Chris
-
A do loop works nice
#include <iostream>
using namespace std;
int main()
{
char response;
do {
int number1 = 0;
cout << "Enter a number";
cin >> number1;
int number2;
cout << "Enter another number";
cin >> number2;
int total;
total = (number1) + (number2);
cout << "Total is:";
cout << total << endl;
cout << "Add another number? (Y/N)";
cin >> response;
} while (response == 'y' || response == 'Y');
return 0;
}
-
Look up control loops in your text or tutorial. They include the do/while loop, an example of which was provided, as well as while loops and for loops. Loops are a big thing in writing code so learning how to use them effectively will be good training for you. Basically the loops allow you to control how often to do something so you don't need to keep writing the same basic code over and over again.