Search This Blog

C Program for Reflection Transformation for Computer Graphics Lab

Reflection is one of the 2d transformation operations in computer graphics. Here i present a c program to implement reflection. The reflection transformation can be applied on any polygon given by user using this c program. Reflection of points is done which results is reflection of lines or polygons drawn from the points. The reflection transformation is sometimes called flipping or mirroring. Reflection of a polygon about horizontal axis is called vertical flip and reflection about vertical axis is called vertical flip. Whatever we call, flipping or reflecting it is producing mirror image about an axis. The following c program performs reflection transformation on given polygon about both axes.

C Program for Shear Transformation - Shear Transformation in 2D Computer Graphics

Shear transformation or shearing is one of the 2d transformations in computer graphics. Here i present a c program for shear transformation of polygons. The shear transformation works as follows:

For shearing along X axis, shearfactor* (y coordinate) is added with x co-ordinates of all points. That is:
newx=oldx+shearfactor*oldy

Similarly, to shear along Y axis, we add shearfactor* (x coordinate) to y co-ordinates of all points.
newy=oldy+shearfactor*oldx

C Program for Scaling 2D transformation - Scaling Polygons in Computer Graphics

This is a c program for scaling transformation in computer graphics. Scaling is one of the important 2d transformations in computer graphics. The program will tell you how to scale lines or polygons. This CG lab program in c language using the graphics library reads the number of sides of polygon, co-ordinates of its vertices and the scale factors in horizontal and vertical directions. It displays the original polygon and scaled polygon in different colors in same screen. More Computer graphics lab problems are available under related posts heading.


C Program for Rotation of Polygon - 2D Transformation in Computer Graphics

This is a c program for rotation transformation in computer graphics. Rotation is one of the important 2d transformations in computer graphics. The program will tell you how to rotate points or polygon around a point (the pivot point). This CG lab program in c language using the graphics library reads the number of sides of polygon, co-ordinates of its vertices, the pivot point for rotation, and angle of rotation. It displays the original polygon and rotated polygon in different colors in same screen. More Computer graphics lab problems are available under related posts heading.


C Program for Translation 2D Transformation in Computer Graphics

This is a c program for translation transformation in computer graphics. Translation (or shifting) is a very basic 2d transformation operation in computer graphics. Translation or shifting is done by adding the distance to shifted to the co-ordinates. For example, if we want to shift a polygon 50 units (pixels) horizontally, we just have to add 50 to x co-ordinates of all vertices of the polygon. Similarly, if it is translate only vertically by 100 unit, add 100 to y co-ordinates of all vertices. This CG lab program in c language using the graphics library reads the number of sides of polygon, co-ordinates of its vertices and the translation distance along both axes. It displays the original polygon and translated polygon in different colors in same screen. This is only a very simple and basic Computer graphics lab problem.


2D Transformations C Program - Computer Graphics Lab 2D Transformation

The main two dimensional transformation operations in computer graphics are: translation or shifting, scaling, rotation, reflection (or flipping) and shearing. Here in this c program, we can do all these transformations on any polygon. Rotation can be done about any pivot point. Reflection includes reflection about horizontal axis (flip horizontal) and reflection about vertical axis (flip vertical). Similarly, shear transformation is also done about horizontal axis (x-axis) and vertical axis (y-axis). The input to the program are number of sides of polygon and its vertices.


Two Stroke Engine Piston Movement Animation C Program - CG Lab Program

This program simulates the motion of the components of a two stroke engine. It shows the movement of piston, connecting rod and crank by animating them in c. The program uses the graphics library (grapics.h) to simulate the piston movement in two stroke engine. This is a computer graphics lab (CG lab) problem. The program is given below. The program uses sin and cos functions to simulate the crank. Also it uses the equation to find the distance between to points.


Output:



Program


#include<stdio.h>
#include<graphics.h>
#include<math.h>
#include<stdlib.h>
void main()
{
int gd=DETECT,gm;
int tt,midx,midy,radius=40,rodlen=150,deg=0,jointx,jointy,px;
float radian,sqrodlen,t;
initgraph(&gd,&gm,"C:\\TURBOC3\\BGI\\");
midx=getmaxx()/2;
midy=getmaxy()/2;
sqrodlen=rodlen*rodlen;

while(!kbhit())
 {
 circle(midx,midy,radius);
 radian=(float)deg*3.14f/180;
 jointx=midx+radius*sin(radian);
 jointy=midy+radius*cos(radian);
 line(midx,midy,jointx,jointy);
 t=pow(jointy-midy,2);
 tt=(int)sqrt(sqrodlen-t);
 px=jointx-tt;
 line(jointx,jointy,px,midy);
 rectangle(px-30,midy-10,px+20,midy+10);
 rectangle(px-45,midy-35,px-30,midy+35);
 rectangle(midx-240,midy-35,midx-90,midy+35);
 deg+=10;
 delay(80);
 cleardevice();
 }
}

Program to Display Multiplication Table of All Numbers From 1 to 10

This is  a C program to display multiplication tables of all number from 1 to 10. To see c program to display multiplication table of given number only, see this program:
Program to Display Multiplication Table of Given Number

#include<stdio.h> int main() {   int i,j;   for(i=1;i<=10;i++){       for(j=1;j<=10;j++)            printf("%1d*%1d=%2d ",i,j,i*j);       printf("\n");   }   return 0; }

Output:

1*1= 1 1*2= 2 1*3= 3 1*4= 4 1*5= 5 1*6= 6 1*7= 7 1*8= 8 1*9= 9 1*10=10
2*1= 2 2*2= 4 2*3= 6 2*4= 8 2*5=10 2*6=12 2*7=14 2*8=16 2*9=18 2*10=20
3*1= 3 3*2= 6 3*3= 9 3*4=12 3*5=15 3*6=18 3*7=21 3*8=24 3*9=27 3*10=30
4*1= 4 4*2= 8 4*3=12 4*4=16 4*5=20 4*6=24 4*7=28 4*8=32 4*9=36 4*10=40
5*1= 5 5*2=10 5*3=15 5*4=20 5*5=25 5*6=30 5*7=35 5*8=40 5*9=45 5*10=50
6*1= 6 6*2=12 6*3=18 6*4=24 6*5=30 6*6=36 6*7=42 6*8=48 6*9=54 6*10=60
7*1= 7 7*2=14 7*3=21 7*4=28 7*5=35 7*6=42 7*7=49 7*8=56 7*9=63 7*10=70
8*1= 8 8*2=16 8*3=24 8*4=32 8*5=40 8*6=48 8*7=56 8*8=64 8*9=72 8*10=80
9*1= 9 9*2=18 9*3=27 9*4=36 9*5=45 9*6=54 9*7=63 9*8=72 9*9=81 9*10=90
10*1=10 10*2=20 10*3=30 10*4=40 10*5=50 10*6=60 10*7=70 10*8=80 10*9=90 10*10=100

Program to Display Multiplication Table of Given Number

This is a c program to display multiplication table of given number. For program to display multiplication table of all numbers from 1 to 10, see this post: Program to display multiplication table of all numbers from 1 to 10
#include <stdio .h>
void main()
{
    int n, i;
    printf("Enter the number:");
    scanf("%d",&n);
    for(i=1; i<=10; ++i)
        printf("%d * %d = %d \n", i, n, n*i);
}

Output:

Enter the number:5
1 * 5 = 5
2 * 5 = 10
3 * 5 = 15
4 * 5 = 20
5 * 5 = 25
6 * 5 = 30
7 * 5 = 35
8 * 5 = 40
9 * 5 = 45
10 * 5 = 50

C Program for Matrix Multiplication

This is a c program for Matrix Multiplication. To understand how it works, you should first know how matrix multiplication is done mathematically.

#include <stdio.h>
void main()
{
int m1[10][10],i,j,k,m2[10][10],prod[10][10],r1,c1,r2,c2;
printf("Enter number of rows and columns of first matrix:\n");
scanf("%d%d",&r1,&c1);
printf("Enter number of rows and columns of second matrix:\n");
scanf("%d%d",&r2,&c2);
if(r2==c1)
    {
    printf("Enter elements of First matrix (row wise):\n");
    for(i=0;i<r1;i++)
        for(j=0;j<c1;j++)
            scanf("%d",&m1[i][j]);
    printf("Matrix1 is :\n");
    for(i=0;i<r1;i++)
        {
        for(j=0;j<c1;j++)
            printf("%d ",m1[i][j]);
        printf("\n");
        }
    printf("Enter elements of Second matrix (row wise):\n");
    for(i=0;i<r2;i++)
        for(j=0;j<c2;j++)
            scanf("%d",&m2[i][j]);
    printf("Matrix2 is:\n");
    for(i=0;i<r2;i++)
        {
        for(j=0;j<c2;j++)
            printf("%d ",m2[i][j]);
        printf("\n");
        }
    printf("Product of the Matrices (M1 x M2):\n");
    for(i=0;i<r1;i++)
        {
        for(j=0;j<c2;j++)
            {
            prod[i][j]=0;
            for(k=0;k<r1;k++)
                prod[i][j]+=m1[i][k]*m2[k][j];
            printf("%d\ ",prod[i][j]);
            }
        printf("\n");
        }
    }
else
    {
    printf("Matrices can't be multiplied.\n");
    printf("No. of columns of first matrix and no of rows of second are different.");
    }
}

Program to Find Power of a Number

This is a c program to calculate power of a given number. The inputs are the number and its exponent (power). For example, if you give m and n, the result is m^n.

#include<stdio.h>
int main()
{
    int m, n, i,p=1;
    printf("Enter the number and its power (exponent)\n");
    scanf("%d%d",&m,&n);
    for( i = 0 ; i < n ; i++ )
        p*=m;
    printf("%d raised to %d is: %d",m,n,p);
}

Output:

Enter the number and its power (exponent) 2 3 2 raised to 3 is: 8

Program to Find Transpose of a Matrix

This is a c program to find the transpose of a matrix. Finding transpose of a matrix is simple like displaying the matrix. You just have to interchange i and j at the matrix indices.
#include<stdio.h>
int main()
{
    int m, n, i, j;
    int mat[10][10], trans[10][10];
    printf("Enter the number of rows and columns of matrix\n");
    scanf("%d%d",&m,&n);
    printf("\nEnter the elements of matrix \n");
    for( i = 0 ; i < m ; i++ )
        {
        for( j = 0 ; j < n ; j++ )
            scanf("%d", &mat[i][j] );
        }

    for( i = 0 ; i<m ; i++ )
        {
        for( j = 0 ; j < n ; j++ )
            trans[j][i] = mat[i][j];
        }
    printf("Transpose is:\n ");
    for( i = 0 ; i < n ; i++ )
        {
        printf("\n");
        for( j = 0 ; j < m ; j++ )
            printf("%d\t ", trans[i][j] );
        }
}

C Program to Find Inverse of a Matrix

This is a c program to find the inverse of matrix. If M is the matrix and M-1 is its inverse, M x M-1 gives I (identity matrix). Inverse of a matrix M is:
adjoint(M) / det(M)
If determinant is zero, the matrix is not invertible. Adjoint of matrix M is transpose of cofactor matrix of M.


The c program to find inverse of matrix is as follows:


#include<stdio.h>
#include<math.h>
float detrminant(float[][], float);
void cofactors(float[][], float);
void trans(float[][], float[][], float);
main()
{
float a[25][25], n, d;
int i, j;
printf("Enter the order of the matrix:\n");
scanf("%f", &n);
printf("Enter the elemnts into the matrix:\n");
for (i = 0; i < n; i++)
 {
 for (j = 0; j < n; j++)
  scanf("%f", &a[i][j]);
 }
d = detrminant(a, n);
printf("\nTHE DETERMINANT IS=%2f", d);
if (d == 0)
 printf("\nMATRIX IS NOT INVERSIBLE\n");
else
 cofactors(a, n);
}

float detrminant(float a[25][25], float k)
{
float s = 1, det = 0, b[25][25];
int i, j, m, n, c;
if (k == 1)
 return (a[0][0]);
else
 {
 det = 0;
 for (c = 0; c < k; c++)
  {
  m = 0;
  n = 0;
  for (i = 0; i < k; i++)
   {
   for (j = 0; j < k; j++)
    {
    b[i][j] = 0;
    if (i != 0 && j != c)
     {
     b[m][n] = a[i][j];
     if (n < (k - 2))
      n++;
     else
      {
      n = 0;
      m++;
      }
     }
    }
   }
  det = det + s * (a[0][c] * detrminant(b, k - 1));
  s = -1 * s;
  }
 }
return (det);
}

void cofactors(float num[25][25], float f) {
float b[25][25], fac[25][25];
int p, q, m, n, i, j;
for (q = 0; q < f; q++)
 {
 for (p = 0; p < f; p++)
  {
  m = 0;
  n = 0;
  for (i = 0; i < f; i++)
   {
   for (j = 0; j < f; j++)
    {
    b[i][j] = 0;
    if (i != q && j != p)
     {
     b[m][n] = num[i][j];
     if (n < (f - 2))
      n++;
     else
      {
      n = 0;
      m++;
      }
     }
    }
   }
  fac[q][p] = pow(-1, q + p) * detrminant(b, f - 1);
  }
 }
trans(num, fac, f);
}

void trans(float num[25][25], float fac[25][25], float r)
{
int i, j;
float b[25][25], inv[25][25], d;
for (i = 0; i < r; i++)
 {
 for (j = 0; j < r; j++)
  b[i][j] = fac[j][i];
 }
d = detrminant(num, r);
inv[i][j] = 0;
for (i = 0; i < r; i++)
 {
 for (j = 0; j < r; j++)
  inv[i][j] = b[i][j] / d;
 }
printf("\nTHE INVERSE OF THE MATRIX:\n");
for (i = 0; i < r; i++)
 {
 for (j = 0; j < r; j++)
  printf("\ %2f", inv[i][j]);
 printf("\n");
 }
}

C Program to Check Perfect Number

This is a c program to check whether a given number is a perfect number or not. But, what is a perfect number? If the sum of all proper divisors of a number is equal to the number itself, it is a perfect number. Proper divisors of a number means all its divisors except the number itself. A perfect number is a positive integer which is equal to sum of its proper divisors. An example is 6. 6 = 1 + 2 + 3. 28 is also an example for perfect number (1+2+4+7+14=28).

The following program checks a given number and tells whether it is a perfect number or not.
#include<stdio.h>
int main()
{
int n,i=1,sum=0;
printf("Enter a number:");
scanf("%d",&n);
while(i<n)
    {
    if(n%i==0)
        sum=sum+i;
    i++;
    }
if(sum==n)
    printf("%d is a perfect number",i);
else
    printf("%d is not a perfect number",i);
return 0;
}

How to Get Random Number in C

C Language has functions to generate random numbers. It is not actually random number. Computer cannot generate real random number. Rather they produce pseudo random number. We will see later in another post how pseudo random number generator work. In this post, we will see how to use pseudo random number generation functions in C.

The function rand() is used to get random number. The random numbers generated by the function depend on a an initial 'seed'. We may use time as seed here. We will give current time as initial seed by calling srand() function. Calling time(NULL) will return current time. It is in time.h library. Thus srand(time(NULL)) will set initial seed as current time. As we call rand(), we will get different random numbers. The random numbers start from zero (inclusive). To set a maximum value for random number, we may use the % operator.


rand()%10 returns random number from 0 to 9 (inclusive).
rand()%50 returns random number from 0 to 49 (inclusive).
rand()%51 returns random number from 0 to 50 (inclusive).
rand()%101 returns random number from 0 to 100 (inclusive).

Therefore we may say,
rand()%max returns random number from 0 to max-1.

To get random number from 50 to 99 (inclusive):
use 50+rand()%(100-50)

In general, to get a random number from min to max (including min and max) use the following code:

min+rand()%(max+1-min)


#include<stdio.h> #include<stdlib.h> #include<time.h> main() { int min,max,rnum,i; printf("Enter the minimum and maximum value of random number"); scanf("%d%d",&min,&max); printf("Five random numbers from %d to %d are :\n",min,max); srand(time(NULL)); for(i=0;i<5;i++) printf("%d, ",min+rand()%(max+1-min)); getch(); }

Program to List All Prime Numbers Less Than Given Number

This is a c program to list all prime numbers less than a given number. Within a loop it checks each number less than the given number, whether it is prime or not.

Program to Check Whether a Number is Prime or Not

This is a c program to check whether a given number is prime or not. To check whether a number 'n' is prime or not, it is enough to check whether it is divisible by any number less than or equal to square root of n. If there is any number i less than or equal to square root of n which divides n completely, then it is not prime. Otherwise it is prime.

Program to Swap Numbers with Bitwise (EXOR) Operators

Here is a c program to swap two numbers. This method of swapping does not use a third (temporary) variable. Instead, swapping is done by bitwise operation. We perform bitwise EXOR operations on the two numbers. The program is as follows:

#include<stdio.h>
void main()
{ int x,y; x=200; y=140; printf("\nBefore swapping x=%d,y=%d",x,y); x=x^y; y=x^y; x=x^y; printf("\nAfter swapping x=%d y=%d",x,y); }

Array Rearrangement Without Another Array - Zoho Programming Round Question


Question:

You are given two integer arrays. The first one is a set of integers which you should rearrange and produce an output array based on the second array. The second array, we call it Order array, is an array which directs the rearrangement by specifying the required position of each element in given array. You should rearrange the elements just as specified by the order array without using any additional arrays. You should write a c program to rearrange the number array but without using another array. An example is as follows:

number array: 46   80  10   8    7    2   11   16  17  43
order array   :  5     2    0   6    8    7    1     3    4   9
output          :  2    10  46  11  17  16   80    8   7    43


Problem Explanation:

order[0]=5 means the current element at index 5 in the given number array should be at index 0 in the desired array. Similarly order[1]=2 means  the current element at index 2 in the given number array (10) should come at index 1 in the desired array.

Thus, the question is to write a c program to rearrange the given array without using another array to produce the desired array as specified by the order array.

This was one of the questions asked in a programming test conducted as a part of recruitment process of Zoho corporation, an IT firm. This is one of the tough c programming questions asked in second hands on coding round.

Before answering the question, you must know that it is possible to produce the desired output array without actually performing the rearrangement. It is not so difficult.The following code fragment can do it.

for(i=0;i<10;i++)
printf("%d  ",nums[order[i]]);

As emphasized in the question, the array should be rearranged, but your are not allowed to use any additional arrays.

Answer:

Actually, this can't be done without additional allocation of memory. But, to answer this question, we should avoid explicit use of additional arrays. So, we can make use of recursion. In fact, for each call of a recursive function, memory is allocated in stack for its local variables. We make use of recursion to exploit the stack. I would first write the program, then explain it.

#include<stdio.h>
int nums[]={ 46,80,10,8,7,2,11,16,17,43};
int order[]={5,2,0,6,8,7,1,3,4,9};
int i;
void rec(int index)
{
int num;
num=nums[order[index]];
if(index<9)
rec(index+1);
nums[index]=num;
}
void main()
{
printf("rearranging\n");
i=0;
rec(i);
printf("rearranged:\n");
for(i=0;i<10;i++)
printf("%d  ",nums[i]);
}


The parameter index in each recursion stores the index (position) and local variable num stores the desired number at that position. Thus value of parameter 'index' varies from 0 to 9 (here) and corresponding number at the index is also held in variable num. Thus, after the last call of recursive function, the whole array (index and the number at that index) get stored in stack. Only after this, the num is placed at its index.

C Program to Convert Between Hexadecimal, Octal, Binary and Decimal Numbers

This program deals with four number systems. They are:

  • Decimal (base 10)
  • Binary (base 2)
  • Octal (base 8)
  • Hexadecimal (base 16)
Here i post a  program for following operations:
  • Decimal to binary conversion
  • Decimal to Octal conversion
  • Decimal to Hexadecimal conversion
  • Binary to Decimal conversion
  • Binary to Octal conversion
  • Binary to Hexadecimal conversion
  • Octal to Decimal conversion
  • Octal to Binary conversion
  • Octal to Hexadecimal conversion
  • Hexadecimal to Decimal conversion
  • Hexadecimal to Binary conversion
  • Hexadecimal to Octal conversion
The following program lets you convert between the four number systems; decimal, binary, octal and hexadecimal number systems.

Octal to Decimal Converter Program - Program to Convert from Octal to Decimal

This is a c program to convert any Octal number to decimal number system. Octal number system represents numbers using digits 0 to 7. The decimal number system is the commonly used number system which uses digits 0 to 9. The following program performs conversion from octal to decimal.

Program to Convert Hexadecimal to Decimal - Hexadecimal Conversion Program

Hexadecimal number system is base 16 number system in which the digits used are 0 to 9 and A to F. Here is a c program to convert hexadecimal number to decimal number system.

Program to Convert Binary to Decimal - Binary to Decimal Converter Program

This is a c program to convert a binary number to decimal number. The input (binary number) should contain only zeros and ones. Binary number system represents numbers using only two digits; 0 and 1. The following is a binary to decimal converter program in C.

Program to Convert Decimal to Binary - Binary Converter Program

This is a C program to convert decimal numbers to Binary numbers. Binary number system is the base 2 number system. The digits used in this number system are 0 and 1 only. The program is as follows:

Program to Convert Decimal to Octal Number - Decimal to Octal converter

This is a program to convert a number in decimal (base 10) number system to octal number system. In octal number system, numbers are represented with base 8. That is, the digits are 0 to 7. The following program converts decimal numbers to octal.

Program to Convert Decimal Number to Hexadecimal Number

This program is to convert a number in decimal number system (base 10) to a hexadecimal number (base 16). I have wrote a function reversestring to reverse a string. You may use strrev function instead if available. The program is as follows:

C Program for Quick Sorting - Quick Sort Program in to Sort Numbers

Quick sort is one of the most efficient sorting algorithms. Here i post a C program to implement Quick sorting. This program is to sort given numbers is ascending order. To sort in descending order using quick sort, only slight changes are needed in program. Changes needed for sorting in descending order are marked in the program as comments.

#include<stdio.h>
void quicksort(int [10],int,int);
int main()
  {
  int x[20],size,i;
  printf("Enter size of the array: ");
  scanf("%d",&size);
  printf("Enter %d elements: ",size);
  for(i=0;i<size;i++)
     scanf("%d",&x[i]);
  quicksort(x,0,size-1);
  printf("Sorted elements: ");
  for(i=0;i<size;i++)
     printf(" %d",x[i]);
  return 0;
  }

void quicksort(int x[10],int first,int last)
  {
  int pivot,j,temp,i;
  if(first<last)
     {
     pivot=first;
     i=first;
     j=last;
     while(i<j)
        {
        while(x[i]<=x[pivot]&&i<last)//for descending, use >= instead of <=
            i++;
        while(x[j]>x[pivot])//for descending, use < instead of >=
            j--;
        if(i<j)
            {
            temp=x[i];
            x[i]=x[j];
            x[j]=temp;
            }
        }
    temp=x[pivot];
    x[pivot]=x[j];
    x[j]=temp;
    quicksort(x,first,j-1);
    quicksort(x,j+1,last);
}
}

Output:
Enter size of the array: 5

Enter 5 elements:
3
8
0
1
2
Sorted elements: 0 1 2 3 8

Algorithm and C Program to Find Candidate Key from Functional Dependencies

First of all, we will see the algorithm to find candidate keys from functional dependencies. The input is functional dependencies.

Algorithm:


1. Find the attributes that are neither on the left and right side
2. Find attributes that are only on the right side
3. Find attributes that are only on the left side
4. Combine the attributes on step 1 and 3
5. Test if the closures of attributes on step 4 constitutes all the attributes. If yes it is a candidate key.
6. If not, find the relation exteriors, that is the attributes not included in step 4 and step 2.
7. Now test the closures of attributes on step 4 + one attribute in step 6 one at a time. All those combinations are candidate keys if their closures constitute all the attributes.

C Program:



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

struct fd
 {
   int left[8],right[8];
   int lcount,rcount;
   }f[10];

int attrcount,closcount=0,fdcount,closure[10];
char attr[10][25];
int nolnor[8],ronly[8],lonly[8],merg1n3[8],exteriors[8];

void getclosure();
void get_nolnor();
void get_ronly();
void get_lonly();
void get_merg1n3();
int iscomplete();

void getclosure()
{
int i,j,k,l=0,issubset,found;
do
 {
   for(i=0;i<=fdcount;i++)//Checking each functional dependancy
    {
      issubset=1;
      for(j=0;j<f[i].lcount;j++)//select each attr in leftside
   {
         found=0;
         for(k=0;k<closcount;k++) //checking with each element of 

closure
          

{
            if(closure[k]==f[i].left[j])
             

{
               found=1;
               break;
               }
            }
         if(found==0)
    {
          

issubset=0;
            break;
            }
   }
  if(issubset==1)
       {
         for(k=0;k<f[i].rcount;k++)
          

{
            found=0;
            for(j=0;j<closcount;j++)
             

{
               if(closure[j]==f[i].right[k])
                found=1;
               }
    if(found==0)
             

{
     closure[closcount]=f[i].right

[k];
             

closcount++;
               }
            }
         }
  }
   l++;
 }while(l<attrcount);
}


void get_nolnor()
 {
   int i,found,j,k,l=0;
   for(i=0;i<attrcount;i++)//take an attribute
    {
      found=0;
      for(j=0;j<=fdcount;j++) //take an fd
          {
          for(k=0;k<f[j].lcount;k++) //check in left
           

{
            if(i==f[j].left[k])
               {
             

found=1;
               break;
               }
            }
          if(found==1) //stop if found.
           

break;
          for(k=0;k<f[j].rcount;k++) //check in right
           

{
            if(i==f[j].right[k])
               {
             

found=1;
               break;
               }
            }
          if(found==1) //stop if found.
           

break;
          }
      if(found==0)
       {
         nolnor[l]=i;
         l++;
         }
      }
 nolnor[l]=222;
 }


void get_ronly()
 {
   int rpresent,lpresent,i,j,k,l=0;
   for(i=0;i<attrcount;i++)//take an atrribute
    {
      rpresent=0;
      for(j=0;j<=fdcount;j++)//take an fd
       {
         for(k=0;k<f[j].rcount;k++)
          

{
            if(i==f[j].right[k])
             

{
               rpresent=1;
               break;
               }
            }
         if(rpresent==1)
          

break;
         }
      lpresent=0;
      if(rpresent==1)
       {
         for(j=0;j<=fdcount;j++)//take an fd
        {
          

for(k=0;k<f[j].lcount;k++)
           

{
             

if(i==f[j].left[k])
             

 {
                lpresent=1;
                break;
                }
             

}
          

if(lpresent==1)
             

break;
          

}
         }
      if(lpresent==0&&rpresent==1)
       ronly[l++]=i;
  }
   ronly[l]=222;
   }

void get_lonly()
 {
   int rpresent,lpresent,i,j,k,l=0;
   for(i=0;i<attrcount;i++)//take an atrribute
    {
      lpresent=0;
      for(j=0;j<=fdcount;j++)//take an fd
       {
         for(k=0;k<f[j].lcount;k++) //looking in leftside
          

{
            if(i==f[j].left[k])
             

{
               lpresent=1;
               break;
               }
            }
         if(lpresent==1)
          

break;
         }
      rpresent=0;
      if(lpresent==1)
       {
         for(j=0;j<=fdcount;j++)//take an fd
        {
          

for(k=0;k<f[j].rcount;k++)//checking in right side
           

{
            

  if(i==f[j].right[k])
      {
                rpresent=1;
                break;
                }
             

}
          if

(rpresent==1)
             

break;
          

}
         }
      if(lpresent==1&&rpresent==0)
         lonly[l++]=i;
      }
   lonly[l]=222;
 }


void get_merg1n3()
 {
   /* combine lonly and nolnor */
   int i,j;
   for(i=0,j=0;lonly[j]!=222;i++,j++)
    merg1n3[i]=lonly[j];
   for(j=0;nolnor[j]!=222;i++,j++)
    merg1n3[i]=nolnor[j];

   merg1n3[i]=222;
   }

int compare(char temp[25])
 {
   int i;
   for(i=0;i<attrcount;i++)
    {
      if(strcmp(temp,attr[i])==0)
      return i;
      }
   return 0;
   }


int iscomplete()
 {
   if(closcount!=attrcount)
    return 0;
   else
    return 1;
   }

void main()
 {
   int i,j,k,attcode,found;
   char schema[100],temp[45],temp1[50];
   for(i=0;i<10;i++)
    {
      f[i].lcount=0;
      f[i].rcount=0;
      }
   printf("\nEnter the schema\n");
   scanf("%s",schema);
   attrcount=0;
   for(i=0;schema[i]!='(';i++);

   do
    {
    j=0;
      i++;
    while(schema[i]!

=','&&schema[i]!=')')
     {
       temp

[j]=schema[i];
       j++;
       i++;
       }
    temp[j]='\0';
    strcpy(attr

[attrcount],temp);
  attrcount++;
      }while(schema[i]==',');

   fdcount=-1;
   printf("\nEnter the functional dependancies\nEnter 0 to stop\n");
   for(i=0;i<10;i++)
    {
      scanf("%s",temp1);
      if(strcmp(temp1,"0")==0)
       break;
      fdcount++;
      j=0;
      if(temp1[0]=='{'||temp1[0]=='(')
       j++;
      do
       {
         if(temp1[j]==',')
             

j++;
         k=0;
         while(temp1[j]!=','&&temp1[j]!=')'&&temp1[j]!

='}'&&temp1[j]!='-')
           

{
            temp[k]=temp1[j];
            k++;
            j++;
            }
            temp[k]='\0';
            attcode=compare(temp);
            f[fdcount].left[f[fdcount].lcount]=attcode;
            f[fdcount].lcount++;
         }while(temp1[j]==',');
  if(temp1[j]==')'||temp1[j]=='}')
       j+=3;
      else if(temp1[j]=='-')
       j+=2;
      if(temp1[j]=='{'||temp1[j]=='(')
       j++;
      do
       {
         if(temp1[j]==',')
             

j++;
         k=0;
         while(temp1[j]!=','&&temp1[j]!=')'&&temp1[j]!

='}'&&temp1[j]!='\0')
           

{
            temp[k]=temp1[j];
            k++;
            j++;
            }
            temp[k]='\0';
            attcode=compare(temp);
            f[fdcount].right[f[fdcount].rcount]=attcode;
            f[fdcount].rcount++;
         }while(temp1[j]==',');

  }


/**************Step1**************
1. Find the attributes that are neither on the left and right side*/
 get_nolnor();

/**************Step2*************
2. Find attributes that are only on the right side*/
   get_ronly();

/**************Step3*************
3. Find attributes that are only on the left side*/
   get_lonly();

/**************Step4*************
4. Combine the attributes on step 1 and 3*/
 get_merg1n3();  //combine 

nolnor and lonly

/**************Step5*************
5. Test if the closures of attributes on step 4 are all the attributes*/
   closcount=0;
   for(i=0;merg1n3[i]!=222;i++)
    {
      closure[closcount++]=merg1n3[i];
      }
   getclosure();
 i=iscomplete();//check whether 

closure of merg1n3 is complete
   if(i==1)
    {
      printf("\nThe candidate key is:\n{");
      for(i=0;merg1n3[i]!=222;i++)
       {
         printf("%s,",attr[merg1n3[i]]);
         }
      printf("\b ");
      printf("}");
      }
   else
    {
/************** Step 6 **************
6. Find the relation exteriors, that is the attrbutes included not in 4 and not in 2
     included not in (ronly & merg1n3)
     */
      k=0;
      for(i=0;i<attrcount;i++)
       {
         found=0;
         for(j=0;ronly[j]!=222;j++)
          

{
            if(i==ronly[j])
             

{
               found=1;
               break;
               }
            }
         if(found==0)
          

{
            for(j=0;merg1n3[j]!=222;j++)
               {
             

if(i==merg1n3[j])
             

 {
                found=1;
                break;
                }
               }
            }
         if(found==0)
          

{
            exteriors[k++]=i;
            }
         }

      exteriors[k]=222;
      printf("Candidate Keys:");
/************** Step 6 **************
7. Now test the closures of attributes on step 4 + one attribute in step 6 one at a time.
*/
    for(k=0;exteriors

[k]!=222;k++)
     {
       closcount=0;
       for

(i=0;merg1n3[i]!=222;i++)
        {
        closure

[closcount++]=merg1n3[i];
          

}
       closure

[closcount++]=exteriors[k];
       getclosure();
   i=iscomplete();//check whether 

closure of this instance of this step is complete
     if(i==1)
      {
          

printf("\n{");
          

for(i=0;merg1n3[i]!=222;i++)
         {
           

printf("%s,",attr[merg1n3[i]]);
           

}
          

printf("%s}",attr[exteriors[k]]);
          

}
       }
      }
   getch();
   } 

Sorting Numbers based on Weights - Zoho Programming Test question

You are given a set of numbers like <10, 36, 54,89,12>. You should find sum of weights based on the following conditions:

  1. 5 if a perfect square
  2. 4 if multiple of 4 and divisible by 6
  3. 3 if even number
And sort the numbers based on the weight and print it as follows:
<10,its_weight>,<36,its weight><89,its weight>
The program should display the numbers in increasing order of their their weights.


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

int getWeight(int n)
{
int w=0;
float root=sqrt(n);
if(root==ceil(root))
    w+=5;
if(n%4==0&&n%6==0)
    w+=4;
if(n%2==0)
    w+=3;
return w;
}

void main()
{
int nums[15];
int ws[15];
int i,j,t,n;
printf("Enter number of numbers");
scanf("%d",&n);
printf("\nEnter numbers");
for(i=0;i<n;i++)
    scanf("%d",&nums[i]);
for(i=0;i<n;i++)
    ws[i]=getWeight(nums[i]);
printf("\nBefore sorting:\n");
for(i=0;i<n;i++)
    printf("%d:%d\t",nums[i],ws[i]);
for(i=0;i<n;i++)
    for(j=0;j<n-i-1;j++)
        if(ws[j]>ws[j+1])
            {
            t=ws[j+1];
            ws[j+1]=ws[j];
            ws[j]=t;
            t=nums[j+1];
            nums[j+1]=nums[j];
            nums[j]=t;
            }
printf("\nSorted:\n");
for(i=0;i<n;i++)
    printf("%d:%d\t",nums[i],ws[i]);
}

C Program to Validate Sudoku - Checking Correctness of Sudoku

Here we shall see a c program to validate sudoku a sudoku. The c program i have written here checks the correctness of a sudoku. The programs can be used to check sudoku solution for 9x9 sudoku. First of all, we should know what are the constraints.
  • Each row should contain all numbers from 1 to 9 (inclusive)
  • Each column should contain all numbers from 1 to 9 (inclusive)
  • The 3x3 squares should also contain all numbers from 1 to 9 (inclusive)
If all above conditions are satisfied, the sudoku is correct. The c program to check whether a solution for a sudoku is correct is as follows:

#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>

void report(char *s,int i,int j)
{
printf("\nThe sudoku is INCORRECT");
printf("\nin %s. Row:%d,Column:%d",s,i+1,j+1);
getch();
exit(0);
}

void main()
{
int i,j,a[9][9];
char c;
int si,sj,flag;
printf("\nEnter the sudoku");
/*
Going to read sudoku matrix (9x9).
Since numbers 1 to 9 are single digit,
it is enough to read them as char.
To convert them from their ascii to int,
subtract ascii of '0' from the character.
*/
for(i=0;i<9;i++)
    for(j=0;j<9;j++)
    {
    scanf("%c",&c);
    a[i][j]=c-'0';
    }
/*++++++++++++++++++
checking rows
+++++++++++++++++++
we check each cell in each row.
We start with a flag 0x0000.
if 1 is found zeroth bit of flag is set.
if 2 is found, first bit is set
and so on.
If all digits 1 to 9 are present, flag's value
will be 0x01FF.
If flag is 0x01FF after traversing a row,
the row has all numbers 1 to 9.
So, it is correct.
If the flag is not 0x01FF after traversing a row,
the row is incorrectly filled.
Then we call report() function
*/
for(i=0;i<9;i++)
    {
    flag=0x0000;
    for(j=0;j<9;j++)
        flag|=1<<(a[i][j]-1);
    if(flag!=0x01FF)
        report("row",i,j-1);
    }

/*++++++++++++++++++
checking columns
+++++++++++++++++++
Just like row checking.
The flag is for a column.
*/
for(j=0;j<9;j++)
    {
    flag=0x0000;
    for(i=0;i<9;i++)
        flag|=1<<(a[i][j]-1);
    if(flag!=0x01FF)
        report("col",i-1,j);
    }
/*++++++++++++++++++
checking Squares (3x3)
+++++++++++++++++++
Just like row checking.
The flag is for a square.
*/
for(si=0;si<3;si++)
    {
    for(sj=0;sj<3;sj++)
        {
        flag=0x0000;
        for(i=0;i<3;i++)
            {
            for(j=0;j<3;j++)
                flag|=1<<(a[si*3+i][sj*3+j]-1);
            }         if(flag!=0x01FF)                 report("square",si*3+i-1,sj*3+j-1);         }     } printf("\nThe sudoku is correct"); }



To test the program, you may try the following inputs. You may copy paste a line from below sudoku solutions to the program. (Each line is a correct solution)


123456789759183426648297315374915268896372154512864973931528647265749831487631592
123456789857923164964817235386241597275639841491578623538764912642195378719382456
123456789759283614486971253342768591891542367567319428935127846278694135614835972
123456789849173256765298431586941372291735648437862915352617894978524163614389527
123456789784913652569827134316598247845271963297634815652149378938765421471382596
123456789496817235587329461864275193359184627712693854631942578978561342245738916
123456789746198532859732146298314675374569821615287394967845213481623957532971468
123456789867239145954781362392567418416928573578143926745692831281375694639814257
123456789475981362869327541654813927791642853382795614938164275516279438247538196
123456789968137524457892136892374651716285493534619872685943217279561348341728965
123456789645987312897312645972863451536124897418579236364291578289735164751648923

Program to Find Number of Grandchildren - Zoho Programming Test Question

Here we will see a c program to find number of grandchildren, great grandchildren great-great grandchildren and so-on of a given person. In this program, the input is a table with two columns, 'Child' and 'Father'. Then we enter a name whose number grandchildren, great grandchildren  etc is to be calculated. We do not have to count children. An example is:
Given a two dimensional array of strings like
<”luke”, “shaw”>
<”wayne”, “rooney”>
<”rooney”, “ronaldo”>
<”shaw”, “rooney”> 

Where in each row, the first string is “child”, second string is “Father”. And given “ronaldo” we have to find his no of grandchildren. Here “ronaldo” has total 3 grandchildren (2 grandchildren: wayne and shaw ; a great grandchild luke). So our output should be 3.


#include<stdio.h>
#include<string.h>
int n;
char name[20];

struct reln{
char child[20];
char father[20];
}r[10];

int count=0;
void countChildren(char name[])
    {
    int j;
    for(j=0;j<n;j++)
        {
        if(strcmp(name,r[j].father)==0)
            {
            count++;
            countChildren(r[j].child);
            }
        }
    }

void main()
{
int i;
printf("\nEnter the number of inputs: ");
scanf("%d",&n);
for(i=0;i<n;i++)
    {
    scanf("%s",r[i].child);
    scanf("%s",r[i].father);
    }
printf("\nEnter name of the one whose no. of grandchildren is needed: ");
scanf("%s",name);
for(i=0;i<n;i++)
    {
    if(strcmp(r[i].father,name)==0)
        countChildren(r[i].child);
    }
printf("\nNo .of grandchildren of %s=%d",name,count);
}

Program to Display String with Odd Number of Letters in the shape of letter 'X' - Zoho Programming Test Question

One of the previous questions in the programming round of Zoho recruitment process was to write a C program to display any string with odd number of letters as follows, in the shape of letter 'X'.

Print the word with odd number of letters as
P         M
 R      A
   O  R
     G
  O    R
 R       A
P          M 



#include<stdio.h> #include<string.h> #include<stdlib.h> void main() { int n,i,j,k,l; char str[20]; printf("Enter a string with odd number of letters."); scanf("%s",str); if((n=strlen(str))%2==0)     {     printf("\nNot odd");     exit(0);     } for(i=0;i<n;i++)     {     printf("\n");     for(j=0;j<n;j++)         {         if(i==j||j==n-1-i)             printf("%c",str[j]);         else             printf(" ");         }     } }

C Program to Burst Consecutively Repeated Numbers From Array - Zoho Programming Round Question

This was one of the programming round (hands on coding) questions in recruitment process of Zoho, an IT company. The question is to write a c program to remove all consecutive repetition of numbers in given array. We should also keep in mind that, if we remove one set of consecutive repeated number, this removal may cause another repetition as illustrated in following example.

example array: 2  3  5  3  8  8  8 3  3 5  3  1  2

Solving: 2  3  5  3  8  8  8  3  3  5  3  1  2   ->  2  3  5  3  3  3  5  3  1  2 -> 2  3  5  5  3  1  2 -> 2  3   3  1  2   ->  2  1  2
output:  2  1  2
I hope that you understood how the removal of consecutive appearance of numbers should be. I hope the program will explain you more.



#include<stdio.h>

void main()

{
int a[20],i,j,k,n;
printf("Enter Number of elements");
scanf("%d",&n);
printf("Enter elements");
for(i=0;i<n;i++)
 scanf("%d",&a[i]);
i=0;
for(;i<n-1;)
 {
 j=1;
 while(i+j<n&&a[i+j]==a[i])
  j++;
 if(j==1)
  {
  i++;
  continue;
  }

 for(k=0;k<n-(i+j);k++)
  a[i+k]=a[i+j+k];
 n-=j;
 if(i>0)
  i--;
 }

printf("Output:\n");
for(i=0;i<n;i++)
 printf("%d",a[i]);
getch();
}