ProgrammingThis forum is for all programming questions.
The question does not have to be directly related to Linux and any language is fair game.
Notices
Welcome to LinuxQuestions.org, a friendly and active Linux Community.
You are currently viewing LQ as a guest. By joining our community you will have the ability to post topics, receive our newsletter, use the advanced search, subscribe to threads and access many other special features. Registration is quick, simple and absolutely free. Join our community today!
Note that registered members see fewer ads, and ContentLink is completely disabled once you log in.
If you have any problems with the registration process or your account login, please contact us. If you need to reset your password, click here.
Having a problem logging in? Please visit this page to clear all LQ-related cookies.
Get a virtual cloud desktop with the Linux distro that you want in less than five minutes with Shells! With over 10 pre-installed distros to choose from, the worry-free installation life is here! Whether you are a digital nomad or just looking for flexibility, Shells can put your Linux machine on the device that you want to use.
Exclusive for LQ members, get up to 45% off per month. Click here for more info.
I'm still working on indenting the code - it's a work in progress...
But it's important, particularly if the code is going to be viewed by other people, which it is on this thread, JSB. When the eye reads over code, it makes it easier to understand the code if instructions at the same level are using the same indentation. Using the correct indentation also shows us that you have a better understanding of the general code flow.
One of the reasons that I posted is that GazL fixed some of your indenting for you and you ignored those corrections. It would have been trivial for you to amend your code to match that indentation. I would highly recommend that you do so and treat indentation as equally important as the code itself going forward.
Distribution: Currently: OpenMandriva. Previously: openSUSE, PCLinuxOS, CentOS, among others over the years.
Posts: 3,881
Original Poster
Rep:
Quote:
Originally Posted by hydrurga
But it's important, particularly if the code is going to be viewed by other people, which it is on this thread, JSB. When the eye reads over code, it makes it easier to understand the code if instructions at the same level are using the same indentation. Using the correct indentation also shows us that you have a better understanding of the general code flow.
One of the reasons that I posted is that GazL fixed some of your indenting for you and you ignored those corrections. It would have been trivial for you to amend your code to match that indentation. I would highly recommend that you do so and treat indentation as equally important as the code itself going forward.
Yeah, I'm not saying it isn't. I didn't ignore GazL's suggestions, you might wanna go back and compare.
Yeah, I'm not saying it isn't. I didn't ignore GazL's suggestions, you might wanna go back and compare.
Most of us have compared. Hyrdruga is correct.
You've been given plenty of examples and information about indenting code. When you say it is a "work in progress", what questions do you have about it? If the truth here is that you are not giving it any priority, then I'm afraid there's little I, or other members, can do to provide you with further assistance. It is difficult for your fellow LQ members to offer you advice if you fail to follow up properly on their responses.
When you ran it and it "worked as expected". What exactly was it expected to do?
You were asked this before by GazL They were not asking "Did you mean to write that line, that way?"
They were asking, "What is the intention of your code?"
Give a high level description of exactly what that code is supposed to accomplish.
Not that it was practice, not that it was you just exploring.
What "should" the code have done? What are the inputs and expected outputs? This is the question we are asking you. Because if the answer is that you wished to calculate the area of a square, then the code is clearly incorrect.
If the answer is that you wished to accept an input number, if the number was within some range you would do something with that number until some test condition passed or failed, then this answer would seem to be more close. We are looking for more details about exactly what your practice code intended to do. Exactly. Not unclear, general statements. The exact algorithm description.
Distribution: Currently: OpenMandriva. Previously: openSUSE, PCLinuxOS, CentOS, among others over the years.
Posts: 3,881
Original Poster
Rep:
I thought I did indent it as GazL said, but for some reason I just noticed that I indented the wrong part of it (being the first printf statement and the scanf statement), it was an honest oversight, as I honestly did try and follow what GazL said. And yes, I was trying to get the code right. But I'm most certainly not ignoring anyone, I wouldn't even be responding if that were true.
I think compared to what my code looked like when I started, and what it looks like now is a big improvement in itself. And no, I'm not saying it can't be improved anymore either.
I explained what the code is supposed to do in post #215, and have quoted it below;
Quote:
Originally Posted by jsbjsb001
...
Anyway, the idea behind it was so that you can only enter 10 or more, but no more than 49, and if you go outside of that range, it just quits, and won't run the loop, and therefore returns to the shell. And if you do enter a number within that range it will count from that number to 50. Although, I wouldn't mind seeing if I can get it to count from say "0", regardless of which number you enter - as long as it's within range of course (being 10 - 50).
...
I have even tried to get it to count from zero regardless of what number is entered, but either I'm doing it wrong and/or I'm not understanding something. I always do check that the code works before I respond, and if it doesn't, I try and say it doesn't and where it's not working, and also why I think it's not working.
Distribution: Currently: OpenMandriva. Previously: openSUSE, PCLinuxOS, CentOS, among others over the years.
Posts: 3,881
Original Poster
Rep:
I probably should have said instead "if you enter less than 10, it should/does quit, but if you enter more than 50, it will also quit, and the loop will not be run. Therefore it must be a number between 10 and 50 that's entered for the loop to be run.", so sorry I didn't put it that way. But that was what I meant by what I did say - I'll try and be more clear next time though. But that said, it would be interesting to either make it not accept any input out of range, and/or display an error message if a number out of range was entered.
I did also try and get it to display an error message if I entered a number out of range, but it kept ignoring the if statement, for I suspect the same reason as before, when I had tried to have the same condition twice, in both the while statement and the unnecessary if statement that I got rid of before. So I'm not sure how to do it at the moment.
The ++i and i++ are both increments... the only time there is a difference is if these expressions are embedded in more complex expressions - like "j = ++i" is not the same as "j = i++". In "j = ++i", the variable j would get the value i + 1; AND the veriable i also is given the value of i + 1. In "j = i++", the variable j would get the current value of i, and then i would be given the value of i + 1. The result is that j is one less than i in the second case, and is equal to i in the first case.
Quote:
and other: loops count up and count down, say
Code:
for ( done = 0 ; done < MAX ; ++done )
and
Code:
for ( to_do = MAX ; to_do > 0 ; --to_do)
do they loop the same time?
no.
Assume MAX is 5.
In the first case the body of the loop gets the value of done as 0, 1, 2, 3, 4; and the loop is done.
In the second case the body of the loop gets the value of done as 5, 4, 3, 2, 1; and the loop is done.
I probably should have said instead "if you enter less than 10, it should/does quit, but if you enter more than 50, it will also quit, and the loop will not be run. Therefore it must be a number between 10 and 50 that's entered for the loop to be run.", so sorry I didn't put it that way. But that was what I meant by what I did say - I'll try and be more clear next time though. But that said, it would be interesting to either make it not accept any input out of range, and/or display an error message if a number out of range was entered.
I did also try and get it to display an error message if I entered a number out of range, but it kept ignoring the if statement, for I suspect the same reason as before, when I had tried to have the same condition twice, in both the while statement and the unnecessary if statement that I got rid of before. So I'm not sure how to do it at the moment.
What I typically do there is the part when you read the input, have one or more if-tests which check the value to make sure it matches the range, or to check whether it actually was a number versus a letter or other character. For instance, what if the person just presses RET and enters nothing? What if the person enters %, or some other symbol that is not a number? Or if they enter "Frank", or if they enter -21?
The loop should govern the result manipulation and exit decision. Prior to entering the loop you should filter the input to verify that it matches the criteria you require. Meanwhile you can check the outcome of the scanf() function. The scanf() function using a %d or %i should ensure that you get a number, and if you don't, it will return an error.
Edit additions:
From the manual page for scanf():
Quote:
u Matches an unsigned decimal integer; the next pointer must be a pointer to unsigned int.
Quote:
RETURN VALUE
On success, these functions return the number of input items successfully matched and assigned; this can be fewer than provided for, or even zero, in the
event of an early matching failure.
The value EOF is returned if the end of input is reached before either the first successful conversion or a matching failure occurs. EOF is also
returned if a read error occurs, in which case the error indicator for the stream (see ferror(3)) is set, and errno is set to indicate the error.
ERRORS
<following list of errno values which you can encounter with the scanf() function>
scanf() is a bit of a pain in that regard as you can get so many different combinations of return and errno from it: which is probably why people read input using something else and then try and parse them in memory.
Also, if you get a format mismatch, it returns 0, errno 0, but leaves the input stream untouched, so unless you handle that, the next call to scanf() will read the exact same input again!
Here's one I wrote as a learning exercise:
Code:
/*
* scanf_example.c:
* Read integer numbers from stdin using scanf() and sum them.
* Ignore non-numeric input.
* Stop on EOF (ctrl-d).
*
* BUGS:
* scanf("%d") will read real numbers as integers.
*/
#include <stdlib.h>
#include <stdio.h>
#include <limits.h>
#include <errno.h>
#include <error.h> /* GNU */
int main( void )
{
int sum = 0;
int number = 0;
for ( int scanf_return = 0 ; EOF != (scanf_return = scanf("%d", &number)) ; errno = 0 )
{
if ( scanf_return == 1 && errno == 0 )
{
if ( (sum >= 0 && INT_MAX - sum >= number) ||
(sum < 0 && INT_MIN - sum <= number) )
{
sum += number;
}
else
{
error(EXIT_FAILURE, EOVERFLOW, "sum += number ");
}
}
else if ( scanf_return == 0 && errno == 0 )
{ /* format mismatch: discard the current input string */
scanf("%*s");
}
else
{ /* most likely ERANGE */
error(EXIT_FAILURE, errno, NULL);
}
}
printf("Sum is %d.\n", sum);
return EXIT_SUCCESS;
}
Distribution: Currently: OpenMandriva. Previously: openSUSE, PCLinuxOS, CentOS, among others over the years.
Posts: 3,881
Original Poster
Rep:
Thanks again guys.
Thanks for your example GazL, but while I did try modifying it to do what I was trying to do before, in that: I was trying to get the latest code I posted to display an error message if you enter a number that's not in range, and while I did manage to compile what you posted with the "-std=c99" gcc option; it really was/is beyond me how you are supposed to do it. I'm sure you're right in what you're saying, but while at least some of the code you posted makes sense, I'm at a loss as to how I'm supposed to use it. I'm sorry if that doesn't make sense, but I don't know how else I can explain it, other than, it's beyond me at this point.
I did try adding an if statement after the scanf statement, and while I did manage to get it to display the "out of range!" message, the loop no longer worked, and given I tried a few other things after that, and I can't remember exactly what I had typed when it did display the "out of range!" error message, I can't post the code I did there.
I did read both post #233 and post #234, and while they both make sense reading them, whatever I seem to try doesn't work, and it's hard for me to get the idea behind it without actually being able to have an example I can understand and play with to get a better idea.
Before I show what code I've tried that I have saved, I'd just like to say a few things about indenting the code; as I explained to another member in reply to a PM they sent me about it: it's not easy for me to try and learn plus remember the actual C concepts as well as the math, and on top of that trying to indent consistently. It sounds easy in theory, but when programming is as new to me as it is, particularly juggling learning the actual code, etc, AND trying to remember to indent it the same way, while still learning the code, isn't an easy thing to do. I wasn't trying to be a smartass before, I meant what I said as in; "yeah, I understand what you guys are saying about the need to do it, and why it's important, but it's going to take time and practice to get it right, so I'm not ignoring the advice, it's just something I'll have to practice until I can do it without having to think about it too much". I didn't mean it as in "I'm not interested in indenting the code properly". Perhaps I could have been more clear, and if that's what people say, then I'll accept that.
The other point I also made was that, if I don't understand the code, and/or WHAT it's actually doing, then I can get the indenting as perfect as I like, but there's little point if I'm not understanding the code. So to me, I need to understand the code as much as get the indenting right. It's (as I've read) also a matter of personal style, which is another point I want to make, in that; it's much easier for me to "read down the page" rather than try and "read across the page". I'm sorry if that doesn't make sense, but that way is just far easier for me to follow, so I've tried to keep it as simple as I can. I understand that others have different styles, and while each to their own, it gets quite confusing for me, if I'm trying to read "across the page", or maybe a better description would be "along the line". So for example;
which makes it harder for me to read. I can understand indenting it like that if there was say a loop of some kind, etc, so you can see that there is something else going on there for lack of a better description. Hopefully I make sense there. Anyway, I have honestly tried to indent the best I can based on the most recent examples given below.
This is what I tried, and what happens when I ran it, mentioned below each code block;
Code:
#include <stdio.h>
int main(void)
{
int enteredNumber;
printf("Enter a number: \n");
scanf("%i", &enteredNumber);
if ( enteredNumber <= 9 && enteredNumber >= 51 ) {
printf("Out of range!\n");
}
while ( enteredNumber >= 10 && enteredNumber <= 50 ) {
printf("%i\n", enteredNumber);
++enteredNumber;
}
return 0;
}
It does the loop if a number within range (specified in the loop) is entered, but does not display "out of range!" message, if a number outside of the range in the loop is entered. I also changed the "9" to "10", and "51" to "50" in the if statement and got the same result.
Code:
#include <stdio.h>
int main(void)
{
int enteredNumber;
printf("Enter a number: \n");
scanf("%i", &enteredNumber);
if ( enteredNumber <= 9 && enteredNumber >= 51 ) {
printf("Out of range!\n");
while ( enteredNumber >= 10 && enteredNumber <= 50 ) {
printf("%i\n", enteredNumber);
++enteredNumber;
}
}
return 0;
}
Doesn't display the "out of range" message, nor does it do the loop. I moved the curly bracket down to the bottom, just above the return statement. I also changed the "9" to "10", and "51" to "50" in the if statement and got the same result.
I'm not honestly sure what it is I'm doing wrong, other than the obvious that there's something wrong with the way I've done the if statement, and I'm really not sure how else I'm supposed to do it. I did try adding an else statement below the if statement both times, but this just caused a stack of errors from gcc each time.
Next covering your problems/confusion about testing your input criteria:
You're not really thinking.
You just threw in an if-statement fully expecting that it now governs your program flow, when all it does it test and then use the result to decide to output information, or not:
Code:
if( some condition ) {
statement(s) does get executed;
}
else {
statement(s) does not get executed
}
// Any code beyond the if-statement (providing there was no exit or return statements above)
statement(s) does get executed;
Written more close to what you have in your first attempt. The else-clause is not in here, because you didn't use one:
Code:
if( some condition ) {
statement(s) does get executed;
}
// Any code beyond the if-statement (providing there was no exit or return statements above)
statement(s) does get executed;
All your if-statement does is to test the arguments, then it moves forward to the next code statements.
Pure clarity:
Either add a return() statement to your if-statement, after the printf() when it detects illegal values. That will cause the program to print out the error and then exit.
Or, enclose the entire while() loop within an else-statement, because that will be all the actions taken when the if-test determines that the input is valid. You do not enclose the final return() statement.
About your if-test:
The while conditions are (enteredNumber >= 10) and (enteredNumber <= 50).
Your if-test conditions should be the opposites of the while condition tests.
What is the opposite of "greater than or equal to ten"?
What test can you make to ensure that a number is NOT "greater than or equal to ten"?
Same for the other side involving fifty.
Hint: ten and fifty are still part of the answer, you do not need to use different numbers.
Distribution: Currently: OpenMandriva. Previously: openSUSE, PCLinuxOS, CentOS, among others over the years.
Posts: 3,881
Original Poster
Rep:
Thanks guys.
I read and tried what you said RT several times now, and while it is running the loop if I enter a number between 10 and 50; it's not displaying the error message when I don't put in a number in range - but it does quit and go back to the shell. It looks like it's ignoring the if statement, I tried to do what you said, but I'm still at a loss to know why it's still not doing what it's supposed to. I'm not sure how to enclose the while statement in an else statement, so I haven't tried that - I've just tried a return statement. But thanks again for helping me out.
I also noticed that the final return statement wasn't indented properly, so I tried to fix that as well.
Anyhow, here's my code thus far;
Code:
#include <stdio.h>
int main(void)
{
int enteredNumber;
printf("Enter a number: \n");
scanf("%i", &enteredNumber);
if ( (enteredNumber < 10) && (enteredNumber > 50) ) {
printf("Out of range!\n");
return 1;
}
while ( (enteredNumber >= 10) && (enteredNumber <= 50) ) {
printf("%i\n", enteredNumber);
++enteredNumber;
}
return 0;
}
LinuxQuestions.org is looking for people interested in writing
Editorials, Articles, Reviews, and more. If you'd like to contribute
content, let us know.