# Why my code is going wrong in C++?

+1 vote
Why the following code is wrong?

int main()
{
int f(int n)
{
int p;
if(999 % n == 0){
p=999/n;
}
if(999 % n !=0){
p=(999-(999 % n))/n;
}
return n*(p*(p+1)/2);
}

cout<<f(3);
}

answered Apr 20, 2018 by (440 points)

You can not define function inside main function .

int f(int n)
{
int p;
if(999 % n == 0){
p=999/n;
}
else if(999 % n !=0){
p=(999-(999 % n))/n;
}
return n*(p*(p+1)/2);
}

int main()
{
std::cout<<f(3);

return 0;
}

commented Apr 20, 2018 by anonymous
Thanks. It works :)
answered Apr 17, 2018 by (500 points)
i am still learning C++  but try this

#include <iostream>

using namespace std;

int main()
{
int a;
int n;
{
int p;
if(999 % n == 0){
p=999/n;
}
if(999 % n !=0){
p=(999-(999 % n))/n;
}
return n*(p*(p+1)/2);
}

cout<<(3);
}
commented Apr 18, 2018 by anonymous
No, that's wrong :(
answered Apr 18, 2018 by (180 points)

int main()
{   int x;
int f(int n)
{
int p;
if(999 % n == 0)

{
p=999/n;
}
else

{
p=(999-(999 % n))/n;
}
return n*(p*(p+1)/2);
}
x=f(3);         //As the fn is returning a value, it must be held by some other temp varbl of same return type
cout<<x;
}

answered Apr 18, 2018 by (180 points)

int main()
{     int x;
int f(int n)
{
int p;
if(999 % n == 0)

{
p=999/n;
}
else

{
p=(999-(999 % n))/n;
}
return n*(p*(p+1)/2);
}
x=f(3);                    //As the fn returns a value,it must be held somewhere in the                                                  //   memory by a temp variable.
cout<<x;
}

commented Apr 18, 2018 by anonymous
Thanks. But it doesn't still work. I run it  in an online compiler right here

https://www.onlinegdb.com/online_c++_compiler