0

what is the problem while defining it by users it is not working so any of you have a solution for this issue...

#include<iostream>
using namespace std;
int main()
{
    int x;
    cout<<"Enter the value of x =";
    cin>>x;
    for(int x; x < 10; x++)
    {
        cout << x << endl;
    }
    return 0;
}
John Kugelman
  • 349,597
  • 67
  • 533
  • 578
  • 3
    your for loop introduces a new (uninitialized) x variable, you have undefined behavior. it should be `for (; x < 10; x++)` – Borgleader May 18 '22 at 14:02
  • 1
    `for(int x; x < 10; x++)` defines a new `int x` without initializing it, which shadows your `int x;` in the `main` scope. – mch May 18 '22 at 14:02
  • 2
    Maybe you want `for(int i=0; i < x; i++) { cout << i << endl; }` I am not sure because I am unsure of the exact problem you are trying to solve. – drescherjm May 18 '22 at 14:04
  • 1
    Increase your warning level, and compiler would warn for shadowing and more important, uninitialized variable. – Jarod42 May 18 '22 at 14:05

1 Answers1

2

You are creating a variable named x twice: First in line 5 and again in line 8 in the for loop. The second declaration shadows the first one, i.e. the value entered by the user is never used in the loop. It's better to use a loop variable (like i) that is initialized to the value of x and incremented after each iteration, i.e.

...
cin >> x;
for (int i = x; i < 10; ++i)
{
...
}
FMeinicke
  • 639
  • 5
  • 15