Reputation: 171
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!
Upvotes: 0
Views: 130
Reputation: 1666
Mistake:
The int x
is not initialized so it will lead to undefined behavior and x
will give you any random value instead of the correct sum.
Possible Solution:
Before you make any increment to the variable x
, Initialize it with zero to ensure that it will contain only those values which you want to store.
Updated Code:
int func(int a)
{
int x = 0; //updated statement
for (int i=0; i<=a; i++)
{
x+=i;
}
return x;
}
Hope this helps.
Upvotes: 5
Reputation: 20264
int x
is not initialized. Thus leads to undefined behaviour (This is why you got random numbers). You have to initialize it using one of those:
int x=0;
int x(0);
int x{0};
Upvotes: 1