Friday 27 January 2012

Puzzles

Puzzle 1: Classic: If a bear walks one mile south, turns left and walks one mile to the east and then turns left again and walks one mile north and arrives at its original position, what is the color of the bear.
 
 


Puzzle 2: Given a rectangular (cuboidal for the puritans) cake with a rectangular piece removed (a size or orientation), how would you cut the remainder of the cake into two equal halves with one straight cut of a knife?

 

Puzzle 3: There are 3 baskets. one of them have apples, one has oranges only and the other has mixture of apples and oranges. The labels on their baskets always lie. (i.e. if the label says oranges, you are sure that it doesn't have oranges only,it could be a mixture) The task is to pick one basket and pick only one fruit from it and then correctly label all the three baskets.

 

Puzzle 4: You have 8 balls. One of them is defective and weighs less than others. You have a balance to measure balls against each other. In 2 weighings how do you find the defective one?

 

Puzzle 5: Why is a manhole cover round?

 

Puzzle 6: How many cars are there in the USA?

 


Puzzle 7: You've got someone working for you for seven days and a gold bar to pay them. The gold bar is segmented into seven connected pieces. You must give them a piece of gold at the end of every day. If you are only allowed to make two breaks in the gold bar, how do you pay your worker?

 


Puzzle 8: One train leaves Los Angeles at 15mph heading for New York. Another train leaves from New York at 20mph heading for Los Angeles on the same track. If a bird, flying at 25mph, leaves from Los Angeles at the same time as the train and flies back and forth between the two trains until they collide, how far will the bird have traveled?

 


Puzzle 9: You have two jars, 50 red marbles and 50 blue marbles. A jar will be picked at random, and then a marble will be picked from the jar. Placing all of the marbles in the jars, how can you maximize the chances of a red marble being picked? What are the exact odds of getting a red marble using your scheme?

 


Puzzle 10: Imagine you are standing in front of a mirror, facing it. Raise your left hand. Raise your right hand. Look at your reflection. When you raise your left hand your reflection raises what appears to be his right hand. But when you tilt your head up, your reflection does too, and does not appear to tilt his/her head down. Why is it that the mirror appears to reverse left and right, but not up and down?

 


Puzzle 11: You have 5 jars of pills. Each pill weighs 10 gram, except for contaminated pills contained in one jar, where each pill weighs 9 gm. Given a scale, how could you tell which jar had the contaminated pills in just one measurement?

 


Puzzle 12: If you had an infinite supply of water and a 5 quart and 3 quart pail, how would you measure exactly 4 quarts?

 


Puzzle 13: You have a bucket of jelly beans. Some are red, some are blue, and some green. With your eyes closed, pick out 2 of a like color. How many do you have to grab to be sure you have 2 of the same?

 


Puzzle 14: There are four dogs/ants/people at four corners of a square of unit distance. At the same instant all of them start running with unit speed towards the person on their clockwise direction and will always run towards that target. How long does it take for them to meet and where?

 


Puzzle 15: You're given an array containing both positive and negative integers and required to find the sub-array with the largest sum (O(N) a la KBL). Write a routine in C for the above.

 


Puzzle 16: Given an array of size N in which every number is between 1 and N, determine if there are any duplicates in it. You are allowed to destroy the array if you like. [ I ended up giving about 4 or 5 different solutions for this, each supposedly better than the others ].

 


Puzzle 17: Write a routine to draw a circle (x ** 2 + y ** 2 = r ** 2) without making use of any floating point computations at all. [ This one had me stuck for quite some time and I first gave a solution that did have floating point computations ].

 


Puzzle 18: Among 12 identical looking golf balls there is one that is defective in weight. It is either heavier or lighter than the standard one. You have a balance. You can only weigh 3 times to find out which one is defective and whether it is heavier or lighter.

 


Puzzle 19: There are 3 glasses. The biggest one can hold 24 ounces. The medium one can hold 11 ounces and the smallest one can hold 5 ounces. Now you have 24 ounces of soft drink in the largest glass. Can you use just these 3 glasses to make the largest glass contain 12 ounces of soft drink by pouring soft drink from one glass to another?
 



Puzzle 20: There are 4 women who want to cross a bridge. They all begin on the same side. You have 17 minutes to get all of them across to the other side. It is night. There is one flashlight. A maximum of two people can cross at one time. Any party who crosses, either 1 or 2 people, must have the flashlight with them. The flashlight must be walked back and forth, it cannot be thrown, etc. Each woman walks at a different speed. A pair must walk together at the rate of the slower woman's pace.
Woman 1: 1 minute to cross
Woman 2: 2 minutes to cross

Woman 3: 5 minutes to cross

Woman 4: 10 minutes to cross

For example if Woman 1 and Woman 4 walk across first, 10 minutes have elapsed when they get to the other side of the bridge. If Woman 4 then returns with the flashlight, a total of 20 minutes have passed and you have failed the mission. What is the order required to get all women across in 17 minutes? Now, what's the other way?

 


Puzzle 21: If you have two buckets, one with red paint and the other with blue paint, and you take one cup from the blue bucket and poor it into the red bucket. Then you take one cup from the red bucket and poor it into the blue bucket. Which bucket has the highest ratio between red and blue? Prove it mathematically.

 


Puzzle 22 : You have 4 jars of pills. Each pill is a certain weight, except for contaminated pills contained in one jar, where each pill is weight + 1. How could you tell which jar had the contaminated pills in just one measurement?

 


Puzzle 23: The SF Chronicle has a word game where all the letters are scrambled up and you have to figure out what the word is. Imagine that a scrambled word is 5 characters long:
> How many possible solutions are there?
> What if we know which 5 letters are being used?
> Develop an algorithm to solve the word.

 




Puzzle 24: Imagine a disk spinning like a record player turn table. Half of the disk is black and the other is white. Assume you have an unlimited number of color sensors. How many sensors would you have to place around the disk to determine the direction the disk is spinning? Where would they be placed?

 


Puzzle 25: Imagine an analog clock set to 12 o'clock. Note that the hour and minute hands overlap. How many times each day do both the hour and minute hands overlap? How would you determine the exact times of the day that this occurs?

 


Puzzle 26:Pairs of primes separated by a single number are called prime pairs. Examples are 17 and 19. Prove that the number between a prime pair is always divisible by 6 (assuming both numbers in the pair are greater than 6). Now prove that there are no 'prime triples.'

 


Puzzle 27:There is a room with a door (closed) and three light bulbs. Outside the room there are three switches, connected to the bulbs. You may manipulate the switches as you wish, but once you open the door you can't change them. Identify each switch with its bulb.

 


Puzzle 28:Imagine you are standing in front of a mirror, facing it. Raise your left hand. Raise your right hand. Look at your reflection. When you raise your left hand your reflection raises what appears to be his right hand. But when you tilt your head up, your reflection does too, and does not appear to tilt his/her head down. Why is it that the mirror appears to reverse left and right, but not up and down?

 


Puzzle 29:Three people check into a hotel. They pay $30 to the manager and go to their room. The manager finds out that the room rate is $25 and gives $5 to the bellboy to return. On the way to the room the bellboy reasons that $5 would be difficult to share among three people so he pockets $2 and gives $1 to each person.Now each person paid $10 and got back $1. So they paid $9 each, totalling $27. The bellboy has $2, totalling $29.Where is the remaining dollar?

 


Puzzle 30: A line of 100 airline passengers is waiting to board a plane. they each hold a ticket to one of the 100 seats on that flight. (for convenience, let's say that the nth passenger in line has a ticket for the seat number n.) Unfortunately, the first person in line is crazy, and will ignore the seat number on their ticket, picking a random seat to occupy. all of the other passengers are quite normal, and will go to their proper seat unless it is already occupied. if it is occupied, they will then find a free seat to sit in, at random. What is the probability that the last (100th) person to board the plane will sit in their proper seat (#100)?

 


Puzzle 31: You have 100 doors in a row that are all initially closed. you make 100 passes by the doors starting with the first door every time. the first time through you visit every door and toggle the door (if the door is closed, you open it, if its open, you close it). the second time you only visit every 2nd door (door #2, #4, #6). the third time, every 3rd door (door #3, #6, #9), etc, until you only visit the 100th door. What state are the doors in after the last pass? which are open which are closed?

 


Puzzle 32: 100 fogcreek programmers are lined up in a row by an assassin. the assassin puts red and blue hats on them. they can't see their own hats, but they can see the hats of the people in front of them. the assassin starts in the back and says "what color is your hat?" the fogcreek programmer can only answer "red" or "blue." the programmer is killed if he gives the wrong answer; then the assassin moves on to the next programmer. the programmers in front get to hear the answers of the programmers behind them, but not whether they live or die. they can consult and agree on a strategy before being lined up, but after being lined up and having the hats put on, they can't communicate in any way other than those already specified. what strategy should they choose to maximize the number of programmers who are guaranteed to be saved?
 



Puzzle 33: Four men are lined up on some steps. They are all facing in the same direction. A wall seperates the fourth man from the other three.
So to summarise :-
Man 1 can see men 2 and 3.

Man 2 can see man 3.

Man 3 can see none of the others.

Man 4 can see none of the others.

The men are wearing hats. They are told that there are two white hats and two black hats. The men initally don't know what colour hat they are wearing. They are told to shout out the colour of the hat that they are wearing as soon as they know for certain what colour it is.

They are not allowed to turn round.

They are not allowed to talk to each other.

So the question is -

Who is the first person to shout out and why?

 


Puzzle 34: If you are throwing the suitcase out of a floating boat into the water:
If it sinks: The water level will rise ever so slightly if the volume of the suitcase is greater than it's weight. If the volume is less than the weight, the water level will go down when the suitcase sinks. This is because the suitcase's weight would cause it to make the boat a little lower since it has to displace as much water as the suitcase weighs.
If the suitcase floats: The water level will remain the same. since, the water will be displaced enough to account for the weight of the suitcase, either in the boat or by itself.
If the suitcase is being thrown away on a cruise ship: the water level will stay the same.

 


Puzzle 35: An analog clock reads 3:15. What is the angle between the minute hand and hour hand?

 


Puzzle 36: Imagine an analog clock set to 12 o'clock. Note that the hour and minute hands overlap. How many times each day do both the hour and minute hands overlap? How would you determine the exact times of the day that this occurs?

 


Puzzle 37: Imagine a disk spinning like a record player turn table. Half of the disk is black and the other is white. Assume you have an unlimited number of color sensors. How many sensors would you have to place around the disk to determine the direction the disk is spinning? Where would they be placed?

 


Puzzle 38:Two boys sell apples. Each sells thirty apples a day. The first boy sells his apples at two for five rupees (and therefore earns Rs 75 per day). The second boy sells his apples at three for five rupees (and therefore earns Rs 50 per day). The total received by both boys each day is therefore Rs 125. One day, the first boy is sick, and the second boy takes over his apple selling duties. To accommodate the differing rates, the boy sells the sixty apples at five for Rs 10. But selling sixty apples at five for Rs 10 yields only Rs 120 earnings at the end of the day. What happened to the other 5 rupees?

 


Puzzle 39: While a red mark was placed on the forehead of each of three blindfolded women seated facing each other in a circle, they were told that the mark might be either red or white. Upon removal of the blindfolds, each was to raise her hand if she saw at least one red mark, and then to take it down if she could logically deduce the color of her own mark. All three hands were quickly raised, but then one of them lowered her hand. How did she know?

 


Puzzle 40: Potatoes are made up of 99% water and 1% "potato matter." Chaitu bought 100 pounds of potatoes and left them outside in the sun for a while. When he returned, he discovered that the potatoes had dehydrated and were now only made up of 98% water. How much did the potatoes now weigh?

 


Puzzle 41: If a boy and a half can eat a hot dog and a half in a minute and a half, how many hot dogs can six boys eat in six minutes?

 


Puzzle 42: An explorer wishes to cross a barren desert that requires 6 days to cross, but one man can only carry enough food for 4 days. What is the fewest number of other men required to help carry enough food for him to cross, the constraint is that each man should survive?

 


Puzzle 43: Grass grows in a field at some rate r, where r is the units of grass grown per day. It is known that if 10 sheep are turned out in the field, the grass will be gone in 20 days. On the other hand, if 15 sheep are turned out in the field, the grass will be gone in 10 days. If 25 sheep are turned out in the field, when will the grass be gone?

Some FAQs on C & Data Structure

  • Ques 1: How do you reverse a singly linked list? How do you reverse a doubly linked list? Write a C program to do the same.
  • Ques 2: Given only a pointer to a node to be deleted in a singly linked list, how do you delete it.
  • Ques 3: How do you sort a linked list? Write a C program to sort a linked list.
  • Ques 4: How to declare a structure of a linked list?
  • Ques 5: Write a C program to implement a Generic Linked List.
  • Ques 6: How do you reverse a linked list without using any C pointers?
  • Ques 7:How would you detect a loop in a linked list? Write a C program to detect a loop in a linked list.
  • Ques 8:How do you find the middle of a linked list? Write a C program to return the middle of a linked list.
  • Ques 9:If you are using C language to implement the heterogeneous linked list, what pointer type will you use?
  • Ques 10: How to compare two linked lists? Write a C program to compare two linked lists
  • Ques 11: How to create a copy of a linked list? Write a C program to create a copy of a linked list.
  • Ques 12: Write a C program to free the nodes of a linked list.
  • Ques 13: Can we do a Binary search on a linked list?
  • Ques 14: Write a C program to return the nth node from the end of a linked list.
  • Ques 15: How would you find out if one of the pointers in a linked list is corrupted or not?
  • Ques 16: Write a C program to insert nodes into a linked list in a sorted fashion.
  • Ques 17:Write a C program to remove duplicates from a sorted linked list.
  • Ques 18: How to read a singly linked list backwards?
  • Ques 19: How can I search for data in a linked list?
  • Ques 20: What is the difference between a linked list and Array?
  • Ques 21: Implement a linked list. Why did you pick the method you did?
  • Ques 22: Implement an algorithm to sort a linked list. Why did you pick the method you did? Now do it in O(n) time.
  • Ques 23: Given two sorted linked lists, write a function to merge them into one.
  • Ques 24: Delete an element from a doubly linked list.
  • Ques 25: Find the nth node from the end of a singly link list in a single pass.
 
C Functions Implementation Questions
  • Ques 1: Write your own C program to implement the atoi() function.
  • Ques 2: Implement the memmove() function. What is the difference between the memmove() and memcpy() function?
  • Ques 3: Write C code to implement the strstr() (search for a substring) function.
  • Ques 4: Write your own printf() function in C.
  • Ques 5: Implement the strcpy() function.
  • Ques 6: Implement the strcmp(str1, str2) function.
  • Ques 7: Implement the substr() function in C.
  • Ques 8: Write your own File copy() function.
  • Ques 9: Write C programs to implement the toupper() and the isupper() functions.
  • Ques 10: Write a C program to implement your own strdup() function.
  • Ques 11: Write a C program to implement the strlen() function.
  • Ques 12: Write your own strcat() function
  • Ques 10: Write a C program to implement your own strdup() function.
  • Ques 11: Write a C program to implement the strlen() function.
  • Ques 12: Write your own strcat() function
  
C Programming Questions
 
  • Ques 1: Right a program to implement malloc.
  • Ques 2: Write a C program to swap two variables without using a temporary variable .
  • Ques 3: What is the 8 queens problem? Write a C program to solve it.
  • Ques 4: Write a C program to print a square matrix helically.
  • Ques 5: Write a C program to reverse a string.
  • Ques 6: Write a C program to reverse the words in a sentence in place.
  • Ques 7: Write a C program generate permutations.
  • Ques 8: Write a C program to calculate pow(x,n).
  • Ques 9: Write a C program which does wildcard pattern matching algorithm.
  • Ques 10: How do you calculate the maximum subarray of a list of numbers?
  • Ques 11: How to generate fibonacci numbers? How to find out if a given number is a fibonacci number or not? Write C programs to do both.
  • Ques 12: Solve the Rat In A Maze problem using backtracking.
  • Ques 13: What Little-Endian and Big-Endian? How can I determine whether a machine's byte order is big-endian or little endian? How can we convert from one to another?
  • Ques 14: Write C code to solve the Tower of Hanoi problem.
  • Ques 15: Write C code to return a string from a function.
  • Ques 16: Write a C program which produces its own source code as its output.
  • Ques 17: Write a C progam to convert from decimal to any base (binary, hex, oct etc...).
  • Ques 18: Write C code to check if an integer is a power of 2 or not in a single line?
  • Ques 19: Write a C program to find the GCD of two numbers.
  • Ques 20: Finding a duplicated integer problem.
  • Ques 21: Write code to remove duplicates in a sorted array.
  • Ques 22: How do you initialize a pointer inside a function?
  • Ques 23: Write C code to dynamically allocate one, two and three dimensional arrays (using malloc()).
  • Ques 24: How would you find the size of structure without using sizeof().
  • Ques 25: Write a C program to multiply two matrices.
  • Ques 26: Write a C program to check for palindromes.
  • Ques 27: Write C code to implement the Binary Search algorithm.
  • Ques 28: Write code to add two polynomials.
  • Ques 29: Write a program to add two long positive numbers (each represented by linked lists).
  • Ques 30: How do you compare floating point numbers?
  • Ques 31: Is there something we can do in C but not in C++?
  • Ques 32: How to swap the two nibbles in a byte ?
  • Ques 33: How to scan a string till we hit a new line using scanf()?
  • Ques 34: How do you get the line numbers in C?

Thursday 26 January 2012

Write a C program to print the Fibonacci Series upto to the first 'n' terms

#include<stdio.h>
#include<conio.h>
void main()
{
    int f=0, s=1, t, n, ct;
    clrscr();
    printf("Enter the value of 'n': ");
    scanf("%d",&n);
    printf("\nFibonacci series:\n");
    printf("%5d%5d", f, s);
    ct=3; //becoz we already displayed 2 values and we r going the third value
    while(ct<=n)
    {
        t=f+s;
        printf("%5d", t);
        f=s;
        s=t;
        ct++;
    }
    getch();
}

Write a C program to genarate all the prime numbers between 1 to 'n'

#include<stdio.h>
#include<conio.h>
void main()
{
    int st, n, x, flag;
    clrscr();
    printf("Enter the value of 'n': ");
    scanf("%d", &n);
    for(st=1; st<=n; st++)
    {
        x=2; flag=0;
        while(x<=st/2)
        {
            if(st%x==0)
            {
                flag=1; break;
            }
            x++;
        }
        if( flag==0)
        printf("%5d", st);
    }
    getch();
}

Write a C program to calculate the following Sum:- sum=1-x2/2! +x4/4!-x6/6!+x8/8!-x10/10!

#include<stdio.h>
#include<conio.h>
#include<math.h>
void main()
{
    int ct, ft;
    float sum=0, x, power, fact;
    clrscr();
    printf("--------PROGRAM FOR SUM OF EQ. SERIES------");
    printf("\n\nEnter the value of X : ");
    scanf( "%f", &x);
    ct=0;
    for(power=0; power<=10; power=power+2)
    {
        fact=1; for(ft=power; ft>=1; ft--)
        fact =fact* ft;
        sum=sum+(pow(-1,ct)*(pow(x,power)/fact)); //EQ. FOR SUM SERIES
        ct++;
    }
    printf("\n Sum : %f",sum);
    getch();
}

Write a C program to find both the largest and smallest numbers in a list of integers.

#include<stdio.h>
#include<conio.h>
void main(void)
{
    int a[50], max, min, i, n;
    clrscr( );
    printf("Enter how many integers do u want? :");
    scanf(" %d", &n);
    for( i=0; i< n ; i++)
    {
        printf("\nEnter the %d number: ", i );
        scanf(" %d", &a[ i ]);
        if(i==0)
        {
            max=a[i ]; min=a[i ];
        }
        if(a[ i]>max)
        max= a[i ];
        if(a[i ]< min)
        min= a[i ];
    }
    printf("\n Maximum : %d", max);
    printf("\n Minimum : %d", min);
    getch( );
}

Write a C program which copies one file to another.

#include<stdio.h>
#include<conio.h>
void main()
{
    FILE *fp, *fq ;
    char file1[20], file2[20];
    char ch;
    clrscr( );
    printf("Enter the source filename to be copied:");
    gets(file1);
    fp=fopen(file1,"r");
    if(fp==NULL)
    {
        printf("\nCannot open %s",file1);
        exit(0);
    }
    printf("\nEnter the destination filename:");
    gets(file2);
    fq=fopen(file2,"w");
    while((ch=getc(fp))!=EOF )
    {
        putc(ch,fq);
    }
    printf("\n Copied Sucessfully..");
    fclose(fp);
    fclose(fq);
    getch( );
}

Write a C program to construct a pyramid of numbers.

1
2 3
4 5 6
7 8 9 10
11 12 13 14 15



#include<stdio.h>
#include<conio.h>
void main( )
{
    int r, c, num=1 ,len;
    clrscr( );
    printf("Enter the required no. of rows:");
    scanf("%d", &len);
    for( r=1; r<=len; r++ )
    {
        printf("\n");
        for(c=1 ; c<=r; c++)
        {
            printf("%2d ", num);
            num++;
        }
    }
    getch( );
}

Write a C program to read in two numbers, x and n, and then compute the sum of this geometric progression: 1+x+x2+x3+………….+xn

#include<stdio.h>
#include<conio.h>
#include<math.h>
void main( )
{
    int x, n, sum,power;
    clrscr( );
    printf("Enter the values of x and n:");
    scanf("%d%d", &x, &n);
    if(n<0)
    {
        printf("\nSorry, the formula does not make sense for negative exponents & values");
        printf("Enter the values of x and n:");
        scanf("%d%d", &x, &n);
        sum=1;
        for(power=1; power <=n; power++)
        {
            sum=sum+ pow(x,power);
        }
        printf("X value is: %d \nN value is: %d", x, n);
        printf("\nSum of the given geometric progression: %d", sum);
    }
    else
    {
        sum=1;
        for(power=1; power <=n; power++)
        {
            sum=sum+ pow(x,power);
        }
        printf("X value is: %d \nN value is: %d", x, n);
        printf("\nSum of the given geometric progression: %d", sum);
    }
    getch( );
}

Write a C program to insert a sub-string in to given main string from a given position.

#include<stdio.h>
#include<conio.h>
#include<string.h>
void main( )
{
    char st[20],sub[10],temp[10];
    int pos, i, j;
    clrscr( );
    printf("Enter the main string:");
    gets(st);
    printf("\nEnter the substring to insert:");
    gets(sub);
    printf("Enter the index position:");
    scanf("%d",&pos);
    if(pos<=strlen(st))
    {
        for(i=0;i<=strlen(st);i++)
        {
            if(i==pos)
            {
                for(j=0;st[i]!='\0';j++) // to store the 'st' to 'temp' from given position.
                {
                    temp[j]=st[i];
                    i++;
                }
                temp[j]='\0';
                i=pos;
                for(j=0;sub[j]!='\0';j++) // to insert a sub-str to main string.
                {
                    st[i]=sub[j];
                    i++;
                }
                for(j=0;temp[j]!='\0';j++) // Lastly to insert the 'temp' to 'st' after sub-str.
                {
                    st[i]=temp[j];
                    i++;
                }
                st[i]='\0';
            }
        }
        printf("\nAfter adding the sub-string: %s",st);
    }
    else
    printf("\nSorry, it is not possible to insert a substring in that position.");
    getch();
}

Write a C program to delete n Characters from a given position in a given string.

#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
    char st[20],temp[20];
    int pos,i,j,ct=0,n;
    clrscr();
    printf("Enter the string:");
    gets(st);
    printf("\nEntre the index position:");
    scanf("%d",&pos);
    printf("\nEnter the no.of characters:");
    scanf("%d",&n);
    if(pos<=strlen(st))
    {
        for(i=0;i<=strlen(st);i++)
        {
            if(i==pos)
            {
                for(j=0;st[i]!='\0';j++) // to store the 'st' in 'temp' from a giv pos
                {
                    temp[j]=st[i];
                    i++;
                }
                temp[j]='\0';
                i=pos;
                //to delete the 'n' char and after restore the temp in st.
                for(j=0;temp[j]!='\0';j++)
                {
                    ct++;
                    if(ct>n)
                    {
                        st[i]=temp[j];
                        i++;
                    }
                }
                st[i]='\0';
            }
        }
        printf("\n\nAfter deletion the string: %s",st);
    }
    else
    printf("\nSorry, we cannot delete from that position.");
    getch();
}

Write a C program to find the GCD (greatest common divisor) of two given integers using Recursive function.

#include<stdio.h>
#include<conio.h>
int gcd (int, int); //func. declaration.
void main( )
{
    int a, b, res;
    clrscr( );
    printf("Enter the two integer values:");
    scanf("%d%d", &a, &b);
    res= gcd(a, b); // calling function.
    printf("\nGCD of %d and %d is: %d", a, b, res);
    getch( );
}
int gcd( int x, int y) //called function.
{
    int z;
    z=x%y;
    if(z==0)
    return y;
    gcd(y,z); //recursive function
}

Write a C program to solve the Towers of Hanoi problem using Recursive function.

#include<stdio.h>
#include<conio.h>
#include<math.h>
void hanoi(int x, char from, char to, char aux)
{
    if(x==1)
    printf("Move Disk From %c to %c\n",from,to);
    else
    {
        hanoi(x-1,from,aux,to);
        printf("Move Disk From %c to %c\n",from,to);
        hanoi(x-1,aux,to,from);
    }
}

void main( )
{
    int disk;
    int moves;
    clrscr();
    printf("Enter the number of disks you want to play with:");
    scanf("%d",&disk);
    moves=pow(2,disk)-1;
    printf("\nThe No of moves required is=%d \n",moves);
    hanoi(disk,'A','C','B');
    getch( );
}


Output:-
Enter the number of disks you want to play with: 3

The No of moves required is=7
Move Disk from A to C
Move Disk from A to B
Move Disk from C to B
Move Disk from A to C
Move Disk from B to A
Move Disk from B to C
Move Disk from A to C

Write a C program to check whether the given integer is Magic number or not.

Magic number:- A number which is divisible by 9 and also after reverse if it is divisible by 9, then it is said to Magic number.

Example:- Suppose take 18
We know '18' is divisible by 9 (ie., 9 * 2 = 18)
Now After reverse '18' becomes 81.
Here '81' is also is divisible by 9 (ie., 9 * 9 =81 )
So we say '18' is a Magic number.


#include<stdio.h>
#include<conio.h>
void main( )
{
    int rem, rev=0, n;
    clrscr( );
    printf("Enter the required number:");
    scanf("%d",&n);
    while(n>0)
    {
        rem=n%10;
        rev=(10*rev)+ rem;
        n=n/10;
    }
    if(rev%9== 0)
    printf("\nMagic Number.");
    else
    printf("\nNot a Magic number.");
    getch( );
}

Output:-
Enter the required number: 27
Magic Number.

Write a C program to generate the Fibonocci series using Recursion.

#include<stdio.h>
#include<conio.h>
int fibno(int); // function declaration.
void main()
{
    int ct, n, disp;
    clrscr( );
    printf("Enter the no. of terms:");
    scanf("%d", &n);
    printf("\n The Fibonocci series:\n");
    for( ct=0; ct<=n-1; ct++)
    {
        disp= fibno(ct); //calling function.
        printf("%5d", disp);
    }
    getch( );
}

int fibno( int n)
{
    int x, y;
    if(n==0)
    return 0;
    else if(n==1)
    return 1;
    else
    {
        x= fibno( n-1);
        y= fibno( n-2);
        return (x+y);
    }
}


Output:- Enter the no. of terms: 10

The Fibonocci series:
0 1 1 2 3 5 8 13 21 34

Write a C program to find the factors of a given integer.

#include<stdio.h>
#include<conio.h>
void main( )
{
    int no,x;
    clrscr( );
    printf("Enter the required number:");
    scanf("%d",&no);
    printf("\nThe factors are:");
    for(x=1;x<=no;x++)
    {
        if(no%x==0)
        printf("\n%d",x);
    }
    getch( );
}


Output:-
Enter the required number: 27
The factors are:
1
3
9
27

Write a c program which gives you the temperature in Centigrade and in Fahrenheit

#include<stdio.h>
#include<conio.h>

void centigrade();
void fahrenheit();

void main()
{
    int ch;
    char choice;
    do
    {
    clrscr();
    printf("Press 1 for Fahrenheit\n");
    printf("Press 2 for Centigrade\n");
    printf("Enter your choice:");
    scanf("%d",&ch);
    switch(ch)
    {
    case 1:
    centigrade();
    break;

    case 2:
    fahrenheit();
    break;

    default:
    printf("You have Entered wrong choice....\n");

    }
    printf("\nIf u want to continue then press y\n");
    choice=getch();
    if(choice!='y')
    break;
    else
    continue;
    }
    while(1);

    getch();
}

void centigrade()
{
    float c,f;
    printf("Enter the fahrenheit degrees:");
    scanf("%f", &f);
    c= (f-32)/1.8 ;
    printf("\nAfter Fahrenheit degrees, Centigrade Degrees = %f", c);
}

void fahrenheit()
{
    float c,f;
    printf("Enter the Centigrade degrees:");
    scanf("%d",&c);
    f= 1.8*c + 32.0;
    printf("\nAfter Centigrade degrees, Fahrenheit degrees = %f", f);
}

Write a C program to Calculate the sum of the series sum=1+1/x+1/x2+1/x3+...........+1/xn

#include<stdio.h>
#include<conio.h>
#include<math.h>
void main()
{
    int i, x, n;
    float sum, p;
    clrscr();
    printf("Enter the base value 'x':");
    scanf("%d", &x);
    printf("\nEnter the power value 'n':");
    scanf(" %d", &n);
    sum=1;
    for( i=1; i<=n ; i++)
    {
        p=pow(x, i);
        sum=sum+(1/p);
    }
    printf("\nSum of the series: %f", sum);
    getch( );
}

Write a C program to find the roots of a Quadratic equation

#include<stdio.h>
#include<conio.h>
#include<math.h>
void main()
{
    int a , b, c, d;
    float x1, x2,ab;
    ab:
    printf("Enter the value of a, b, c:");
    scanf("%d%d%d", &a, &b, &c);
    if(a==0)
    {
        printf("\nIt is a Linear Equation");
        printf("\nRe-Enter the data again.");
        goto ab;
    }
    d=(b*b)-(4*a*c);
    if(d==0)
    {
        printf("\nRoots are real and equal");
        x1= x2=(-b)/(2*a);
        printf("\nRoots are: %f \t %f ", x1, x2);
    }
    else
    {
        if(d<0)
        printf("\nRoots are imaginary");
        else
        {
            x1=((-b)+sqrt(d))/(2*a);
            x2=((-b)-sqrt(d))/(2*a);
            printf("\nRoots are real");
            printf("\nRoots are : %f \t %f", x1, x2);
        }
    }
    getch( );
}


Output:-
Enter the values of a, b,c : 5
2
4
Roots are imaginary.

Write a C program to print all Combinations of characters A, B, C

#include<stdio.h>
#include<conio.h>
void main()
{
    char ch1, ch2, ch3;
    clrscr();
    for(ch1='A' ; ch1<='C' ; ++ch1)
    {
        for(ch2='A' ; ch2<='C' ; ++ch2)
        for(ch3='A' ; ch3<='C' ; ++ch3)
        printf("%c%c%c\t", ch1, ch2, ch3);
    }
    getch();
}


Output:-
AAA AAB AAC ABA ABB ABC ACA ACB ACC
BAA BAB BAC BBA BBB BBC BCA BCB BCC
CAA CAB CAC CBA CBB CBC CCA CCB CCC

Write a C program to Insert an element at the 'n' th position

#include<stdio.h>
#include<conio.h>
void main()
{
    int a[20], len, i, j, x, n ;
    clrscr( );
    printf("Enter the array length:");
    scanf("%d", &len);
    printf("\nEnter the array elements:\n");
    for(i=0; i<len; i++) //remove the single quotes in for loop
    scanf("%d", &a[i]);
    printf("\nEnter the 'n' th position:");
    scanf("%d", &n);
    printf("\nEnter the array element you want to insert:");
    scanf("%d", &x);
    for(j=len-1;j>=n-1;j--)
    {
        a[j+1]= a[j];
    }
    a[n-1]= x;
    len=len+1;
    printf("\nThe New List is :\n");
    for( i=0; i<len; i++) //remove the single quotes in for loop
    printf("%5d",a[i]);
    getch( );
}

 
Output:-
Enter the array length : 4
Enter the array elements: 5
8
1
9
Enter the 'n' position: 4
Enter the array element you want to insert: 10
The new List is:
5
8
1
10
9

Write a C program to delete an element from the array.

#include<stdio.h>
#include<conio.h>
void main()
{
    int a[20],len,i,n,item,j;
    clrscr();
    printf("Enter how many elements you want to enter:");
    scanf("%d",&len);
    printf("\nEnter the array elements:\n");
    for(i=0;i<len;i++) // remove the single quotes in for loop
    scanf("%d",&a[i]);
    printf("\nEnter the location, where you want to delete:");
    scanf("%d",&n);
    item= a[n-1];
    printf("\nDeleted value is : %d",item);
    for( j= n-1;j<len-1;j++)
    {
        a[j]= a[j+1];
    }
    len=len-1;
    printf("\nThe new element list :");
    for(i=0;i<len;i++)
    printf("%5d", a[i]);
    getch();
}


Enter how many elements you want to enter: 4
Enter the array elements:
10
20
30
40
Enter the location, where you want to delete: 3
Deleted value : 30
The new element list: 10 20 40

Write a C program to print all Armstrong numbers between 1 to 1000.

#include<stdio.h>
#include<conio.h>
void main()
{
    int no,temp,rem,sum;
    clrscr();
    printf("Armstrong numbers between 1 and 1000 are:\n");
    for(no=1; no<=1000; no++)
    {
        temp=no;
        sum=0;
        while(temp>0)
        {
            rem=temp%10;
            sum=sum+(rem*rem*rem);
            temp=temp/10;
        }
        if(no==sum)
        printf("\n%d", no);
    }
    getch( );
}



Output:
Armstrong numbers between 1 and 1000 are:
1
153
370
371
407

Write a program in c to accept any character and check whether the given character is capital or small

#include<stdio.h>
#include<conio.h>
int main( )
{
char ch;
clrscr( );
printf("Enter the any alphabet:");
scanf("%c ", &ch);
if(ch>= 65 && ch<=90) // or if(ch>='A' && ch<='Z')
printf("\nGiven Alphabet is in Upper case");
else
printf("\nGiven Alphabet is in Lower case");
getch( );
return 0;
}

Output:- Enter the any alphabet: A
Given Alphabet is in Upper case

Note :- ASCII value of 'A'=65 and 'Z'= 90

Write a program in c to accept any character and check whether the given character is capital or small using Ctype.h library file

#include<stdio.h>
#include<conio.h>
#include<ctype.h>
void main()
{
    char ch;
    clrscr();
    printf("Enter any alphabet:");
    scanf("%c", &ch);
    if(isupper(ch))
    printf("\nGiven Alphabet is in Upper Case");
    else
    printf("\nGiven Alphabet is in Lower case");
    getch();
}


Output:- Enter any alphabet: a
Given Alphabet is in Lower case

Write a C program to check whether the given number is single digit or more

#include<stdio.h>
#include<conio.h>
void main()
{
    int no;
    clrscr();
    printf("Enter the required number to check:");
    scanf("%d",&no);
    if(no>=0 && no<=9)
    printf("\nSingle Digit number");
    else
    printf("\nMore than one Digit number");
    getch();
}

Output: Enter the required number to check: 9
Single Digit number

Write a C program to display the System date and Change the system date if necessary.

#include<stdio.h>
#include<conio.h>
#include<dos.h>
void main( )
{
    int dd, mm, yy;
    struct date s;
    clrscr( );
    getdate(&s);
    printf("Present System Date ( dd/mm/yy ):-- %d / %d / %d ", s.da_day, s.da_mon, s.da_year);
    printf("\nEnter the new date ( dd/mm/yy) :");
    scanf("%d%d%d", &dd, &mm, &yy);
    s.da_day=dd;
    s.da_mon=mm;
    s.da_year=yy;
    setdate(&s);
    printf("\n After changing, Present date (dd/mm/yy): %d / %d / %d", s.da_day, s.da_mon, s.da_year);
    getch();
}

Output:- Present System Date ( dd/mm/yy): 04/10/2009
Enter the new date (dd/mm/yy): 10
10
2009
After Changing, Present date (dd/mm/yy): 10/10/2009 

Write a C program to display the message "Welcome to C" without a Semicolon.

// C program without a Semicolon.
This can done in three ways but one of them is infinite.(ie, while loop)Solution:1
#include<stdio.h>
void main( )
{
if(printf("Welcome to C"))
{
}
}

Solution:2
void main( )
{
swicth(printf("Welcome to C"))
{
}
}

Solution:3
void main( )
{
while(printf("Welcome to C")) //infinite loop
{
}
}

Write a c program to create a paint brush using graphics

#include<stdio.h>
#include<conio.h>
#include<graphics.h>
#include<stdlib.h>
struct BYTEREGS
{
unsigned char al, ah, bl, bh;
unsigned char cl, ch, dl, dh;
};
struct WORDREGS
{
unsigned int ax, bx, cx, dx;
unsigned int si, di, cflag, flags;
};
union REGS
{
struct WORDREGS x;
struct BYTEREGS h;
};
void main()
{
int x,y,b,px,py,c,p,s,cl;
int d=0,m;
union REGS i,o;
initgraph(&d,&m,"D:\\TC\\BGI");
i.x.ax=1;
int86(0x33,&i,&o);
i.x.ax=8;
i.x.cx=20;
i.x.dx=450;
int86(0x33,&i,&o);
printf("Brush style insert number from 0 to 5 : ");
scanf("%d",&p);
printf("Brush size insert number from 1 to 7 : ");
scanf("%d",&s);
printf("Brush color insert number from 1 to 16 : ");
scanf("%d",&cl);
clrscr( );

cleardevice();
printf("\t\t**********DRAW IMAGE************");
while(!kbhit( ))
{
i.x.ax=3;
b=o.x.bx;
x=o.x.cx;
y=o.x.dx;
px=x;
py=y;
int86(0x33,&i,&o);
if(cl==16)
{
c=random(16);
}
else
{
c=cl;
}
setcolor(c);
if(b==1)
{
i.x.ax=3;
int86(0x33,&i,&o);
x=o.x.cx;
y=o.x.dx;
b=o.x.bx;
switch( p )
{
case 1: circle(px,py,s);break;
case 2: ellipse(px,py,0,270,s,s+2);break;
case 3: fillellipse(px,py,s+2,s);break;
case 4: rectangle(px,py,x,y);break;
case 5: sector(px,py,30,120,s,s);break;
default : line(px,py,x,y);
}
}
}
getch();
restorecrtmode();
closegraph();
}

Write a C program to Sort the list of integers using Bubble Sort

#include<stdio.h>
#include<conio.h>
void bubble(int [], int); // func. declaration
void main( )
{
    int a[10],n,i;
    clrscr();
    printf("Enter the no. of elements u want to fill:");
    scanf("%d",&n);
    printf("\nEnter the array elements:\n");
    for(i=0; i< n; i++)
    scanf("%d",&a[i]);

    bubble(a,n);  // calling function
    getch();
}

void bubble(int b[], int no)  // called function
{
    int i,j,temp;
    for(i=0; i< no-1; i++)
    {
        for(j=0; j< no-i; j++)
        {
            if(b[j]>b[j+1])
            {
                temp=b[j];
                b[j]=b[j+1];
                b[j+1]=temp;
            }
        }
    }
    printf("\nAfter sorting : ");
    for(i=0; i< no; i++)
    printf("%5d",b[i] );
}

Output:- Enter the no. of elements u want to fill: 5
Enter the array elements : 8  1  90  5  4
After sorting : 1  4  5  8  90

Write a C program to get the maximum and minimum values of a Data type

#include<stdio.h>
#include<conio.h>
void main( )
{
int x, y;
clrscr( );
x=1;
while( x > 0)
{
y = x;
x + + ;
}
printf("\nMaximum value : %d ", y );
printf("\nMinimum value : %d", x);
getch( );
}

Output:- Maximum value : 32767
Minimum value : -32768

Similarly we can find the below datatypes,
long int ( %ld )
char ( %d )
unsigned ( %u )
.....

Write a C program to print the Given pyramid

     1
    1 2 
   1 2 3 
  1 2 3 4
 1 2 3 4 5
  .
  .
  .
  n


#include<stdio.h>
#include<conio.h>
void main()
{
    int r,c,n,sp;
    clrscr( );
    printf("Enter the no. of rows u want to print:");
    scanf("%d", &n);
    for(r=1; r<=n; r++)
    {
        for(sp=n; sp>=r; sp--)
        printf(" "); // give one space in between quotations.
        for(c=1; c<=r; c++)
        printf("%2d", c);
        printf("\n");
    }
    getch();
}

Write a C program to merge two unsorted one dimensional arrays in descending order

#include<stdio.h>
#include<conio.h>
#define MAX 20
void main()
{
    int f[MAX],s[MAX];
    int m,n;     // to read the size of two arrays
    int i,j,temp;
    clrscr();
    printf("Enter the 1st array size(1-20) :");
    scanf("%d",&m);
    printf("Enter the 2nd array size(1-20) :");
    scanf("%d",&n);
    printf("\nEnter the 1st array elements:\n");
    for(i=0; i< m; i++)
    scanf("%d",&f[i] );
    printf("\nEnter the 2nd array elements:\n");
    for(j=0; j< n; j++)
    scanf("%d", &s[j] );

    for(j=0; j< n; j++)  // to store 's' elements to 'f'
    {
        f[i]=s[j];
        i++;
    }
    printf("\nBefore descending, the merged array is:\n");
    for(i=0; i< m+n; i++)
    printf("%5d",f[i] );

    for(i=0; i< m+n; i++)// to arrange the 'f' elements in Descending oder
    {
        for(j=i; j< (m+n)-1; j++)
        {
            if(f[i]< f[ j+1])
            {
                temp=f[i];
                f[i]=f[ j+1];
                f[j+1]=temp;
            }
        }
    }
    printf("\nAfter descending, the merged array is:\n");
    for(i=0; i< m+n; i++)
    printf("%5d",f[i] );
    getch();
}



Output:-


Enter the 1st array size(1-20) :4
Enter the 2nd array size(1-20) :5


Enter the 1st array elements:
12
3
45
12


Enter the 2nd array elements:
78
5
43
1
23


Before descending, the merged array is:
   12    3   45   12   78    5   43    1   23
After descending, the merged array is:
   78   45   43   23   12   12    5    3    1

Write a C program to print the given alphabet pyramid.

#include<stdio.h>
#include<conio.h>
void main( )
{
    int r,c,askey,n;
    clrscr( );
    printf("Enter the number of row:\n");
    scanf("%d",&n);

    for( r=n; r>=1; r-- )
    {
        askey=65;
        for(c=1; c<=r; c++ )
        printf("%2c", askey++ );

        askey--;

        for(c=r; c>=1; c-- )
        printf("%2c", askey--);

        printf("\n");
    }
    getch();
}

Output:- 
Enter the number of row:7

A B C D E F G G F E D C B A
A B C D E F F E D C B A
A B C D E E D C B A
A B C D D C B A
A B C C B A
A B B A
A A

Write a C program to print the given alphabet pyramid -2


#include<stdio.h>
#include<conio.h>
void main( )
{
    int r,c,askey,sp,n;
    clrscr( );
    printf("Enter the number of row:\n");
    scanf("%d",&n);
    for(r=n;r>=1;r-- )
    {
        for(sp=n-1; sp>=r; sp--)
        printf("  "); //2 spaces

        askey=65;
        for(c=1; c<=r; c++ )
        printf("%2c", askey++ );

        for(c=r-1; c>=1; c-- )
        printf("%2c", --askey-1);

        printf("\n");
    }
    getch();
}


Output:-
Enter the number of row:7

A B C D E F G F E D C B A
  A B C D E F E D C B A
    A B C D E D C B A
      A B C D C B A
        A B C B A
          A B A
            A

Write a C program to find a peculiar two digit number which is three times the sum of its digits

//    example:- 27
//    =3(2+7)
//    =3(9)
//    =27

#include<stdio.h>
#include<conio.h>
void main()
{
int n,sum=0,rem,temp;
clrscr();
printf("Enter any two digit number:");
scanf("%d",&n);
for(temp=n;temp>0;temp=temp/10)
{
rem=temp%10;
sum=sum+rem;
}
if(n==(sum*3))
printf("\nIts a Peculiar two digit number");
else
printf("\nNot a Peculiar two digit number");
getch();
}

Write a C program that adds n number of terms of the following series 1/1! +2/2! + 3/3! + ..........

#include<stdio.h>
#include<conio.h>
void main( )
{
    int n,i,j,fact;
    float sum=0;
    clrscr();
    printf("Enter the number of terms:\n");
    scanf("%d",&n);
    for(i=1;i<=n;i++)
    {
        fact=1;
        for(j=i;j>=1;j--) // to find the factorial
        fact=fact*j;
        sum=sum+(float)i/fact;
    }
    printf("\nSum : %f",sum);
    getch();
}

Write a c program to find the sum of 1+2+3+.....+n

#include<stdio.h>
#include<conio.h>
void main()
{
    int n,i,sum=0;
    clrscr();
    printf("Enter the 'n' value:");
    scanf("%d",&n);
    for(i=1; i<=n; i++)
    {
        sum=sum+i;
    }
    printf("\nSum of the 'n' terms: %d",sum);
    getch();
}

Write a C program to find the exponential series of 1+x+ x2/2! + x3/3! + ........ + xn/n!

#include<stdio.h>
#include<conio.h>
#include<math.h>

void main()
{
    int x,n,fact,i,j;
    float sum=1;
    clrscr();
    printf("Enter the 'x' value:\n");
    scanf("%d",&x);
    printf("\nEnter the 'n' value:\n");
    scanf("%d",&n);
    for(i=1;i<=n;i++)
    {
        fact=1;
        for(j=i;j>=1;j--)
        fact=fact*j;
        sum=sum+(pow(x,i)/fact);
    }
printf("\nSum of the series : %f ",sum);
getch( );
}

Write a c program to find the GCD of two numbers

#include<stdio.h>
#include<conio.h>
void main()
{
    int a,b,max,min,r;
    clrscr();
    printf("Enter the values of a,b\n");
    scanf("%d%d",&a,&b);
    if(a>b)
    {
        max=a;
        min=b;
    }
    else
    {
        max=b;
        min=a;
    }

    while((max%min)!=0)
    {
        r=max%min;
        if(r==0)
        {
            break;
        }
        max=min;
        min=r;
    }
    printf("GCD=%d",min);
    getch();
}

If five digit number is input through keyboard,write a program to print a new number by adding one to each of its digit

If a five digit number is input through keyboard ,write a program to print a new number by adding one to each of tis digits for example a number is input is 12391 then the output should be displayed as 23502 .

#include< stdio.h>
#include< conio.h>
int main()
{
long int no,sum=0;
int rem,check=0;
clrscr( );
printf("Enter the required number:");
scanf("%ld",&no);
printf("\nGiven Number: %d",no);
while(no>0) // to store the number in reverse by adding one to each digit
{
rem=no%10;
if(rem!=9)
{
if(check==0) // imp , try to take few minutes here
sum=(10*sum)+(rem+1);
else{
sum=(10*sum)+(rem+2);
check=0;
}
} //if closed
else{
sum=(10*sum)+0;
check=1;
}
no=no/10;
} // while closed

// Afftr adding , again to print the reverse number in origianl form.

no=sum; sum=0;
while(no>0)
{
rem=no%10;
sum=(10*sum)+rem;
no=no/10;
}
printf("\nAfter Adding one: %ld",sum);
getch( );
return 0;
}

Output:
Enter the reuired Number: 12391
Given Number: 12391
After Adding one to each of its digits: 23502

Prime Number Using Recursion

#include<stdio.h>

int isPrime(int);

int main(){

    int num,prime;

    printf("Enter a positive number: ");
    scanf("%d",&num);

    prime = isPrime(num);

   if(prime==1)
        printf("%d is a prime number",num);
   else
      printf("%d is not a prime number",num);

   return 0;
}

int isPrime(int num){

    static int i=2;

    if(i<=num/2){
         if(num%i==0)
             return 0;
         else{
             i++;
             isPrime(num);
         }
    }

    return 1;
}

C Interview Questions

1. Write a c program without using any semicolon which output will : Hello word.


Solution: 1
void main(){
    if(printf("Hello world")){
    }
}
Solution: 2
void main(){
    while(!printf("Hello world")){
    }
}
Solution: 3
void main(){
    switch(printf("Hello world")){
    }
}

2. Write a C program to Swap two variables without using third variable.

int main()
{
    int a=5,b=10;
//process one
    a=b+a;
    b=a-b;
    a=a-b;
    printf("a= %d  b=  %d",a,b);

//process two
    a=5;
    b=10;
    a=a+b-(b=a);
    printf("\na= %d  b=  %d",a,b);
//process three
    a=5;
    b=10;
    a=a^b;
    b=a^b;
    a=b^a;
    printf("\na= %d  b=  %d",a,b);
  
//process four
    a=5;
    b=10;
    a=b-~a-1;
    b=a+~b+1;
    a=a+~b+1;
    printf("\na= %d  b=  %d",a,b);
  
//process five
    a=5,
    b=10;
    a=b+a,b=a-b,a=a-b;
    printf("\na= %d  b=  %d",a,b);
    getch();

}

3. What is dangling pointer in c?

If any pointer is pointing the memory address of any variable but after some variable has deleted from that memory location while pointer is still pointing such memory location. Such pointer is known as dangling pointer and this problem is known as dangling pointer problem.

Initially:


Later: 


4. What is wild pointer in c ?

A pointer in c which has not been initialized is known as wild pointer.

Example:

(q)What will be output of following c program?

void main(){
int *ptr;
printf("%u\n",ptr);
printf("%d",*ptr);

}

Output: Any address
Garbage value

Here ptr is wild pointer because it has not been initialized.
There is difference between the NULL pointer and wild pointer. Null pointer points the base address of segmentwhile wild pointer doesn’t point any specific memory location.

5. What is the meaning of prototype of a function ?

Prototype of a function
Answer: Declaration of function is known as prototype of a function. Prototype of a function means
(1) What is return type of function?
(2) What parameters are we passing?
(3) For example prototype of printf function is:
int printf(const char *, …);
I.e. its return type is int data type, its first parameter constant character pointer and second parameter is ellipsis i.e. variable number of arguments.


6. What are merits and demerits of array in c?

(a) We can easily access each element of array.
(b) Not necessity to declare two many variables.
(c) Array elements are stored in continuous memory location.

Demerit:
(a) Wastage of memory space. We cannot change size of array at the run time.
(b) It can store only similar type of data.

Tuesday 24 January 2012

Insert Substring into String

c program to insert substring into a string

c program to insert substring into a string: This code inserts the target string into the source string. For example if the source string is "c programming" and target string is " is amazing" (please note there is space at beginning) and if we add target string to source string at position 14 then we obtain the string "c programming is amazing". In our c code we will make a function which perform the desired task and we pass three arguments to it the source string, target string and position. You can insert the string at any valid position.



#include <stdio.h>
#include <conio.h>
#include <string.h>
#include <stdlib.h>

void insert_substring(char*, char*, int);
char* substring(char*, int, int);

void main()
{
    char text[100], substring[100];
    int position;
    clrscr();
    printf("Enter some text\n");
    gets(text);
    printf("Enter the string to insert\n");
    gets(substring);
    printf("Enter the position to insert\n");
    scanf("%d", &position);
    insert_substring(text, substring, position);
    printf("%s\n",text);
    getch();
}

void insert_substring(char *a, char *b, int position)
{
    char *f, *e;
    int length;
    length = strlen(a);
    f = substring(a, 1, position - 1 );
    e = substring(a, position, length-position+1);
    strcpy(a, "");
    strcat(a, f);
    free(f);
    strcat(a, b);
    strcat(a, e);
    free(e);
}

char *substring(char *string, int position, int length)
{
    char *pointer;
    int c;
    pointer = malloc(length+1);
    if( pointer == NULL )
    exit(EXIT_FAILURE);
    for( c = 0 ; c < length ; c++ )
    *(pointer+c) = *((string+position-1)+c);
    *(pointer+c) = '\0';
    return pointer;
}

Pattern Matching

c program for pattern matching, pattern matching in c

Pattern matching in c: C programming code to check if a given string is present in another string, For example the string "programming" is present in "c programming". If the string is present then it's location (i.e. at which position it is present) is printed. We create a function match which receives two character pointers and return the position if matching occurs otherwise returns -1. We are implementing naive string search algorithm in our c program



#include<stdio.h>
#include<conio.h>

int match(char*, char*);

void main()
{
    char a[100], b[100];
    int position;
    clrscr();
    printf("Enter some text\n");
    gets(a);
    printf("Enter a string to find\n");
    gets(b);
    position = match(a, b);
    if(position!=-1)
    printf("Found at location %d\n", position+1);
    else
    printf("Not found.\n");
    getch();
}

int match(char *a, char *b)
{
    int c;
    int position = 0;
    char *x, *y;
    x = a;
    y = b;
    while(*a)
    {
        while(*x==*y)
        {
            x++;
            y++;
            if(*x=='\0'||*y=='\0')
            break;
        }
        if(*y=='\0')
        break;
        a++;
        position++;
        x = a;
        y = b;
    }
    if(*a)
    return position;
    else
    return -1;
}

Next Prime Palindrome

C program to find next prime palindrome

C program to find next prime palindrome: In this code user will enter a number(say n) and we have to find a number greater than n which is a palindrome as well as prime. For example if the input is 7 then output will be 11 as it is prime as well as palindrome, if input is 21 then output will be 101. In our code we first check if a number is palindrome and then check if it is prime as it will take less time as primes occur more frequently then palindromes.



#include<stdio.h>
#include<conio.h>
#include<math.h>
#define TRUE 1

void main()
{
    long n, t, b = 0, c, d;
    clrscr();
    printf("Enter an integer\n");
    scanf("%ld",&n);      /* n must be a natural number */
    while(TRUE)
    {
        n++;
        t=n;
        while(t)
        {
            b*=10;   /* Compound assignment operator b*=10 => b=b*10 */
            b+=t%10;
            t/=10;
        }
        if(b==n)
        {
            d=(int)sqrt(n);
            for(c=2; c<=d; c++)
            {
                if(n%c==0)
                break;
            }
            if(c==d+1)
            break;
        }
        b=0;
    }
    printf("%ld\n",n);
    getch();
}

Anagrams

anagram in c

Anagram in c: c program to check whether two strings are anagrams or not, string is assumed to consist of alphabets only. Two words are said to be anagrams of each other if the letters from one word can be rearranged to form the other word. From the above definition it is clear that two strings are anagrams if all characters in both strings occur same number of times. For example "abc" and "cab" are anagram strings, here every character 'a', 'b' and 'c' occur only one time in both strings. Our algorithm tries to find how many times characters appears in the strings and then comparing their corresponding counts.



#include<stdio.h>
#include<conio.h>

int check(char [], char []);

void main()
{
    char a[100], b[100];
    int flag;
    printf("Enter first string\n");
    gets(a);
    printf("Enter second string\n");
    gets(b);
    flag = check(a,b);
    if (flag == 1)
    printf("\"%s\" and \"%s\" are anagrams.\n", a, b);
    else
    printf("\"%s\" and \"%s\" are not anagrams.\n", a, b);
    getch();
}

int check(char a[], char b[])
{
    int first[26] = {0}, second[26] = {0}, c = 0;
    while ( a[c] != '\0' )
    {
        first[a[c]-'a']++;
        c++;
    }
    c = 0;
    while ( b[c] != '\0' )
    {
        second[b[c]-'a']++;
        c++;
    }
    for ( c = 0 ; c < 26 ; c++ )
    {
        if( first[c] != second[c] )
        return 0;
    }
    return 1;
}

Moving Car

#include <graphics.h>
#include <dos.h>
#include <conio.h>

main()
{
    int i, j = 0, gd = DETECT, gm;
    initgraph(&gd,&gm,"D:\\TC\\BGI");
    settextstyle(DEFAULT_FONT,HORIZ_DIR,2);
    outtextxy(25,240,"Press any key to view the moving car");
    getch();
    setviewport(0,0,639,440,1);
    for( i = 0 ; i <= 420 ; i = i + 10, j++ )
    {
        rectangle(50+i,275,150+i,400);
        rectangle(150+i,350,200+i,400);
        circle(75+i,410,10);
        circle(175+i,410,10);
        setcolor(j);
        delay(100);
        if( i == 420 )
        break;
        clearviewport();
    }
    getch();
    closegraph();
    return 0;
}

Captcha Program

#include<stdlib.h>
#include<dos.h>
#include<graphics.h>

main()
{
    int i = 0, key, num, midx, gd = DETECT, gm;
    char a[10];
    initgraph(&gd,&gm,"D:\\TC\\BGI");
    midx = getmaxx()/2;
    settextstyle(SCRIPT_FONT,HORIZ_DIR,5);
    settextjustify(CENTER_TEXT,CENTER_TEXT);
    setcolor(GREEN);
    outtextxy(midx,20,"CAPTCHA");
    settextstyle(SCRIPT_FONT,HORIZ_DIR,2);
    outtextxy(midx,125,"Press any key to change the generated random code \"captcha\"");
    outtextxy(midx,150,"Press escape key to exit...");
    setcolor(WHITE);
    setviewport(100,200,600,400,1);
    setcolor(RED);
    randomize();
    while(1)
    {
        while(i<6)
        {
            num = random(3);
            if ( num == 0 )
            a[i] = 65 + random(26);     /* 65 is the ASCII value of A */
            else if ( num == 1)
            a[i] = 97 + random(26);     /* 97 is the ASCII value of a */
            else
            a[i] = 48 + random(10);     /* 48 is the ASCII value of 0 */
            i++;
        }
        a[i] = '\0';
        outtextxy(210,100,a);
        key = getch();
        if( key == 27 )                     /* escape key*/
        exit(0);
        clearviewport();
        i = 0;
    }
}