TIP: Click on subject to list as thread! ANSI
echo: c_echo
to: Bruce D. Wedding
from: Jasen Betts
date: 2004-06-05 07:03:02
subject: [C] C Puzzles

Hi Bruce.

02-Jun-04 22:39:46, Bruce D. Wedding wrote to All


 BDW> From: "Bruce D. Wedding" 

 BDW> I found these on a C Yahoo group and some look like fun.

 BDW> 2. Write a C program without using any loop (if, for, while etc) to
 BDW> print
 BDW> numbers from 1 to 100 and 100 to 1

 puts ("1");
 puts ("2");
 puts ("3");  // get this picture?

 or use the trinary operator as "if" and recursion to loop back.

  int countup(int n)
  {
  return ( n<=100 ? printf("%d\n",n), countup(n+1): 0;
  }
  int countdown(int n)
  {
  return ( n<=100 ? countdown(n+1),printf("%d\n",n): 0;
  }
  main(){
  countup(1)
  countdown(1)
  };

 BDW> 3. Find if the given number is a power of 2.

 unsigned ispow2(int x)
 {
 unsigned n;
 for(n=1;n;n<<=1) if(x=n)return TRUE;
 return FALSE;
 }

 BDW> 4. Multiply x by 7 without using multiplication (*) operator.

 x+x+x+x+x+x+x   or   x<<3-x

 BDW> 5. Write a function in different ways that will return f(7) = 4 and f(4)
 BDW> = 7

int f(int x) { return 11 - x ;}
int f(int x) { return 28 / x ;}

there are infinitely more non-equivalent solutions.
(well actually factorial(number_of_integers-2) but that's pretty close to
infinity.)

 BDW> 6. Remove duplicates in array

this one has been done to death here already.

 BDW> 7. Finding if there is any loop inside linked list.

int looped( listitem *l )
 {
 listitem *p;
 int w,n;
 for(w=1;w;w<<=1)
  {
  p=l;
  for(n=0;nnext
    if(!l)  return 0;
    if(p==l) return 1;
    }
  }
  assert(0=="not enough integers") /* there are more list entries
than ints! */
  return 2
  }

 BDW> 8. Write code to determine if a TYPE is signed or unsigned.  Got it?

   if (0.0 > (TYPE) -1 )
     { puts("signed");}
   else
     { puts("unsigned");};

 BDW> OK, write code to determine if a value is unsigned or signed

if(  value > 0  && ~value > 0 )
    { puts("unsigned");}
 else
   { puts("unsigned");};

 -=> Bye <=-

---
* Origin: How to make Kleenex dance? Blow a little boogie in it. (3:640/1042)
SEEN-BY: 633/267 270
@PATH: 640/1042 531 954 774/605 123/500 106/2000 633/267

SOURCE: echomail via fidonet.ozzmosis.com

Email questions or comments to sysop@ipingthereforeiam.com
All parts of this website painstakingly hand-crafted in the U.S.A.!
IPTIA BBS/MUD/Terminal/Game Server List, © 2025 IPTIA Consulting™.