Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Using a variable to define other variable before taking it as input

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;
 }

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading