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.

Introduction to Linux - A Hands on Guide

This guide was created as an overview of the Linux Operating System, geared toward new users as an exploration tour and getting started guide, with exercises at the end of each chapter.
For more advanced trainees it can be a desktop reference, and a collection of the base knowledge needed to proceed with system and network administration. This book contains many real life examples derived from the author's experience as a Linux system and network administrator, trainer and consultant. They hope these examples will help you to get a better understanding of the Linux system and that you feel encouraged to try out things on your own.

Click Here to receive this Complete Guide absolutely free.

As mentioned before check the return from scanf(), it will tell you if it returned 3 arguments or a different value or EOF.

My blanket recommendation is the you check the return from as many library function calls as you can.

Also get familiar with reading the man pages for them, and learn about errno and how to print a string from it using strerror. Still view the number and learn how to look it up in your errno.h file.

I was reading a few things to try and understand what jpollard was talking about in terms of "integer division". Does it just mean that the fractional part doesn't apply, cuz that term has always confused me. I read this for one thing, but I'm still not really clear about it to be honest.

Look at it as a 12 hour clock. Anything over 12 is a remainder. So if it is 9 AM and you add 4 hours to it, what time is it? 9 + 4 => 13... but there are only 12 hours, so 13/12 = 1 with a remainder of 1. So the time is 1. and since you are over 12, that makes it 1PM. Suppose you are adding 23 hours? 9 + 23 => 32, also over 12; 32/12 = 2 remainder 8. the 2 indicates two 12 hour long periods so it went from AM to PM to AM, so the time is 8AM, the next day. The 12 is the number of hours in a unit, and is the divisor, the remainder is the number of hours left over.

This rather common for setting appointments, telling the family when dinner will be ready, determining how long you have before a flight leaves the airport.

A brief set of definitions for modulus (which you can skip, as we are specifically talking about integer arithmetic):

Location: Earth? I would say I hope so but I'm not so sure about that... I could just be a figment of your imagination too.

Distribution: CentOS at the time of this writing, but some others over the years too...

Posts: 2,539

Original Poster

Rep:

Thanks again for everyone's help!

Thanks again for chiming in and helping me out jpollard. I think I understand what you're saying, although I'll probably have to do some re-reading of what you and others and have said about the different math concepts spoken about here. But thanks again.

astrogeek, I've been having a look at the little program you wrote me about converting decimal numbers to the different bases (base2, base8 and base16), and while I think I understand it now; I had to break it (sorry about that) to figure out what the different loops in it actually do. While I tried to change the "1" in the first while loop to something else to see what happened, I ended up having to Google it to properly understand what it means, and found out that it's an "infinite loop" - which makes sense given the program asks me again after converting the decimal number to the other bases to input another number to convert.

But trying to figure out what the "for loop" is there for, was quite a different matter. I understand the the "index variable" of it is equal to "1", and that the condition of it has been omitted, and that the expression of it is, "pow2 = pow2 * 2", and that the if statement in it is "if the variable pow2 is more than or equal to variable x, then break that loop", and also that the following while loop is nested in that same for loop, and that if I comment the for loop out, I get the following;

Code:

[james@jamespc devel]$ ./bases_test
Enter a positive integer to convert (0 to exit): 1222
Base 10 Base 8 Base 16 Base 2
(Decimal) (Octal) (Hex) (Binary)
========= ======= ======= ===========
1222 2306 4C6

...clearly it therefore doesn't give me the conversion to base2. But I don't know why it has to be there other than the fact that the following loop is once again nested within - and that's why I don't get the conversion to base2. And the same result if I comment both of the last two loops out.

But if I comment out only the last while loop, but leave the printf statements under it in place, I get the following regardless of what numbers I enter in;

Code:

[james@jamespc devel]$ ./bases_test
Enter a positive integer to convert (0 to exit): 54664
Base 10 Base 8 Base 16 Base 2
(Decimal) (Octal) (Hex) (Binary)
========= ======= ======= ===========
54664 152610 D588 01
Enter a positive integer to convert (0 to exit): 466464
Base 10 Base 8 Base 16 Base 2
(Decimal) (Octal) (Hex) (Binary)
========= ======= ======= ===========
466464 1617040 71E20 01

...I'm not exactly clear on what's actually going on here other than the obvious. So clearly the last loop gives the actual base2 conversion, but while I don't know if my question will make sense (sorry if it doesn't), why does the "for loop" need to be there, other than what's obvious? I'm sure there is a reason for it, I just don't know exactly what it is.

I was wondering if you could explain what I'm missing here?

But trying to figure out what the "for loop" is there for, was quite a different matter.

A "for" loop is syntactic sugar - it isn't absolutely necessary.

Code:

for(i = 0; i < 10; i++) {
block of code
to be processed while i is less than 10
}

Is EXACTLY the same thing as

Code:

i = 0;
while (i < 10) {
block of code
to be processed while i is less than 10
i++;
}

It is perfectly legal to leave out any of the three parts of the while - only the semicolons are needed. Leaving out the conditional test always makes it an infinite loop:

Code:

for (i = 0;;i++){
block of code to be executed
forever...
}

is the same as

Code:

i = 0;
while(1) {
block of code to be executed
forever
i++;
}

So

Code:

for(;;) {
block of code to be executed
forever
}

is also an infinite loop like:

Code:

while(1){
block of code to be executed
forever
}

The only reason for using the "for" loop is that it allows an association of the three (optional) parts together,
making it easier to understand the conditions around the block of code to be executed.

It is easier to read:

Code:

for(;;) {
long block
of code
to be executed forever
}

Than it is to read one of the equivalents, though the while(1) is about the same:

Code:

while(1){
long block
of code
to be executed forever
}

and the harder to interpret:

Code:

do {
long block
of code
to be executed forever
} while(1);

The "for( ; ; )" is an idiom of C that is used to immediately signify an infinite loop at the beginning of the loop.

"while(1)" programmatically is the same, but reading it you also have to realize the "(1)" means (true)... and that takes a little more effort (there have been cases where the 1 is interpreted as a lower case "L", which is (l), and can cause people to look for the variable "l" until they realize it is actually a 1. This was also why C added the boolean type and defined symbols "true" and "false" (of course, used without the quoting, and you have to include the boolean definitions from "stdbool.h").

Oh, forgot to mention that boolean type and "stdbool.h" is only C99 standard or later...

Location: Earth? I would say I hope so but I'm not so sure about that... I could just be a figment of your imagination too.

Distribution: CentOS at the time of this writing, but some others over the years too...

Posts: 2,539

Original Poster

Rep:

Thanks guys.

I understand what you're saying jpollard, and thanks for the examples. Other than the for loop doesn't need to be there, I still can't say why it's there. I can only guess that maybe because it's index value is set to "1", that might have something to do with it, although I'm not honestly real sure about that. So I don't know.

Anyway, I've reached the end of the "Making Decisions" chapter (chapter 6). I think I've already done most of the exercises at the end of it in one way or another by now. While I've already written a basic calculator, other than what the word implies, I don't know exactly what it means by "accumulator". In regards to exercise 6, while I figured it's probably a switch statement, and a loop of some description involved, I have no idea about the mathematics behind it, so I'll skip that one as well. And pretty much the same story with exercise 7 - in that, I don't even know how to begin with the mathematics behind "improving" Program 6.10 in the C book.

But before I move on to the next chapter, I've gotta say that "Conditional Operator" looks really weird, but it's really cool! I quite like that particular operator, very nifty - and cool! I wrote a little program that takes user input and uses that operator to either display "-2" (negative 2) or multiply the entered number. It will multiply the entered number if you type in "100" or less than "100".

Here it is anyway;

Code:

#include <stdio.h>
int main(void)
{
int a, b;
puts("Enter value: ");
scanf("%i", &a);
b = ( a <= 100 ) ? -2 : a * a;
printf("Value is: %i\n", b);
return 0;
}

First, I am happy to see you making good progress! I haven't been able to participate as much as I would have liked, but have been happy to see participation by so many others with always helpful replies!

But I am the only one who can actually tell you what I had in mind in response to this, maybe...

Quote:

Originally Posted by jsbjsb001

astrogeek, I've been having a look at the little program you wrote me about converting decimal numbers to the different bases (base2, base8 and base16), and while I think I understand it now; I had to break it (sorry about that) to figure out what the different loops in it actually do. While I tried to change the "1" in the first while loop to something else to see what happened, I ended up having to Google it to properly understand what it means, and found out that it's an "infinite loop" - which makes sense given the program asks me again after converting the decimal number to the other bases to input another number to convert.

But trying to figure out what the "for loop" is there for, was quite a different matter. I understand the the "index variable" of it is equal to "1", and that the condition of it has been omitted, and that the expression of it is, "pow2 = pow2 * 2", and that the if statement in it is "if the variable pow2 is more than or equal to variable x, then break that loop", and also that the following while loop is nested in that same for loop, and that if I comment the for loop out, I get the following;

...

...I'm not exactly clear on what's actually going on here other than the obvious. So clearly the last loop gives the actual base2 conversion, but while I don't know if my question will make sense (sorry if it doesn't), why does the "for loop" need to be there, other than what's obvious? I'm sure there is a reason for it, I just don't know exactly what it is.

I was wondering if you could explain what I'm missing here?

I'll give it my best shot!

First, I had to go look it up so will include a link to the original post here, which includes the code you refer to.

Next, it is not necessarily obvious to me what you mean by, "...why does the 'for loop' need to be there, other than what's obvious?". Please tell us what you think is obvious about it?

I cannot tell you exactly why I used "for" instead of "while" at the time, but it was very likely intended to simply show you another way to construct a loop. Also, use of "for" clearly initializes and increments the loop variable in a single place, which I think makes the use more "obvious".

The best way to answer the question of what it is doing is to simply look at what change or product the loop produces, and how that product is used by what follows. In this case, it produces a "special" value of the variable pow2 (suggestive name, don't you think?), which is the lowest power of two which contains the variable x. See how that works? So when the for loop breaks, pow2 is equal to x, or it is the lowest power of two which is greater than x.

The while loop which follows is not nested in the for loop, the for loop is done when the while begins. When you exit a loop by meeting its limit condition, or by "break"ing out of it - it is done.

The while loop uses the value produced by the preceeding for loop to print out the binary value of x, from MSB to LSB, left to right, natural human readable ordering, one bit at a time.

In other words, the for loop is there to set up the entry conditions for what follows, in this case the following while loop.

It is probably important that the intent of that little program and the focus of the discussion at that time was try to use your growing C knowledge and your growing math knowledge to complement and advance each other. So toward that end, do you see how the while uses that power of two to print out the binary value, and why it needs that special value?

Location: Earth? I would say I hope so but I'm not so sure about that... I could just be a figment of your imagination too.

Distribution: CentOS at the time of this writing, but some others over the years too...

Posts: 2,539

Original Poster

Rep:

It seems I might have missed a bit more than I thought. It might be easier for me to explain what I can see, so I'll try...

For the "for" loop; it has an index value of "1", the condition is omitted from it, and the expression of it is pow2 = pow2 * 2. That's what I meant by "obvious".

The while loop's condition is if the pow2 (which I thought meant the "power of 2" or similar) variable is more than "0". Then it has the if statement that reads "if the x variable is less than variable pow2". If it is then print a "0" on the screen, if it isn't then print a "1". I know it has variable x = x - pow2 and then pow2 = pow2 / 2 after it, but other than it's base2 it's referring to, I don't know why it's there. Other than it's got something to do with base2, I'm not exactly sure why it needs that special value.

Last edited by jsbjsb001; 02-13-2019 at 03:14 AM.
Reason: forgot to mention "for" loop, sorry.

It seems I might have missed a bit more than I thought. It might be easier for me to explain what I can see, so I'll try...

The while loop's condition is if the pow2 (which I thought meant the "power of 2" or similar) variable is more than "0". Then it has the if statement that reads "if the x variable is less than variable pow2". If it is then print a "0" on the screen, if it isn't then print a "1". I know it has variable x = x - pow2 and then pow2 = pow2 / 2 after it, but other than it's base2 it's referring to, I don't know why it's there. Other than it's got something to do with base2, I'm not exactly sure why it needs that special value.

It isn't so much that you have missed anything, it simply illustrates the fact that it is necessary to understand some minimum level of the math in order to understand the program. You are making great progress, but I have the sense that you still expect to get the programming without really understanding the basic math, and that just isn't going to happen.

For example, judging by your explanation above, you can see "what" the while loop is doing, comparing, printing, subtracting and dividing. But you cannot see why it is doing each of those operations, and why it is doing them in exactly the order they occur. The "what" is the language syntax, the "why" is the algorithm, the equation, or the program, purely math.

Let me try to explain it in terms of the number line, always a useful way to visualize these things.

First, we have some quantity, x, which we represent as being a point some distance from zero on the number line (we will not dwell on the fact that it is to the right of zero, or that we take "x" to literally be the distance).

Now, in base 10 we might say x = 803, that is the point 803-base-ten times the distance of the point 1, to the right of zero. When we write "803" we are saying (zero times 1000, or 10^3, implied, plus...) 8 times 100, or 8 x 10^2, plus 0 times 10, or 0 x 10^1, plus 3 times 1, or 3 x 10^0. Add them up and you get 803. You could start that process at a higher power of 10, but that just adds leading zeroes, so we start at the lowest power of ten greater or equal to the number and throw away leading zeroes.

In base 2 we do exactly the same thing, but first we must find the lowest power of two greater or equal to x - what the for loop does. Then with that as our starting point... you will find that to be 1024, or 2^10. How many 2^10s are there in 803? None, so we toss the leading zero (my little program prints it but no harm done). So we go to the next lower power of 2 by dividing 1024 by 2, and ask again, how mmany 512s are there in 803, one, so we print the leftmost digit, "1" and subtract that much from 803 (i.e., move left a distance of 512). Take the next lower power of 2, 256, and ask how many 256s in 291, one... how many 128s in 35, none, print 0, how many 64s in 35...

Now continue that process until we run out of pow2 and x (i.e. until we move left all the way to zero), and what have we got?

Code:

1100100011
MSB... LSB

... the binary representation of the point 803-base-10 places to the right of zero.

I don't know any way to answer your question of why it does what it does better than that, and you are only going to understand why when you begin to think in terms of the math... that day will come!

Last edited by astrogeek; 02-13-2019 at 03:42 AM.
Reason: typos

Location: Earth? I would say I hope so but I'm not so sure about that... I could just be a figment of your imagination too.

Distribution: CentOS at the time of this writing, but some others over the years too...

Posts: 2,539

Original Poster

Rep:

Quote:

Originally Posted by astrogeek

...
You are making great progress, but I have the sense that you still expect to get the programming without really understanding the basic math, and that just isn't going to happen.
...

Yeah, I do understand why the math is important, but I figured if I can learn what I can about programming, then I can use that to help me understand the math side of things better. I haven't forgotten about learning maths better than I know it at the moment.

Quote:

...
For example, judging by your explanation above, you can see "what" the while loop is doing, comparing, printing, subtracting and dividing. But you cannot see why it is doing each of those operations, and why it is doing them in exactly the order they occur. The "what" is the language syntax, the "why" is the algorithm, the equation, or the program, purely math.
...

Yeah, that's basically the size of it, and what I was basically trying to say. That's why I couldn't understand why the "for" loop was there. I'll have another read of your post above and see what research I can do to understand better what you're saying - I do understand your post above for the most part though. It's like you said, it's trying to visualize it that's hard for me. Thanks for explaining it to me astrogeek.

PS: I edited my previous post above, and added what I can see for the "for" loop just before you posted above - I forgot to mention about that before, sorry about that.

Yeah, I do understand why the math is important, but I figured if I can learn what I can about programming, then I can use that to help me understand the math side of things better. I haven't forgotten about learning maths better than I know it at the moment.

That is the right way to do it, carry on! I was not beating you with the "math stick" again, just trying to point out that it is essential to move both forward in parallel while a clear example of how they work together was at hand.

You are now beginning to understand the mechanics of loops, so this is also the right time to try to understand how that mechanism can be used to solve real problems such as this one - how to convert to or display a base-ten number in binary representation.

It is ultimately all about solving some problem or other, usually expressed in simple math.

Don't be sad*, be happy that you are learning something new every day! Keep it up!

(* Q. Why are math books so sad? A. Because they have so many problems. )

Location: Earth? I would say I hope so but I'm not so sure about that... I could just be a figment of your imagination too.

Distribution: CentOS at the time of this writing, but some others over the years too...

Posts: 2,539

Original Poster

Rep:

Thanks again astrogeek!

So, now I'm up to "Chapter 7 Working with Arrays", only 12 more chapters to go... But anyway, arrays seem to be interesting so far, while I haven't finished reading the whole chapter yet; I have written a little program to get used to them.

So what does it do? Well good question... I first wrote something that just used arrays, but then thought, it would be nice to incorporate some other concepts I've learnt thus far.

So I did. It basically asks you to enter a number (don't they all ), then depending on the entered number it will do something else, that involves working with my little array. Surprised? I'll bet you're not. I don't blame you for that either.

So a basic summary of it: If you enter "0" it will just read the value in values[1] of my little array, print it to the screen and that's it. If you enter "1", it will do the same thing but read values[2] instead. Yeppie! And pretty much the same if you enter in "2", but this time it will read values[3] instead. BUT, if you enter in "3", it will run my little for loop, reading the value from values[1] of my little array.

But if you enter in any other number(s), then you're screwed, because it will just complain about that and quit on you.

Anyways, here's the code below, take it for a spin, it should do what's promised - I tested it, and it seems to work as above, so enjoy!

So, now I'm up to "Chapter 7 Working with Arrays", only 12 more chapters to go... But anyway, arrays seem to be interesting so far, while I haven't finished reading the whole chapter yet; I have written a little program to get used to them.

Don't think of it like that, JSB. Just take your time with all of this, absorbing what you can and moving on only when you feel ready. It's not the twelve labours of Heracles, or it shouldn't be anyway.

LinuxQuestions.org is looking for people interested in writing
Editorials, Articles, Reviews, and more. If you'd like to contribute
content, let us know.