0

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!

Leśny Rumcajs
  • 2,259
  • 2
  • 17
  • 33
Noir
  • 171
  • 1
  • 9

3 Answers3

5

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.

Itban Saeed
  • 1,660
  • 5
  • 25
  • 38
  • Thank you a lot Itban. The issue was solved as soon as I added the "=0". A very unfortunate blunder from my side for failing to notice the fallacy in the code. Regardless I compliment how you structured the solution, it is very clear and concise. – Noir Dec 29 '15 at 13:26
  • You are welcome @Noir :) I just tried to provide a clear solution – Itban Saeed Dec 29 '15 at 13:29
2

you must init x in func body

int x = 0;
1

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};
Humam Helfawi
  • 19,566
  • 15
  • 85
  • 160