Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.c > #78230 > unrolled thread
| Started by | Alla _ <modelling.data@gmail.com> |
|---|---|
| First post | 2015-12-09 05:00 -0800 |
| Last post | 2015-12-11 11:09 +0100 |
| Articles | 20 on this page of 93 — 17 participants |
Back to article view | Back to comp.lang.c
Program to compute the amount of bottles of water... Alla _ <modelling.data@gmail.com> - 2015-12-09 05:00 -0800
Re: Program to compute the amount of bottles of water... Malcolm McLean <malcolm.mclean5@btinternet.com> - 2015-12-09 05:13 -0800
Re: Program to compute the amount of bottles of water... Alla _ <modelling.data@gmail.com> - 2015-12-09 05:17 -0800
Re: Program to compute the amount of bottles of water... Richard Heathfield <rjh@cpax.org.uk> - 2015-12-09 13:29 +0000
Re: Program to compute the amount of bottles of water... Alla _ <modelling.data@gmail.com> - 2015-12-09 06:54 -0800
Re: Program to compute the amount of bottles of water... Richard Heathfield <rjh@cpax.org.uk> - 2015-12-09 15:45 +0000
Re: Program to compute the amount of bottles of water... Alla _ <modelling.data@gmail.com> - 2015-12-09 08:39 -0800
Re: Program to compute the amount of bottles of water... Barry Schwarz <schwarzb@dqel.com> - 2015-12-09 08:38 -0800
Re: Program to compute the amount of bottles of water... Richard Heathfield <rjh@cpax.org.uk> - 2015-12-09 19:09 +0000
Re: Program to compute the amount of bottles of water... Alla _ <modelling.data@gmail.com> - 2015-12-09 07:07 -0800
Re: Program to compute the amount of bottles of water... "Osmium" <r124c4u102@comcast.net> - 2015-12-09 09:40 -0600
Re: Program to compute the amount of bottles of water... Udyant Wig <udyantw@gmail.com> - 2015-12-10 18:12 +0530
Re: Program to compute the amount of bottles of water... "Osmium" <r124c4u102@comcast.net> - 2015-12-10 07:47 -0600
Re: Program to compute the amount of bottles of water... Barry Schwarz <schwarzb@dqel.com> - 2015-12-09 08:29 -0800
Re: Program to compute the amount of bottles of water... Alla _ <modelling.data@gmail.com> - 2015-12-14 08:23 -0800
Re: Program to compute the amount of bottles of water... Richard Heathfield <rjh@cpax.org.uk> - 2015-12-14 16:55 +0000
Re: Program to compute the amount of bottles of water... Lew Pitcher <lew.pitcher@digitalfreehold.ca> - 2015-12-14 12:17 -0500
Re: Program to compute the amount of bottles of water... Lew Pitcher <lew.pitcher@digitalfreehold.ca> - 2015-12-14 13:26 -0500
Re: Program to compute the amount of bottles of water... Richard Heathfield <rjh@cpax.org.uk> - 2015-12-14 19:20 +0000
Re: Program to compute the amount of bottles of water... Keith Thompson <kst-u@mib.org> - 2015-12-14 12:54 -0800
Re: Program to compute the amount of bottles of water... Richard Heathfield <rjh@cpax.org.uk> - 2015-12-14 21:01 +0000
Re: Program to compute the amount of bottles of water... Ben Bacarisse <ben.usenet@bsb.me.uk> - 2015-12-14 21:36 +0000
Re: Program to compute the amount of bottles of water... Ben Bacarisse <ben.usenet@bsb.me.uk> - 2015-12-14 21:26 +0000
Re: Program to compute the amount of bottles of water... Richard Heathfield <rjh@cpax.org.uk> - 2015-12-14 21:40 +0000
Re: Program to compute the amount of bottles of water... Lew Pitcher <lew.pitcher@digitalfreehold.ca> - 2015-12-14 16:42 -0500
Re: Program to compute the amount of bottles of water... Ben Bacarisse <ben.usenet@bsb.me.uk> - 2015-12-14 21:49 +0000
Re: Program to compute the amount of bottles of water... Lew Pitcher <lew.pitcher@digitalfreehold.ca> - 2015-12-14 17:25 -0500
Re: Program to compute the amount of bottles of water... Keith Thompson <kst-u@mib.org> - 2015-12-14 16:18 -0800
Re: Program to compute the amount of bottles of water... Jerry Stuckle <jstucklex@attglobal.net> - 2015-12-14 20:24 -0500
Re: Program to compute the amount of bottles of water... "Osmium" <r124c4u102@comcast.net> - 2015-12-14 16:04 -0600
Re: Program to compute the amount of bottles of water... Barry Schwarz <schwarzb@dqel.com> - 2015-12-14 11:07 -0800
Re: Program to compute the amount of bottles of water... G G <gdotone@gmail.com> - 2015-12-15 09:51 -0800
Re: Program to compute the amount of bottles of water... "Osmium" <r124c4u102@comcast.net> - 2015-12-09 08:26 -0600
Re: Program to compute the amount of bottles of water... Alla _ <modelling.data@gmail.com> - 2015-12-09 06:57 -0800
Re: Program to compute the amount of bottles of water... G G <gdotone@gmail.com> - 2015-12-09 08:06 -0800
Re: Program to compute the amount of bottles of water... Alla _ <modelling.data@gmail.com> - 2015-12-09 08:30 -0800
Re: Program to compute the amount of bottles of water... G G <gdotone@gmail.com> - 2015-12-09 09:45 -0800
Re: Program to compute the amount of bottles of water... Vécu BOSSEUR <vecu.bosseur@gmail.com> - 2015-12-10 12:44 +0100
Re: Program to compute the amount of bottles of water... Keith Thompson <kst-u@mib.org> - 2015-12-10 08:38 -0800
Re: Program to compute the amount of bottles of water... Vécu BOSSEUR <vecu.bosseur@gmail.com> - 2015-12-11 22:02 +0100
Re: Program to compute the amount of bottles of water... Barry Schwarz <schwarzb@dqel.com> - 2015-12-11 15:23 -0800
Re: Program to compute the amount of bottles of water... Vécu BOSSEUR <vecu.bosseur@gmail.com> - 2015-12-12 12:05 +0100
Re: Program to compute the amount of bottles of water... Barry Schwarz <schwarzb@dqel.com> - 2015-12-12 07:00 -0800
Re: Program to compute the amount of bottles of water... James Kuyper <jameskuyper@verizon.net> - 2015-12-12 10:40 -0500
Re: Program to compute the amount of bottles of water... BartC <bc@freeuk.com> - 2015-12-12 11:34 +0000
Re: Program to compute the amount of bottles of water... Alla _ <modelling.data@gmail.com> - 2015-12-11 00:43 -0800
Re: Program to compute the amount of bottles of water... Richard Heathfield <rjh@cpax.org.uk> - 2015-12-11 09:51 +0000
Re: Program to compute the amount of bottles of water... Alla _ <modelling.data@gmail.com> - 2015-12-11 03:14 -0800
Re: Program to compute the amount of bottles of water... Richard Heathfield <rjh@cpax.org.uk> - 2015-12-11 11:55 +0000
Re: Program to compute the amount of bottles of water... Alla _ <modelling.data@gmail.com> - 2015-12-11 10:15 -0800
Re: Program to compute the amount of bottles of water... Alla _ <modelling.data@gmail.com> - 2015-12-13 05:20 -0800
Re: Program to compute the amount of bottles of water... Malcolm McLean <malcolm.mclean5@btinternet.com> - 2015-12-13 05:59 -0800
Re: Program to compute the amount of bottles of water... Jerry Stuckle <jstucklex@attglobal.net> - 2015-12-13 11:24 -0500
Re: Program to compute the amount of bottles of water... Ben Bacarisse <ben.usenet@bsb.me.uk> - 2015-12-13 19:29 +0000
Re: Program to compute the amount of bottles of water... Jerry Stuckle <jstucklex@attglobal.net> - 2015-12-13 17:47 -0500
Re: Program to compute the amount of bottles of water... Ben Bacarisse <ben.usenet@bsb.me.uk> - 2015-12-13 20:43 +0000
Re: Program to compute the amount of bottles of water... Richard Heathfield <rjh@cpax.org.uk> - 2015-12-13 17:10 +0000
Re: Program to compute the amount of bottles of water... James Kuyper <jameskuyper@verizon.net> - 2015-12-13 13:00 -0500
Re: Program to compute the amount of bottles of water... Richard Heathfield <rjh@cpax.org.uk> - 2015-12-13 18:25 +0000
Re: Program to compute the amount of bottles of water... Alla _ <modelling.data@gmail.com> - 2015-12-13 10:04 -0800
Re: Program to compute the amount of bottles of water... Malcolm McLean <malcolm.mclean5@btinternet.com> - 2015-12-13 10:29 -0800
Re: Program to compute the amount of bottles of water... Alla _ <modelling.data@gmail.com> - 2015-12-13 10:43 -0800
Re: Program to compute the amount of bottles of water... Richard Heathfield <rjh@cpax.org.uk> - 2015-12-13 19:35 +0000
Re: Program to compute the amount of bottles of water... Udyant Wig <udyantw@gmail.com> - 2015-12-14 11:49 +0530
Re: Program to compute the amount of bottles of water... Ben Bacarisse <ben.usenet@bsb.me.uk> - 2015-12-14 12:34 +0000
Re: Program to compute the amount of bottles of water... Ben Bacarisse <ben.usenet@bsb.me.uk> - 2015-12-14 14:38 +0000
Re: Program to compute the amount of bottles of water... Ben Bacarisse <ben.usenet@bsb.me.uk> - 2015-12-14 15:09 +0000
Re: Program to compute the amount of bottles of water... Steve Thompson <stevet810@gmail.com> - 2015-12-14 05:24 +0000
Re: Program to compute the amount of bottles of water... Malcolm McLean <malcolm.mclean5@btinternet.com> - 2015-12-14 13:07 -0800
Re: Program to compute the amount of bottles of water... Keith Thompson <kst-u@mib.org> - 2015-12-13 13:42 -0800
Re: Program to compute the amount of bottles of water... Richard Heathfield <rjh@cpax.org.uk> - 2015-12-13 22:14 +0000
Re: Program to compute the amount of bottles of water... Malcolm McLean <malcolm.mclean5@btinternet.com> - 2015-12-11 09:51 -0800
Re: Program to compute the amount of bottles of water... Alla _ <modelling.data@gmail.com> - 2015-12-11 10:15 -0800
Re: Program to compute the amount of bottles of water... Steve Thompson <stevet810@gmail.com> - 2015-12-12 20:42 +0000
Re: Program to compute the amount of bottles of water... Keith Thompson <kst-u@mib.org> - 2015-12-12 18:10 -0800
Re: Program to compute the amount of bottles of water... Ben Bacarisse <ben.usenet@bsb.me.uk> - 2015-12-13 11:16 +0000
Re: Program to compute the amount of bottles of water... Keith Thompson <kst-u@mib.org> - 2015-12-13 03:41 -0800
Re: Program to compute the amount of bottles of water... Steve Thompson <stevet810@gmail.com> - 2015-12-14 01:43 +0000
Re: Program to compute the amount of bottles of water... Steve Thompson <stevet810@gmail.com> - 2015-12-14 01:41 +0000
Re: Program to compute the amount of bottles of water... Ben Bacarisse <ben.usenet@bsb.me.uk> - 2015-12-11 18:45 +0000
Re: Program to compute the amount of bottles of water... Keith Thompson <kst-u@mib.org> - 2015-12-11 12:34 -0800
Re: Program to compute the amount of bottles of water... Malcolm McLean <malcolm.mclean5@btinternet.com> - 2015-12-11 13:18 -0800
Re: Program to compute the amount of bottles of water... raltbos@xs4all.nl (Richard Bos) - 2015-12-15 17:48 +0000
Re: Program to compute the amount of bottles of water... Malcolm McLean <malcolm.mclean5@btinternet.com> - 2015-12-15 10:58 -0800
Re: Program to compute the amount of bottles of water... raltbos@xs4all.nl (Richard Bos) - 2015-12-17 00:14 +0000
Re: Program to compute the amount of bottles of water... Barry Schwarz <schwarzb@dqel.com> - 2015-12-11 09:53 -0800
Re: Program to compute the amount of bottles of water... Alla _ <modelling.data@gmail.com> - 2015-12-11 10:20 -0800
Re: Program to compute the amount of bottles of water... Keith Thompson <kst-u@mib.org> - 2015-12-11 12:40 -0800
Re: Program to compute the amount of bottles of water... Barry Schwarz <schwarzb@dqel.com> - 2015-12-11 02:01 -0800
Re: Program to compute the amount of bottles of water... Richard Heathfield <rjh@cpax.org.uk> - 2015-12-11 10:18 +0000
Re: Program to compute the amount of bottles of water... Alla _ <modelling.data@gmail.com> - 2015-12-11 03:02 -0800
Re: Program to compute the amount of bottles of water... "Osmium" <r124c4u102@comcast.net> - 2015-12-11 08:13 -0600
Re: Program to compute the amount of bottles of water... "Skybuck Flying" <skybuck2000@hotmail.com> - 2015-12-11 11:09 +0100
Page 4 of 5 — ← Prev page 1 2 3 [4] 5 Next page →
| From | Malcolm McLean <malcolm.mclean5@btinternet.com> |
|---|---|
| Date | 2015-12-13 10:29 -0800 |
| Message-ID | <7dccf87d-baf7-46c3-8caa-a359d11f65f4@googlegroups.com> |
| In reply to | #78554 |
On Sunday, December 13, 2015 at 6:04:55 PM UTC, Alla _ wrote: > On Sunday, December 13, 2015 at 9:11:02 PM UTC+4, Richard Heathfield wrote: > > On 13/12/15 13:20, Alla _ wrote: > > > > > But, in case you are able to find time (and motive, or will), could you, > > > please, guide me through the process of writing code for those two functions > > > (fgets and strtoul)? I believe it would be very helpful for the learning > > > process. > > > > I'm not sure whether you realise what you're asking! I've seen Malcolm's > > reply, and it is evident that /he/ doesn't realise what you're asking. > > > Your reply shows me that indeed I didn't realize what I was asking for, or I > have meant something different. > Thank you for this post. I didn't think you will write that for me; I was > actually asking for the step-by-step guidance, so I could come up with my > solutions. But given the sluggishness of my thought processes, I understand > that it could require too much time and patience ) I will study your message. > I misunderstood what you were asking for. Most standard library functions are just functions like any other, they take arguments and either return values based on those arguments, or modify things pointed to. strlen() is a very simple function, and a good place to start. You need to call your version mystrlen() or something similar. But it's so easy to write that you don't need to do all the formal planning. Generally, however, you need to understand what the function's requirements are. Then you must consider if you have the ability to write the algorithm - with something as simple as strlen() it shouldn't be a problem. With say pow() or log() it depends on your mathematical background. With other functions, eg letter recognition, it's a research question. Assuming that you've understood the requirements and you're confident that you've got the ability to carry out the calculation, you need to specify the interface, write code, and set up tests. Everyone works in a slightly different way, you need to code, compile, remove the compile time errors, test, then usually code again to add a bit more functionality or remove bugs, then test again, then maybe rewrite to make neater or more efficient. Some people like to write the tests first, others after. It's rare for even good programmers to write complex functions correctly first time.
[toc] | [prev] | [next] | [standalone]
| From | Alla _ <modelling.data@gmail.com> |
|---|---|
| Date | 2015-12-13 10:43 -0800 |
| Message-ID | <c71efec2-e460-4342-9cf7-c360f9a716ec@googlegroups.com> |
| In reply to | #78560 |
On Sunday, December 13, 2015 at 10:30:06 PM UTC+4, Malcolm McLean wrote: > On Sunday, December 13, 2015 at 6:04:55 PM UTC, Alla _ wrote: > > On Sunday, December 13, 2015 at 9:11:02 PM UTC+4, Richard Heathfield wrote: > > > On 13/12/15 13:20, Alla _ wrote: > > > > > > > But, in case you are able to find time (and motive, or will), could you, > > > > please, guide me through the process of writing code for those two functions > > > > (fgets and strtoul)? I believe it would be very helpful for the learning > > > > process. > > > > > > I'm not sure whether you realise what you're asking! I've seen Malcolm's > > > reply, and it is evident that /he/ doesn't realise what you're asking. > > > > > Your reply shows me that indeed I didn't realize what I was asking for, or I > > have meant something different. > > Thank you for this post. I didn't think you will write that for me; I was > > actually asking for the step-by-step guidance, so I could come up with my > > solutions. But given the sluggishness of my thought processes, I understand > > that it could require too much time and patience ) I will study your message. > > > I misunderstood what you were asking for. > > Most standard library functions are just functions like any other, > they take arguments and either return values based on those > arguments, or modify things pointed to. > > strlen() is a very simple function, and a good place to start. > You need to call your version mystrlen() or something similar. > But it's so easy to write that you don't need to do all the > formal planning. > > Generally, however, you need to understand what the function's > requirements are. Then you must consider if you have the ability > to write the algorithm - with something as simple as strlen() > it shouldn't be a problem. With say pow() or log() it depends > on your mathematical background. With other functions, eg > letter recognition, it's a research question. > > Assuming that you've understood the requirements and you're > confident that you've got the ability to carry out the calculation, > you need to specify the interface, write code, and set up tests. > Everyone works in a slightly different way, you need to code, compile, > remove the compile time errors, test, then usually code again > to add a bit more functionality or remove bugs, then test again, > then maybe rewrite to make neater or more efficient. Some people > like to write the tests first, others after. It's rare for even > good programmers to write complex functions correctly first time. Indeed, big process, that maybe awaits me ) I already have a set of easy functions like strlen, strcpy, and, yes, those are not difficult to implement. I also don't think that programmers create algorithms: if I am correct, mathematicians create certain sophisticated algorithms (like the sorting ones), and programmers implement them in a given language.
[toc] | [prev] | [next] | [standalone]
| From | Richard Heathfield <rjh@cpax.org.uk> |
|---|---|
| Date | 2015-12-13 19:35 +0000 |
| Message-ID | <n4kh68$vrs$1@dont-email.me> |
| In reply to | #78561 |
On 13/12/15 18:43, Alla _ wrote:
<snip>
> I also don't think that programmers create algorithms:
You are mistaken.
> if I am correct, mathematicians create certain sophisticated algorithms (like
> the sorting ones), and programmers implement them in a given language.
The obvious counter-example is quicksort, which was invented by C A R
Hoare, whose academic background was in Classics and Philosophy.
It is perhaps in order to reflect on what an algorithm actually is.
Following Knuth, we can define an algorithm as follows:
An algorithm is a finite set of rules that gives a sequence of
operations for solving a specific type of problem, and having the
following characteristics:
1) Finiteness - an algorithm must always terminate after a finite number
of steps.
2) Definiteness - each step of an algorithm must be precisely defined.
3) Input - an algorithm has zero or more inputs, quantities that are
given to it initially before the algorithm begins, or dynamically as the
algorithm runs.
4) Output - an algorithm has one or more outputs: quantities that have a
specified relation to the inputs.
5) Effectiveness - an algorithm is also generally expected to be
effective, in the sense that its operations must all be sufficiently
basic that they can in principle be done exactly and in a finite length
of time by someone using pencil and paper.
For example, if you asked me to solve the problem of printing the vowels
(and only the vowels) of an English word, I could develop an algorithm
as follows:
Algorithm A: copy the vowels of an English word w to location y
Step 1: set n to number of letters in w
Step 2: set s to 0
Step 3: set t to 0
Step 3: if s = n proceed from Step 9
Step 4: if w[s] is not in the set { a, e, i, o, u }
then proceed from Step 7.
Step 5: set y[t] to w[s]
Step 6: set t to t + 1
Step 7: set s to s + 1
Step 8: proceed from Step 3.
Step 9: terminate. The result is in y.
And that's an algorithm, even though I'm not a mathematician.
Whenever you solve a problem in a well-defined, finite way, you are
creating an algorithm. One might reasonably say that the job of the
computer programmer is to devise algorithms (and then to implement them
in a programming language).
--
Richard Heathfield
Email: rjh at cpax dot org dot uk
"Usenet is a strange place" - dmr 29 July 1999
Sig line 4 vacant - apply within
[toc] | [prev] | [next] | [standalone]
| From | Udyant Wig <udyantw@gmail.com> |
|---|---|
| Date | 2015-12-14 11:49 +0530 |
| Message-ID | <87twnl1rig.fsf@gmail.com> |
| In reply to | #78563 |
As basic sanity checks, I perused two books I had that I knew carried
definitions of algorithms and offered overviews of the general concept
of an algorithm.
Richard Heathfield <rjh@cpax.org.uk> writes:
[snip]
> It is perhaps in order to reflect on what an algorithm actually is.
>
> Following Knuth, we can define an algorithm as follows:
>
> An algorithm is a finite set of rules that gives a sequence of
> operations for solving a specific type of problem, and having the
> following characteristics:
>
> 1) Finiteness - an algorithm must always terminate after a finite
> number of steps.
> 2) Definiteness - each step of an algorithm must be precisely defined.
> 3) Input - an algorithm has zero or more inputs, quantities that are
> given to it initially before the algorithm begins, or dynamically as
> the algorithm runs.
> 4) Output - an algorithm has one or more outputs: quantities that have
> a specified relation to the inputs.
> 5) Effectiveness - an algorithm is also generally expected to be
> effective, in the sense that its operations must all be sufficiently
> basic that they can in principle be done exactly and in a finite
> length of time by someone using pencil and paper.
CLRS, on their part, echo much the same, saying:
Informally, an _algorithm_ is any well-defined computational
procedure that takes some value, or set of values, as _input_ and
produces some value, or set of values, as _output_. An algorithm is
thus a sequence of computational steps that transform the input into
the output.
We can also view an algorithm as a tool for solving a well-specified
_computational_problem_. The statement of the problem specifies in
general terms the desired input/output relationship. The algorithm
describes a specific computational procedure for achieving that
input/output relationship.
However, a book by Vladimir Uspensky on Gödel's Incompleteness Theorem
says:
... we shall only need the most general intuitive idea of what an
_algorithm_ is: a set of instructions which, given in _input_ (also
called the _initial_data_ or the _argument_) form some set of
_possible_inputs_ (for the given algorithm), enables us to obtain an
_output_ if such an output exists or else obtain nothing at all if
there is no output for our particular input. Notice that the set of
possible inputs consists of all inputs to which the algorithm can be
applied, not only those for which the algorithm gives an output. If
there is an output for a particular input, then we say that the
algorithm can be _applied_ to this input and _processes_ it to give
the corresponding output.
I was unaware of this broader definition until I read it in Uspensky's
book.
--
Udyant Wig
[toc] | [prev] | [next] | [standalone]
| From | Ben Bacarisse <ben.usenet@bsb.me.uk> |
|---|---|
| Date | 2015-12-14 12:34 +0000 |
| Message-ID | <87d1u91a66.fsf@bsb.me.uk> |
| In reply to | #78590 |
Udyant Wig <udyantw@gmail.com> writes: > As basic sanity checks, I perused two books I had that I knew carried > definitions of algorithms and offered overviews of the general concept > of an algorithm. > > Richard Heathfield <rjh@cpax.org.uk> writes: > > [snip] > >> It is perhaps in order to reflect on what an algorithm actually is. >> >> Following Knuth, we can define an algorithm as follows: >> >> An algorithm is a finite set of rules that gives a sequence of >> operations for solving a specific type of problem, and having the >> following characteristics: >> >> 1) Finiteness - an algorithm must always terminate after a finite >> number of steps. >> 2) Definiteness - each step of an algorithm must be precisely defined. >> 3) Input - an algorithm has zero or more inputs, quantities that are >> given to it initially before the algorithm begins, or dynamically as >> the algorithm runs. >> 4) Output - an algorithm has one or more outputs: quantities that have >> a specified relation to the inputs. >> 5) Effectiveness - an algorithm is also generally expected to be >> effective, in the sense that its operations must all be sufficiently >> basic that they can in principle be done exactly and in a finite >> length of time by someone using pencil and paper. > > CLRS, on their part, echo much the same, saying: > > Informally, an _algorithm_ is any well-defined computational > procedure that takes some value, or set of values, as _input_ and > produces some value, or set of values, as _output_. An algorithm is > thus a sequence of computational steps that transform the input into > the output. > > We can also view an algorithm as a tool for solving a well-specified > _computational_problem_. The statement of the problem specifies in > general terms the desired input/output relationship. The algorithm > describes a specific computational procedure for achieving that > input/output relationship. > > However, a book by Vladimir Uspensky on Gödel's Incompleteness Theorem > says: > > ... we shall only need the most general intuitive idea of what an > _algorithm_ is: a set of instructions which, given in _input_ (also > called the _initial_data_ or the _argument_) form some set of > _possible_inputs_ (for the given algorithm), enables us to obtain an > _output_ if such an output exists or else obtain nothing at all if > there is no output for our particular input. Notice that the set of > possible inputs consists of all inputs to which the algorithm can be > applied, not only those for which the algorithm gives an output. If > there is an output for a particular input, then we say that the > algorithm can be _applied_ to this input and _processes_ it to give > the corresponding output. > > I was unaware of this broader definition until I read it in Uspensky's > book. A term as general as "algorithm" is bound to have various meanings depending on context. The distinction between always terminating and maybe terminating algorithms matters when talking about the things Uspensky is writing about, but the two can be rolled into one by defining a special "output" (usually called "bottom" and written _|_) when an algorithm does not terminate on some input. There is yet another meaning promoted by the fact that some "algorithms" must be correct and provably never terminate. -- Ben.
[toc] | [prev] | [next] | [standalone]
| From | Ben Bacarisse <ben.usenet@bsb.me.uk> |
|---|---|
| Date | 2015-12-14 14:38 +0000 |
| Message-ID | <877fkh14ep.fsf@bsb.me.uk> |
| In reply to | #78617 |
ram@zedat.fu-berlin.de (Stefan Ram) writes:
> Ben Bacarisse <ben.usenet@bsb.me.uk> writes:
> ...
>>>algorithm is a finite set of rules
> ...
>>>well-defined computational procedure
> ...
>>>a set of instructions which
> ...
>>A term as general as "algorithm" is bound to have various meanings
>>depending on context. The distinction between always terminating and
>
> I agree with you that there is no general definition of the term.
>
> The definitions mentioned above (not fully quoted here
> again), say that an algorithm was a »set of rules« or a
> »procedure« or a »set of instructions«.
>
> We can exclude the definitions including the word »set«,
> because in a set no element can appear twice and there is no
> order, while with rules and instructions order matters and
> multiple appearences are possible.
You are making unwarranted assumptions about the rules! Here is a GCD
algorithm as set of rules:
{<t: goto p>, <q: t = b>, <p: stop if b = 0>, <s: a = t>, <r: b := a%b>}
It is the same not mater what order the set is written and it will never
contain a duplicate because of what I've decided a rule is.
You may be right that the author made a mistake, but it's not certain
from what you said about it.
> (If they do not want to
> refer to the mathematical term, they should at least give
> their definition of »set«, then.)
>
> Remains the definition as a »procedure« - it depends on how
> »procedure« is defined. As long as this is not given, it
> remains unclear.
It is likely that the word is being used informally. Even before Church
and Turing et al I think the term "effective procedure" was used to
describe the notion, and it's important that it *wasn't* too formally
defined. If it is, phrases like "there is no effective procedure to
..." become statements about some particular formalism rather than
claims about anything that might reasonably be called an effective
procedure.
> To me, an algorithm is a function in the sense of C,
> because this here is comp.lang.c, and, in C, »function«
> is sufficiently well-defined.
I think that's too loose because so many C functions are formally
undefined for some or all inputs.
--
Ben.
[toc] | [prev] | [next] | [standalone]
| From | Ben Bacarisse <ben.usenet@bsb.me.uk> |
|---|---|
| Date | 2015-12-14 15:09 +0000 |
| Message-ID | <87k2ohysm0.fsf@bsb.me.uk> |
| In reply to | #78626 |
ram@zedat.fu-berlin.de (Stefan Ram) writes:
> Ben Bacarisse <ben.usenet@bsb.me.uk> writes:
>>You are making unwarranted assumptions about the rules! Here is a GCD
>>algorithm as set of rules:
>>{<t: goto p>, <q: t = b>, <p: stop if b = 0>, <s: a = t>, <r: b := a%b>}
>>It is the same not mater what order the set is written and it will never
>>contain a duplicate because of what I've decided a rule is.
>
> This is possible, but then an appropriate definition of
> »rule« should already have been included in the definitions
> of »algorithm« that use the word »rule«.
Unfortunately I don't know what you mean. You have omitted definitions
of "possible", "appropriate", "definition", "should", "already",
"included", "use" and "word". How can I possibly make any sense of such
ill-defined waffle!
--
Ben.
[toc] | [prev] | [next] | [standalone]
| From | Steve Thompson <stevet810@gmail.com> |
|---|---|
| Date | 2015-12-14 05:24 +0000 |
| Message-ID | <Hja520.XzJ.BBsgr@gmail.com> |
| In reply to | #78563 |
On Sun, Dec 13, 2015 at 07:35:57PM +0000, Richard Heathfield wrote:
> On 13/12/15 18:43, Alla _ wrote:
>
> <snip>
>
> >I also don't think that programmers create algorithms:
>
> You are mistaken.
>
> >if I am correct, mathematicians create certain sophisticated algorithms
> >(like
> >the sorting ones), and programmers implement them in a given language.
>
> The obvious counter-example is quicksort, which was invented by C A R
> Hoare, whose academic background was in Classics and Philosophy.
>
> It is perhaps in order to reflect on what an algorithm actually is.
>
> Following Knuth, we can define an algorithm as follows:
>
> An algorithm is a finite set of rules that gives a sequence of
> operations for solving a specific type of problem, and having the
> following characteristics:
>
> 1) Finiteness - an algorithm must always terminate after a finite number
> of steps.
> 2) Definiteness - each step of an algorithm must be precisely defined.
> 3) Input - an algorithm has zero or more inputs, quantities that are
> given to it initially before the algorithm begins, or dynamically as the
> algorithm runs.
> 4) Output - an algorithm has one or more outputs: quantities that have a
> specified relation to the inputs.
> 5) Effectiveness - an algorithm is also generally expected to be
> effective, in the sense that its operations must all be sufficiently
> basic that they can in principle be done exactly and in a finite length
> of time by someone using pencil and paper.
>
> For example, if you asked me to solve the problem of printing the vowels
> (and only the vowels) of an English word, I could develop an algorithm
> as follows:
>
> Algorithm A: copy the vowels of an English word w to location y
>
> Step 1: set n to number of letters in w
> Step 2: set s to 0
> Step 3: set t to 0
> Step 3: if s = n proceed from Step 9
> Step 4: if w[s] is not in the set { a, e, i, o, u }
> then proceed from Step 7.
> Step 5: set y[t] to w[s]
> Step 6: set t to t + 1
> Step 7: set s to s + 1
> Step 8: proceed from Step 3.
> Step 9: terminate. The result is in y.
>
> And that's an algorithm, even though I'm not a mathematician.
>
> Whenever you solve a problem in a well-defined, finite way, you are
> creating an algorithm. One might reasonably say that the job of the
> computer programmer is to devise algorithms (and then to implement them
> in a programming language).
Alternately one may make a distinction between computer science and
software engineering. The fields have considerable overlap, but it
should be obvious that the engineering constraints of a real-world
application are one thing while the constraints driving a computer
scientist with his algorithm may be something else entirely.
One of the things about learning C which has bothered me immensely is
the difference between the trivial learning example and what often
ends up being required for "real" programming. The great gulf
separating the design constraints of the learning example and the
non-trivial application of an algorithm or programming technique is
not in any way a trifling matter.
It is possible I would not be quite so jaded and disillusioned had I
not ended up learning C from one half-assed book in my youth and later
from compiler diagnostics and a whole lot of barely readable code
programmers had released into the wild as "done". To the last point
it seems to me that a considerable fraction of programmers are of a
mind to consider that needlessly obscure or complex code constructions
as a barrier to understanding are something of a right of passage into
the "mysteries" of computer programming, making the programming
avocation into something of a priesthood of the elite -- those who
have transcended the (quasi-invisible) barriers and attained a certain
Enlightenment.
Fortunately that attitude is not universal and there remain a subset
of computer programmers who strive for clarity in all things. To that
end simplicity is the watchword, but as luck would have it simplicity
is not synonymous with easy, and may be quite difficult to attain in
practice. I suggest it is the province of tooling to make simplicity
easier to attain without necessarily sacrificing capability or
correctness.
Regards,
Steve Thompson
--
"The civil war in Spain is being carried on with extreme brutality on
both sides, is being prolonged by the support of foreign States
professing a policy of non-intervention, and has led to a recru-
descence of piracy. In Russia nad in Germany alike, whatever be the
differences in ideologies, we find regimes which rest ultimately on
force, which shrink from no kind of persecution, which, if the Howard
League is to be credited, are reintroducing torture into their
political machinery, and which seem to regard a blood bath as the only
satisfactory substitute for a general election." -- H.J. Paton, 1937
[toc] | [prev] | [next] | [standalone]
| From | Malcolm McLean <malcolm.mclean5@btinternet.com> |
|---|---|
| Date | 2015-12-14 13:07 -0800 |
| Message-ID | <788426fc-343d-43ad-bb2d-c7bfdbfcd40a@googlegroups.com> |
| In reply to | #78675 |
On Monday, December 14, 2015 at 7:35:08 PM UTC, Steve Thompson wrote:
>
> Alternately one may make a distinction between computer science and
> software engineering. The fields have considerable overlap, but it
> should be obvious that the engineering constraints of a real-world
> application are one thing while the constraints driving a computer
> scientist with his algorithm may be something else entirely.
>
Computer science is about making computers do clever things.
Software engineering is about wrapping that up into a product
that meets commercial or occasionally other objectives.
What you often find is that you wonder about writing a program
to do X, and there's already one available, often for free.
But it's not really usable. The core algorithm is there, but all
the surrounding routines which enable the user to get data in
and out are missing.
>
> One of the things about learning C which has bothered me immensely is
> the difference between the trivial learning example and what often
> ends up being required for "real" programming. The great gulf
> separating the design constraints of the learning example and the
> non-trivial application of an algorithm or programming technique is
> not in any way a trifling matter.
>
Many things don't scale. That's the great lesson of programming
methodologies.
[toc] | [prev] | [next] | [standalone]
| From | Keith Thompson <kst-u@mib.org> |
|---|---|
| Date | 2015-12-13 13:42 -0800 |
| Message-ID | <lnwpsidnzl.fsf@kst-u.example.com> |
| In reply to | #78546 |
Richard Heathfield <rjh@cpax.org.uk> writes:
[...]
> HOW TO WRITE AN fgets CLONE
> ---------------------------
>
> Step 1 - define the problem
> Step 2 - pick a good name
> Step 3 - define the interface
> Step 4 - write a stub function
> Step 5 - create a build environment
> Step 6 - test the stub function
> Step 7 - design the function
> Step 8 - implement the function
> Step 9 - test the function
>
>
> All of these steps are important. Let's take the first step first.
>
> Step 1 - define the problem
> We want a function that can read a string from a stream, and write it
> into an array. We *must not* exceed the bounds of the array, so we need
> to be told how much space is available. We should stop on a newline
> character (including it in the array if there's room). We should return
> a null pointer if we encounter an error or an end-of-file condition (not
> changing the array if we haven't yet done so).
That's not *quite* an accurate description of the behavior of fgets().
You've left some of the details to steps 7 and 8 -- which, let's face
it, is sometimes unavoidable. It's common to go back and update the
problem definition as new issues come up.
If we encounter an end-of-file condition after reading one or more
characters, the call is successful (but we don't store a neline
character in the buffer). You also haven't specified what the function
returns on success (it returns its first argument).
To be even more quibbly, fgets() doesn't read a *string* from a stream.
A string is terminated by a '\0' character; we typically won't see a
'\0' character in an input stream, and if we do it doesn't terminate the
input. "read a (possibly partial) line" would be more accurate.
But the array does need to contain a string after a successful call to
fgets(); you didn't mention storing a '\0'.
I would have said "store it into an array" rather than "write". The
word "write" isn't wrong, but it could imply an output operation rather
than storing data in an object in memory.
[...]
> Here's a simplified Makefile (my actual CFLAGS are a bit more involved
> than this, but these'll be fine for now). Instruction lines begin with a
> hard TAB character (the TAB in your text editor should work fine for this):
It depends on how your editor is configured. When I type TAB in vim,
for example, it can insert either a hard tab character or sequence of
one or more spaces, depending on the setting of the "expandtab" option.
If that's set (or even if it isn't), Ctrl-V TAB will insert a hard tab
character.
[...]
> if(argc > 1)
> {
> fp = fopen(argv[1], "r");
> if(NULL == fp)
> {
> fprintf(stderr, "Can't open test file %s\n", argv[1]);
> fp = stdin;
> }
> }
It's interesting that your program reads from stdin if you specify
a file on the command line and it fails to open it. A more usual
approach would be to abort on that kind of error.
[...]
> if('\n' == ch)
https://en.wikipedia.org/wiki/Yoda_conditions
*shudder*
[...]
> A more thorough test would normally be indicated. You'd want to test for
> things like a corrupted stream, an array size of 0, an empty file, all
> that kind of thing. But those are refinements.
One final quibble: An array cannot have a size of 0. But fgets() can be
called with a size of 0, and should handle it consistently.
[...]
--
Keith Thompson (The_Other_Keith) kst-u@mib.org <http://www.ghoti.net/~kst>
Working, but not speaking, for JetHead Development, Inc.
"We must do something. This is something. Therefore, we must do this."
-- Antony Jay and Jonathan Lynn, "Yes Minister"
[toc] | [prev] | [next] | [standalone]
| From | Richard Heathfield <rjh@cpax.org.uk> |
|---|---|
| Date | 2015-12-13 22:14 +0000 |
| Message-ID | <n4kqga$5a7$1@dont-email.me> |
| In reply to | #78578 |
On 13/12/15 21:42, Keith Thompson wrote: > Richard Heathfield <rjh@cpax.org.uk> writes: > [...] >> HOW TO WRITE AN fgets CLONE >> --------------------------- >> >> Step 1 - define the problem >> Step 2 - pick a good name >> Step 3 - define the interface >> Step 4 - write a stub function >> Step 5 - create a build environment >> Step 6 - test the stub function >> Step 7 - design the function >> Step 8 - implement the function >> Step 9 - test the function Step 10 - post on Usenet so that Keith can have his say. :-) <many excellent points snipped> -- Richard Heathfield Email: rjh at cpax dot org dot uk "Usenet is a strange place" - dmr 29 July 1999 Sig line 4 vacant - apply within
[toc] | [prev] | [next] | [standalone]
| From | Malcolm McLean <malcolm.mclean5@btinternet.com> |
|---|---|
| Date | 2015-12-11 09:51 -0800 |
| Message-ID | <456b5432-709c-4be0-b44a-12419e480843@googlegroups.com> |
| In reply to | #78412 |
On Friday, December 11, 2015 at 11:14:39 AM UTC, Alla _ wrote:
>
> /*
> * Reads a line of text from standard input and returns it as an
> * int in the range of [-2^31 + 1, 2^31 - 2], if possible; if text
> * does not represent such an int, user is prompted to retry. Leading
> * and trailing whitespace is ignored. For simplicity, overflow is not
> * detected. If line can't be read, returns INT_MAX.
> */
>
> int
> GetInt(void)
> {
> // try to get an int from user
> while (true)
> {
> // get line of text, returning INT_MAX on failure
> string line = GetString();
> if (line == NULL)
> return INT_MAX;
>
> // return an int if only an int (possibly with
> // leading and/or trailing whitespace) was provided
> int n; char c;
> if (sscanf(line, " %d %c", &n, &c) == 1)
> {
> free(line);
> return n;
> }
> else
> {
> free(line);
> printf("Retry: ");
> }
> }
> }
>
> /*
> * Reads a line of text from standard input and returns it as a
> * string (char *), sans trailing newline character. (Ergo, if
> * user inputs only "\n", returns "" not NULL.) Returns NULL
> * upon error or no input whatsoever (i.e., just EOF). Leading
> * and trailing whitespace is not ignored. Stores string on heap
> * (via malloc); memory must be freed by caller to avoid leak.
> */
>
> string
> GetString(void)
> {
> // growable buffer for chars
> string buffer = NULL;
>
> // capacity of buffer
> unsigned int capacity = 0;
>
> // number of chars actually in buffer
> unsigned int n = 0;
>
> // character read or EOF
> int c;
>
> // iteratively get chars from standard input
> while ((c = fgetc(stdin)) != '\n' && c != EOF)
> {
> // grow buffer if necessary
> if (n + 1 > capacity)
> {
> // determine new capacity: start at 32 then double
> if (capacity == 0)
> capacity = 32;
> else if (capacity <= (UINT_MAX / 2))
> capacity *= 2;
> else
> {
> free(buffer);
> return NULL;
> }
>
> // extend buffer's capacity
> string temp = realloc(buffer, capacity * sizeof(char));
> if (temp == NULL)
> {
> free(buffer);
> return NULL;
> }
> buffer = temp;
> }
>
> // append current character to buffer
> buffer[n++] = c;
> }
>
> // return NULL if user provided no input
> if (n == 0 && c == EOF)
> return NULL;
>
> // minimize buffer
> string minimal = malloc((n + 1) * sizeof(char));
> strncpy(minimal, buffer, n);
> free(buffer);
>
> // terminate string
> minimal[n] = '\0';
>
> // return string
> return minimal;
> }
>
Beginner programs usually work by printing something to the console,
then reading the reply, then printing something else to the console,
conducting a sort of dialogue with the user.
It's not a very common model for modern real life programs. And it has
the problem that stdin is quite difficult to work with. It's hard to test
a function in isolation to see if it actually does what you want if it's
reading from stdin.
I'd prefer to see you write your own function to test if a string is an
integer, from scratch. (The scanf() method will work, but it's "tricky"
programming). It's quite easy - an integer must be 0 or more leading
whitespace character, one digit 1-9, 0 or more digits 0-9, and 0
or more trailing whitespace characters, then nul.
For now just assume that an integer will fit in an int (but you can think
about how to extend the function to reject very big numbers).
[toc] | [prev] | [next] | [standalone]
| From | Alla _ <modelling.data@gmail.com> |
|---|---|
| Date | 2015-12-11 10:15 -0800 |
| Message-ID | <8b7c6d81-6aff-4d8d-800c-c634d28eef3c@googlegroups.com> |
| In reply to | #78441 |
On Friday, December 11, 2015 at 9:51:45 PM UTC+4, Malcolm McLean wrote:
> On Friday, December 11, 2015 at 11:14:39 AM UTC, Alla _ wrote:
> >
> > /*
> > * Reads a line of text from standard input and returns it as an
> > * int in the range of [-2^31 + 1, 2^31 - 2], if possible; if text
> > * does not represent such an int, user is prompted to retry. Leading
> > * and trailing whitespace is ignored. For simplicity, overflow is not
> > * detected. If line can't be read, returns INT_MAX.
> > */
> >
> > int
> > GetInt(void)
> > {
> > // try to get an int from user
> > while (true)
> > {
> > // get line of text, returning INT_MAX on failure
> > string line = GetString();
> > if (line == NULL)
> > return INT_MAX;
> >
> > // return an int if only an int (possibly with
> > // leading and/or trailing whitespace) was provided
> > int n; char c;
> > if (sscanf(line, " %d %c", &n, &c) == 1)
> > {
> > free(line);
> > return n;
> > }
> > else
> > {
> > free(line);
> > printf("Retry: ");
> > }
> > }
> > }
> >
> > /*
> > * Reads a line of text from standard input and returns it as a
> > * string (char *), sans trailing newline character. (Ergo, if
> > * user inputs only "\n", returns "" not NULL.) Returns NULL
> > * upon error or no input whatsoever (i.e., just EOF). Leading
> > * and trailing whitespace is not ignored. Stores string on heap
> > * (via malloc); memory must be freed by caller to avoid leak.
> > */
> >
> > string
> > GetString(void)
> > {
> > // growable buffer for chars
> > string buffer = NULL;
> >
> > // capacity of buffer
> > unsigned int capacity = 0;
> >
> > // number of chars actually in buffer
> > unsigned int n = 0;
> >
> > // character read or EOF
> > int c;
> >
> > // iteratively get chars from standard input
> > while ((c = fgetc(stdin)) != '\n' && c != EOF)
> > {
> > // grow buffer if necessary
> > if (n + 1 > capacity)
> > {
> > // determine new capacity: start at 32 then double
> > if (capacity == 0)
> > capacity = 32;
> > else if (capacity <= (UINT_MAX / 2))
> > capacity *= 2;
> > else
> > {
> > free(buffer);
> > return NULL;
> > }
> >
> > // extend buffer's capacity
> > string temp = realloc(buffer, capacity * sizeof(char));
> > if (temp == NULL)
> > {
> > free(buffer);
> > return NULL;
> > }
> > buffer = temp;
> > }
> >
> > // append current character to buffer
> > buffer[n++] = c;
> > }
> >
> > // return NULL if user provided no input
> > if (n == 0 && c == EOF)
> > return NULL;
> >
> > // minimize buffer
> > string minimal = malloc((n + 1) * sizeof(char));
> > strncpy(minimal, buffer, n);
> > free(buffer);
> >
> > // terminate string
> > minimal[n] = '\0';
> >
> > // return string
> > return minimal;
> > }
> >
>
> Beginner programs usually work by printing something to the console,
> then reading the reply, then printing something else to the console,
> conducting a sort of dialogue with the user.
>
> It's not a very common model for modern real life programs. And it has
> the problem that stdin is quite difficult to work with. It's hard to test
> a function in isolation to see if it actually does what you want if it's
> reading from stdin.
>
> I'd prefer to see you write your own function to test if a string is an
> integer, from scratch. (The scanf() method will work, but it's "tricky"
> programming). It's quite easy - an integer must be 0 or more leading
> whitespace character, one digit 1-9, 0 or more digits 0-9, and 0
> or more trailing whitespace characters, then nul.
> For now just assume that an integer will fit in an int (but you can think
> about how to extend the function to reject very big numbers).
Thank you. I will do my best to come up with a reasonable code.
[toc] | [prev] | [next] | [standalone]
| From | Steve Thompson <stevet810@gmail.com> |
|---|---|
| Date | 2015-12-12 20:42 +0000 |
| Message-ID | <yxQIzB.1Kr.IIKhJ@gmail.com> |
| In reply to | #78449 |
On Fri, Dec 11, 2015 at 10:15:58AM -0800, Alla _ wrote:
> On Friday, December 11, 2015 at 9:51:45 PM UTC+4, Malcolm McLean wrote:
> > On Friday, December 11, 2015 at 11:14:39 AM UTC, Alla _ wrote:
> > >
> > > /*
> > > * Reads a line of text from standard input and returns it as an
> > > * int in the range of [-2^31 + 1, 2^31 - 2], if possible; if text
> > > * does not represent such an int, user is prompted to retry. Leading
> > > * and trailing whitespace is ignored. For simplicity, overflow is not
> > > * detected. If line can't be read, returns INT_MAX.
> > > */
> > >
> > > int
> > > GetInt(void)
> > > {
> > > // try to get an int from user
> > > while (true)
> > > {
> > > // get line of text, returning INT_MAX on failure
> > > string line = GetString();
> > > if (line == NULL)
> > > return INT_MAX;
> > >
> > > // return an int if only an int (possibly with
> > > // leading and/or trailing whitespace) was provided
> > > int n; char c;
> > > if (sscanf(line, " %d %c", &n, &c) == 1)
> > > {
> > > free(line);
> > > return n;
> > > }
> > > else
> > > {
> > > free(line);
> > > printf("Retry: ");
> > > }
> > > }
> > > }
> > >
> > > /*
> > > * Reads a line of text from standard input and returns it as a
> > > * string (char *), sans trailing newline character. (Ergo, if
> > > * user inputs only "\n", returns "" not NULL.) Returns NULL
> > > * upon error or no input whatsoever (i.e., just EOF). Leading
> > > * and trailing whitespace is not ignored. Stores string on heap
> > > * (via malloc); memory must be freed by caller to avoid leak.
> > > */
> > >
> > > string
> > > GetString(void)
> > > {
> > > // growable buffer for chars
> > > string buffer = NULL;
> > >
> > > // capacity of buffer
> > > unsigned int capacity = 0;
> > >
> > > // number of chars actually in buffer
> > > unsigned int n = 0;
> > >
> > > // character read or EOF
> > > int c;
> > >
> > > // iteratively get chars from standard input
> > > while ((c = fgetc(stdin)) != '\n' && c != EOF)
> > > {
> > > // grow buffer if necessary
> > > if (n + 1 > capacity)
> > > {
> > > // determine new capacity: start at 32 then double
> > > if (capacity == 0)
> > > capacity = 32;
> > > else if (capacity <= (UINT_MAX / 2))
> > > capacity *= 2;
> > > else
> > > {
> > > free(buffer);
> > > return NULL;
> > > }
> > >
> > > // extend buffer's capacity
> > > string temp = realloc(buffer, capacity * sizeof(char));
> > > if (temp == NULL)
> > > {
> > > free(buffer);
> > > return NULL;
> > > }
> > > buffer = temp;
> > > }
> > >
> > > // append current character to buffer
> > > buffer[n++] = c;
> > > }
> > >
> > > // return NULL if user provided no input
> > > if (n == 0 && c == EOF)
> > > return NULL;
> > >
> > > // minimize buffer
> > > string minimal = malloc((n + 1) * sizeof(char));
> > > strncpy(minimal, buffer, n);
> > > free(buffer);
> > >
> > > // terminate string
> > > minimal[n] = '\0';
> > >
> > > // return string
> > > return minimal;
> > > }
> > >
> >
> > Beginner programs usually work by printing something to the console,
> > then reading the reply, then printing something else to the console,
> > conducting a sort of dialogue with the user.
> >
> > It's not a very common model for modern real life programs. And it has
> > the problem that stdin is quite difficult to work with. It's hard to test
> > a function in isolation to see if it actually does what you want if it's
> > reading from stdin.
> >
> > I'd prefer to see you write your own function to test if a string is an
> > integer, from scratch. (The scanf() method will work, but it's "tricky"
> > programming). It's quite easy - an integer must be 0 or more leading
> > whitespace character, one digit 1-9, 0 or more digits 0-9, and 0
> > or more trailing whitespace characters, then nul.
> > For now just assume that an integer will fit in an int (but you can think
> > about how to extend the function to reject very big numbers).
>
> Thank you. I will do my best to come up with a reasonable code.
A programming pattern you may find helpful is the use of indicator
flags. Assuming you have a well-formed char * array at hand from
GetString(), the following fragment demonstrates a common programming
pattern:
#define MAX_STR_LEN 16
int i;
int invalid_flag;
char * input;
...
while(1) {
invalid_flag = 0;
input = GetString();
for(i = 0; input[i] != '\0'; i++) {
if(isspace(input[i]));
continue;
if(!isdigit(input[i])) {
invalid_flag = 1;
break;
}
}
if(i > MAX_STR_LEN) {
printf("Input string is too long. Please try again.\n");
continue;
}
if(invalid_flag == 1)
printf("Invalid characters found in text. Please enter a valid decimal number.\n");
else
break;
}
number = strtol(input, NULL, 10);
...
The advantage with this particular 'flag' approach is that you do not
end up relying on the behavior of strtol() to qualify your program
input. In a more complicated program you might have any number of
'flags' to characterize program objects, and the scheme avoids
encoding program object state as an implicit property of particular
code sequences. Code then may concern itself with the characteristics
of program objects which are of immediate interest at that point in
the program. This is not specific to C, but it is easy to implement
in C by way of bit-fields in structures. Thus you could construct an
input string structure along the lines of the following:
struct input_object {
char * string;
long int number;
unsigned int flag_input_ok:1;
unsigned int flag_conversion_ok:1;
unsigned int flag_bad_characters:1;
unsigned int flag_out_of_range:1;
};
You could use individual 'int' variables as flag varibles, but this is
wasteful since the range of an int is far more than is required for a
simple flag variable. A bit field which is '1' bit wide can hold a
value of '0' or '1' which directly maps to the notion of 'true' or
'false', and in fact people often define 'true' as 1 and 'false' as 0
for the sake of clarity.
At any rate it is a matter of first initializing the structure fields
to sensible default values, developing a GetString() function which
accepts the structure and which only concerns itself with getting
input from the user and then storing it with the 'string' field
pointing at the allocated char array. Then you may pass the structure
to another function which examines the input string for non-numeric
characters, etc. If it passes muster, this function may then set the
flag_input_ok field, or indicate error by way of setting one of the
other flags. Then you might pass the object to a function which does
strtol() and which checks its result, etc. And finally then to a
function which verifies there are no specified errors and which then
processes the converted number as appropriate to the program.
This approach helps to modularize the program and gather related
information in one place. Structures are a little tricky to grasp
initially because they often force you to consider pointers, but in
principle a structure is not much different from a char array.
Passing structures to functions may be done directly (in which case
the function is given a copy of the original structure) or by
reference, in which case you are passing a pointer which identifies
your original structure instance to a function and it will operate
directly on the original contents. So then,
struct input_object io;
defines an input_object structure which is identified by the variable
name 'io'.
some_function(io);
A copy is made of the original structure and made available to the
code in some_function(). If that function modifies its copy of the
structure those changes are not reflected in your original.
another_function(&io);
passes a pointer to your original structure to another_function(),
which may then examine or modify parts of the original object.
struct input_object *ptr;
defines a pointer varible that is intended to point at input_object
structures.
ptr = &io;
uses the '&' operator to take the address of the io input_object
structure and assigns it to the 'ptr' variable.
another_function(ptr);
accomplishes the same thing as another_function(&io);
C makes the distinction between structures and pointers to structures
in the way that structure elements are referenced.
io.string = GetString();
ptr->string = GetString();
do exactly the same thing. You cannot use a pointer variable with the
'.' operator, and conversely you cannot use the '->' operator with a
structure directly as with "io->string" since 'io' is a structure and
'ptr' is a pointer to the structure as defined previously.
Functions may be defined to return structures or pointers to
structures, and the difference is crucial due to the fact that in one
case the whole structure is being copied around and in the other only
a pointer to a structure is copied. e.g.:
struct input_object NewGetString()
{
struct input_object io;
... code to allocate the string buffer and read input ...
return io;
}
This will create a new input_object structure and returns a copy of
it to the function's caller:
struct input_object abc;
abc = NewGetString();
On the other hand:
int NewGetString2(struct input_object * io)
{
int result;
... code to allocate string buffer, read input ...
return result;
}
This function expects to be passed a pointer to an existing
input_object structure, modifies its contents, and then returns an
integer status code. It could equally well return no value (use void
instead of int) and indicate a result status within the structure
itself, again by modifying its contents. Therefore, in the second
instance you would have something like the following:
struct input_object abc;
NewGetString2(&abc);
Which variety you use in any specific instance is a matter of style
and preference. Note that the input_object structure and the char *
buffer will be two distinct program objects and that the input_object
structure only has a field 'string' which points *to* the char * array
you will have allocated with malloc() and/or realloc(). You may of
course use malloc() to allocate structures:
ptr = malloc(sizeof(input_object));
A final note. Pointers are rather flexible, and of course we can have
pointers to pointers, pointers to functions, arrays of pointers to
functions, and so forth. I would recommend avoiding complex pointers
until you are more familiar with basic pointers and arrays. It will
take some time to train your mind to reason about pointers and
structures, so take it slowly and experiment with the simple forms
first.
Regards,
Steve Thompson
--
"The civil war in Spain is being carried on with extreme brutality on
both sides, is being prolonged by the support of foreign States
professing a policy of non-intervention, and has led to a recru-
descence of piracy. In Russia nad in Germany alike, whatever be the
differences in ideologies, we find regimes which rest ultimately on
force, which shrink from no kind of persecution, which, if the Howard
League is to be credited, are reintroducing torture into their
political machinery, and which seem to regard a blood bath as the only
satisfactory substitute for a general election." -- H.J. Paton, 1937
[toc] | [prev] | [next] | [standalone]
| From | Keith Thompson <kst-u@mib.org> |
|---|---|
| Date | 2015-12-12 18:10 -0800 |
| Message-ID | <lnzixff69g.fsf@kst-u.example.com> |
| In reply to | #78510 |
Steve Thompson <stevet810@gmail.com> writes:
[...]
> #define MAX_STR_LEN 16
>
> int i;
> int invalid_flag;
> char * input;
> ...
>
> while(1) {
> invalid_flag = 0;
>
> input = GetString();
>
> for(i = 0; input[i] != '\0'; i++) {
> if(isspace(input[i]));
> continue;
>
> if(!isdigit(input[i])) {
> invalid_flag = 1;
> break;
> }
> }
>
> if(i > MAX_STR_LEN) {
> printf("Input string is too long. Please try again.\n");
> continue;
> }
>
> if(invalid_flag == 1)
> printf("Invalid characters found in text. Please enter a valid decimal number.\n");
> else
> break;
> }
>
> number = strtol(input, NULL, 10);
> ...
You set invalid_flag to 0 at the top of the loop. The only time it's
set to a non-zero value, you immediately break out of the loop, so it's
not possible for invalid_flag to have a non-zero value inside the loop.
You then test (invalid_flag == 1) inside the loop. The "Invalid
characters" message cannot possibly appear.
Also, since it's a flag, it would be clear if it were defined as a bool,
with the values false and true assigned to it rather than 0 and 1. If
you're concerned about portability to pre-C99 compilers:
typedef enum { false, true } bool;
--
Keith Thompson (The_Other_Keith) kst-u@mib.org <http://www.ghoti.net/~kst>
Working, but not speaking, for JetHead Development, Inc.
"We must do something. This is something. Therefore, we must do this."
-- Antony Jay and Jonathan Lynn, "Yes Minister"
[toc] | [prev] | [next] | [standalone]
| From | Ben Bacarisse <ben.usenet@bsb.me.uk> |
|---|---|
| Date | 2015-12-13 11:16 +0000 |
| Message-ID | <871taq4mzg.fsf@bsb.me.uk> |
| In reply to | #78517 |
Keith Thompson <kst-u@mib.org> writes:
> Steve Thompson <stevet810@gmail.com> writes:
> [...]
>> #define MAX_STR_LEN 16
>>
>> int i;
>> int invalid_flag;
>> char * input;
>> ...
>>
>> while(1) {
>> invalid_flag = 0;
>>
>> input = GetString();
>>
>> for(i = 0; input[i] != '\0'; i++) {
>> if(isspace(input[i]));
>> continue;
>>
>> if(!isdigit(input[i])) {
>> invalid_flag = 1;
>> break;
>> }
>> }
>>
>> if(i > MAX_STR_LEN) {
>> printf("Input string is too long. Please try again.\n");
>> continue;
>> }
>>
>> if(invalid_flag == 1)
>> printf("Invalid characters found in text. Please enter a valid decimal number.\n");
>> else
>> break;
>> }
>>
>> number = strtol(input, NULL, 10);
>> ...
>
> You set invalid_flag to 0 at the top of the loop. The only time it's
> set to a non-zero value, you immediately break out of the loop, so it's
> not possible for invalid_flag to have a non-zero value inside the loop.
> You then test (invalid_flag == 1) inside the loop. The "Invalid
> characters" message cannot possibly appear.
The break is in a nested loop. It seems to be a very complicated way to
do something but I'm not entirely sure what the objective is, so I
hesitate to re-write it.
<snip>
--
Ben.
[toc] | [prev] | [next] | [standalone]
| From | Keith Thompson <kst-u@mib.org> |
|---|---|
| Date | 2015-12-13 03:41 -0800 |
| Message-ID | <lna8pefue8.fsf@kst-u.example.com> |
| In reply to | #78526 |
Ben Bacarisse <ben.usenet@bsb.me.uk> writes:
> Keith Thompson <kst-u@mib.org> writes:
>> Steve Thompson <stevet810@gmail.com> writes:
>> [...]
>> You set invalid_flag to 0 at the top of the loop. The only time it's
>> set to a non-zero value, you immediately break out of the loop, so it's
>> not possible for invalid_flag to have a non-zero value inside the loop.
>> You then test (invalid_flag == 1) inside the loop. The "Invalid
>> characters" message cannot possibly appear.
>
> The break is in a nested loop. It seems to be a very complicated way to
> do something but I'm not entirely sure what the objective is, so I
> hesitate to re-write it.
Ah, you're right.
--
Keith Thompson (The_Other_Keith) kst-u@mib.org <http://www.ghoti.net/~kst>
Working, but not speaking, for JetHead Development, Inc.
"We must do something. This is something. Therefore, we must do this."
-- Antony Jay and Jonathan Lynn, "Yes Minister"
[toc] | [prev] | [next] | [standalone]
| From | Steve Thompson <stevet810@gmail.com> |
|---|---|
| Date | 2015-12-14 01:43 +0000 |
| Message-ID | <ijrSqs.uqL.nH4Nx@gmail.com> |
| In reply to | #78528 |
On Sun, Dec 13, 2015 at 03:41:19AM -0800, Keith Thompson wrote: > Ben Bacarisse <ben.usenet@bsb.me.uk> writes: > > Keith Thompson <kst-u@mib.org> writes: > >> Steve Thompson <stevet810@gmail.com> writes: > >> [...] > >> You set invalid_flag to 0 at the top of the loop. The only time it's > >> set to a non-zero value, you immediately break out of the loop, so it's > >> not possible for invalid_flag to have a non-zero value inside the loop. > >> You then test (invalid_flag == 1) inside the loop. The "Invalid > >> characters" message cannot possibly appear. > > > > The break is in a nested loop. It seems to be a very complicated way to > > do something but I'm not entirely sure what the objective is, so I > > hesitate to re-write it. > > Ah, you're right. You mean I didn't screw up quite as I thought? Crap. Now I will have to revist the original and give it another once over. Maybe if we all take turns making mistakes we can all become equally confused. Regards, Steve Thompson -- "The civil war in Spain is being carried on with extreme brutality on both sides, is being prolonged by the support of foreign States professing a policy of non-intervention, and has led to a recru- descence of piracy. In Russia nad in Germany alike, whatever be the differences in ideologies, we find regimes which rest ultimately on force, which shrink from no kind of persecution, which, if the Howard League is to be credited, are reintroducing torture into their political machinery, and which seem to regard a blood bath as the only satisfactory substitute for a general election." -- H.J. Paton, 1937
[toc] | [prev] | [next] | [standalone]
| From | Steve Thompson <stevet810@gmail.com> |
|---|---|
| Date | 2015-12-14 01:41 +0000 |
| Message-ID | <OTd0AM.O1U.SJKAv@gmail.com> |
| In reply to | #78517 |
On Sat, Dec 12, 2015 at 06:10:19PM -0800, Keith Thompson wrote:
> Steve Thompson <stevet810@gmail.com> writes:
> [...]
> > #define MAX_STR_LEN 16
> >
> > int i;
> > int invalid_flag;
> > char * input;
> > ...
> >
> > while(1) {
> > input = GetString();
> >
> > for(i = 0; input[i] != '\0'; i++) {
> > if(isspace(input[i]));
> > continue;
> >
> > if(!isdigit(input[i])) {
> > printf("Invalid characters found in text. Please enter a valid decimal number.\n");
> > free(input);
> > continue;
> > }
> > }
> >
> > if(i > MAX_STR_LEN) {
> > printf("Input string is too long. Please try again.\n");
> > continue;
> > }
> > }
> >
> > number = strtol(input, NULL, 10);
> > ...
>
> You set invalid_flag to 0 at the top of the loop. The only time it's
> set to a non-zero value, you immediately break out of the loop, so it's
> not possible for invalid_flag to have a non-zero value inside the loop.
> You then test (invalid_flag == 1) inside the loop. The "Invalid
> characters" message cannot possibly appear.
You're right. That'll teach me to compile in my head. I didn't even
notice I'd shot myself in the foot.
I fixed it above and eliminated the %^&* flag, thus cleverly
invalidating the premise of my argument. Back, as they say, to the
drawing board.
> Also, since it's a flag, it would be clear if it were defined as a bool,
> with the values false and true assigned to it rather than 0 and 1. If
> you're concerned about portability to pre-C99 compilers:
>
> typedef enum { false, true } bool;
I hate using a whole int for flags, especially in structures where
there might be a few and where the structure might be manifested in
many instances. Habitually, then, I use bit fields or unsigned char
if I think I'll ever be needing the address of the flag. (Why would I
ever need the address of a flag? Instrumentation.)
Regards,
Steve Thompson
--
"The civil war in Spain is being carried on with extreme brutality on
both sides, is being prolonged by the support of foreign States
professing a policy of non-intervention, and has led to a recru-
descence of piracy. In Russia nad in Germany alike, whatever be the
differences in ideologies, we find regimes which rest ultimately on
force, which shrink from no kind of persecution, which, if the Howard
League is to be credited, are reintroducing torture into their
political machinery, and which seem to regard a blood bath as the only
satisfactory substitute for a general election." -- H.J. Paton, 1937
[toc] | [prev] | [next] | [standalone]
| From | Ben Bacarisse <ben.usenet@bsb.me.uk> |
|---|---|
| Date | 2015-12-11 18:45 +0000 |
| Message-ID | <87h9jorfir.fsf@bsb.me.uk> |
| In reply to | #78441 |
ram@zedat.fu-berlin.de (Stefan Ram) writes: <snip> > That's why in my C course, I do not teach reading input at all. Same here when I taught programming. Eventually, yes, but not right away and I always[1] covered data input from a file before interactive input, because interacting correctly and clearly with the user is the hardest of all. <snip> > I do not want to say that learning to read from files is not > important. It's just too difficult for beginners, I think you can cover reading data files (thought they may not actually come from a file of course) without too much bother. Once the students have the basics, you need to be able to read data in order to write more interesting programs. > and also > real-world software today rarely has user-dialogs via stdin > and stdout - such dialogs are more often found in > traditional C courses Yes, I am always surprised by that. It's (a) not that important a skill and (b) so fiddly in most languages, that it's hardly worth the effort. <snip> [1] By which I mean eventually I always did that! When I first taught programming, I did it exactly like every other course I'd seen (and taken). -- Ben.
[toc] | [prev] | [next] | [standalone]
Page 4 of 5 — ← Prev page 1 2 3 [4] 5 Next page →
Back to top | Article view | comp.lang.c
csiph-web