Noir
Noir

Reputation: 171

Random numbers on output

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

Answers (3)

Itban Saeed
Itban Saeed

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

DvoryankinEvgeny
DvoryankinEvgeny

Reputation: 128

you must init x in func body

int x = 0;

Upvotes: 2

Humam Helfawi
Humam Helfawi

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

Related Questions