Early beginner learning arrays and for and while loops ...

B

bpascal123

Hi,

This code below works until value 22. I really wonder why from this
point, the merging is not working and my computer says value 22 is
423, value 23 : 431, value 24 : 0, value 25 : 1 and as you can see if
you run this code, it's not matching table B... Why so?

Thanks for helping,

Pascal


#include <stdio.h>

main()
{
int a[50], b[50], merg[100] ;
int ia, ib ;
int i, j, k, k2, imerg ;
int op, cnt ;

ia = 10 ; ib = 15 ;

printf("\n\n==============================\n\n") ;

printf("This code reads, displays 2 arrays and merges them into a
third array \"merg\".") ;



printf("\n\n===============\n\n") ;


printf("\nTable A : \n\n") ;

for ( i = 0 ; i < ia ; i++ )
{
a = op * 10 / 8 + 6 ;
op = a ;
printf("Value %2d : %4d \n", cnt++, a) ;
}

printf("\n\nTable B : \n\n") ;

for ( j= 0, cnt = 1, op = 0 ; j < ib ; j++ )
{
b[j] = op * 10 / 7 + 4 ;
op = b[j] ;
printf("Value %2d : %4d \n", cnt++, b[j]) ;
}

/* MERGING OF TABLE A AND B */

i = 0 ; j = 0 ; imerg = 0 ;

k2 = ia + ib ;

/*
(ia < ib ) ? k2 = ib : k2 = ia ;
*/

for ( k = 0 ; k < k2 ; k++ )
{
if ( a < b[j] )
{
merg[imerg] = a ;
imerg++ ;
i++ ;
}
else if ( a > b[j] )
{
merg[imerg] = b[j] ;
imerg++ ;
j++ ;
}
else if ( i <= ia )
{
merg[imerg] = a ;
imerg++ ;
i++ ;
}
else if ( j <= ib )
{
merg[imerg] = b[j] ;
imerg++ ;
j++ ;
}
}

/*
while ( ( i < ia ) && ( j < ib ) )
if ( a < b[j] )
{
merg[imerg] = a ;
imerg++ ;
i++;
}
else
{
merg[imerg] = b[j] ;
imerg++ ;
j++ ;
}

while ( i < ia )
{
merg[imerg] = a ;
imerg++ ;
ia++ ;
}

while (j < ib )
{
merg[imerg] = b[j] ;
imerg++ ;
j++ ;
}
*/

printf("\n\n===============\n\n") ;

printf("Affichage rsltat ");

printf("\n===============\n\n") ;

for ( imerg = 0, cnt = 1 ; imerg < k2 ; imerg++ )
printf("\nValeur %2d : %4d ", cnt++, merg[imerg]) ;

printf("\n\n==============================\n\n") ;

return 0 ;

}
 
N

Nick Keighley

This code below works until value 22.

not on my computer. Did you post the actual code?
On my machine it glitches at entry 19 when the first table runs out
(it says its zero).
And omits the last entry of the second table. Sounds like some
sort of off-by-error.

I really wonder why from this
point, the merging is not working and my computer says value 22 is
423, value 23 : 431, value 24 : 0, value 25 : 1 and as you can see if
you run this code, it's not matching table B... Why so?

none of the symptoms you describe occur on my machine.

your layout is rather peculiar.

you need to learn how to debug. For this you will need more
information about what your program is doing.

1. don't put everything in main()
2. add some assert()s
3. print out intermediate values
4. use a debugger


#include <stdio.h>

main()

int main (void)

<snip>
 
B

Ben Bacarisse

This code below works until value 22. I really wonder why from this
point, the merging is not working and my computer says value 22 is
423, value 23 : 431, value 24 : 0, value 25 : 1 and as you can see if
you run this code, it's not matching table B... Why so?
#include <stdio.h>

main()
{
int a[50], b[50], merg[100] ;
int ia, ib ;
int i, j, k, k2, imerg ;
int op, cnt ;

ia = 10 ; ib = 15 ;

printf("\n\n==============================\n\n") ;

printf("This code reads, displays 2 arrays and merges them into a
third array \"merg\".") ;



printf("\n\n===============\n\n") ;


printf("\nTable A : \n\n") ;

for ( i = 0 ; i < ia ; i++ )
{
a = op * 10 / 8 + 6 ;


The program is undefined from this point on. 'op' is "indeterminate"
and anything can happen from here on.
op = a ;
printf("Value %2d : %4d \n", cnt++, a) ;


The same for 'cnt'.
<snip>

Please reconsider the advice to use a text that encourages you to
learn in a more sensible order. It is much easier to get this sort of
thing correct when writing short, simple functions.
 
B

bpascal123

           a = op * 10 / 8 + 6 ;


The program is undefined from this point on.  'op' is "indeterminate"
and anything can happen from here on.
           op = a ;
           printf("Value %2d : %4d \n", cnt++, a) ;


The same for 'cnt'.

Please reconsider the advice to use a text that encourages you to
learn in a more sensible order.  It is much easier to get this sort of
thing correct when writing short, simple functions.

Hi Ben,

I thought op would be determined when i declare it ; int op ; ... then
op is 0, isn't it?
Same for cnt.

I'd really wish someone would post the right code from this code.

Thanks for your interest Ben,

Pascal
 
B

bpascal123

1. don't put everything in main()
2. add some assert()s
3. print out intermediate values
4. use a debugger



int main (void)

<snip>

Hi Nick,

I'm not into functions yet as i think such basic loops can be mastered
without using functions...
Inserting int main(void) changes nothing.
Are asserts the same as comments?

Where can I find a debugger, easy to use?

Thanks for your interest Nick,

Pascal
 
N

Nick Keighley

I'm not into functions yet as i think such basic loops can be mastered
without using functions...

oh they *can* be, but breaking your program into
small independent pieces makes it easier to understand.
And the fact that you have a bug indicates that you *don't*
understand your program. You can verify that the parts are
independently correct and then assemble them into a complete
program that is also (hopefully) correct.
Inserting int main(void) changes nothing.

it's better style. You are using a feature called implicit
int. This has been removed from the latest C standard.
Are asserts the same as comments?

no. An assert basically states an assumption about your
program. If the assumption is not true the program will
halt. They act as a sort of active documentation
Where can I find a debugger, easy to use?

depends which compiler you are using. Both gcc
and the common Windows compilers come with debuggers.

It really will pay you to learn how to debug.

It's perhaps the second most importnat programming skill.
 
M

Mark Bluemel

           a = op * 10 / 8 + 6 ;

The program is undefined from this point on.  'op' is "indeterminate"
and anything can happen from here on.
           op = a ;
           printf("Value %2d : %4d \n", cnt++, a) ;

The same for 'cnt'.
Please reconsider the advice to use a text that encourages you to
learn in a more sensible order.  It is much easier to get this sort of
thing correct when writing short, simple functions.

Hi Ben,

I thought op would be determined when i declare it ; int op ; ... then
op is 0, isn't it?
Same for cnt.


No. As the variables are automatic, not static, they are not
guaranteed to be initialised to anything.

A good text book would explain this to you.
I'd really wish someone would post the right code from this code.

As the farmer said when asked for directions "I wouldn't start from
here".
 
M

Mug

hello,if i well understand,you just want to put two
different array into one array in order,the correct code should be :

#include <stdio.h>

int main()
{
int a[50], b[50], merg[100] ;
int ia, ib ;
int i, j, k, k2;
int op=0; /* n'oublie pas initialize les valeurs */

ia = 10 ; ib = 15 ;

printf("\n\n==============================\n\n") ;

printf("This code reads, displays 2 arrays and merges them
into a third array merg") ;

printf("\n\n===============\n\n") ;

printf("\nTable A : \n\n") ;

for ( i = 0 ; i < ia ; i++ )
{
a = op * 10 / 8 + 6 ;
op = a ;
printf("Value %2d : %4d \n", i+1, a) ;
}

printf("\n\nTable B : \n\n") ;

for ( j= 0, op = 0 ; j < ib ; j++ )
{
b[j] = op * 10 / 7 + 4 ;
op = b[j] ;
printf("Value %2d : %4d \n", j+1, b[j]) ;
}

/* MERGING OF TABLE A AND B */

i = 0 ; j = 0 ;

k2 = ia + ib ;

/*
(ia < ib ) ? k2 = ib : k2 = ia ;
*/

for ( k = 0 ; k < k2 ; k++ )
{
if ( i >= ia ) /* si premier tableau est run out ,on
copy le reste de tableau B*/
{
merg[k] = b[j] ;
j++ ;
}
else if ( j >= ib ) /* si deuxieme tableau est run
out ,on copy le reste de tableau A*/
{
merg[k] = a ;
i++ ;
}
else if ( a < b[j] ) /* comparer les valeurs */
{
merg[k] = a ;
i++ ;
}
else if ( a > b[j] )
{
merg[k] = b[j] ;
j++ ;
}

}

printf("\n\n===============\n\n") ;

printf("Affichage resltat ");

printf("\n===============\n\n") ;

for ( k = 0 ; k < k2 ; k++ )
printf("\nValeur %2d : %d ", k+1, merg[k]) ;

printf("\n\n==============================\n\n") ;

return 0 ;
}

the given code was so broken,there are lot of problems,i did less
modifications as possible.
you program on windows environment i think,they initialize the integer
to 0 by default,
that's why some part of your program works.the better way is to
initialize by yourself.
bon courage.
Mug
 
M

Mug

gdb or ddd could be a good choice,
by the way,there's no need to play with debugger,
my first time use a
debugger is when i dealed with memory leak issue on double linked
list,otherwise simple printf at important point is far more than
enough.
well learn how to use debugger could be a good exercise.
 
B

Ben Bacarisse

Hi Nick,

I'm not into functions yet as i think such basic loops can be mastered
without using functions...

I hope you will forgive a digression... There is a common
misconception in many students learning programming that loops and
variables and arrays and so on (all the seemingly hard technical
things) are the programmer's tools -- like chisels and planes are for
a carpenter -- and if only these can be mastered by repeated use in
lots of programs the student will become skilled in using these tools
and soon they will be making fine furniture: real programs.

But this is based on an entirely false analogy. Programming is not
like carpentry with its physical skills and its precise and well-designed
single-purpose tools. It is much more like writing poetry or
composing music -- the primary problem is one of imagination. You
have to imagine patterns and combinations patterns that produce some
specific effect. Of course there are skills to be learnt, and there
is much to be gained by experience (just as there is in poetry and
music) but the basic operation is the inventive combination of simple
units into complex and often surprising patterns.

Why does this matter? Because functions are both the basic
building-blocks of these patterns and one of the main ways of
combining them. They must be the first (or pretty much the first)
thing that you learn.

I know you don't want to hear this, but i don't know why. In part it
may simply be that you are ill-severed by some bad textbook, but
surely you can find another? Already your code has reached a
level of complexity where many people will be reluctant to help you
because the proper help is to break the program into functions. For
one thing, even testing code without function is almost impossible.

Take, for example, your previous post that looked for a number in an
array. You had to test it but typing in different numbers and
checking (by hand) that the answer is correct. A programmer's
instinct should be to write:

int test_array1[] = {1, 3, 5, 7, 9};
show_result(find_in_array(test_array1, 1) == 0);
show_result(find_in_array(test_array1, 2) == -1);
show_result(find_in_array(test_array1, 9) == 4);

or maybe:

for (int k = 0; k < 11; k++)
show_result(find_in_array(test_array1, k) == k%2 ? k/2 : -1);

Don't worry if you don't follow this code -- the point is not what it
does but that this instinct helps with even the simplest programs.
But you can't start to develop this instinct until you know about
functions.

<snip>
 
B

bpascal123

....
the given code was so broken,there are lot of problems,i did less
modifications as possible.
you program on windows environment i think,they initialize the integer
to 0 by default,
that's why some part of your program works.the better way is to
initialize by yourself.
bon courage.
Mug

Hi Mug,

It works just fine for my level of understanding loops.

So if i have a good picture from your code :

from /* si premier tableau est run out ,on
copy le reste de tableau B*/ your loop first starts to check at each
new loops if i or j has reached the end of an array and if yes copies
values in the new table.

I had the same instruction but at the end of the loop. And it seems
it's an issue. At this point it's a bit confusing but your code helps
me a lot, thanks Mug.

=o=

This code isn't from me, it's from an application I just copied the
answer and played around with FOR and WHILE.

However when I first tried to achieve the same result from this
application, it didn't work at all, is it because I did it this way :

for ( i = 0 ; i <= ia ; i++)
merg = a ;

k = ++ia ;

for ( i = 0 ; i <= ib ; i++, k++)
merg[k] = b ;

I kinda come to realize that merging into a new table, table b after
table a ( k = ++ia ), I suppose i should find myself with a whole new
table!

But if I go on with a loop to sort merg out, it wouldn't work at all.
Any explanation for this?

Thanks again for your interest in this and your help,

Pascal
 
B

bpascal123

....
Don't worry if you don't follow this code -- the point is not what it
does but that this instinct helps with even the simplest programs.
But you can't start to develop this instinct until you know about
functions.

<snip>

Hi Ben,

I fully understand and agree.
I can only say I'll do my best to catch up with functions very very
soon.

I should repost a similar result working code with functions in it so
you see soon doesn't mean next moon :).

Pascal
 
A

Andrew Tomazos

This code below works until value 22. I really wonder why from this
point, the merging is not working and my computer says value 22 is
423, value 23 : 431, value 24 : 0, value 25 : 1 and as you can see if
you run this code, it's not matching table B... Why so?

C is the wrong language to be learning these basic concepts with. Use
one of Java, C#, Perl, Python, Ruby or Lua. Any of those will provide
a safer and easier-to-debug environment than C. Once you are up to
speed with a high-level language, than you can start to use C (if you
have to). Overall the learning curve will be shorter and shallower.
-Andrew.
 
N

Nick Keighley

"(e-mail address removed)" <[email protected]> writes:

[buggy monolithic code]
I hope you will forgive a digression...  There is a common
misconception in many students learning programming that loops and
variables and arrays and so on (all the seemingly hard technical
things) are the programmer's tools -- like chisels and planes are for
a carpenter -- and if only these can be mastered by repeated use in
lots of programs the student will become skilled in using these tools
and soon they will be making fine furniture: real programs.

But this is based on an entirely false analogy.  Programming is not
like carpentry with its physical skills and its precise and well-designed
single-purpose tools.  It is much more like writing poetry or
composing music -- the primary problem is one of imagination.  

as a tone-deaf Software Engineer I have to disagree!

You
have to imagine patterns and combinations patterns that produce some
specific effect.  Of course there are skills to be learnt, and there
is much to be gained by experience (just as there is in poetry and
music) but the basic operation is the inventive combination of simple
units into complex and often surprising patterns.

Why does this matter?  Because functions are both the basic
building-blocks of these patterns and one of the main ways of
combining them.  They must be the first (or pretty much the first)
thing that you learn.

whilst on the other hand I can't disagree with this

I know you don't want to hear this, but i don't know why.  In part it
may simply be that you are ill-severed by some bad textbook, but
surely you can find another?  Already your code has reached a
level of complexity where many people will be reluctant to help you
because the proper help is to break the program into functions.  For
one thing, even testing code without function is almost impossible.

yes (for the benefit of the original poster)
Take, for example, your previous post that looked for a number in an
array.  You had to test it but typing in different numbers and
checking (by hand) that the answer is correct.  A programmer's
instinct should be to write:

   int test_array1[] = {1, 3, 5, 7, 9};
   show_result(find_in_array(test_array1, 1) == 0);
   show_result(find_in_array(test_array1, 2) == -1);
   show_result(find_in_array(test_array1, 9) == 4);

that is, write a program to test your program
 
N

Nick Keighley

C is the wrong language to be learning these basic concepts with.  Use
one of Java, C#, Perl,

perl!? To learn programming?

Python, Ruby or Lua.  Any of those will provide
a safer and easier-to-debug environment than C.

I'd never thought the debugging environments of perl or python
were particularly brilliant.

 Once you are up to
speed with a high-level language, than you can start to use C (if you
have to).  Overall the learning curve will be shorter and shallower.

you could learn some really bad habbits with perl
 
M

Mug

It works just fine for my level of understanding loops.
So if i have a good picture from your code :

from /* si premier tableau est run out ,on
copy le reste de tableau B*/  your loop first starts to check at each
new loops if  i or j has reached the end of an array and if yes copies
values in the new table.

I had the same instruction but at the end of the loop. And it seems
it's an issue. At this point it's a bit confusing but your code helps
me a lot, thanks Mug.

yes it's very inmportant to check if the array is reached it's end
at first place,otherwise
it's always possible to get the value out of array in C ,system will
return you a random value
without warning you that index out of bound,so sometime they can give
u some funny result --> sometime works sometime not.
best regard
Mug
 
L

luserXtrog

Nick Keighley said:



As a tone-deaf Software Engineer, you are not qualified to comment.
If you have never composed music, of course you will not see the
similarity between programming and music, just as you will not see
the similarity between the works of Douglas Adams and the earlier
work of Terry Pratchett if you've never read any Douglas Adams.

Those who /have/ composed music, however, cannot escape the
comparison. In fact, musical notation has the same three basic
components - sequence, selection, and iteration - that programming
languages have. And you can kind of fake up subroutines if you have
to. It even has a (somewhat limited) goto: "to coda".

But D.S. does quite a good impression of COME FROM.
When I transcribe music that I have composed or am composing, I use
a program called Lilypond. It's a kind of framework - you write
your music as a Scheme subroutine, and then pass it to Lilypond to
interpret - and the output is a nice shiny PDF file (or, quite
often, a whole bunch of error messages instead). This makes the
comparison between music and programming inevitable. It is easily
(or, at times, difficultly!) possible to express a piece of music
as a computer program. What I'm not sure about is how possible it
would be to express a computer program as a piece of music.

Through a midi setup, you could definitely use an instrument
as an input device. I'm not sure what sorts of operations
would best be triggered that way. (An explosion when John Stamos'
brother hits the high F in Loving You? A musical combination lock
(ala Doctor Who and IIRC Batman)?
Am I the first to ask the question "Is Musical Notation
Turing-Complete?"?

I suspect not, for the same reason that text can't easily
convey heavy dialect without sacrificing legibility or
authenticity. There are unmusical sounds.
 
N

Nick Keighley

Nick Keighley said:


As a tone-deaf Software Engineer, you are not qualified to comment.

I dispute it's general applicability. There may be programmers
who have a deep interest and appreciation of music (or cooking)
but I'm not convinced it is a generally useful analogy. Programming
*is* partly a set of skills and techniques. You must be aware of
the components and the ways in which they may be assembled. Though it
has a creative aspect (as does any form engineering) imagination is
*not*
its primary problem.

I have no interest in music (yes really) yet I am a reasonably
competant programmer.

I can test a program for correctness. Can I do that with music?
With jazz?

If you have never composed music, of course you will not see the
similarity between programming and music, just as you will not see
the similarity between the works of Douglas Adams and the earlier
work of Terry Pratchett if you've never read any Douglas Adams.

Those who /have/ composed music, however, cannot escape the
comparison. In fact, musical notation has the same three basic
components - sequence, selection, and iteration

I'll check that out with the (non-programming) musicians and
poets of my acquaintance.
- that programming
languages have. And you can kind of fake up subroutines if you have
to. It even has a (somewhat limited) goto: "to coda".

"fake up" "somewhat limited". Symptoms of a strained analogy.
Cooking a meal can be described in a program-like notation.
Cooking is not programming.
When I transcribe music that I have composed or am composing, I use
a program called Lilypond. It's a kind of framework - you write
your music as a Scheme subroutine, and then pass it to Lilypond to
interpret - and the output is a nice shiny PDF file (or, quite
often, a whole bunch of error messages instead). This makes the
comparison between music and programming inevitable.

some music may be describable in a program-like notation.
It doesn't mean they are isomorphic.
It is easily
(or, at times, difficultly!) possible to express a piece of music
as a computer program.

there are lots of things that can be described in program-like
notations. Cooking, knitting, giving directions, carpentry,
car assembly, etc. etc.

Yet none of these things are programming.

Programming is most similar to the design end of various
engineering disciplines.

Music is just another branch of civil engineering.
:)

What I'm not sure about is how possible it
would be to express a computer program as a piece of music.

Am I the first to ask the question "Is Musical Notation
Turing-Complete?"?


--
Nick Keighley

must be a Dijkstra quote... ah!

In this respect a program is like a poem:
you cannot write a poem without writing it.
-- Edsger W Dijkstra
 
B

Ben Bacarisse

Nick Keighley said:
I dispute it's general applicability. There may be programmers
who have a deep interest and appreciation of music (or cooking)
but I'm not convinced it is a generally useful analogy. Programming
*is* partly a set of skills and techniques. You must be aware of
the components and the ways in which they may be assembled. Though it
has a creative aspect (as does any form engineering) imagination is
*not*
its primary problem.

I apologise for seeding what might become a heated off-topic thread.
Composing (which I can't do) and writing poetry (which I do with all
the flair of a Vogon) are extraordinarily different from programming
but they all share two things in common: they start with an act of
imagination and they use some form of restricted combination of
pattern to achieve their goals. I was using "primary" (problem) to
mean "fundamental" or "initial" rather than "only important"
(problem).
I have no interest in music (yes really) yet I am a reasonably
competant programmer.

I can test a program for correctness. Can I do that with music?
With jazz?

In some ways I think you can. To my mind, testing in software is
often misunderstood. The engineering analogy has become so pervasive
that people think software engineers test programs like civil
engineers test bridges, but they don't. Software is tested to verify
that is has no obvious mistakes -- tested to see if the imagination
failed. This not what engineers mean by testing but I suspect
composers do this all the time -- trying out chords, modulations and
phrases as they go -- surprisingly similar to test-driven coding. (My
grandfather was a composer, so I have one data point -- perfect for
extrapolation to the general case!)

[The big exception is system performance testing where what software
engineers do is very similar to other kinds of engineering testing,
but that is not what most people think of initially.]
I'll check that out with the (non-programming) musicians and
poets of my acquaintance.

I used to start my programming course with three slides: one of a
piece of sheet music, a recipe and a knitting pattern. All had strong
elements of programming language structure. The recipe even had an
obvious parameterised procedure call.
"fake up" "somewhat limited". Symptoms of a strained analogy.
Cooking a meal can be described in a program-like notation.
Cooking is not programming.

No, writing (imagining) recipes is more like it. Of course the
analogy is strained, but no more so than many that go un-commented on
every day: "reliability", "test harness", "defensive programming"
and so on. The purpose of the analogy is to illuminate an often
overlooked corner, rather than to say that a program is "just like" a
recipe or a piece of sheet music.
some music may be describable in a program-like notation.
It doesn't mean they are isomorphic.

Analogies and isomorphisms are not isomorphic (but they are analogous).
there are lots of things that can be described in program-like
notations. Cooking, knitting, giving directions, carpentry,
car assembly, etc. etc.

Yet none of these things are programming.

Programming is most similar to the design end of various
engineering disciplines.

Here it is my turn to disagree. I would find "most similar" hard to
quantify so maybe you can win this argument on a technicality, but the
key difference is that engineering structures don't combine like
software structures do. You can't take a bridge, scale it down by
factor of 10,000, replicate it N times with slight variations each
time are make a car; but that is what "software engineers" do all the
time.
Music is just another branch of civil engineering.
:)

No, but the joke asks the right question: if music is not engineering
what is programming?
 
B

Ben Bacarisse

Richard Heathfield said:
Ben Bacarisse said:



Not quite on a par with Micah Cowan's "Perl is a great language to
break your teeth on", but a sig-worthy statement nonetheless.

Not bad! This is the great joy of spell-checkers -- the errors will
always be words.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,955
Messages
2,570,117
Members
46,705
Latest member
v_darius

Latest Threads

Top