I'm practicing writing C++ on HackerRank and try makin' a good, clean code. So, is my code clean enough?
#include <iostream>
#include <cstdio>
using namespace std;
string number [9]
{
"one",
"two",
"three",
"four",
"five",
"six",
"seven",
"eight",
"nine"
};
int minN, maxN;
void checkN(int);
int main()
{
cin >> minN >> maxN;
for (int i = minN; i <= maxN; i++)
{
checkN(i);
}
return 0;
}
void checkN(int n)
{
if (n >= 1 && n <=9)
cout << number[n - 1] << endl;
else if (n > 9)
cout << ((n % 2 == 1) ? "odd" : "even") << endl;
}
If my code is clean, could you tell me what part is clean, vice versa for not-very-clean. Thanks in advance.
Đăng Tú
I'm ME! Surprise!
If clean = readable then your code is very clean.
Đăng Tú I would recommand you something like this:
#include <iostream>
#include <cstdio>
using namespace std;
void printParity(int n)
{
string number[9] =
{
"one",
"two",
"three",
"four",
"five",
"six",
"seven",
"eight",
"nine"
};
if (n >= 1 && n <=9)
cout << number[n - 1] << endl;
else if (n > 9)
cout << ((n % 2 == 1) ? "odd" : "even") << endl;
}
void checkNumbers() {
int minN, maxN;
cin >> minN >> maxN;
for (int i = minN; i <= maxN; i++)
{
printParity(i);
}
}
int main()
{
checkNumbers();
return 0;
}
I don't know if this code compile but some recommendations about code clarity
Well, it's C syntax, so code clarity is off the table before you even got started, but within that context I've seen far, far worse.
My only issues is the vague naming conventions. whilst certainly i,j,k for loops is "industry standard" and require no explanation, what is "n"? What are maxN and minN the max and minimum of? I mean I get it, it's a number where the min and max are read from the console, but you come back to this in a year or two or if someone less skilled has to deal with it, more verbose/explanatory names are your friend.
Mark
formerly known as M
I'm not great at C++, but two general opinions:
checkNcould be named more clearly, because now one has to read the function to know what it does. MaybeprintParity?