I'm teaching myself C would somebody look at my...

ManyBeers

Platinum Member
Aug 30, 2004
2,519
1
81
solution to this exercize:
Write a program that sorts the number of twenties,tens,fives,and ones from a user inputted value. From the book K.N.King C Progr
amming: A Modern Approach 2nd Edition....pg 34 ex.7.
I am studying this on google books. By the way this is Not homework I am 61 years old. My program compiles and works
but I would just like some experienced coders to look it over and
tell me what they think. Thanks

Code:
        /*Sorts twenties,tens,fives,and ones*/
#include <stdio.h>

int main(void)
{
    int T=(20),t=(10),f=(5),o=(1);
    int Tv,tv,fv,ov;/*number of each dollar value*/
    int value;
    
    printf("Enter a dollar amount 1-100\n");/*I limited this value*/
    scanf("%d", &value);
    
    Tv=value / T;
    tv=(value % T)/t;
    fv=(value % t)/f;
    ov=(value % T % t % f);
    
    printf("There are %d twenties %d tens %d fives and %d ones\n", Tv ,tv, fv, ov);
    return 0;
}
 
Last edited:

Leros

Lifer
Jul 11, 2004
21,867
7
81
The basic structure of the program seems fine. I have some stylistic suggestions, although style is subjective and sometimes almost religious.

Code:
# If you're going to have variables for the different values,
# I would make them all capitalized.
# You can also label them as const, since you know they will never be reassigned. 
const int TWENTY = 20, TEN = 10, ....

# I don't like single variable names
# Spell things out for readability 
int twentyValue, tenValue, ....

# I think your math could be structured a bit cleaner
# But this is totally subjective.
# I would do something like this:
remainingValue = value;
twentyValue = remainingValue % 20;
remainingValue -= twentyValue * 20;
tenValue = remainingValue % 10;
remainingValue -= tenValue * 10;
...
 
Last edited:

SteveGrabowski

Diamond Member
Oct 20, 2014
9,034
7,768
136
If you're just learning how to program, you might really like this course from edx:

https://www.edx.org/course/harvardx/harvardx-cs50x-introduction-computer-1022#.VEc7xvnF95Y

I haven't gone through all of it, but the parts I have watched are incredible and this is supposed to be a legendary course at Harvard. You don't have to know any programming but if you do know a bit they have a second harder tier for their homework assignments so that you don't get bored. You can tell the students and teacher really enjoy this course, and it will take you from Hello World to some pretty advanced C (like buffer overflows). It's not a course on C, as it's a course on programming and as it also has some other languages it uses too. But it's really fun and challenging and seems like a very efficient way to build your skill. You should consider trying it out to see if you like it.
 

ManyBeers

Platinum Member
Aug 30, 2004
2,519
1
81
The basic structure of the program seems fine. I have some stylistic suggestions, although style is subjective and sometimes almost religious.

Code:
# If you're going to have variables for the different values,
# I would make them all capitalized.
# You can also label them as const, since you know they will never be reassigned. 
const int TWENTY = 20, TEN = 10, ....

# I don't like single variable names
# Spell things out for readability 
int twentyValue, tenValue, ....

# I think your math could be structured a bit cleaner
# But this is totally subjective.
# I would do something like this:
remainingValue = value;
twentyValue = remainingValue % 20;
remainingValue -= twentyValue * 20;
tenValue = remainingValue % 10;
remainingValue -= tenValue * 10;
...

Hey thanks for chiming in.
Yes you're right I should have made them constants which they are. As for the variables I did that just to reduce the amount of typing. Also this is just practice.

I was looking for input on the math and thanks for the suggestions. Math has never been my strong suit so I will
have to pay special attention to it.
 

purbeast0

No Lifer
Sep 13, 2001
53,664
6,546
126
i agree to definitely spell out your variables. when i think back in college, many variable names in my beginner courses were just letters, because in context, they really had no meaning. but looking back, i think they should teach you from early on to give variable names meaning.

imo, ideally you want people to be able to read your code without having to have any comments in there, and let the code speak for itself. contrary to what you are taught in school, imo, there is such thing as too many comments. to me, comments should be left for explaining the reasoning behind what you are doing or the business rules that are going into play with the code below it.

and as Leros mentioned, the math is subjective as to "how" to do it. i personally prefer your method over Lero's.
 

cabri

Diamond Member
Nov 3, 2012
3,616
1
81
i agree to definitely spell out your variables. when i think back in college, many variable names in my beginner courses were just letters, because in context, they really had no meaning. but looking back, i think they should teach you from early on to give variable names meaning.

imo, ideally you want people to be able to read your code without having to have any comments in there, and let the code speak for itself. contrary to what you are taught in school, imo, there is such thing as too many comments. to me, comments should be left for explaining the reasoning behind what you are doing or the business rules that are going into play with the code below it.

and as Leros mentioned, the math is subjective as to "how" to do it. i personally prefer your method over Lero's.

Back in the 70s, technology was using cassette tape drives - Basic only allowed one character and one number.

How things have advanced
 

TridenT

Lifer
Sep 4, 2006
16,800
45
91
Even if it's a practice exercise, always use better variable names. You're practicing writing good code. So, you should follow good coding guidelines as part of your practice. :)
 

Cogman

Lifer
Sep 19, 2000
10,286
147
106
i agree to definitely spell out your variables. when i think back in college, many variable names in my beginner courses were just letters, because in context, they really had no meaning. but looking back, i think they should teach you from early on to give variable names meaning.

imo, ideally you want people to be able to read your code without having to have any comments in there, and let the code speak for itself. contrary to what you are taught in school, imo, there is such thing as too many comments. to me, comments should be left for explaining the reasoning behind what you are doing or the business rules that are going into play with the code below it.

and as Leros mentioned, the math is subjective as to "how" to do it. i personally prefer your method over Lero's.

I agree on the comments. Good code, IMO, should have almost no comments. Comments are best used method documentation (xdocs) and warning a developer that the code that follows is complex, is trying to do x, and here is why it is complex.

Beyond that, comments tend to just obfuscate the code, especially when overly done and done incorrectly (common mistake for newer guys). Most of what you would normally put in comments should go into the commit message of your version control system.
 

Spungo

Diamond Member
Jul 22, 2012
3,217
2
81
i agree to definitely spell out your variables. when i think back in college, many variable names in my beginner courses were just letters, because in context, they really had no meaning. but looking back, i think they should teach you from early on to give variable names meaning.
Forget deducting marks and forget failing classes. They should execute people who write terrible code. A coworker sent me an AutoLISP file that he got from someone on the internet, and the code is completely unreadable. There are no comments. Not even one. There are tons of variables with single letter names, and it doesn't say what they are for. All of the variables are global, so it's difficult to guess what they do because the variable might have been created a few dozen lines earlier, in a totally unrelated section of code.
AutoLISP looks sort of like this, leaving the terrible names in so you're left guessing what I'm trying to do here:
Code:
(setq c 0);
(setq ss  (ssget "x" (list (cons 2 62))));
(setq i (entget (ssname ss c));
(entmod (subst (cons 8 "1") (assoc 8 i) i));
(setq c (+ c 1));
.....
...
What the hell does that mean? Now imagine 100 lines like that.

I try to put a comment on every line. It makes changing the code a lot easier. My Perl code often looks like this (comments begin with #):
Code:
my %supplies;                               #store data like $supplies{$name} = [list of supplies]
my @names = qw(steve bob cliff);  #names to be used in %supplies
my @something;                            #this will be used for... blah blah reason
......blah blah code
foreach my $name (@names) {        #checking if everyone has the required supplies, one name at a time
 foreach my $item (@required_items) {    #checking one required item at a time
....
 } #foreach @required_items
} #foreach @names

I'm trying to learn C# from a book right now, and it's brutal. Lack of comments around the closing } makes it difficult to know where I am supposed to be. The book will have something that looks like this:
Code:
        }
      }
     }
   Console.ReadKey();   
   }
  }
}
wtf? Where is that? Are we still in a function? Are we in a class? I think what I've done below looks a lot easier to read:

Code:
       }                               //while
      }                                //for
     }                                 //if
     Console.ReadKey();
   }                                  //Main()
  }                                   //class MyClass
}                                     //namespace Testing

It's difficult to make it show properly on the forum using spaces. Everything lines up nicely when using tab.
 
Last edited:

sm625

Diamond Member
May 6, 2011
8,172
137
106
Why even create the variables T,t,f, and o? o is in fact not even used.

Also, the program does not work properly. If I reach into my pocket and pull out $40, it is going to tell me I have two twenties. Well, this is just not true. lol. I have one twenty, one ten, one five, and five ones.

Also, if you type in 6 it will tell you that you have 1 fives and 1 ones. This is not quite grammatically correct. As a programmer you have the power to easily correct that. Also, it should not bother telling you that you have 0 tens and 0 twenties. That is superfluous information that can also be eliminated.

If you want to make a nice program, write one that takes that input of $40, as well as the number of bills, and uses that information to calculate what bills you do have. In my example, I would enter $40, 8. I have eight bills totalling $40, so what do I have? I must have one twenty, one ten, one five, and five ones. Or I have eight $5 bills. Those are the only combinations of 8 bills that yields $40. I could write such a program pretty easily, and I can tell you for sure that such a task will teach you a thing or two about programming.
 
Last edited:

Cogman

Lifer
Sep 19, 2000
10,286
147
106
Forget deducting marks and forget failing classes. They should execute people who write terrible code. A coworker sent me an AutoLISP file that he got from someone on the internet, and the code is completely unreadable. There are no comments. Not even one. There are tons of variables with single letter names, and it doesn't say what they are for. All of the variables are global, so it's difficult to guess what they do because the variable might have been created a few dozen lines earlier, in a totally unrelated section of code.

Ok, so lack of comments are not the problem here, rather poorly written code is the problem. Code should be written to be read later. Single letter variables should almost never be used.

Overly commenting things is just a bad idea. Comments get out of date faster than anything. Most programmers ignore comments completely. Your problem with C#'s lack of comments for ending braces is simply not an issue in real code development, pretty much ever editor under the sun will highlight which brace opens and closes another brace, especially in a language like C#.

Commenting every single line will make me want to murder you in your sleep, especially with comments like "assigns x to y". I can read the code, thank you, I know that "y = x" assigns x to y.

Write code with descriptive construct names and you will won't generally need comments. They are crutch, throw them away.
 

purbeast0

No Lifer
Sep 13, 2001
53,664
6,546
126
the only place a single letter variable is ever okay IMO is when it's used as the index iterating through a loop.
 

Spungo

Diamond Member
Jul 22, 2012
3,217
2
81
Overly commenting things is just a bad idea. Comments get out of date faster than anything.
Here's the code from one of my scripts. It's not complicated. If one could get a degree coding Perl, this would be first year material. Here's the documentation for map, sort, and glob:
map
sort
glob
"$_" is the default variable in Perl. It points to the original data, not a copy of the data. In C# syntax, it would be like for ($_ in array) { ....}.
Now that you have the information on how variables are named and how the functions work, try to explain how this works or what it does:
Code:
my @output_list = 
	map $_->[0],		
	sort {$b->[1] <=> $a->[1]}
	map [$_, -s],			
	glob '*';


Most programmers ignore comments completely. Your problem with C#'s lack of comments for ending braces is simply not an issue in real code development, pretty much ever editor under the sun will highlight which brace opens and closes another brace, especially in a language like C#.
I shouldn't need to scroll up 3 pages just to see which brace pair I'm looking at.


Here's how my original comments describe what's happening in the above Perl code (select this text to read it). Don't immediately look at the answer. Actually think about the code for a couple minutes:

The code starts at the end and works backward.
1) glob '*' returns a list of every file in the directory and passes it to the map function.
2) map [$_, -s] means create an array of [<filename>, <filesize>]
3) List $b before $a in sort means it's a descending order list. Sorting by $b->[1] means it's sort by the <filesize>
4) map $_->[0] means it's only taking the <filename> part of that sorted list of lists
5) the result @output_list is a list of file names sorted by file size, in descending order

Does the meaning of that code jump out and slap you in the face or do you need to pause and think about it? Do you want to figure out what this thing does every time you look at it, or would it be nice to put a comment on each line to say what that line is doing?
 
Last edited:

cabri

Diamond Member
Nov 3, 2012
3,616
1
81
Does the meaning of that code jump out and slap you in the face or do you need to pause and think about it? Do you want to figure out what this thing does every time you look at it, or would it be nice to put a comment on each line to say what that line is doing?
Many that fight against comments are those that have not had to maintain another's code or go back and look at their own weakly commented code 6-18 months later.

Variables and method names that are descriptive are valuable; however, comments to explain why something is being done is different that the obvious is the properly described variables are used.

Also,code that is required by certain standards ensures that comments are more used than that of internal commercial/freeware/shareware code.

In those types of projects; no one gets pointed out for having to much documentation/comments.
 

Cogman

Lifer
Sep 19, 2000
10,286
147
106
Many that fight against comments are those that have not had to maintain another's code or go back and look at their own weakly commented code 6-18 months later.

Well, you would be wrong. I've been maintaining my current 5 year old app for the last 1 1/2 years. Most of it is uncommented and usually that is just fine. In fact, the more heavily commented sections are often the ones that were done the worst.

Variables and method names that are descriptive are valuable; however, comments to explain why something is being done is different that the obvious is the properly described variables are used.

Certainly comments for why something is done unintuitively is valuable, though arguably you should re-evaluate why you are doing something in the unintuitive way (you are probably wrong).

Also,code that is required by certain standards ensures that comments are more used than that of internal commercial/freeware/shareware code.

In those types of projects; no one gets pointed out for having to much documentation/comments.

And the only thing that keeps those policies in check is some draconian crony who is overly obsessed with rules/procedures/policies. If the project doesn't have someone like that who is combing over every commit to look for violations, you are going to end up with violations which will slowly stack up to a mess.
 

Spungo

Diamond Member
Jul 22, 2012
3,217
2
81
Many that fight against comments are those that have not had to maintain another's code or go back and look at their own weakly commented code 6-18 months later.
On the flip side, one might write confusing code then rely on comments to explain how it works instead of trying to improve the code itself.

A problem I'm running into right now while learning C# from a book is that it seems like everything in this book is global, and it makes the code extremely difficult to follow. Even something simple like shuffling a deck of cards turns into a nightmare. Where did the "cards" variable come from? Is that only part of this method, or was it defined earlier? I'm having trouble writing comments in the example code to explain what's going on. I can't imagine having to deal with something as large as MS Word if it were written like this.

It might just be a Perl thing, but I think most of the code should use extremely narrow scope variables, and functions should pass values or references to each other. Example of something my C# book would have:
Code:
int variable1 = 35;
int variable2 = 25;
.......
50 lines later
......

int Sum() {
return variable1 + variable2;
}
.....
50 lines later
.....
int mySum = Sum();   //sum of what? wtf is this?

Note that the function Sum() is using variables declared outside of itself. This gets confusing when code gets larger, and it makes the code break a lot easier. My guess is that Cogman has seen people use comments to explain what the Sum() function is doing instead of rewriting the code to make the function more transparent:
Code:
int variable1 = 35;
int variable2 = 25;
.......
50 lines later
.......
int Sum(int x, int y)
{
   return x + y;
}
......
50 lines later
.......
int mySum = Sum(variable1, variable2);   //you can clearly see it's the sum of variable1 and variable2
 
Dec 30, 2004
12,553
2
76
i agree to definitely spell out your variables. when i think back in college, many variable names in my beginner courses were just letters, because in context, they really had no meaning. but looking back, i think they should teach you from early on to give variable names meaning.

imo, ideally you want people to be able to read your code without having to have any comments in there, and let the code speak for itself. contrary to what you are taught in school, imo, there is such thing as too many comments. to me, comments should be left for explaining the reasoning behind what you are doing or the business rules that are going into play with the code below it.

and as Leros mentioned, the math is subjective as to "how" to do it. i personally prefer your method over Lero's.

The basic structure of the program seems fine. I have some stylistic suggestions, although style is subjective and sometimes almost religious.

Code:
# If you're going to have variables for the different values,
# I would make them all capitalized.
# You can also label them as const, since you know they will never be reassigned. 
const int TWENTY = 20, TEN = 10, ....

# I don't like single variable names
# Spell things out for readability 
int twentyValue, tenValue, ....

# I think your math could be structured a bit cleaner
# But this is totally subjective.
# I would do something like this:
remainingValue = value;
twentyValue = remainingValue % 20;
remainingValue -= twentyValue * 20;
tenValue = remainingValue % 10;
remainingValue -= tenValue * 10;
...

Even if it's a practice exercise, always use better variable names. You're practicing writing good code. So, you should follow good coding guidelines as part of your practice. :)

on the contrary I disagree with these comments and think his variable names are intuitively obvious given a working knowledge of the program and think it helps the code visually flow/read more easily.

then again, I spent years writing dense, clean looking C.
 
Dec 30, 2004
12,553
2
76
On the flip side, one might write confusing code then rely on comments to explain how it works instead of trying to improve the code itself.

A problem I'm running into right now while learning C# from a book is that it seems like everything in this book is global, and it makes the code extremely difficult to follow. Even something simple like shuffling a deck of cards turns into a nightmare. Where did the "cards" variable come from? Is that only part of this method, or was it defined earlier? I'm having trouble writing comments in the example code to explain what's going on. I can't imagine having to deal with something as large as MS Word if it were written like this.

It might just be a Perl thing, but I think most of the code should use extremely narrow scope variables, and functions should pass values or references to each other. Example of something my C# book would have:
Code:
int variable1 = 35;
int variable2 = 25;
.......
50 lines later
......

int Sum() {
return variable1 + variable2;
}
.....
50 lines later
.....
int mySum = Sum();   //sum of what? wtf is this?

Note that the function Sum() is using variables declared outside of itself. This gets confusing when code gets larger, and it makes the code break a lot easier. My guess is that Cogman has seen people use comments to explain what the Sum() function is doing instead of rewriting the code to make the function more transparent:
Code:
int variable1 = 35;
int variable2 = 25;
.......
50 lines later
.......
int Sum(int x, int y)
{
   return x + y;
}
......
50 lines later
.......
int mySum = Sum(variable1, variable2);   //you can clearly see it's the sum of variable1 and variable2

IDK if it's just me but I've always found books to be completely stupid when it comes to programming examples, leaving out key insights or using 3 paragraphs to explain something I can condense into one sentence. Part of me thinks it's a conspiracy, or maybe just that if the guy were any good at writing code at all, he would be, you know, writing it for a living, and not writing a book.
 

Markbnj

Elite Member <br>Moderator Emeritus
Moderator
Sep 16, 2005
15,682
14
81
www.markbetz.net
Obviously there are only two acceptable naming practices for variables in a C program. ONE_IS_ALL_CAPS, and the other is lpstrzHungarianNotation.

;)
 

Spungo

Diamond Member
Jul 22, 2012
3,217
2
81
IDK if it's just me but I've always found books to be completely stupid when it comes to programming examples, leaving out key insights or using 3 paragraphs to explain something I can condense into one sentence. Part of me thinks it's a conspiracy, or maybe just that if the guy were any good at writing code at all, he would be, you know, writing it for a living, and not writing a book.
The worst is when the guy writing the book knows a lot but can't present his thoughts in a way that is easy to follow. Learning Python. That book is brutal. 1500 pages of scattered thoughts. It would probably be a great book if 700 of the pages were removed.

Imagine you're talking to a contractor about fixing your roof. The guy really knows his stuff. He says he can patch the roof and replace the shingles, or he can patch it and put solar panels, or he can patch it and put cedar shakes, or he can replace the roof, or he can raise the roof and create an attic, or he can put in a sky light, or he can paint the roof white so it reflects sun light, and he can replace the insulation while doing this in addition to adding a whirlybird. After 20 minutes of talking about everything that could be done, you still have no idea what's going on.
 
Dec 30, 2004
12,553
2
76
The worst is when the guy writing the book knows a lot but can't present his thoughts in a way that is easy to follow. Learning Python. That book is brutal. 1500 pages of scattered thoughts. It would probably be a great book if 700 of the pages were removed.

Imagine you're talking to a contractor about fixing your roof. The guy really knows his stuff. He says he can patch the roof and replace the shingles, or he can patch it and put solar panels, or he can patch it and put cedar shakes, or he can replace the roof, or he can raise the roof and create an attic, or he can put in a sky light, or he can paint the roof white so it reflects sun light, and he can replace the insulation while doing this in addition to adding a whirlybird. After 20 minutes of talking about everything that could be done, you still have no idea what's going on.

so why does it happen?