I am new to programming and have been learning C++. I was working on using while conditions and the exercise was use while in a compound-statement to count down for a number to 1. With out looking at the example source code my program came out looking like this:
#include <iostream>
usingnamespace std;
int main() {
int n;
//Get a number from the keyboard.
cout << "Enter a number and press ENTER: ";
cin >> n;
while (n >= 1) {
cout << n << " ";
n = n - 1;
}
return 0;
}
Now this code worked just fine to do what was asked but then I looked at the example code and it shows this:
#include <iostream>
usingnamespace std;
int main() {
int i, n;
// Get a number from the keyboard and initialize i to n.
cout << "Enter a number and press ENTER: ";
cin >> n;
i = n;
while (i > 0) { // While i greater than 0,
cout << i << " "; // Print i,
i = i - 1; // Add 1 to i.
}
return 0;
}
Now both of these work just fine and I understand that you can often find different ways to solve the same problem in programing but I was wondering which was a better way to do it? I would like to start out using the best practices possible and learning good coding habits along the way assuming one is better, so any input on this would be greatly appreciated.
Thank you.
Ok, i am also new at C++, but the second code looks pointless. What is the point of initaiazing(wow spellign sucks) a variable to equal a variabel if it is already there. On the other hand it could be useful for things like this code:
.....
cin >> n;
i=n;
then...
h=i*n
j=(n-1+1)
stuff like that.
But on even antoher hand all of that could be done diffrent ways with only 2 vars instead of 3
i=n
j=i*n
or
j=n*n(or n squared or sioomething)
well anywasy definetly second and sorry for horribel spelling
I would recommend the first way. I don't see the point in making one variable equal to another just for the sake of using it later in the code when the original variable would do just as well.
Ok, thanks for the information. I was thinking some of the same things but when your new to something and the authority on the matter (the book or person that you are learning from) tells you different, you tend to second guess yourself. At least I do at first.
Thanks for the input!
You know I started to play with it and tried to see if maybe the books way worked better with negative numbers but they handled them the same. I guess they only did it that way because the example before it was using i = i + 1 to count up and they wanted to show it in that context like in this example:
#include <iostream>
usingnamespace std;
int main() {
int i, n;
//Get a number from the keyboard and initialize i.
cout << "Enter a number and press Enter: " <<endl;
cin >> n;
i = 1;
while (i <= n) { //While i less than or equal to n,
cout << i << " "; // Print i,
i = i + 1; // Add 1 to i.
}
return 0;
}