Search This Blog

Algorithm and C Program to Find Closure From Functional Dependencies

In this post we will see how to find closure of an attribute or a set of attributes. Before learning how to get closure, we should first know what is a closure. Closure of a given set C is the set of attributes that are functionally determined by the set C under the set of functional dependencies F. There can be closure for any set. Every attribute in the set whose closure is to be found out, will be a member of its closure set C+ also. Consider an example:

Macro Preprocessor for C Using C - Simulation of Macro Processor in C Language

You might have used macros in different languages. In C language, we use #define preprocessor directive for macros. Macro preprocessor expands macro calls (macro invocation) using the macro definition. In this post, we will see a c program to simulate macro preprocessing. This program implements a macro preprocessor for c using c. The program obtains macro definition and parameters from #define directives and replaces every macro call with macro definition with formal parameters substituted with actual ones.

The input to the program is a c program named input.c which should located in the same directory of this program. The output of this program will be displayed in screen and also an output file is generated with name output.c which is located in the same directory. The following is the macro preprocessor program. Below that, i have added a sample input program and corresponding output (with expanded macros).

Macro Preprocessor Program

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

struct argItem
{
 char name[15];
 int argCount;
 char args[10][15];
 char def[100];
}MacroTab[10];

char ch,*sourceCode;
char *output,*line;
int MacroCount=0,MacroUsed=0;

int indexof(char *subString,int fromIndex,char *MainString)
{

 int Mainlength,subLength,i,j,retIndex=-1;
 Mainlength=strlen(MainString);
 subLength=strlen(subString);
 if(Mainlength<1||subLength<1||Mainlength-fromIndex<subLength)
  return(-1);
 for(i=fromIndex;Mainlength-i>=subLength;i++)
  {
  if(*(MainString+i)==*(subString))
   {
   retIndex=i;
   for(j=0;j<subLength;j++)
    {
    if(*(MainString+i+j)!=*(subString+j))
     {
     retIndex=-1;
     break;
     }
    }
   if(retIndex!=-1)
    return retIndex;
   }
  }
 return (-1);
}

char * subString(char *MainString,int fromIndex,int toIndex)
{
int Mainlength,j;
char *subStr;
Mainlength=strlen(MainString);
if(fromIndex<0||fromIndex>=Mainlength||toIndex<fromIndex||toIndex>=Mainlength)
 {
 return(NULL);
 }
subStr=(char *)malloc(1000*sizeof(char));
for(j=0;j<=toIndex-fromIndex;j++)
 *(subStr+j)=*(MainString+fromIndex+j);

*(subStr+j)='\0';
return(subStr);
}

char * replace(char *MainString,char *victim,char *newComer)
{
int Mainlength,victimLength,newComerLength,MainI,OutI,j,found;
char *output;
Mainlength=strlen(MainString);
victimLength=strlen(victim);
newComerLength=strlen(newComer);
if(Mainlength<victimLength||victimLength<1||newComerLength<1)
 {
 return(NULL);
 }
output=(char *)malloc(1000*sizeof(char));
OutI=0;
for(MainI=0;MainI<Mainlength;MainI++)
 {
 if(*(MainString+MainI)!=*(victim))
  {
  *(output+OutI)=*(MainString+MainI);
  OutI++;
  }
 else
  {
  found=1;
  if(Mainlength-MainI<victimLength)
   found=0;
  else
   {
   for(j=1;j<victimLength;j++)
    {
    if(*(MainString+MainI+j)!=*(victim+j))
     {
     found=0;
     break;
     }
    }
   }
  if(found==0)
   {
   *(output+OutI)=*(MainString+MainI);
   OutI++;
   }
  else
   {
   for(j=0;j<newComerLength;j++)
    {
    *(output+OutI)=*(newComer+j);
    OutI++;
    }
   MainI+=victimLength-1;
   }
  }
 }
*(output+OutI)='\0';
return(output);
}


char* NextLine()
{
 int i=0,end=0,j,k;
 char *ret;
 if(strlen(sourceCode)<1)
  return(NULL);
 i=indexof("\n",0,sourceCode);
 if(i==-1)
  {
  i=strlen(sourceCode);
  end=1;
  }
 ret=subString(sourceCode,0,i);
 sourceCode=sourceCode+i+1-end;
 return(ret);
}

void scan()
{
int i,j,k,l;
char temp[30];
i=indexof("#define",0,sourceCode);
if(i>0)
 {
 printf("\nMacros found in source code");
 MacroUsed=1;
 i=0;
 while(indexof("#define",i,sourceCode)>0)
  {
  i=indexof("#define",i,sourceCode)+1;
  j=indexof(" ",i,sourceCode)+1;
  k=indexof("(",j,sourceCode)-1;
  strcpy(MacroTab[MacroCount].name,subString(sourceCode,j,k));
  strcpy(temp,subString(sourceCode,k+2,indexof(")",k+2,sourceCode)-1));
  i=indexof(")",k+2,sourceCode);
  k=0;
  for(j=0;temp[j]!='\0';j++)
   {
   if(temp[j]==',')
    {
    strcpy(MacroTab[MacroCount].args[MacroTab[MacroCount].argCount],subString(temp,k,j-1));
    k=j+1;
    MacroTab[MacroCount].argCount++;
    }
   }
  strcpy(MacroTab[MacroCount].args[MacroTab[MacroCount].argCount],subString(temp,k,j-1));
  MacroTab[MacroCount].argCount++;
  strcpy(MacroTab[MacroCount].def,subString(sourceCode,i+2,indexof("\n",i+2,sourceCode)-1));
  MacroCount++;
  }
 }
else
 {
 MacroUsed=0;
 }

}

void main()
{
FILE *input,*outfile;
int i=0,t,u,j,k,l;
char *tempDef,var[15];
input=fopen("input.c","r");
tempDef=(char*)malloc(200*sizeof(char));
sourceCode=(char*)malloc(1500*sizeof(char));
while((ch=getc(input))!=EOF)
 {
 sourceCode[i++]=ch;
 }
sourceCode[i]='\0';
printf("%s",sourceCode);
fclose(input);
scan();
output=(char*)malloc(1200*sizeof(char));
*output='\0';

if(MacroUsed==1)
 {
    for(l=0;l<MacroCount;l++)
        {
        printf("\nMacro Name:%s, Macro def:%s, args: ",MacroTab[l].name,MacroTab[l].def);
  for(i=0;i<MacroTab[l].argCount;i++)
            printf("%s ",MacroTab[l].args[i]);
        }

 while((line=NextLine(sourceCode))!=NULL)
  {
  if(indexof("#define",0,line)!=-1)
   continue;
  for(i=0;i<MacroCount;i++)
   {
   t=indexof(MacroTab[i].name,0,line);
   if(t!=-1)
    {
    t=0;
    while((t=indexof(MacroTab[i].name,t,line))!=-1)
     {
     strcpy(tempDef,MacroTab[i].def);
     u=indexof("(",t,line)+1;
     j=0;
     while((k=indexof(",",u,line))!=-1)
      {
      strcpy(var,subString(line,u,k-1));
      tempDef=replace(tempDef,MacroTab[i].args[j],var);
      u=k+1;
      j++;
      }
     k=indexof(")",u,line)-1;
     strcpy(var,subString(line,u,k));
     tempDef=replace(tempDef,MacroTab[i].args[j],var);
     j=indexof(")",t,line);
     line=replace(line,subString(line,t,j),tempDef);
     t=t+strlen(MacroTab[i].name);
     }
    }
   }
   strcat(output,line);
   if(indexof("\n",0,line)<0)
    strcat(output,"\n");
  }

 }
else
 {
 strcpy(output,sourceCode);
 }

outfile=fopen("output.c","w");
l=0;
printf("\nCode After macro preprocessing:\n");
while(l<strlen(output))
{
 putc(*(output+l),outfile);
    printf("%c",*(output+l));
 l++;
}
fclose(outfile);
}


Sample Input Program (input.c)

#include<stdio.h>
#define cube(x) x*x*x
#define min(x,y) (x<y)?x:y
void main()
{
printf("\nCube of 4=%d",cube(4));
printf("\nMin of 3 and 4 =%d",min(3,4));
printf("\nMin of 10 and 15 =%d",min(15,10));
}

Corresponding Output (output.c)

#include<stdio.h>


void main()

{

printf("\nCube of 4=%d",4*4*4);

printf("\nMin of 3 and 4 =%d",(3<4)?3:4);

printf("\nMin of 10 and 15 =%d",(15<10)?15:10);

}

C Program To Find Largest Interval of Integers For Which All Numbers In It Are Present In Given Array

This is a question asked in technical interview or programming round by the IT company Zoho during its recruitment process. The question is:

Write a program to find the largest interval (of integers) such that all the integers in the interval are present in the given array.

The input to the program is an integer array. The output is an integer interval (two integers as lower bound and upper bound of interval). All the elements in between the bounds (including the bounds) should be present in the array. Also, it should not be possible to find any other larger interval with all the numbers in it present in the array.

We first sort the given array in ascending order. Let
tlb= lower bound of temporary interval (interval in consideration)
tub= upper bound of temporary interval
upper_bound=upper bound of largest interval
lower_bound=lower bound of largest interval
We copy first element (a[0]) to all above variables. Then traverse the array from second element (a[1]) to its end. If the current element is equal to the previous element plus one, then the temporary upper bound (tub) is set to the current element. Otherwise, if (tub-tlb)>(upper_bound-lower_bound), temporary bounds are copied to the largest bounds and tlb and tub are set to current element.

The program is as follows:

#include<stdio.h>

void main()
{
int i,j,t,a[20],n,lower_bound,upper_bound,tlb,tub;
printf("\nEnter number of elements:");
scanf("%d",&n);
printf("\nEnter elements:");
for(i=0;i<n;i++)
    scanf("%d",&a[i]);
for(i=0;i<n-1;i++)
    {
    for(j=0;j<n-i-1;j++)
        {
        if(a[j]>a[j+1])
            {
            t=a[j];
            a[j]=a[j+1];
            a[j+1]=t;
            }
        }
    }
lower_bound=upper_bound=tlb=tub=a[0];
for(i=1;i<n;i++)
    {
    if(a[i]==a[i-1]+1)
        {
            tub=a[i];
        }
    else
        {
        if(tub-tlb>upper_bound-lower_bound)
            {
            upper_bound=tub;
            lower_bound=tlb;
            }
        tlb=a[i];
        tub=a[i];
        }
    }
if(tub-tlb>upper_bound-lower_bound)
            {
            upper_bound=tub;
            lower_bound=tlb;
            }
printf("\nLargest interval with all its elements present in array:[%d,%d]",lower_bound,upper_bound);
}

C Program to Replace All Occurrences of a Substring with Another String

After the c programs to replace first occurrence of substring and last occurrence of substring, i am posting a c program to replace all the occurrences of a given substring inside the original string.

You may also see:
C Program to Replace First Occurrence of a Substring With Another String
C Program to Replace Last Occurrence of a Substring With Another String

Here also, i have written a function which takes three parameters (the main string, the substring to be replaced and the substring to replace with). The function return a string with all the occurrences of the substring replaced with the specified string. The program uses pointer for manipulating the strings. The program is as follows:


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

char* replaceAll(char* mainstr,char * substr,char* newstr)
{
int lenmain,lensub,i,j,lennew,startindex=-1,limit,c;
lenmain=strlen(mainstr);
lensub=strlen(substr);
lennew=strlen(newstr);
char *result=(char*)malloc(sizeof(char)*(lenmain+200));
for(c=0,i=0;i<lenmain;i++)
    {
    if(lenmain-i>=lensub&&*(mainstr+i)==*(substr))
        {
        startindex=i;
        for(j=1;j<lensub;j++)
            if(*(mainstr+i+j)!=*(substr+j))
                {
                startindex=-1;
                break;
                }
        if(startindex!=-1)
            {
            for(j=0;j<lennew;j++,c++)
                {
                *(result+c)=*(newstr+j);
                }
            i=i+lensub-1;
            }
        else
            {
            *(result+c)=*(mainstr+i);
            c++;
            }
        }
    else
        {
        *(result+c)=*(mainstr+i);
        c++;
        }
    }
*(result+c)='\0';
return result;
}

void main()
{
char a[300],sub[50],news[50];
printf("\nEnter original:");
gets(a);
printf("\nEnter sub string to be replaced:");
gets(sub);
printf("\nEnter new string to replace with:");
gets(news);
printf("\nresult:");
puts(replaceAll(a,sub,news));
}

C Program to Replace First Occurrence of a Substring With Another String

In another post, i have wrote a c program to replace the last occurrence of a substring with another string within a given main string. (Click here for that program). Here, i am writing a  c program to replace the first occurrence of a string within another string. The program is as follows:
#include<stdio.h>
#include<string.h>

char* replaceFirst(char* mainstr,char * substr,char* newstr)
{
int lenmain,lensub,i,j,lennew,startindex=-1,limit,c;
lenmain=strlen(mainstr);
lensub=strlen(substr);
lennew=strlen(newstr);
char *result=(char*)malloc(sizeof(char)*(lenmain+100));
for(i=0;i<lenmain;i++)
    {
    if(lenmain-i>=lensub&&*(mainstr+i)==*(substr))
        {
        startindex=i;
        for(j=1;j<lensub;j++)
            if(*(mainstr+i+j)!=*(substr+j))
                {
                startindex=-1;
                break;
                }
        if(startindex!=-1)
            break;
        }
    }
limit=(startindex==-1)?lenmain:startindex;
for(i=0;i<limit;i++)
    *(result+i)=*(mainstr+i);
if(startindex!=-1)
    {
    for(j=0;j<lennew;j++)
        *(result+i+j)=*(newstr+j);
    c=i+lensub;
    i=i+j;
    for(;c<lenmain;c++,i++)
        *(result+i)=*(mainstr+c);
    }
*(result+i)='\0';
return result;
}

void main()
{
char a[100],sub[50],news[50];
printf("\nEnter original:");
gets(a);
printf("\nEnter sub string to be replaced:");
gets(sub);
printf("\nEnter new string to replace with:");
gets(news);
printf("\nresult:");
puts(replaceFirst(a,sub,news));
}

C Program to Replace Last Occurrence of a Substring With Another String

Functions to play with strings are very useful. I have wrote a program to replace first occurrence of a substring inside another string. (Click here for that program). Here i write a function in c to replace the last occurrence of a substring in a given string with the given new string. The function written in c, takes three arguments; the main string, the substring which is to be replaced and the new new string to replace with. I have written a full c program with main function to test the working of the c program. The function simply finds the last occurrence of the substring in the main string and replaces it with the new string (third parameter). The program is as follows:

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

char* replaceLast(char* mainstr,char * substr,char* newstr)
{
int lenmain,lensub,i,j,lennew,startindex=-1,limit,c;
lenmain=strlen(mainstr);
lensub=strlen(substr);
lennew=strlen(newstr);
char *result=(char*)malloc(sizeof(char)*(lenmain+100));
for(i=lenmain-1;i>=0;i--)
    {
    if(lenmain-i>=lensub&&*(mainstr+i)==*(substr))
        {
        startindex=i;
        for(j=1;j<lensub;j++)
            if(*(mainstr+i+j)!=*(substr+j))
                {
                startindex=-1;
                break;
                }
        if(startindex!=-1)
            break;
        }
    }
limit=(startindex==-1)?lenmain:startindex;
for(i=0;i<limit;i++)
    *(result+i)=*(mainstr+i);
if(startindex!=-1)
    {
    for(j=0;j<lennew;j++)
        *(result+i+j)=*(newstr+j);
    c=i+lensub;
    i=i+j;
    for(;c<lenmain;c++,i++)
        *(result+i)=*(mainstr+c);
    }
*(result+i)='\0';
return result;
}

void main()
{
char a[100],sub[50],news[50];
printf("\nEnter original:");
gets(a);
printf("\nEnter sub string to be replaced:");
gets(sub);
printf("\nEnter new string to replace with:");
gets(news);
printf("\nresult:");
puts(replaceLast(a,sub,news));
}


Linear Search in C - C Program for Linear Search

Linear search simply means 'looking for an element in the whole array from one end to the other'. The searched element is compared with the first element of array first, then with the second, then with the third, so on upto the end of the array. This is time consuming when the array is pretty large. The time complexity is highest.The C program for linear search is given below.

#include<stdio.h>

void main()
{
int array[30], num, search, i;
printf("\nEnter the number of elements");
scanf("%i", &num);
printf("\nEnter the elements\n");
for (i = 0; i < num; i++)
{
scanf("%i", &array[i]);
}
printf("\nEnter the number to search for");
scanf("%i", &search);
for (i = 0; i < num; i++)
{
if (search == array[i])
printf("found at %i th position", i);
}
}

C Program to Find Largest Positive Number Formed Using Digits of Given Number

Here i post a c program to find the largest positive number (integer) that can be formed using the digits of a given number (positive integer). The program just splits the number into digits and stores in an array. Then we sort the digits in descending order so that the largest integer comes first. Then we find the largest number by placing the last digit in the array in one's place, the second last in ten's place, and so on. This is a programming round question asked by Zoho company. You may expect this question for technical interviews to test your basic programming skill. The program is as follows:
#include <stdio.h>
int main(void) {
int n,a[30],i,j,t,c;
printf("Enter the number\n");
scanf("%d",&n);
for(i=0,t=n;t!=0;t/=10)
   a[i++]=t%10;
c=i;
for(i=0;i<c-1;i++)
   for(j=0;j<c-i-1;j++)
       if(a[j]<a[j+1])
           {
              t=a[j];
              a[j]=a[j+1];
              a[j+1]=t;
           }
for(t=0,i=0;i<c;i++)
   t=t*10+a[i];
printf("\nLargest number that can be formed by digits of %d is %d",n,t);
return 0;
}

String Comparison in C and Working of strcmp function

In both C and C++ programming languages, an inbuilt function strcmp() is used to compare two strings. This function is defined in string.h header file. So, to use this function, you have to include the header file string.h in the program. Most of the people ( i mean beginners) have a wrong idea about the working of the this function. I also had made some false assumptions. This function takes two strings as arguments. And it compares the two strings using the ASCII equivalent of each character. Some of the false ideas about this function are:
  • The function returns 1 when the strings are equal and 0 when they are not equal
  • The function returns 1 when they are not equal
  • The function returns 1 when the first string is greater than the second and returns -1 when the first one is less than the second one
The correct statements about this function are:
  • The function returns 0 when the strings are equal
  • The function returns a positive value (which depends on the strings) when the first string is greater than the second
  • The function returns a negative value (which depends on the strings) when the first string is less than the second

And the 'less than' and 'greater than' are not based on the length of the string. As i have told earlier, although string is array of characters, each individual character is considered like an integer. And this integer value can be understood from the ASCII chart. To see the ASCII chart, click the following link.

ASCII chart

The comparison is as follows:

Both the strings are considered character by character. First, the function takes the first character of both and subtracts the ASCII equivalent of the character from second string from that of the character from the first string. If the difference is positive or negative, the comparison is over and this difference is returned by the function. If the first letters of both are the same, the difference will be zero. Then it takes the next character of both the strings and compares until the end (occurrence of null character) of either of the strings or getting a non zero difference. When a non zero difference is obtained , the function stops comparison and returns this value. If no non zero difference is obtained until the end of either of the strings, then it will return the value zero indicating that both are equal.

For example, let the input strings be "kings" and "kingfisher". Suppose we are using "kings" as first parameter and "kingfisher" as second.


strcmp("kings" , "kingfisher");



The function will compare these strings and give an output 13. The function will first take the first character of both. They are same (k) and therefore the difference is zero. So, it will look for the second. Again equal (i). Then it will look for third. equal. Then fourth. Again it is equal. Then looks for 5th. And now they are different ( s and f ). The function will return the difference s-f, i.e 115-102 which is equal to 13.



#include<string.h>
#include<stdio.h>&#62
#include<conio.h>
void main()
{
char st1[80], st2[80];
int i;
printf("Enter the first string: ");
gets(st1);
printf("Enter the second string: ");
gets(st2);
printf("The size of %s is %d:\n", st1, strlen(st1));
printf("The size of %s is %d:\n", st2, strlen(st2));
i = strcmp(st1,st2);
if (!i)
     printf("The strings are equal.\n");
else if (i<0)
printf("\nstring %s is greater",st2);
else
printf("\nstring %s is greater",st1);
getch();
}

Conditional Operator in C and C++

Conditional Operator is an operator which is substitutive for if-else statements. It is a ternary operator (operator which operates on 3 operands). It is often called ?: operator. The operands are expression1, expression2 and expression3. The syntax is as follows:

expression1 ? expression2 : expression3

The expression expression1  will be evaluated always. Execution of expression2 and expression3 depends on the outcome of expression1. expression1 is checked whether true or not. It is considered like a boolean variable. The outcome of an expression is true if it has a non zero value. If its value is zero, the outcome of expression is false. If the expression1 is true, then expression2 is evaluated. If the expression1 is false, then expression3 is evaluated. Consider the following example:



int t=(a>b)?a:b;

In the above assignment statement,if the value of variable a is greater than that of variable b, the outcome of expression a>b is non zero (true) and second expression will be evaluated. Therefore, a will be stored in t. If the value of variable a is less than that of variable b, the outcome of expression a>b is zero (false) and third expression will be evaluated. Therefore, b will be stored in t.



The test expression expression1 can be any expression like a>b, a==b, a!=b etc. It is also possible that expression2 and/or expression3 are variables  or expressions. A nesting of conditional operator is possible while any of the two expressions expression2 and expression3 is an expression with conditional operator. They can be printf statements also.

Simple Example programs:


1) Finding largest of two numbers:


#include<stdio.h>
main()
{
int a,b,c;
printf("Enter two numbers");
scanf("%i%i",&a,&b);
c=(a>b)?a:b;
printf("largest=%d",c);
}
 

2) Checking odd or even:

#include<stdio.h>
main()
{
int num;
printf("Enter the Number : ");
scanf("%d",&num);
(num%2==0)?printf("Even"):printf("Odd");
// using printf statements in conditional operator.
}

3) Finding largest of three numbers:


Using conditional operator inside  conditional operator (nesting)

#include<stdio.h>
main()
{
int a,b,c,d;
printf("Enter three numbers");
scanf("%i%i%i",&a,&b,&c);
d=(a>b)?((a>c)?a:c):((b>c)?b:c);
printf("largest=%i",d);
}

C Program to Check Whether a Given Year is Leap Year or Not

This is post contains a C program and a C++ program to check whether an input year is leap year or not. A year is a leap year if:

  1. The year is divisible by 400
  2. The year is divisible by 4 but not divisible by 100.
Any other year is not a leap year.

C program
#include <stdio.h>
void main()
{
int year;
printf("Enter a year to check if it is a leap year\n");
scanf("%d", &year);
if(year%400==0 || ((year%4=0) && (year%100!=0)))
printf("%d is a leap year.\n", year); else
printf("%d is not a leap year.\n", year);
}

C Program to Check Whether a Given Number is Even or Odd

C and C++ programs to check whether a given number is Odd or even

C Program

#include<stdio.h>
void main()
{
int n;
printf("Enter an integer\n");
scanf("%d",&n);
if ( n%2 == 0 )
printf("Even");
else
printf("Odd");
}

2 Different C Programs to Check Whether a Given String is Palindrome or Not

Here i am writing two different programs to check whether a given string (text) us palindrome or not. These are the programs for this.

C Programs:

(i) Using string functions:




#include<stdio.h>
#include<string.h>
#include<conio.h>
void main()
{
char a[100],b[100];
printf("Enter the string to check if palindrome or not\n");
gets(a);
strcpy(b,a);
strrev(b);
if(strcmp(a,b)==0)
printf("\nEntered string is palindrome");
else
printf("\nEntered string is not palindrome");
getch();
} 

(ii) Comparing Character by Character


#include<string.h>
#include<stdio.h>
#include<conio.h>
void main()
{
int len,i;
char a[100];
printf("Enter the string to check whether it is palindrome or not\n");
gets(a);
len=strlen(a);
for(i=0;i<len/2;i++)
{
if(a[i]!=a[len-i-1])
break;
}

if(i==len/2)
printf("\nEntered string is palindrome");
else
printf("\nEntered string is not palindrome");
getch();
}

C and C++ Programs to Check Whether a Number is Strong Number or Not

This post contains C and C++ program to check whether a given number is Strong number or not. A strong number is a number for which the sum of factorials of its digits is equal to the number itself. The first one is C program to check whether the input number is a strong number or not. An example is 145. 1!+4!+5!=1+24+120=145 Therefore 145 is a strong number.

C Program:

#include<stdio.h>
long int factorial(int n)
{
 if (n == 0)
  return 1;
 else
  return (n * factorial(n - 1));
}

void main()
{
 int n, t;
 int sum = 0;
 printf("\nEnterthe number");
 scanf("%i", &n);
 t = n;
 while (t != 0)
 {
  sum += factorial(t % 10);
  t /= 10;
 }

 if (sum == n)
  printf("\nIt is a Strong number");
 else
  printf("\nIt is not a Strong number");
}


C Program to Swap Numbers

The following are C and C++ programs to swap the values of two variables using a third variable.

C Program:
#include<stdio.h>
void main()
{
int x,y,temp;
printf("Enter the value of xand y\n");
scanf("%d%d", &x, &y);
printf("Before Swapping\n x= %d\n y = %d\n",x,y);
temp = x;
x= y;
y = temp;
printf("After Swapping\n x= %d\ny= %d\n",x,y);
}


C Program to Find Sum of Digits of a Given Number

The following C program calculates sum of digits of any given integer.

C Program

#include<stdio.h>
#include<conio.h>
void main()
{

clrscr();
int n,sum=0;
printf("Enter a number");
scanf("%d",&n);
while(n>0)
{
sum=sum+n%10; //adding last digit
n=n/10; //removing last digit
}
printf("Sum of digits of the number = %d",sum);
getch();
}

C Program to Swap Two Numbers Without Third Variable

This post contains C program to swap two given numbers without using any temporary variable. Only the two variables are required, not a third.

C Program
#include<stdio.h>
void main()
{

int a,b;
printf("Enter first number, a:");
scanf("%d",&a);
printf("Enter second number, b:");
scanf("%d",&b);
printf("values of a and b before swapping is a=%d,b=%d",a,b);
/*swapping*/
a=a+b;
b=a-b;
a=a-b;
printf("value of a and b after swapping is a=%d,b=%d"a,b);
}


C Program to Sort Strings using Selection Sorting

Here i am writing programs in c and c++ languages to sort a given number of strings. Sorting is carried out based on the ASCII values of the letters in the strings. The string comparing function strcmp() is used in the program. These programs sort a given set of strings in ascending order.To change it into descending order just replace > with < in comparison line. The comparison line in the code is marked by comment.

C Program:
#include<stdio.h>
#include<string.h>
#include<conio.h>
void main()
{

int i,j,n;
char str[20][20],temp[20];
puts("\nEnter the number of strings to be sorted\n");
scanf("%d",&n);
printf("\nEnter the strings one by one\n");
for(i=0;i<=n;i++)
gets(str[i]);
for(i=0;i<=n;i++)
{
for(j=i+1;j<=n;j++)
{
if(strcmp(str[i],str[j])>0) /* Comparison line */
{
strcpy(temp,str[i]);
strcpy(str[i],str[j]);
strcpy(str[j],temp);
}
}
}
printf("\nThe sorted strings:\n");
for(i=0;i<=n;i++)
puts(str[i]);
getch();
}

C++ program:


#include<iostream.h>
#include<string.h>
#include<stdio.h>
#include<conio.h>
void main()
{
int i,j,n;
char str[20][20],temp[20];
cout<<"\nEnter the number of strings to be sorted\n";
cin>>n;
cout<<"\nEnter the strings one by one\n";
for(i=0;i<n;i++)
gets(str[i]);
for(i=0;i<n;i++)
{
for(j=i+1;j<n;j++)
{
if(strcmp(str[i],str[j])>0) /* Comparison line */
{
strcpy(temp,str[i]);
strcpy(str[i],str[j]);
strcpy(str[j],temp);
}
}
}
cout<<"\nThe sorted strings:\n";
for(i=0;i<n;i++)
puts(str[i]);
getch();
}

C Program to Reverse a Number - Reverse Digits of a Number using C Program

This post includes a C program to reverse a given number. That is, to reverse the order of digits. If 543 is entered, it will be displayed as 345.

C Program:

#include<stdio.h>
main()
{
int n, reverse = 0;
printf("Enter a number to reverse:\n");
scanf("%d",&n);
while (n != 0)
    {
    reverse = reverse * 10;
    reverse = reverse + n%10;
n = n/10;
    }
printf("Reverse of entered number is = %d\n", reverse);
}

C program to Find Index of a Substring in a String

Here, we will see a function written in C language, which helps to find the index (starting index) of any substring in a given string. The function returns the index of first letter of the first occurrence substring inside the original string. The function in C language is as follows:


int indexof(char *subString,int fromIndex,char *MainString)
{
 int Mainlength,subLength,i,j,retIndex=-1;
 Mainlength=strlen(MainString);
 subLength=strlen(subString);
 if(Mainlength<1||subLength<1||Mainlength-fromIndex<subLength)
  return(-1);
 for(i=fromIndex;Mainlength-i>=subLength;i++)
  {
  if(*(MainString+i)==*(subString))
   {
   retIndex=i;
   for(j=0;j<subLength;j++)
    {
    if(*(MainString+i+j)!=*(subString+j))
     {
     retIndex=-1;
     break;
     }
    }
   if(retIndex!=-1)
    return retIndex;
   }
  }
 return (-1);
}

The function returns -1, if the substring cannot be found within the main string.

Caterpillar Eating Leaf - Computer Graphics Lab Animation in C

This is a CG lab program in C using graphics.h library to animate a caterpillar eating a leaf. As it eats, the caterpillar (or worm) should grow proportionally in size. The leaf should also be reduced in size. The program is given below:
 The ouput is:


DDA Line Drawing Program in C : Computer Graphics Lab Program

Digital Differential Analyzer Algorithm or DDA algorithm is the simplest line drawing algorithm. The algorithm is taught in computer graphics subjects. The algorithm is implemented in CG labs (computer graphics labs). Borland Graphics Interface (BGI) in C is commonly used for implementing computer graphics algorithms in computer graphics labs. Here i am adding c program to draw any line with any slope using the DDA line drawing algorithm. The DDA line drawing program is as follows:

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

void dda(int x1,int y1,int x2,int y2)
{
float xincr,yincr,x,y,dx,dy,s,i;
dx=x2-x1;
dy=y2-y1;
if(abs(dx)>abs(dy))
	s=abs(dx);
else
	s=abs(dy);
xincr=dx/s;
yincr=dy/s;
x=x1;
y=y1;
for(i=0;i<s;i++)
	{
	putpixel(x,y,2);
	x+=xincr;
	y+=yincr;
	}
}

void main()
{
int gd=DETECT,gm,theta=0;
initgraph(&gd,&gm,"C:\\TURBOC3\\BGI\\");
while(!kbhit())
	{
	theta=(theta+1)%361;
	dda(300,150,300+50*sin(3.14f*theta/180),150+50*cos(3.14f*theta/180));
	delay(50);
	cleardevice();
} }


In this program, the dda line drawing algorithm is implemented as a function named dda which takes the co-ordinates of the two end points as parameters. In the main program, i have written a code which tests the DDA algorithm by drawing lines of almost all slopes.