Re: small C puzzles

From: ByteSurfer (bytesurfer_at_gmail.com)
Date: 09/03/04


Date: 2 Sep 2004 23:11:32 -0700

madhav_a_kelkar@hotmail.com wrote in message news:<338e571.0409010104.1f53512d@posting.google.com>...
> i was browsing this problem:
>
> The following is a piece of C code, whose intention was to print a
> minus sign 20 times. But you can notice that, it doesn't work.
>
> #include <stdio.h>
> int main()
> {
> int i;
> int n = 20;
> for( i = 0; i < n; i-- )
> printf("-");
> return 0;
> }
>
> Well fixing the above code is straight-forward. To make the problem
> interesting, you have to fix the above code, by changing exactly one
> character. There are three known solutions. See if you can get all
> those three.
>
>
> one solution is to use n-- instead of i--. please let me know the
> other two.

Sure it was obvious that the looping you do was always will decrement
by one so . how on earth will be the looping exit when all decrement
of 1 from zero will become more negative . so. just by letting the n
to be n-- will work.

if not you can think of putting the condition to be n<=i then the
updating you put the increment of n++ then surely at one time the the
n will bigger than the value i so it will be exiting the loop.

If not you can try this method. of putting negative in front of n or
even i.
But this was not that practical, cos it just will make your coding
more complicated. So, poosibly stick to the more simple alogarithm.

Regard,
ByteSurfer



Relevant Pages

  • Re: Brian Kernighan, maybe Im not worthy, maybe Im scum
    ... The decrement happens BEFORE the assignment (simple operator ... or int. ... Question 14 does NOT depend on whether the English word "between" is ... In ordinary speech it is used both ways! ...
    (comp.programming)
  • Re: Curious compiler warning
    ... During this method, I decrement start ... public static int foo ... code in this class basically just does String functions to count the ...
    (comp.lang.java.programmer)
  • Curious compiler warning
    ... I'm getting an odd compiler warning that I don't really understand. ... I decrement start and finish ... public static int foo ... I modified the code as follows to get rid of the warnings but is it really ...
    (comp.lang.java.programmer)
  • Re: Curious compiler warning
    ... I decrement start and finish ... public static int foo ...
    (comp.lang.java.programmer)