Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's wrong with this C program [duplicate]

Tags:

c

for-loop

Possible Duplicate:
Help with C puzzle

The intention of the program was to print a minus sign 20 times, but it doesn't work.

  #include <stdio.h>
  int main()
  {
      int i;
      int n = 20;
      for( i = 0; i < n; i-- )
          printf("-");
      return 0;
  }
like image 261
SurajRk Avatar asked Aug 11 '10 18:08

SurajRk


1 Answers

This is a classic puzzle!

The way I saw it was

"You can only change/insert/delete one character in the code to make the - print 20 times".

Some answers are (if I remember them correctly)

1)

 #include <stdio.h> 
  int main() 
  { 
      int i; 
      int n = 20; 
      for( i = 0; -i < n; i-- ) 
          printf("-"); 
      return 0; 
  }

Here you change the i < n to -i < n

2)

 #include <stdio.h> 
  int main() 
  { 
      int i; 
      int n = 20; 
      for( i = 0; i < n; n-- ) 
          printf("-"); 
      return 0; 
  }

Here you change the i-- to n--

3)

 #include <stdio.h> 
  int main() 
  { 
      int i; 
      int n = 20; 
      for( i = 0; i + n; i-- ) 
          printf("-"); 
      return 0; 
  }

You change the i < n to i+n.

For a challenge, try changing/inserting/deleting one character to make it print the - 21 times. (Don't read the comments to this answer if you want to try it!)

like image 74
2 revsAryabhatta Avatar answered Sep 28 '22 11:09

2 revsAryabhatta