Reputation: 177
I made a simple program to test whether I am able to call main in any other function like we call different functions in other function.
Therefore, I made a program to generate the maximum number by getting input of 3 numbers from the user. For this I made the function containing if else. Surprisingly (especially for me) it worked. I got that I am keep inputting the numbers then I made another variable to control the inputs. I made it to input 3 times. I got answer from bottom to end and 3 answers are generated.
#include <iostream>
using namespace std;
int main();
void max(int a, int b, int c,int p);
int p = 0;
int main()
{
p++;
int a, b, c;
cout << "\n\n";
cout << "Enter 1st number :\t";
cin >> a;
cout << "Enter 2nd number :\t";
cin >> b;
cout << "Enter 3rd number :\t";
cin >> c;
max(a, b, c, p);
cout << "\n\n\n";
system("pause");
return 0;
}
void max(int a, int b, int c,int p)
{
if (p < 3)
{
main();
}
if (a > b&&a > c)
{
cout << a << " is maximum";
}
else if (b > a&&b > c)
{
cout << b << " is maximum";
}
else
{
cout << c << " is maximum";
}
}
The output was as follows: -
Enter 1st number : 12
Enter 2nd number : 14
Enter 3rd number : 15
Enter 1st number : 45
Enter 2nd number : 69
Enter 3rd number : 88
Enter 1st number : 14
Enter 2nd number : 20
Enter 3rd number : 11
20 is maximum
Press any key to continue . . .
88 is maximum
Press any key to continue . . .
15 is maximum
Press any key to continue . . .
I don't get the logic behind it. I used Visual Studio 2017 for this.
Upvotes: 2
Views: 138
Reputation: 155
So I worked a bit on your code, and managed to maybe make it work as you intended it do to. It really wasn't such a big deal. I found a cleaner and easier to read code.
The changes in the code are 1st in the beginning :
#include <iostream>
void max(int a, int b, int c);
int a, b, c;
int main()
{
for(int p = 0; p < 3; p++) {
std::cout << "\n\n";
std::cout << "Enter 1st number :\t";
std::cin >> a;
std::cout << "Enter 2nd number :\t";
std::cin >> b;
std::cout << "Enter 3rd number :\t";
std::cin >> c;
max(a, b, c);
std::cout << "\n\n\n";
}
system("pause");
return 0;
}
You can see I removed the using namespace std; because I really don't like having that, you can add it if you want it it's just my preference. You see I made the whole code repeat in a for loop to remove the calling of the main function, and don't worry many of us have done it too. As you can see I also changes the max() function's parameters The second change in the code is in the last part of the code:
void max(int a, int b, int c)
{
if (a > b&&a > c)
{
std::cout << a << " is maximum";
}
else if (b > a&&b > c)
{
std::cout << b << " is maximum";
}
else
{
std::cout << c << " is maximum";
}
}
Here I just removed the part of the code which calls the main function. And overall it's all that had to change in your code to work.
Upvotes: 1