Why Does My C++ Code Result in an Infinite Loop?

  • C/C++
  • Thread starter fluidistic
  • Start date
  • Tags
    C++ Logic
In summary: I will update my code to make the numbers truly random. Thank you for your help and explanation!In summary, the code is designed to generate random numbers between 1 and 3 and write them into a file until the new random number differs by either +1 or -1 from the previous random number. However, there are two variables called xold and two called x, which causes the loop to never end. Deleting the "ints" inside the do-while loop fixes the issue. Additionally, it is recommended to make the starting value for xold something far enough away from the range of the random numbers to ensure truly random results.
  • #1
fluidistic
Gold Member
3,949
264
I don't understand why I enter in an infinite loop with the following code:
Code:
#include <iostream> //for cout
#include <cstdlib> //for rand()
#include <ctime> // for time()
#include <fstream> //to write into a text file
using namespace std;

static const int M = 3;

ofstream myfile;
int main()
{
	srand(time(0)); // set initial seed value to system clock
		myfile.open("data.txt", ios::app);
int x=0;
int xold=0;
int i;
do
{
	int xold=x;
	int x = rand() % M+1;
	myfile << x << endl;
	i++;
}
while(x-xold!=1 && x-xold!=-1);
cout << "It took" << i << "iterations"  << endl;


return 0;

myfile.close();
}

The idea is to generate a random number between 1 and 3, write it into a file. Repeat until the new random number differs by either +1 or -1 from the previous random number. With the current code, the loop never ends and in a matter of a few seconds my file.txt is filled by 1's, 2's and 3's up to several Mb's.
As I understand it, my do {...} wile(x-xold!=1 && x-xold!=-1) should continue when x-xold is not equal to 1 and when x-xold is not equal to -1. So if I get xold=0 and x=1, then x-xold=1 and the loop should stop because the first condition is not satisfied... but it doesn't stop at all.
I guess my logic is flawed but I'm blind and don't see it. Any help will be appreciated.
P.S.:I started c++ 5 days ago for fun.
 
Technology news on Phys.org
  • #2
fluidistic said:
Code:
int x=0;
int xold=0;
int i;
do
{
	int xold=x;
	int x = rand() % M+1;
	myfile << x << endl;
	i++;
}
while(x-xold!=1 && x-xold!=-1);

You have defined two variables called xold, and two called x. Delete the "ints" inside the do-while loop.

FWIW a sensible compiler should give you a warning message if you "mask" one variable with another.
 
  • Like
Likes 1 person
  • #3
Also, if you want to make the numbers be truly random, I would make the number int xold be something like 10, something far enough away from the range of the random numbers.

Otherwise, you will always be starting with xold = 0, and you will be more likely to break with the results 0, 1; (unless that was your intention).

Writing to console worked in C#...
Code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace PFPlayground
{
    class Program
    {
        static void Main(string[] args)
        {
            Random random = new Random();
            int x = 0;
            int xold = 10;
            int i = 0;

            do
            {
                xold = x;
                x = random.Next(1, 4);
                Console.WriteLine(x);
                i++;      
            }
            while (x - xold != 1 && x - xold != -1);
            Console.WriteLine("It took {0} iterations", i);

            Console.ReadLine();
        }
    }
}
 
  • Like
Likes 1 person
  • #4
AlephZero said:
You have defined two variables called xold, and two called x. Delete the "ints" inside the do-while loop.

FWIW a sensible compiler should give you a warning message if you "mask" one variable with another.
Ah I see! I didn't even notice this. The program works fine now! Thanks!
TheDemx27 said:
Also, if you want to make the numbers be truly random, I would make the number int xold be something like 10, something far enough away from the range of the random numbers.

Otherwise, you will always be starting with xold = 0, and you will be more likely to break with the results 0, 1; (unless that was your intention).

Writing to console worked in C#...
Code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace PFPlayground
{
    class Program
    {
        static void Main(string[] args)
        {
            Random random = new Random();
            int x = 0;
            int xold = 10;
            int i = 0;

            do
            {
                xold = x;
                x = random.Next(1, 4);
                Console.WriteLine(x);
                i++;      
            }
            while (x - xold != 1 && x - xold != -1);
            Console.WriteLine("It took {0} iterations", i);

            Console.ReadLine();
        }
    }
}
Well spotted, thank you!
 
  • #5


I would recommend starting by checking the syntax and logic of your code. It is possible that there is a mistake in the way you are checking the condition in the while loop. Additionally, it may be helpful to use a debugger to step through the code and see where the loop is getting stuck. You can also try printing out the values of x and xold within the loop to see if they are changing as expected.

It is also important to consider the limitations of the rand() function in C++. It is not truly random and can produce patterns or biases in the generated numbers. You may want to explore other methods for generating random numbers, such as using the <random> library in C++.

Overall, it's great that you are learning C++ for fun and trying to solve this problem. Keep exploring and experimenting, and don't be afraid to ask for help or consult online resources for guidance. Good luck!
 

FAQ: Why Does My C++ Code Result in an Infinite Loop?

What is C++ used for?

C++ is a high-level programming language that is commonly used for developing operating systems, games, web browsers, and other software applications. It is also used in embedded systems, such as those found in cars and medical devices.

How does C++ differ from other programming languages?

C++ is an object-oriented language, which means it allows for the creation of reusable code and data structures. It also supports low-level programming, giving developers more control over memory usage and performance. Additionally, C++ is known for its speed and efficiency, making it a popular choice for applications that require high performance.

Is C++ difficult to learn?

Like any programming language, learning C++ requires time and practice. It has a steep learning curve, especially for beginners, but it is a powerful and versatile language that is worth the effort to learn.

Can C++ be used for web development?

C++ is not typically used for web development because it is a compiled language, meaning it needs to be converted to machine code before it can be executed. This process makes it less suitable for creating interactive and dynamic websites. However, it can be used for server-side scripting and backend development.

What is the difference between C and C++?

C++ is an extension of the C programming language, meaning it includes all of its features and adds new ones. C++ is an object-oriented language, while C is a procedural language. C++ also has a more extensive library and supports features such as templates and classes, making it more versatile and suitable for larger projects.

Similar threads

Replies
22
Views
3K
Replies
5
Views
2K
Replies
10
Views
2K
Replies
1
Views
1K
Replies
23
Views
2K
Replies
6
Views
10K
Replies
8
Views
2K
Back
Top