Do both tasks one after another. Take the contents of the main function of each and put them into the third, "combined" main function.
1 2 3 4
int main () {
// program 1's code here
// program 2's code here
}
If you choose, you can introduce a new lexical scope so that both independent programs get their own "num" variable and you don't have to worry about name collisions (in other words, you can guarantee it compiles on the first try) by writing
1 2 3 4
int main () {
{ /* program 1's code here */ }
{ /* program 2's code here */ }
}
You'll have to remove the explicit return statement from the bottom of the main function in the first program you put in.
#include <iostream>
usingnamespace std;
void printNumbersInRow(int startValue, int stopValue, int stepSize, int numberOfValuesInSingleRow)
{
int numberOfValuesToOutput = 0;
int step;
if (startValue > stopValue)
{
step = 0 - stepSize; // in this case we should count backwards
numberOfValuesToOutput = (startValue-stopValue)/stepSize;
}
else
{
step = stepSize;
numberOfValuesToOutput = (stopValue-startValue)/step;
}
for (int counter = 0; counter < numberOfValuesToOutput; counter++) // this loop now counts up or down depending on what we want
{
if (counter > 0 && counter%numberOfValuesInSingleRow==0) cout << endl; // after every tenth value, we go to a new line
if (startValue % stepSize == 0) cout << startValue << " "; // output the desired values
startValue = startValue + step;
}
cout << endl;
}
int main()
{
printNumbersInRow(0,100, 2, 10);
cout << "-------\n";
printNumbersInRow(99,0, 3, 5);
system("pause");
return 0;
}
Using functions is typically a good idea if you have to do things multiple times (re-use your code) and/or if you want to separate the code you use for separate tasks.
Often to make a function more general usable (more re-usable) makes the function itself a bit more difficult, so note that while you are learning this is something to think about but not something that is important. It is far more important that you properly understand the code that you write.