Home > OS >  Using a variable to define other variable before taking it as input
Using a variable to define other variable before taking it as input

Time:11-10

In the below code I defined both n and k initially and then if I define n as k/2 after I take k as input using cin, the code is successful but instead of this if I define n=k/2 before cin function I get an infinite loop as output? Please tell why is defining below or after cin function is affecting the output.

#include <iostream>
using namespace std;
int main () {
cout<< "how many asterisks you want in the middle column:";
int n,k;
// n=k/2 ; 
cin>>k;
// n=k/2;

//some code involving n
return 0;
 }

CodePudding user response:

The order of statements makes a difference:

int k = 2;
int n = k/2;
k = 4;

is different than

int k = 2;
k = 4;
int n = k/2;

In the first case, you get n = 1, and in the second n = 2. This really shouldn't surprise you! You might need to revise your programming basics before dealing with loops if it does :)

Other things:

  • never use using namespace std;. Not doing that, but specifically only importing the things you need will save you a lot of time later on, debugging very strange problems (I don't know why this is still taught): using std::cin;, using std::cout; is maybe longer, but much better, because you know what you get in your name space!
  • Properly indent your code. Yes, your editor has a function for that, and if it hasn't, get a better editor (these things really make a difference, especially for a beginner, because they help you spot little typos much easier!). Many beginners like Code::blocks as editor, because it's easy to set up and good, others like the more mightier VS Code.
  • Related