I am a relative beginner with C++ and currently I am learning how to do functions. Recently I received the following exercise:
#include <iostream>
#include <string>
using namespace std;
int main(int argc, char* argv[])
{
int a,sum=0;
cout<<"Enter a number:";
cin>>a;
int func(int x);
sum=func (a );
cout<<"\n"<<sum;
}
int func(int a)
{
int x;
for (int i=0; i<=a; i++)
{
x+=i;
}
return x;
}
I was already given the int main part of the code in advance, what I need to do is to complete the int func
part so the code would execute properly. If I run this code I just get some random numbers. What the func
should do is to return the sum of all natural numbers limited by the number imputed by the user. Could you tell me how would I have to change this code so it would work properly? Thank you for any feedback!