My For Loops Aren't Working...

I've been wanting to make a very simple console based game in C++ and I was working on the map generation function but my for loops were not outputting the number of characters I wanted. Here is my code:

#include <iostream>
using namespace std;
int height = 40;
int width = 40;
void mapgeneration()
{
for (int i; i = width; i++)
{
cout << "-";
}
}
int main()
{
mapgeneration();
return 0;
}

You would think this would output:

----------------------------------------

but it outputs dashes infinitely for some reason I can't seem to put my finger on. Can anyone help?
Last edited on
This is a common operator confusion issue in C and C++.

    = != ==

It outputs infinitely because width is not zero, and not zero evaluates to true.

You also did not initialize i.


The usual (and correct) way to perform a numbered loop in C and C++ is the following form:

1
2
3
4
  for (int n = 0; n < N; n++)
  {
    ...
  }

where n is your counter variable (whatever you name it) and N is the number of times to go through the loop. In your case, it would be:

 
  for (int i = 0; i < width; i++)

Hope this helps.
Thank you so much for your reply! Your method did help. The reason my code may seem a bit sloppy is because I have only 2 months of C++ experience and I am 11 years old. But, thanks again for the help.
No problem, and don’t apologize; it is a common mistake, even for people plenty older than you. C and C++ are notorious for these kinds of syntax issues.

Going forward, try to find a reference or tutorial where you can see examples of using loops and functions and stuff, and try to stick with the syntactical conventions you see being used. Once you gain more experience about how the grammar is actually defined you can freely play with it more without getting surprised by odd behavior.

It is also worth your time to tell your IDE or compiler to complain about everything. Your compiler should have caught the uninitialized variable error for you and complained about it.

:O)
Topic archived. No new replies allowed.