TryOmar's blog

By TryOmar, history, 2 years ago, In English

Hello guys.. I was solving a simple problem that asked me to find the sum of n numbers So I thought about solving this problem with recursion And since I don't like making a lot of functions, instead I decided to use the main function. And yeah that program worked in an efficient way ✅ If you want to try it here it is (just don't use freopen)

#include <bits/stdc++.h>

using namespace std;
int n = 0, x;
int main() {
	//Made By Benjamin007
	static long long sum = 0;
	static int i = 0;
	if (n == 0)
		cin >> n;
	i++;
	if (i <= n) {
		cin >> x;
		sum += x;
		if (i == n)cout << sum;
		return main();
	}
	return 0;
}

  • Vote: I like it
  • +19
  • Vote: I do not like it

| Write comment?
»
2 years ago, # |
Rev. 2   Vote: I like it +19 Vote: I do not like it

Just because something would appear to work in a test example doesn't mean it always will, or is correct.

According to the C++ standard The main function has several special properties:

1) It cannot be used anywhere in the program

a) in particular, it cannot be called recursively

b) its address cannot be taken