Carlos
Carlos

Reputation: 425

C++ - Loop runs infinitely

I've been working on this problem for hours now, but can't seem to be able to figure it out. The while loop is running infinitely because the increment function is not working properly. Would really appreciate any pointers.

void Increment(int);

int main()
{
    int count = 1;
    while(count < 10){
        cout << “ The number after “ << count; /* Function Increment adds 1 to count */
        Increment(count);
        cout << “ is “ << count << endl;
    }
    return 0;
}

void Increment (int nextNumber)
// Increment the parameter by 1
{
    nextNumber++;
}

Upvotes: 0

Views: 211

Answers (4)

AKV
AKV

Reputation: 455

#include <iostream>

using namespace::std;

void Increment(int*);
int main()
{
    int count = 1;
    while(count < 10){
        cout << "The number after "  << count << endl;
        Increment(&count);
        cout <<  "is "  << count << endl;
    }
    return 0;
}

void Increment (int *nextNumber)
// Increment the parameter by 1
{
    (*nextNumber)++;
}

Upvotes: 0

Rhnbmpl
Rhnbmpl

Reputation: 88

The increment is only happening to the object created in the "Increment" method. Outside the method, the "nextNumber" does not exist as there is no link to the main function. The solution is to pass the addrress of the "count" variable, store the address in the pointer in the "Increment" method and do the operation. The pointer operation will affect the memory of the variable "count" as the memory reference of "count" is passed to "nextNumber"

void Increment(int*);

int main()
{
    int count = 1;
    while(count < 10){
    std::cout << " The number after " << count; /* Function Increment adds 1 to count */
    Increment(&count);
    std::cout << " is " << count << std::endl;
    }
return 0;
}

void Increment (int *nextNumber)
// Increment the parameter by 1
{
    *nextNumber=*nextNumber+1;
}

Upvotes: 0

Nhan Phan
Nhan Phan

Reputation: 1302

void Increment(int) will not change the variable after the method is called. You must add & to the medhod: void Increment(int &).

Then your code will look like:

void Increment(int &);

int main()
{
    int count = 1;
    while(count < 10){
        cout << “ The number after “ << count; /* Function Increment adds 1 to count */
        Increment(count);
        cout << “ is “ << count << endl;
    }
    return 0;
}

void Increment (int & nextNumber)
// Increment the parameter by 1
{
    nextNumber++;
}

Upvotes: 0

adn.911
adn.911

Reputation: 1314

It's not working because when you are passing count to the function Increment a separate copy is created and that value is updated, not the original one. If you want the original value to be updated pass by reference or pointer.

void Increment (int &nextNumber)
// Increment the parameter by 1
{
    nextNumber++;
}

Also, I don't think it's necessary to create a separate function for incrementing, you can just do count++ on the main function.

Upvotes: 4

Related Questions