Praveen's Blog

An Eternal Quest for Incremental Improvement

C and C++ puzzles

I always have an interest towards interview questions and puzzles, especially the programming ones. Here are some of the trivial C and C++ puzzles that I have come across. Please note that the solutions that I have given are tested, but no guarentee that they are the most efficient ones. There may exist more efficient version of the solutions.

Write a "Hello World" program in C without using a semicolon.

#include <stdio .h>

void
main()
{
  if( printf( "Hello, world!\n" ) ) {}
}

Write a C program without using any loop to print numbers from 1 to 100 and 100 to 1.

#include <stdio .h>

void
rec_print_aseq( int n )
{
  if ( 1 == n ) {
    printf( "%d ", n );
    return;
  }
  rec_print_aseq( n - 1 );
  printf( "%d ", n );
}

void
rec_print_dseq( int n )
{
  printf( "%d ", n );
  if ( 1 == n ) {
    return;
  }
  rec_print_dseq( n - 1 );
}


int
main()
{
  int x;
  printf( "Enter the upper limit for the sequence: " );
  scanf( "%d", &x );
  printf( "Ascending order sequence: " );
  rec_print_aseq( x );
  printf( "\n" );
  printf( "Descending order sequence: " );
  rec_print_dseq( x );
  printf( "\n" );
  return 0;
}

Write a C program to find if the given number is a power of 2 using a single expression.

#include <stdio .h>

int
main()
{
  int a;
  printf( "Enter the number to be tested: " );
  scanf( "%d", &a );
  if( a && ( a & ( a - 1 ) ) == 0 ) {
    printf( "The number %d is a power of 2\n", a );
  }
  else {
    printf( "The number %d is not a power of 2\n", a );
  }
  return 0;
}

C/C++ : Multiply x by 7 without using multiplication (*) operator.

#include <stdio .h>

int
main()
{
  int x, p;
  printf( "Enter the number to be multiplied by 7: " );
  scanf( "%d", &x );
  p = (x << 3 ) - x;
  printf( "%d multiplied by 7 is %d\n", x, p );
  return 0;
}

C++: Write a function to swap two integers without using a temporary variable, + or - operator.

int swap( int &a, int &b ) {
    a ^= b;
    b ^= a;
    a ^= b;
}

Note: Use pointers instead of references to implement this function in C.


Comments