CodingPuzzles.com - the place for your programming interview questions

Coding Puzzles is your source for programmer interview questions and just plain interesting computer problems.  Enjoy the puzzles and questions we collected from around the web and if you have your favorite one - go ahead and submit it.  We'll add it to the list!

Thanks!

Create sleep function

posted Feb 14, 2010, 4:43 AM by Erika E

Please write a program to create sleep function on your screen.

SOLUTION:

#include <time.h>

 

void sleep_seconds ( long seconds ) {

  clock_t limit, now = clock();

  limit = now + seconds * CLOCKS_PER_SEC;

  while ( limit > now )

    now = clock();

}

 

void sleep_ticks ( long ticks ) {

  clock_t limit, now = clock();

  limit = now + ticks;

  while ( limit > now )

    now = clock();

}

 

void wait(long milliseconds)

{

  long timeout = clock() + milliseconds;

  while( clock() < timeout ) continue;

}

 


Get a line of text from the user/keyboard (C)

posted Feb 14, 2010, 4:41 AM by Erika E

Please write a program to get a line of text from the user/keyboard (C)

SOLUTION:

#include <stdio.h> 
#include <string.h> 
 
int main()
{
  char buf[BUFSIZ];
  char *p;
  
  printf ("Please enter a line of text, max %d characters\n", sizeof(buf));
  
  if (fgets(buf, sizeof(buf), stdin) != NULL)
  {
    printf ("Thank you, you entered >%s<\n", buf);
    
    /*
     *  Now test for, and remove that newline character
     */
    if ((p = strchr(buf, '\n')) != NULL)
      *p = '\0';
      
    printf ("And now it's >%s<\n", buf);
  }
  
  return 0;
}
 
 
/*
 Program output:
 
Please enter a line of text, max 512 characters
this is a test
Thank you, you entered >this is a test
And now it's >this is a test<
*/

Generate random numbers

posted Feb 14, 2010, 4:39 AM by Erika E

Please write a program to generate random numbers

SOLUTION:

#include <stdio.h> 

#include <stdlib.h> 

#include <time.h> 

 

int main(void)

{

  int i;

 

  srand(time(NULL));

 

  i = rand();

 

  printf ("Your random number is %d\n", i); 

 

  printf ("This compiler can generate random numbers from 0 to %d\n", RAND_MAX);

 

  return(0);

}

 


Test an int to determine if it is even or odd

posted Feb 14, 2010, 4:38 AM by Erika E

Please write a program to test an int to determine if it is even or odd

SOLUTION:


#include <stdio.h>

 

int is_even ( int i )

{

  return i % 2 == 0;

}

 

int main ( void )

{

  int i;

 

  for ( i = 0; i < 10; i++ ) {

    printf ( "Testing %d...", i );

 

    if ( is_even ( i ) )

      printf ( "Yep, it's even\n" );

    else

      printf ( "Nope, it's odd\n" );

  }

 

  return 0;

}



Program to clear the screen

posted Feb 14, 2010, 4:35 AM by Erika E

Please write a program to clear the screen

SOLUTION:


#include <stdio.h>

#define SCREEN_HEIGHT 25

 

int main ( void )

{

  int i;

 

  for ( i = 0; i < SCREEN_HEIGHT; i++ )

    putchar ( '\n' );

   

  return 0;

}



C# interview questions and answers

posted Feb 14, 2010, 4:28 AM by Erika E

The following sample questions might be part of a  job interview when applying for  a programmer position

  1. What’s the advantage of using System.Text.StringBuilder over System.String? StringBuilder is more efficient in the cases, where a lot of manipulation is done to the text. Strings are immutable, so each time it’s being operated on, a new instance is created.
  2. Can you store multiple data types in System.Array? No.
  3. What’s the difference between the System.Array.CopyTo() and System.Array.Clone()? The first one performs a deep copy of the array, the second one is shallow.
  4. How can you sort the elements of the array in descending order? By calling Sort() and then Reverse() methods.
  5. What’s the .NET datatype that allows the retrieval of data by a unique key? HashTable.
  6. What’s class SortedList underneath? A sorted HashTable.
  7. Will finally block get executed if the exception had not occurred? Yes.
  8. What’s the C# equivalent of C++ catch (…), which was a catch-all statement for any possible exception? A catch block that catches the exception of type System.Exception. You can also omit the parameter data type in this case and just write catch {}.
  9. Can multiple catch blocks be executed? No, once the proper catch code fires off, the control is transferred to the finally block (if there are any), and then whatever follows the finally block.
  10. Why is it a bad idea to throw your own exceptions? Well, if at that point you know that an error has occurred, then why not write the proper code to handle that error instead of passing a new Exception object to the catch block? Throwing your own exceptions signifies some design flaws in the project.
  11. What’s a delegate? A delegate object encapsulates a reference to a method. In C++ they were referred to as function pointers.
  12. What’s a multicast delegate? It’s a delegate that points to and eventually fires off several methods.
  13. How’s the DLL Hell problem solved in .NET? Assembly versioning allows the application to specify not only the library it needs to run (which was available under Win32), but also the version of the assembly.
  14. What are the ways to deploy an assembly? An MSI installer, a CAB archive, and XCOPY command.
  15. What’s a satellite assembly? When you write a multilingual or multi-cultural application in .NET, and want to distribute the core application separately from the localized modules, the localized assemblies that modify the core application are called satellite assemblies.
  16. What namespaces are necessary to create a localized application? System.Globalization, System.Resources.
  17. What’s the difference between // comments, /* */ comments and /// comments? Single-line, multi-line and XML documentation comments.
  18. How do you generate documentation from the C# file commented properly with a command-line compiler? Compile it with a /doc switch.
  19. What’s the difference between <c> and <code> XML documentation tag? Single line code example and multiple-line code example.
  20. Is XML case-sensitive? Yes, so <Student> and <student> are different elements.
  21. What debugging tools come with the .NET SDK? CorDBG – command-line debugger, and DbgCLR – graphic debugger. Visual Studio .NET uses the DbgCLR. To use CorDbg, you must compile the original C# file using the /debug switch.
  22. What does the This window show in the debugger? It points to the object that’s pointed to by this reference. Object’s instance data is shown.
  23. What does assert() do? In debug compilation, assert takes in a Boolean condition as a parameter, and shows the error dialog if the condition is false. The program proceeds without any interruption if the condition is true.
  24. What’s the difference between the Debug class and Trace class? Documentation looks the same. Use Debug class for debug builds, use Trace class for both debug and release builds.
  25. Why are there five tracing levels in System.Diagnostics.TraceSwitcher? The tracing dumps can be quite verbose and for some applications that are constantly running you run the risk of overloading the machine and the hard drive there. Five levels range from None to Verbose, allowing to fine-tune the tracing activities.
  26. Where is the output of TextWriterTraceListener redirected? To the Console or a text file depending on the parameter passed to the constructor.
  27. How do you debug an ASP.NET Web application? Attach the aspnet_wp.exe process to the DbgClr debugger.
  28. What are three test cases you should go through in unit testing? Positive test cases (correct data, correct output), negative test cases (broken or missing data, proper handling), exception test cases (exceptions are thrown and caught properly).
  29. Can you change the value of a variable while debugging a C# application? Yes, if you are debugging via Visual Studio.NET, just go to Immediate window.
  30. Explain the three services model (three-tier application). Presentation (UI), business (logic and underlying code) and data (from storage or other sources).
  31. What are advantages and disadvantages of Microsoft-provided data provider classes in ADO.NET? SQLServer.NET data provider is high-speed and robust, but requires SQL Server license purchased from Microsoft. OLE-DB.NET is universal for accessing other sources, like Oracle, DB2, Microsoft Access and Informix, but it’s a .NET layer on top of OLE layer, so not the fastest thing in the world. ODBC.NET is a deprecated layer provided for backward compatibility to ODBC engines.
  32. What’s the role of the DataReader class in ADO.NET connections? It returns a read-only dataset from the data source when the command is executed.
  33. What is the wildcard character in SQL? Let’s say you want to query database with LIKE for all employees whose name starts with La. The wildcard character is %, the proper query with LIKE would involve ‘La%’.
  34. Explain ACID rule of thumb for transactions. Transaction must be Atomic (it is one unit of work and does not dependent on previous and following transactions), Consistent (data is either committed or roll back, no “in-between” case where something has been updated and something hasn’t), Isolated (no transaction sees the intermediate results of the current transaction), Durable (the values persist if the data had been committed even if the system crashes right after).
  35. What connections does Microsoft SQL Server support? Windows Authentication (via Active Directory) and SQL Server authentication (via Microsoft SQL Server username and passwords).
  36. Which one is trusted and which one is untrusted? Windows Authentication is trusted because the username and password are checked with the Active Directory, the SQL Server authentication is untrusted, since SQL Server is the only verifier participating in the transaction.
  37. Why would you use untrusted verificaion? Web Services might use it, as well as non-Windows applications.
  38. What does the parameter Initial Catalog define inside Connection String? The database name to connect to.
  39. What’s the data provider name to connect to Access database? Microsoft.Access.
  40. What does Dispose method do with the connection object? Deletes it from the memory.
  41. What is a pre-requisite for connection pooling? Multiple processes must agree that they will share the same connection, where every parameter is the same, including the security settings.

All types of linked list operations

posted Feb 14, 2010, 4:25 AM by Erika E

Please write a program for all types of linked list operations

SOLUTION:


#include<stdio.h>

#include<conio.h>

#include<stdlib.h>

#include<alloc.h>

#include<dos.h>

void disp(struct node*);

struct node *addbeg(struct node *,int);

void addend(struct node *,int);

void sortlist(struct node*,int);

struct node *addbef(struct node *,int);

void addaft(struct node *,int);

void addbet(struct node *,int,int);

struct node *del(struct node *,int);

struct node *befdel(struct node *,int);

void aftdel(struct node *,int);

void betdel(struct node *,int,int);

void update(struct node *,int);

void search(struct node *,int);

struct node *reverse(struct node *);

struct node{ int n;

                     struct node *next;

                   } ;

void main()

{ char ch,boolc1,boolc2,boolc3,boolc4,boolc5,boolc6,boolc7;

  int

i,num,no,addb,adde,befadd,aftadd,fnode,snode,cut,befcut,aftcut,prnode,succ

node,change,find;

  struct node *head,*tail,*ptr;

  clrscr();

  printf("THIS IS A PROGRAM ABOUT LINKED LIST

");

  printf("supply no. of elements in the linked list

");

  scanf("%d",&num);

  head=tail=ptr=NULL;

  for(i=0;i<num;i++)

  { printf("supply new node

");

    scanf("%d",&no);

    ptr=(struct node*)malloc(sizeof(struct node));

    if(tail==NULL)

    { head=tail=ptr;

      ptr->n=no;

      ptr->next=NULL;

    }

    else

    { tail->next=ptr;

      ptr->n=no;

      ptr->next=NULL;

      tail=ptr;

    }

  }

  disp(head);

  printf("node you want to add before

");

  scanf("%d",&addb);

  if(addb>=0)

  { head=addbeg(head,addb);

  printf("Now");

  disp(head);

 }

 else  printf("ayou don't! OK

");

  printf("node you want to add end

");

  scanf("%d",&adde);

  if(adde>=0)

  { addend(head,adde);

  printf("Now");

  disp(head);

  }

  else  printf("ayou don't! OK

");

  printf("before which node you want to add?

");

  scanf("%d",&befadd);

  head=addbef(head,befadd);

  printf("Now");

  disp(head);

  printf("after which node you want to add?

");

  scanf("%d",&aftadd);

  addaft(head,aftadd);

  printf("Now");

  disp(head);

  printf("between which two nodes you want to add?

");

  fflush(stdin);

  scanf("%d %d",&fnode,&snode);

  addbet(head,fnode,snode);

  printf("Now");

  disp(head);

  printf("want to delete any node? (y/n)

");

  fflush(stdin);

  scanf("%c",&boolc1);

  if(boolc1=='y')   {  printf("supply node to be deleted

");

                                      scanf("%d",&cut);

                                      head=del(head,cut);

                                      printf("Now");

                                      disp(head);

                                  }

  else     printf("OK. list remains same

");

   printf("want to delete before any node? (y/n)

");

  fflush(stdin);

  scanf("%c",&boolc2);

  if(boolc2=='y')   { printf("supply that node

");

                                     scanf("%d",&befcut);

                                     head=befdel(head,befcut);

                                      printf("Now");

                                      disp(head);

                                  }

  else     printf("OK. list remains same

");

  printf("want to delete after any node? (y/n)

");

  fflush(stdin);

  scanf("%c",&boolc3);

  if(boolc3=='y')   { printf("supply that node

");

                                     scanf("%d",&aftcut);

                                     aftdel(head,aftcut);

                                      printf("Now");

                                      disp(head);

                                  }

  else     printf("OK. list remains same

");

  printf("want to delete node between any two node? (y/n)

");

  fflush(stdin);

  scanf("%c",&boolc4);

  if(boolc4=='y')    { printf("supply those nodes

");

                                      scanf("%d %d",&prnode,&succnode);

                                      betdel(head,prnode,succnode);

                                      printf("Now");

                                      disp(head);

                                    }

  else    printf("OK. list remains same

");

  printf("want to update any node? (y/n)

");

  fflush(stdin);

  scanf("%c",&boolc5);

  if(boolc5=='y')  {  printf("supply node to be updated

");

                                    scanf("%d",&change);

                                    update(head,change);

                                    printf("Now");

                                    disp(head);

                                   }

  else    printf("OK. list remains same

");

  printf("want to search any node? (y/n)

");

  fflush(stdin);

  scanf("%c",&boolc6);

  if(boolc6=='y')  { printf("node to be searched

");

                                    scanf("%d",&find);

                                    search(head,find);

                                  }

  else    printf("OK. list remains same

");

  printf("want to display the list in reverse order? (y/n)

");

  fflush(stdin);

  scanf("%c",&boolc7);

  if(boolc7=='y')  { printf("In reverse order");

                                    head=reverse(head);

                                    disp(head);

                                  }

  else    printf("OK. list remains same

");

  printf("wish to sort the list? (y/n)

");

  fflush(stdin);

  scanf("%c",&ch);

  if(ch=='y')

  { sortlist(head,num);

  printf("after sorting");

  disp(head); }

  else{ printf("Finally");

                disp(head); }

  getch();

}

 void disp(struct node *head)

 {  struct node *p;

    p=head;

    printf(" entire linked list is

");

    while(p->next!=NULL)

    { printf("%d->",p->n);

      p=p->next;

      if (p->next==NULL)

       printf("%d

",p->n);

    }

   return;

 }

 void sortlist(struct node *head,int num)

 {  struct node *temp,*q;

    int i,j;

    q=head;

    temp=(struct node *)malloc(sizeof(struct node));

    for(i=0;i<num;i++)

     for(j=0;j<num-1;j++)

     { while(q->next!=NULL)

       { if((q->n)>(q->next->n))

                 { temp->n=q->n;

                   q->n=q->next->n;

                   q->next->n=temp->n;

                 }

                 q=q->next;

       }

                if(q->next==NULL && i<num)

                  q=head;

     }

   q=head;

   return;

 }

 struct node *addbeg(struct node *head,int addn)

 { struct node *p;

   p=(struct node *)malloc(sizeof(struct node));

   p->n=addn;

   p->next=head;

   head=p;

   return head;

 }

 void addend(struct node *head,int addn)

 { struct node *p,*q;

   p=(struct node *)malloc(sizeof(struct node));

   q=head;

   while(q->next!=NULL)

    q=q->next;

   q->next=p;

   p->n=addn;

   p->next=NULL;

   return;

 }

 struct node *addbef(struct node *head,int befadd)

 { struct node *p,*q,*r;

   int addp;

   printf("new node

");

   scanf("%d",&addp);

   p=(struct node *)malloc(sizeof(struct node));

   p->n=addp;

   q=r=head;

   while(q->n!=befadd)

   { r=q;

     q=q->next;

     if(q==NULL) break;

   }

   if(q==NULL) {  printf("anode %d not found

",befadd);

                                 delay(1000);

                                 return head;

                       }

   if(q==head) {  p->next=q;

                                 head=p;

                                 return head;

                       }

   r->next=p;

   p->next=q;

   return head;

 }

 void addaft(struct node *head,int aftadd)

 {  struct node *p,*q;

    int addp;

    printf("new node

");

    scanf("%d",&addp);

    p=(struct node *)malloc(sizeof(struct node));

    p->n=addp;

    q=head;

    while(q->n!=aftadd)

    { q=q->next;

      if(q==NULL)  break;

    }

   if(q==NULL) {  printf("anode %d not found

",aftadd);

                                 delay(1000);

                                 return;

                       }

    p->next=q->next;

    q->next=p;

    return;

 }

 void addbet(struct node *head,int no1,int no2)

 {  struct node *p,*q,*r,*s;

    int addp;

   // printf("%d %d

",*no1,*no2);

    printf("new node

");

    scanf("%d",&addp);

    p=(struct node *)malloc(sizeof(struct node));

    p->n=addp;

    r=head;

    q=r;

    if(q->n!=no1)

      { r=q;

                q=q->next;

      }

    else

   { if (q->next->n!=no2)

                {      s=q->next;

                       while(s!=NULL) { s=s->next;

                                                               if(s->n==no2)

                                                     { printf("anodes are not successive

");

                                                               delay(1000);

                                                               return;

                                                     }

                                                     }

                       printf("aillegal node selection

");

                       delay(1000);

                       return;

                }

     else { q=q->next;

                    r->next=p;

                    p->next=q;

                    return;

                  }

   }

   while(r->n!=no1 || q->n!=no2)

    {  r=q;

       q=q->next;

       if(q==NULL)

       { printf("aillegal node selection

");

                 delay(1000);

                 return;

       }

    }

     r->next=p;

     p->next=q;

     return;

 }

struct node *del(struct node *head,int cut)

 { struct node *p,*q;

   p=head;

   q=p;

   while(p->n!=cut)

   { q=p;

     p=p->next;

     if(p==NULL)  { printf("anode %d not found

",cut);

                                   delay(1000);

                                   return head;

                                 }

   }

   if(p==head) {  head=q->next;

                                 q=head;

                                 free(p);

                                 return head;

                       }

   q->next=p->next;

   free(p);

   return head;

 }

 struct node *befdel(struct node *head,int befcut)

 { struct node *p,*q;

   p=head;

   q=p;

   while(p->next->n!=befcut)

   { q=p;

     p=p->next;

     if(p==NULL) {  printf("anode %d not found

",befcut);

                                   delay(1000);

                                   return head;

                                }

   }

   if(p==head) { head=q->next;

                                q=head;

                                free(p);

                                return head;

                       }

   q->next=p->next;

   free(p);

   return head;

 }

void aftdel(struct node *head,int aftcut)

{ struct node *p,*q;

  p=head;

  q=p;

  while(q->n!=aftcut)

  { q=p;

    p=p->next;

    if(p==NULL) { if(q->next==NULL)  printf("ano node after node

%d

",aftcut);

                                 else      printf("anode %d not found

",aftcut);

                                 delay(1000);

                                 return;

                               }

  }

  if(q==head) p=q->next;

  q->next=p->next;

  free(p);

  return;

 }

void betdel(struct node *head,int prnode,int succnode)

{ struct node *p,*q,*r,*s;

  p=head;

  q=p;

  if(p->n!=prnode)

  { q=p;

    p=p->next;

  }

  else { r=p->next;

                 if(r->next->n!=succnode)

                 { s=r->next;

                   while(s!=NULL) { s=s->next;

                                                   if(s->n==succnode)

                                                   { printf("amore nodes between those nodes

");

                                                     delay(1000);

                                                     return;

                                                   }

                                                 }

                   printf("aillegal node selection

");

                   delay(1000);

                   return;

                 }

                 else   { q->next=r->next;

                                 free(r);

                                 return;

                               }

       }

  while(q->n!=prnode || p->next->n!=succnode)

  { q=p;

    p=p->next;

    if(p->next==NULL)  { printf("aillegal node selection

");

                                                delay(1000);

                                                return;

                                      }

   }

    q->next=p->next;

    free(p);

    return;

 }

 void update(struct node *head,int change)

 { struct node *p;

   int upd;

   p=head;

   printf("updated node

");

   scanf("%d",&upd);

   while(p->n!=change)

   { p=p->next;

     if(p==NULL) { printf("anode %d not found

",change);

                                delay(1000);

                                return;

                       }

   }

   p->n=upd;

   return;

  }

 void search(struct node *head,int find)

 { struct node *p;

   int j=1;

   p=head;

   while(p->n!=find)

   { p=p->next;

     j++;

     if(p==NULL) { printf("

SORRY. node %d is not present

",find);

                                  delay(1000);

                                  return;

                                }

   }

   printf("aYES! the node %d is present in the %dth

position

",find,j);

   delay(1000);

   return;

 }

 struct node *reverse(struct node *head)

 { struct node *t1,*t2;

  t1=head->next;

  t2=t1->next;

  head->next=NULL;

  while(t1!=NULL)

  { t1->next=head;

    head=t1;

    t1=t2;

    t2=t2->next;

  }

   return head;

 }

Vertical histogram

posted Feb 14, 2010, 4:21 AM by Erika E

Please write a program for a Vertical Histogram

SOLUTION:


#include<stdio.h>

#define MAXWL 20  /* Maximum length of a word */

#define MAXNO 25 /* Maximum No of words in a sentence */

 

int main(void)

{

                int word[MAXNO];

                int i,c,j,nc,nw;

 

                for(i=0;i<MAXNO;++i)

                               word[i]=0;

 

                nc = nw = 0;

 

                while( (c=getchar()) != EOF)

                {

                               ++nc;

                               if( c ==' ' || c =='

' || c =='              ')

                               {

                                               word[nw] = nc -1; /* -1 for excluding the space in the word length */

                                               ++nw;

                                               nc = 0; /* resetting the word-length for the next word */

                               }

               

                }

 

                for( i = MAXWL; i >= 1; --i)

                {

                               for(j=0;j <= nw;++j)

                               {

                                               if( i <= word[j])

                                                               putchar('*');

                                               else      

                                                               putchar(' ');

                                               }

                putchar('

');

                }

 

return 0;

}

UNIX cat like utility

posted Feb 14, 2010, 4:20 AM by Erika E

Please write a program for UNIX cat like utility

SOLUTION:


#include<stdio.h>

#include<string.h>

#include<conio.h>

 

int main(int argc,char* argv[]){

        FILE* fp;

        int i=0;

        char c;

        if(argc==1){

                fprintf(stderr,"Error using cat...

");

                exit(2);

        }

        if(!strcmp(argv[1],"-w")){  /* This returns 1 if match is found */

 

                if(argc!=3){

                        fprintf(stderr,"Invalid no. of arguments

");

                        exit(2);

                }

                fp=fopen(argv[2],"w");

                if(fp==NULL)

                {

                        fprintf(stderr,"Error in opening file...

");

                        exit(2);

                }

                c=getchar();

                while(c!=EOF)

                {

                        fputc(c,fp);

                        c=getchar();

                }

                fclose(fp);

        }

        else{

        for(--argc;argc>0;argc--){

                 fp=fopen(argv[++i],"r");

                 if(fp==NULL){

                        fprintf(stderr,"File not found...Aborting

");

                        exit(2);

                 }

                 while((c=fgetc(fp))!=EOF)

                        fputc(c,stdout);

                 fclose(fp);

        }

        }

 

}

Understanding IVT table

posted Feb 14, 2010, 4:18 AM by Erika E

Please write a program for understanding IVT table

SOLUTION:


// understanding ivt table

#include<stdio.h>

#include<dos.h>

main()

{

   unsigned long far *address = (unsigned long far *)0x00000000;

   unsigned long intadd[256];

   unsigned int segment, offset;

   int i;

   FILE *fp;

   fp = fopen("IVT.txt", "wb");

   for(i = 0; i < 256; i++)

   {

      intadd[i] = *(address++);

      segment = FP_SEG(intadd[i]);

      offset = FP_OFF(intadd[i]);

      fprintf(fp, "interrupt %3X : vector %Fp(hex) : %lu(dec)

",

            i, intadd[i], (unsigned long)segment * 16 + offset);

   }

   fclose(fp);

}

1-10 of 100