Bettering myself with C++

Hello! I am currently a student pursuing a degree in computer engineering.

I want to eventually get into writing code and programming professionally.

I will be posting code that I write (Maybe a program a week) And asking for improvement in anyway possible.

The code will start out semi simple, and as I grow, it will grow with me.

If you suggest changes, please explain why you suggest the change and what effect it would have on the code, may it be speed wise or flow wise or what have you.

I want everyone to be able to learn from the improvements that are given to the code.

Here we go, this is a fairly simple program that converts celcius values to farenheit values by increments set by the user.


/* This progarm converts Celcius to farenheit. It does so by taking a user input
of a celcius temperature they would like to start at. It then asks for an end celcius
number. Finally, the program asks the user what imcriment they would like the program
to calculate farenheit differences in. */


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
#include <iostream>
#define MAX_TEMP  50000
#define MIN_TEMP  0

using namespace std;

int main()

{
    int start, end, step, stepDif, count; // Start is the temperature to start at. end is the temp to end at. step is the step size between calucations. 
    //stepDifference is the difference between end and start.
    double cel, far, rep;

    cout << "Welcome to the Temperature converter!" << endl;
    cout << "Please enter in a minimum temperature above 0 in Celcius. " << endl;
    cin >> start;
    while(start < MIN_TEMP)
       {
              cout << "Please enter in a value above 0 in Celcius. " << endl;
              cin >> start;
              }
       cout << "Please enter in a maxiumum temperature to end at below 50000 and above " << start << " in celcius."<< endl;
       cin >> end;
       while (end > MAX_TEMP || end < start)
       {
          cout << "Please enter a value below 50000, and above " << start << " in celcius." << endl;
          cin >> end;
          }
    stepDif = end - start;
    cout << "Next, enter a step value that is less than: " << stepDif << " celcius. "<< endl;
    cin >> step;
    while (step > stepDif)
    {
          cout << "Please enter a step value that is les than: " << stepDif << " celcius." << endl;
          cin >> step;
          }
    cout << "Celcius      " << "  Farenheight" << endl;
    cout << "_______      " << "  ___________"<<  endl;
    rep = start;
          for(count=0; rep<end; count++) // This loop is to add the step number to the celcius temp, and translate celcius into farenheit for every temp.
           {
                        cel = rep;
                        far = rep*1.8-32;
                           cout << endl;
                           cout << rep << "                " << far << "         " << endl;
                           rep=rep+step;
                           }     
           cin >> count;
    return 0;
}

closed account (D80DSL3A)
I think most of it looks OK for early coding.

All of those uninitialized variable declarations on lines 10 and 12 look a bit scary, but I see that you get values assigned to them all OK.

Some clear flaws:
Two of the aforementioned variables (rep, count) don't really serve any useful purpose in the program. count serves no purpose in the for loop lines 40 through 47 (it's not affecting anything), although it looks like it may be serving a useful purpose on line 48 by keeping the program from ending (so the console window remains open). The variable 'rep' can be eliminated from the for loop. The quantity being incremented is cel. This can be done directly in the for loop (what it's for)
The loop could be written as compactly as this:
1
2
3
4
for(cel=start; cel<end; cel = cel+step)
{                   
        cout << endl << cel << "                " <<  cel*1.8-32 << "         " << endl;
}

Isn't it easier to see what this loop is doing?
Keep up the good work on your studies.

EDIT:
I was going to suggest creating a function to handle the user input validation since that would cleanup the code in main a lot, but I don't know quite where you're at with that, so I'll just show you an example based off of your code.
I got a little carried away and delegated table output to a function as well.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
#include <iostream>
#define MAX_TEMP  50000
#define MIN_TEMP  0

using namespace std;

void getInt_BetweenLimits( int loVal, int hiVal, int& data )
{
    cin >> data;
    while( (data <= loVal ) || (data >= hiVal) )
    {
        cout << "Please enter a value between " << loVal << " and " << hiVal << endl;
        cin >> data;
    }
}

void displayTable( int start, int end, int step )
{
    cout << "Celcius      " << "  Farenheight" << endl;
    cout << "_______      " << "  ___________"<<  endl;
    for(int cel=start; cel<end; cel = cel+step)
    {
        cout << endl << cel << "                " <<  cel*1.8-32 << "         " << endl;
    }
}

//** main function **

int main()

{
    int start, end, step;

    cout << "Welcome to the Temperature converter!" << endl;

    cout << "Please enter in a minimum temperature above 0 in Celcius. " << endl;
    getInt_BetweenLimits( MIN_TEMP, MAX_TEMP, start );

    cout << "Please enter in a maxiumum temperature to end at below 50000 and above " << start << " in celcius."<< endl;
    getInt_BetweenLimits( start, MAX_TEMP, end );

    cout << "Next, enter a step value that is less than: " << end-start << " celcius. "<< endl;
    getInt_BetweenLimits( 0, end-start, step );

    displayTable( start, end, step );

    cin >> start;// keep window open
    return 0;
}
Last edited on
It's good that you are trying to avoid magic numbers in your code with:
1
2
#define MAX_TEMP  50000
#define MIN_TEMP  0 


But this would be even better:
1
2
3
4
constexpr int MAX_TEMP = 50000 ; // C++11
constexpr int MIN_TEMP = 0 ; // C++11
// const int MAX_TEMP = 50000 ; // C++98
// const int MIN_TEMP = 0 ; // C++98 

See: http://www.parashift.com/c++-faq/const-vs-define.html



This is not a good idea:
1
2
3
4
5
6
7
int start, end, step, stepDif, count; 
// ...
// and ten, much later:
stepDif = end - start;
// ...
for(count=0; rep<end; count++) 
// ... 


Instead:
1
2
3
4
5
6
int start, end ; 
// ...
int stepDif = end - start;
// ...
for( int count=0;  rep<end; ++count ) 
// ... 

See: http://stackoverflow.com/questions/6429460/should-one-keenly-consciously-attempt-to-postpone-variable-definitions-as-long



This can be made more compact, and the magic number can be avoided:
1
2
3
4
5
6
cin >> start;
while(start < MIN_TEMP)
{
    cout << "Please enter in a value above 0 in Celcius. " << endl;
    cin >> start;
}


Instead:
1
2
3
4
5
6
7
8
while( cin>>start && start<MIN_TEMP )
{
    // avoid magic numbers. 
    // http://www.parashift.com/c++-faq/naming-numeric-literals.html
    cout << "Please enter in a value not lower than " << MIN_TEMP << " in Celcius.\n" ;
    // and if needed, we can later add extra error handling here
    // for instance, if the user has not entered a number at all. 
}



I only see 3 comments in the code, not a very good start for someone wanting to be a computer engineer.

Thank you for all of the replies and good comments on what I need to improve.

What I am getting from your comments is that I need to make the code more compact, initialize my variables right before I need to use them, and use a lot more comments in the code.

I will definitely keep all of that in mind.

Should I start working more on this code, or should I just start a whole new program and incorporate what you guys taught me?
closed account (o3hC5Di1)
Hi there,

Depends on your own preference.
Sometimes it is good thought to go back at existing code and see how you can improve it, at other times it can be frustrating because a program that used to compile is now throwing a bunch of errors at you.

One small note: The amount of commenting is highly subjective. Some people swear by "self explaining code", where they claim the code is so clearly written it doesn't need much commenting, others swear by copious amounts of comments. I like to think the ideal is probably somewhere in the middle, where your code is self explaining, but you add comments here and there to explain why you did something in a certain way if it might not be so obvious.

All the best,
NwN
> Some people swear by "self explaining code"

I do.

Tend to agree with most of this:
Use comments to explain what you cannot state directly in code. Comments are for you and your friends. Compilers don’t understand them.

Do not imitate comments in the book that explain what a language feature does – by the time you use a feature you are supposed to know that.

Don’t say in comments what can be said clearly in code. Code is good at saying exactly what is done (in minute detail and even if it wasn’t what you wanted it to do). Comments are good for

1. Stating intent (what is this code supposed to do)
2. Strategy (the general idea of this is …)
3. Stating invariants, pre- and post-conditions

If the comments and the code disagree, both are most likely wrong.

- Stroustrup in 'PPP Style Guide'


Even for invariants:
1
2
3
4
5
// invariant: by now, we have established that n is a positive, even integer
// That is just a comment; if that assumption is wrong, the comment is not going to do anything about it.

assert( n > 0 && n%2 == 0 ) ; // documents the invariant in *working* code
// with this in place , a comment would be an unnecessary distraction. 


This does not require any comment; the code explains everything that needs to be explained:
void getInt_BetweenLimits( int loVal, int hiVal, int& data ) ;

And this is completely unnecessary; it just impairs readability:
1
2
3
4
//** main function **

int main()
{


closed account (D80DSL3A)
@JLBorges. I am in general agreement on your last point. I ordinarily wouldn't place a comment like //** main function ** .

This raises a point, which I don't see explicitly treated above, re. how the target audience (OP) can influence commenting decisions.
In most of the posts above I believe an assumption is being made that the comments are being placed for the benefit of experienced coders.

When I posted I didn't feel it reasonable to assume that PatricBernard had ever seen functions defined outside of main before.
That comment was intended to serve as a visual cue to help delineate the unfamiliar looking code from the familiar, which I thought wold be helpful.

I will take your comment regarding the lack of need for comment on
void getInt_BetweenLimits( int loVal, int hiVal, int& data ) ;
as a compliment. I was trying to make the code do as much of the talking as possible.

It is hard (perhaps impossible) to regain the perspective of an untrained eye when responding to newbies, so my commenting may err on the side of excess in that context.

Do you have any good rules for adapting commentary aimed at newcomers?
This is All very good info. I didn't leave as many comments because I figured the code was fairly simple to understand. I have seen code written with functions outside of the main program, but I am not comfortable with writing like that yet. I will definitely be doing that I'm my next program, because I feel like it's just something you have to just jump into.
> In most of the posts above I believe an assumption is being made
> that the comments are being placed for the benefit of experienced coders.

Yes.


> This raises a point, which I don't see explicitly treated above,
> re. how the target audience (OP) can influence commenting decisions.

Comments in code intended for educational purposes is for teaching what an unfamiliar language feature or algorithm does. Comments in production code are for aiding programmers who write and maintain the code.

So:
Do not imitate comments in the book that explain what a language feature does – by the time you use a feature you are supposed to know that.


For example, this could be appropriate in a beginners forum post, and inappropriate in production code:
1
2
3
4
5
6
7
8
while( cin>>start && start<MIN_TEMP ) // while the user has entered a number, and the number is valid 
{
    // avoid magic numbers. 
    // http://www.parashift.com/c++-faq/naming-numeric-literals.html
    cout << "Please enter in a value not lower than " << MIN_TEMP << " in Celcius.\n" ;
    // and if needed, we can later add extra error handling here
    // for instance, if the user has not entered a number at all. 
}



> When I posted I didn't feel it reasonable to assume that PatricBernard
> had ever seen functions defined outside of main before.

Yeah, that was careless of me; I had copied excerpts from your code under the belief that it was from PatricBernard's code. Didn't scroll up all the way.

Topic archived. No new replies allowed.