Loading....
Coupon Accepted Successfully!

 

Question 41

How can we sum the digits of a given number in single statement?


Try something like this


# include

void main()
{
  int num=123456; 
  int sum=0;

  for(;num>0;sum+=num%10,num/=10);  // This is the "single line".

  printf("\nsum = [%d]\n", sum);
}



If there is a simpler way to do this, let me know!


Question 42

Given two strings A and B, how would you find out if the characters in B were a subset of the characters in A?


Try this out


isSubset(char *a, char *b)
{
  int letterPresent[256];
  int i;

  for(i=0; i<256; i++)
     letterPresent[i]=0;

  for(i=0; a[i]!='\0'; i++)
     letterPresent[a[i]]++;

  for(i=0; b[i]!='\0'; i++)
     if(letterPresent[b[i]])
        return(FALSE);

  return(TRUE);
}



Question 43

Write a C program generate permutations.


Iterative C program


#include 
#define SIZE 3
int main(char *argv[],int argc)
{
  char list[3]={'a','b','c'};
  int i,j,k;

  for(i=0;i     for(j=0;j       for(k=0;k         if(i!=j && j!=k && i!=k)
          printf("%c%c%c\n",list[i],list[j],list[k]);

  return(0);
}




Recursive C program


#include 
#define N  5


int main(char *argv[],int argc)
{
  char list[5]={'a','b','c','d','e'};
  permute(list,0,N);
  return(0);
}


void permute(char list[],int k, int m)
{
  int i;
  char temp;

  if(k==m)
  {
    /* PRINT A FROM k to m! */
    for(i=0;i     printf("\n");
  }
  else
  {
     for(i=k;i      {
        /* swap(a[i],a[m-1]); */ 
        temp=list[i];
        list[i]=list[m-1];
        list[m-1]=temp;

        permute(list,k,m-1);

        /* swap(a[m-1],a[i]); */ 

        temp=list[m-1];
        list[m-1]=list[i];
        list[i]=temp;
       }
  }
}



Question 44

Write a program to check if the stack grows up or down


Try noting down the address of a local variable. Call another function with a local variable declared in it and check the address of that local variable and compare!.


#include 
#include 

void stack(int *local1);

int main()
{
  int local1;
  stack(&local1);
  exit(0);
}

void stack(int *local1)
{
   int local2;
   printf("\nAddress of first  local : [%u]", local1);
   printf("\nAddress of second local : [%u]", &local2); 
   if(local1     {
     printf("\nStack is growing downwards.\n");
   }
   else
   {
     printf("\nStack is growing upwards.\n");
   }
   printf("\n\n");
}



Question 45

How to add two numbers without using the plus operator?


Actually,


SUM   = A XOR B
CARRY = A AND B



On a wicked note, you can add two numbers wihtout using the + operator as follows


a - (- b)


:)


Question 46

How to generate prime numbers? How to generate the next prime after a given prime?


This is a very vast subject. There are numerous methods to generate primes or to find out if a given number is a prime number or not. Here are a few of them. I strongly recommend you to search on the Internet for more elaborate information.

Brute Force
Test each number starting with 2 and continuing up to the number of primes we want to generate. We divide each numbr by all divisors upto the square root of that number. If no factors are found, its a prime.

Using only primes as divisors
Test each candidate only with numbers that have been already proven to be prime. To do so, keep a list of already found primes (probably using an array, a file or bit fields).

Test with odd candidates only
We need not test even candidates at all. We could make 2 a special case and just print it, not include it in the list of primes and start our candidate search with 3 and increment by 2 instead of one everytime.


Table method
Suppose we want to find all the primes between 1 and 64. We write out a table of these numbers, and proceed as follows. 2 is the first integer greater than 1, so its obviously prime. We now cross out all multiples of two. The next number we haven't crossed out is 3. We circle it and cross out all its multiples. The next non-crossed number is 5, sp we circle it and cross all its mutiples. We only have to do this for all numbers less than the square root of our upper limit, since any composite in the table must have atleast one factor less than the square root of the upper limit. Whats left after this process of elimination is all the prime numbers between 1 and 64.


Question 47

Write a program to print numbers from 1 to 100 without using loops!


Another "Yeah, I am a jerk, kick me! kind of a question. I simply dont know why they ask these questions.

Nevertheless, for the benefit of mankind...



Method1 (Using recursion)


void printUp(int startNumber, int endNumber) 

  if (startNumber > endNumber) 
    return; 
  
  printf("[%d]\n", startNumber++); 
  printUp(startNumber, endNumber); 
}





Method2 (Using goto)


void printUp(int startNumber, int endNumber) 

start: 

    if (startNumber > endNumber) 
    {
       goto end; 
    }
    else 
    { 
       printf("[%d]\n", startNumber++); 
       goto start; 
    } 

end: 
    return;
}



Question 48

Write your own trim() or squeeze() function to remove the spaces from a string.


Here is one version...


#include 

char *trim(char *s);

int main(int argc, char *argv[])
{
  char str1[]=" Hello   I am Good ";
  printf("\n\nBefore trimming : [%s]", str1);
  printf("\n\nAfter trimming  : [%s]", trim(str1));
  
  getch();
}


// The trim() function...

char *trim(char *s) 

    char *p, *ps; 
    
    for (ps = p = s; *s != '\0'; s++) 
    {
        if (!isspace(*s)) 
        {
            *p++ = *s; 
        }
    }

    *p = '\0'; 

    return(ps); 
}



And here is the output...


Before trimming : [ Hello   I am Good ]
After trimming  : [HelloIamGood]




Another version of this question requires one to reduce multiple spaces, tabs etc to single spaces...


Question 49

Write a C program for calculating the factorial of a number



Here is a recursive C program


fact(int n)
{
    int fact;
    if(n==1)
        return(1);
    else
        fact = n * fact(n-1);
    return(fact);
}




Please note that there is no error handling added to this function (to check if n is negative or 0. Or if n is too large for the system to handle). This is true for most of the answers in this website. Too much error handling and standard compliance results in a lot of clutter making it difficult to concentrate on the crux of the solution. You must ofcourse add as much error handling and comply to the standards of your compiler when you actually write the code to implement these algorithms.


Question 50

Write a C program to calculate pow(x,n)?


There are again different methods to do this in C

Brute force C program


int pow(int x, int y)
{
  if(y == 1) return x ;
  return x * pow(x, y-1) ;
}




Divide and Conquer C program


#include 
int main(int argc, char*argv[])
{
  printf("\n[%d]\n",pow(5,4));
}

int pow(int x, int n)
{
  if(n==0)return(1);
  else if(n%2==0)
  {
    return(pow(x,n/2)*pow(x,(n/2)));
  }
  else 
  {
    return(x*pow(x,n/2)*pow(x,(n/2)));
  }
}




Also, the code above can be optimized still by calculating pow(z, (n/2)) only one time (instead of twice) and using its value in the two return() expressions above.






Test Your Skills Now!
Take a Quiz now
Reviewer Name