Computer Science‎ > ‎

Miscellaneous C Programs - Area of a Circle, Armstrong Numbers, Bezier Curve, Bisection Method, Bitwise Operator, GCD, etc





Computing the Area of a Circle in C 

/*This is a program to calculate area of a circle after getting the radius as input from the user*/
#include<stdio.h>
int main()
{
    double radius,area;//variables for storing radius and area
    printf("Enter the radius of the circle whose area is to be calculated\n");
    scanf("%lf",&radius);//entering the value for radius of the circle as float data type
    area=(22.0/7.0)*pow(radius,2);//Mathematical function pow is used to calculate square of radius
    printf("The area of the circle is %lf",area);//displaying the results
    getch();
}
/*A test run for the program was carried out and following output was observed
Enter the radius of the circle whose area is to be calculated
5.00
The area of the circle is 78.571429*/

C Program to check for Armstrong Numbers

/*The following program checks whether a number is armstrong number or not and also displays all armstrong numbers
from 1 to 1000. Armstrong numbers are such numbers whose sum of the cubes of digits is equal to the number itself.
For Example
371 is an Armstrong number
371=3*3*3+7*7*7+1*1*1
*/
#include<stdio.h>
#include<conio.h>
#include<math.h>
int main()
{
int numcheck;
int choice;
int rem;
int sum;
int temp;
printf("Enter Choice 1 to check whether a number is armstrong or not and Choice 2 to display all armstrong numbers from 1 to 1000\n");
scanf("%d",&choice);//It's a menu driven program and we work as per user's choice
switch(choice)
{
case 1:
    printf("Enter the number\n");
    scanf("%d",&numcheck);
    temp=numcheck;/*We create a temporary copy of the number we will require to divide the number zero which changes it
    and we need the actual number to compare after the loop operations.*/
    sum=0;//variable to hold the sum of cubes of digits
    while(temp>0)
    {
        rem=temp%10;//We find the digit at last place by finding the remainder after division by 10
        sum=sum+rem*rem*rem;
        temp=temp/10;
    }
    if(sum==numcheck)//Finally we check if the sum of the cubes of the digits equals the number or not
        printf("The Number is an armstrong number\n");
    else
        printf("The Number is not an armstrong number\n");
    break;
case 2:
    for(numcheck=1;numcheck<=1000;numcheck++)
    {//A loop which allows us to move through all numbers from 1 to 1000
    //Now we perform the same operations on all numbers
    temp=numcheck;
    sum=0;
    while(temp>0)
    {
        rem=temp%10;
        sum=sum+rem*rem*rem;
        temp=temp/10;
    }
    if(sum==numcheck)
        printf("The Number %d is an armstrong number\n",numcheck);

    }
break;
}
getch();
return 0;
}
/*A sample run of the program was carried out and it was found to give result as
Enter Choice 1 to check whether a number is armstrong or not and Choice 2 to display all armstrong numbers from 1 to 1000
2
The Number 1 is an armstrong number
The Number 153 is an armstrong number
The Number 370 is an armstrong number
The Number 371 is an armstrong number
The Number 407 is an armstrong number
*/

C Program for Bezier Curves

C Program implementing the Bisection Method ( Numerical Computing )

/*This program in C is used to demonstarte bisection method.
Bisection method is one of the many root finding methods.
In this method we are given a function f(x) and we approximate 2 roots a and b for the function such that f(a).f(b)<0.
Then we find another point
c=(a+b)/2
if f(c)==0
then root=c;
else
if f(a).f(c)<0
b=c;
if f(b).f(c)<0
a=c;
and we repeat these steps for the given number of iterations*/
#include<stdio.h>
#include<math.h>
double F(double x)
{
    return(pow(x,3)+3*x-5);//This return the value of the function
}
int main()
{
    printf("This program illustrates the bisection method in C\n");
    printf("x^3 + 3*x - 5 = 0\n");
    double x0,x1;
    printf("Enter the first approximation to the root\n");
    scanf("%lf",&x0);
    printf("Enter the second approximation to the root\n");
    scanf("%lf",&x1);
    int iter;
    printf("Enter the number of iterations you want to perform\n");
    scanf("%d",&iter);
    int ctr=1;
    double l1=x0;
    double l2=x1;
    double r,f1,f2,f3;
    //We check if the initail approximations are the root or not
    if(F(l1)==0)
    r=l1;
    else
    if(F(l2)==0)
    r=l2;
    else
    {
    while(ctr<=iter)
    {//this is an implementation of the algorithm mentioned above
        f1=F(l1);
        r=(l1+l2)/2.0;
        f2=F(r);
        f3=F(l2);
        if(f2==0)
        {
            r=f2;
            break;
        }
        printf("The root after %d iteration is %lf\n",ctr,r);
        if(f1*f2<0)
        l2=r;
        else
        if(f2*f3<0)
        l1=r;
        ctr++;
    }
    }
    printf("The approximation to the root is %lf",r);
    getch();
}
/*A sample run of the program was carried out and the results were found as:-
This program illustrates the bisection method in C
x^3 + 3*x - 5 = 0
Enter the first approximation to the root
1
Enter the second approximation to the root
2
Enter the number of iterations you want to perform
9
The root after 1 iteration is 1.500000
The root after 2 iteration is 1.250000
The root after 3 iteration is 1.125000
The root after 4 iteration is 1.187500
The root after 5 iteration is 1.156250
The root after 6 iteration is 1.146025
The root after 7 iteration is 1.148438
The root after 8 iteration is 1.152344
The root after 9 iteration is 1.154297
The root is 1.154297
*/

C Program demonstrating the use of Bitwise Operators


/*This program demonstartes the bitwise operations OR,XOR,NOT,AND,LEFT SHIFT and RIGHT SHIFT.*/
#include<stdio.h>
int main()
{
    int num1,num2,resOR,resAND,resXOR,resNOT,resLSHIFT,resRSHIFT;
    printf("This is program to demonstrate the results of bitwise OR,AND,NOT,XOR,LEFT SHIFT and RIGHT SHIFT operations \n");
    printf("Enter the numbers on which the operations are to be performed\n");
    scanf("%d%d",&num1,&num2);
    /*In the OR operatrion the numbers are represented by the computer in binary form and then
    Logical OR operation is performed on each subsequent pair.The resulting binary number is converted in decimal form and is the result.*/
    resOR=num1|num2;
    printf("The result of bitwise OR operation is %d\n",resOR);
    /*In the AND operatrion the numbers are represented by the computer in binary form and then
    Logical AND operation is performed on each subsequent pair.The resulting binary number is converted in decimal form and is the result.*/
    resAND=num1&num2;
    printf("The result of bitwise AND operation is %d\n",resAND);
    /*In the NOT operatrion the number is represented by the computer in binary form and then
    each bit is inverted.The resulting binary number is converted in decimal form and is the result.*/
    resNOT=~num1;
    printf("The result of bitwise NOT operation on %d is %d\n",num1,resNOT);
    resNOT=~num2;
    printf("The result of bitwise NOT operation on %d is %d\n",num2,resNOT);
    //Logical XOR operation is performed on the indivisual pair of bits.
    resXOR=num1^num2;
    printf("The result of bitwise XOR operation is %d\n",resXOR);
    resLSHIFT=num1<<1;    //The bits are shifted left wards by one place and the MSD occupies the LSD
    printf("The result of bitwise LEFT SHIFT by 1 bits operation on %d is %d\n",num1,resLSHIFT);
    resLSHIFT=num2<<1;
    printf("The result of bitwise LEFT SHIFT by 1 bits operation on %d is %d\n",num2,resLSHIFT);
    resRSHIFT=num1>>1; //The bits are shifted right wards by one place and the MSD occupies its place unchanged
    printf("The result of bitwise RIGHT SHIFT by 1 bits operation on %d is %d\n",num1,resRSHIFT);
    resRSHIFT=num2>>1;
    printf("The result of bitwise RIGHT SHIFT by 1 bits operation on %d is %d\n",num2,resRSHIFT);
    getch();
}
/*A sample run of the program was carried out and the results were found as:-
This is program to demonstrate the results of bitwise OR,AND,NOT,XOR,LEFT SHIFT and RIGHT SHIFT operations
Enter the numbers on which the operations are to be performed
2 3
The result of bitwise OR operation is 3
The result of bitwise AND operation is 2
The result of bitwise NOT operation on 2 is -3
The result of bitwise NOT operation on 3 is -4
The result of bitwise XOR operation is 1
The result of bitwise LEFT SHIFT by 1 bits operation on 2 is 4
The result of bitwise LEFT SHIFT by 1 bits operation on 3 is 6
The result of bitwise RIGHT SHIFT by 1 bits operation on 2 is 1
The result of bitwise RIGHT SHIFT by 1 bits operation on 3 is 1
*/

C Program demonstrating the use of Command Line Arguments

/*A C program is executed as if it is a function called by the Operating System, the Operating System can and does pass parameters to the program.
There are two parameters. These two parameters fully specify the command line that was used to invoke the executing program.
The first parameter is argc. It is an integer that represents the number of white space separated strings on the command line. 
For example if we execute program learn , where we pass command line arguments as
learn hello, world then the argc=3
The second parameter is argv.
It is an array of pointers to strings. The strings(represented in a charcter array form) and the array pointer(argv) points to the first string.
If a program is executed (invoked) with a command line that looks like
learn hello, world
then the value of argc is 3 (three), and argv can be diagrammed as
  argv
  ---         ---        -------------------------
 |  -|---->  |  -|----> | l | e | a | r | n |\0 |
  ---        |---|       -------------------------
             |  -|----> | h | e | l | l | o | , |\0 |
             |---|       -------------------
             |  -|----> | w | o | r | l | d |\0 |
             |---|       ---------------------------
            

Each of the values within the boxes to the right (representing each string) is a single character. 
argv[0] is the (pointer to the) string "learn".
argv[1] is the (pointer to the) string "hello,".
argv[2] is the (pointer to the) string "world".

In addition, for ANSI standard C, the array element argv[argc] exists, and is defined to be a null pointer. Therefore, the diagram for the example command line given will be:

 argv
  ---         ---        -------------------------
 |  -|---->  |  -|----> | l | e | a | r | n |\0 | This is can also be pointed to by argv[0]
  ---        |---|       ----------------------------
             |  -|----> | h | e | l | l | o | , |\0 | This is can also be pointed to by argv[1]
             |---|       ----------------------------
             |  -|----> | w | o | r | l | d |\0 | This is can also be pointed to by argv[3]
             |---|       ---------------------------
             | 0 | This points to NULL
             |---|
 */
#include<stdio.h>
int main(int argc,char *argv[])
{
    int i;
    //Displaying the value of the argc
    printf("%d\n",argc);
    //loop to siplay all the arguments passed after the program name on separate lines
    for(i=1;i<argc;i++)
    printf("%s%s",argv[i],"\n");//Displaying the argument first and then changing the line
    getch();
}
/*
A test run on the program was carried out with arguments being passed as commandline Learning Point is Awsum.commandline here is
the name of the program and rest of the arguments are diplayed indivsually on separate lines after displaying hte number of arguments(argc).
Hence the resulting output was
5
Learning
Point
is
Awsum
*/

C Program for an Expression Evaluator


/*This program in C evaluates very basic arithemtic expressions.
The program converts an infix expression into a postfix expression and then evaluates the postfix expression.
*/
#include<stdio.h>
char expr[20];//array to store entered expression
char stack[20];//store the postfix expression
int precedence(char a,char b)
{//returns true if precedence of operator a is more or equal to than that of b
    if(((a=='+')||(a=='-'))&&((b=='*')||(b=='/')))
    return 0;
    else
    return 1;
}
int i;
int ctr;
int top=-1;//top of postfix stack
int topOper=-1;//top of operator stack
int operate(int a,int b,char oper)
{
    int res=0;
switch(oper)
{
    case '+':res=a+b;break;
    case '-':res=a-b;break;
    case '*':res=a*b;break;//return result of evaluation
    case '/':res=a/b;break;
}
return res;
}
void postfixConvert()
{
char topsymb,operatorStack[20];
ctr=0;
while(expr[ctr]!='\0')
{//read till the end of input
if(expr[ctr]>='0'&&expr[ctr]<='9')
stack[++top]=expr[ctr];//add numbers straightaway
else
{
while(topOper>=0&&precedence(operatorStack[topOper],expr[ctr]))
{//check for the operators of higher precedence and then add them to stack
topsymb=operatorStack[topOper--];
stack[++top]=topsymb;
}
operatorStack[++topOper]=expr[ctr];
}
ctr++;
}
while(topOper>=0)//add remaining operators to stack
stack[++top]=operatorStack[topOper--];
printf("The Resulting Postfix expression for the given infix expression\n%s\n",stack);
}
int main()
{
printf("\t\tExpression Evaluator\n");
printf("This Program Evaluates Basic Expressions(without brackets) with arithmetic operations(+,-,*,/) on single digit operand length below 20\n");
printf("Enter the Expression\n");
scanf("%s",expr);
postfixConvert();//function to convert in postfix form
char oper;
int operand1,operand2;
ctr=0;
int result[2];//stack to keep storing results
int rTop=-1;//top of result stack
while(stack[ctr]!='\0')
{
oper=stack[ctr];
if(oper>='0'&&oper<='9')
result[++rTop]=(int)(oper-'0');//add numbers
else
{//if an operator is encountered than pop twice and push the result of operation to the stack
    operand1=result[rTop--];
    operand2=result[rTop--];
    result[++rTop]=operate(operand2,operand1,oper);
}
ctr++;
}
printf("The result of the expression is\n%d\n",result[0]);
getch();
}
/*
A sample run of the program works as:-
        Expression Evaluator
This Program Evaluates Basic Expressions(without brackets) with arithmetic operations(+,-,*,/) on single digit operand length below 20
Enter the Expression
2+3*6-5+7+8/4
The Resulting Postfix expression for the given infix expression
236*+5-7+84/+
The result of the expression is
24
*/

C Program to demonstrate File Handling Functions


/*This program demonstrates various operation on files*/
#include<stdio.h>
int main()
{
    FILE *fp;//we declare a file pointer fp
    fp=fopen("C:\\Users\\Desktop\\ReadExample.txt","r");
    //This tries to open the file ReadExample in reading mode present at location C:\Users\Desktop\
    //(we have to specify the location of the file before reading it)
    if(fp!=NULL)//if fp==NULL then there exists no such file
    {
    char c="";//by ysing getc we read the file from charcater by character and then dipslay its contents
    while(c!=EOF)
    {
    c=getc(fp);
    printf("%c",c);
    }
    }
    else
    printf("No such file exists");
    char *str;
    fscanf(stdin,"%s",str);//The I/O devices can also be treated as files and we use file pointers stdin and stdout for them
    //So we use fscanf to read a string from the standard input device and store it in str
    fprintf(stdout,"%s",str);////Similarly we use fprintf to write a string to the standard output device
    fp=fopen("C:\\Users\\Desktop\\WriteExample.txt","w");
    //Now we open the file pointer in write mode and try to open(if exists) or create(if doesnot exist) file WriteExample
    fprintf(fp,"The Learning Poin");
    putc('t',fp);//We use fprintf and putc to write contents in the file
    close(fp);
    getch();
}
/*A sample run of the program is found to work as follows:-
The program tries to open the file ReadExample from the specified location and then displays the content of the file on standar O/P device
Otherwise NULL is stored in file pointer. After this the program reads a string from the standard I/P device and diplays it back in standard
O/P device. Then a file WriteExample is created at the specified location and The Learning Point is stored in it using fprintf and put c.
*/

C Program to demonstrate the Gaussian Elimination Method


#include<stdio.h>
double **matrix;
double *temp;
double **coeff;
double *unknownvar;
int variables;
int row,column,inner;
void setdiagonal(int row)
{//this function exchanges rows in case we have the diagonal entries while tranforming as zero
    int ctr=0;
    while(matrix[row][row]==0)
            {
                if(row+1!=variables)
                {//exchange with the next row until we are not on the last row
                    temp=matrix[row];
                    matrix[row]=matrix[row+1];
                    matrix[row+1]=temp;
                    temp=coeff[row];
                    coeff[row]=coeff[row+1];
                    coeff[row+1]=temp;
                }
                else
                {//exchange the last row with thr first one
                    temp=matrix[row];
                    matrix[row]=matrix[0];
                    matrix[0]=temp;
                    temp=matrix[row];
                    coeff[row]=coeff[0];
                    coeff[0]=temp;
                }
                ctr++;
                if(ctr==variables)
                {//exchanging the row with all others rows doesnot make diagonal entry non-zero then we do not have a solution
                    printf("The system of equations can not be solved by gauss elimination method");
                    getch();
                    exit(0);
                }
            }
}
void reduceMatrices()
{//this function reduces the matrix in upper triangular form
    double multfactor;
    for(row=0;row<variables;row++)
    {
        if(matrix[row][row]==0)
        setdiagonal(row);//set the diagonal if it's entry is 0
        for(inner=row+1;inner<variables;inner++)
        {
            multfactor=matrix[inner][row]/matrix[row][row];//the multfactor is a factor which is used to multiply with a row to make the next row's some entry 0
            coeff[inner][0]=coeff[inner][0]-multfactor*coeff[row][0];
            for(column=0;column<variables;column++)
            matrix[inner][column]=matrix[inner][column]-multfactor*matrix[row][column];
        }
    }
}
int main()
{
    printf("Enter the number of variables\n");
    scanf("%d",&variables);
    matrix=(double**)malloc(variables*sizeof(double));//declare the matrix to hold the coefficents
    coeff=(double **)malloc(variables*sizeof(double));//declare the matrix to hold the rhs coefficients
    unknownvar=(double*)malloc(variables*sizeof(double));//declare the matrix of the unknown variables
    int i,j;
    for(row=0;row<variables;row++)
    {
        matrix[row]=(double*)malloc(variables*sizeof(double));
        coeff[row]=(double*)malloc(variables*sizeof(double));
    }
    temp=(double*)malloc(variables*sizeof(double));//temporary array used while swapping rows
    printf("Enter the coefficent matrix of the unknown variables\n");
    for(row=0;row<variables;row++)
    for(column=0;column<variables;column++)
        scanf("%lf",&matrix[row][column]);
    printf("Enter the coefficent matrix of the RHS\n");
    for(row=0;row<variables;row++)
        scanf("%lf",&coeff[row][0]);
    reduceMatrices();//We call the function to reduce both coefficent matrices to a form to allow apllication of backward substitution
    double sum;
    for(row=variables-1;row>=0;row--)
    {//This is the coding for the backward substitution
    sum=coeff[row][0];
    for(column=row+1;column<variables;column++)
    sum=sum-matrix[row][column]*unknownvar[column];
    if(matrix[row][row]==0)
    {//If any diagonal entry in the reduced matrix is 0 we can not find solution
        printf("The system of equations can not be solved by gauss elimination method");
        getch();
        exit(0);
    }
    unknownvar[row]=sum/matrix[row][row];
    }
    printf("The unknowns are\n");//display the unknowns
    for(row=0;row<variables;row++)
    printf("%lf  ",unknownvar[row]);
    for(row=0;row<variables;row++)
    {
        free(matrix[row]);
        free(coeff[row]);
    }
    free(matrix);
    free(temp);
    free(coeff);
    free(unknownvar);
    getch();
}
/*A sample run of the program was carried and the resulta were found as:-
Enter the number of variables
3
Enter the coefficent matrix of the unknown variables
0 1 1
2 0 3
1 1 1
Enter the coefficent matrix of the RHS
2
5
3
The unknowns are
1.000000 1.000000 1.000000
*/

C Program to compute the GCD (HCF) of two numbers


/*This program finds out the GCD of two numbers with and without using recursion.
The method using recursion for finding the GCD was given by EUCLID and one can read more about EULICD's algorithm.
*/
#include<stdio.h>
#include<conio.h>
int num1,num2;
int Recursiveapproach(int copy1,int copy2);//recursive function which return the GCD of two numbers
void NonRecursiveapproach(int copy1,int copy2);//non recursive function
int main()
{
    int gcd;
    printf("This programs demonstrate GCD calculation using recursive and non-recursive approach\n");
    printf("\nEnter first number\n");
    scanf("%d",&num1);
    printf("\nEnter second number\n");
    scanf("%d",&num2);
    if(num1>num2)//Our first parameter is the larger of the two numbers
    gcd=Recursiveapproach(num1,num2);
    else
    gcd=Recursiveapproach(num2,num1);
    printf("The GCD calculated using recursive approach is %d\n",gcd);
    NonRecursiveapproach(num1,num2);
    getch();
    return 0;
}
int Recursiveapproach(int copy1,int copy2)
{/*In the recursive method the larger number is divided by the smaller number ,the remainder is checked and then another call is made with
paramters as smaller number and the remainder*/
    if(copy2==0)//when the rmainder passed is zero than we have GCD as the smaller number passed(wiz copy1)
        return copy1;
    else
        Recursiveapproach(copy2,copy1%copy2);
}
void NonRecursiveapproach(int copy1,int copy2)
{
int div=2;//We divide both the numbers with div. We use the prime factorisation method.
int gcd=1;//Initialise the GCD as 1
while(!(copy1==1||copy2==1||div>copy1||div>copy2))
{
if((copy1%div==0)&&(copy2%div==0))
{//If both the numbers are divisible by div then divide and multiply div to the gcd
gcd=gcd*div;
copy1=copy1/div;
copy2=copy2/div;
}
else//Otherwise divide the number which is divisible by div
if((copy1%div==0)&&(copy2%div!=0))
copy1=copy1/div;
else
if((copy1%div!=0)&&(copy2%div==0))
copy2=copy2/div;
else
if((copy1%div!=0)&&(copy2%div!=0))
div++;//else increment div
}
printf("The GCD calculated without using recursion is %d",gcd);
}
/*A sample run of the program was carried out and the results were found as:-
This programs demonstrate GCD calculation using recursive and non-recursive approach
Enter first number
45
Enter second number
36
The GCD calculated using recursive approach is 9
The GCD calculated without using recursion is 9
*/

C Program to solve the Josephus Problem


/*The following program is an implementation of the Josephus Problem in C.
Consider a problem of a group of soldiers overpowered and surrounded by enemy forces. A single soldier can escape and all soldiers stand
in a circle and a number n is picked up and a soldier's name is picked up. Beggining with the soldier whose name is picked they begin to count clock wise
When count reaches n,the soldier is removed and count begins with next soldier. This countinues till only one soldier remains. Josephus Problem
is to determine the soldier which escapes.
*/
#include<stdio.h>
struct node
{
    struct node *next;//stroes address to next node
    char name[10];//stroes the name
}*start;//points to beginning of the list
typedef struct node *Nodeptr;
void add(char namePassed[])//add a node
{
Nodeptr temp=(struct node *)malloc(sizeof(struct node));//newly declared node
Nodeptr move;
move=start;//points to the start
if(temp==NULL)
{
    printf("OverFlow\n");
    return;//can not allocate space so return
}
while((move->next)!=NULL)
move=move->next;//move to appropriate place to add new node to end
strcpy(temp->name,namePassed);
temp->next=NULL;
move->next=temp;
}
int main()
{
char choice[20];
start=(Nodeptr)malloc(sizeof(struct node));
printf("\t\tJosephus Problem\n");
printf("Enter the name \n");//Enter the begining node
scanf("%s",start->name);
start->next=NULL;
printf("Enter end to stop entering data otherwise enter the name\n");
scanf("%s",choice);
while(strcmp(choice,"end")!=0)
{
add(choice);
printf("Enter end to stop entering data otherwise enter the name\n");
scanf("%s",choice);
}
Nodeptr move=start;
while((move->next)!=NULL)
move=move->next;
move->next=start;//Make the list circular by making the end point to start
move=start;
int count;//takes the count after which the soldier is removed
char begin[20];//stores name of soldier to begin with
printf("Enter the count after which deletion is to happen and Enter the name of starting soldier\n");
scanf("%d%s",&count,begin);
int ctr=0;
while(strcmp(move->name,begin)!=0)
move=move->next;//move to the soldier which user told to start with
int pass=1;
while(move->next!=move)//when move->next==move than we have only one soldier left
{
ctr++;
if(ctr==count-1)//delete next node
{
    Nodeptr temp=move->next;
    move->next=temp->next;
    printf("The soldier who eliminated in pass number %d is %s\n",pass,temp->name);
    free(temp);//free space
    ctr=0;
    pass++;
}
move=move->next;
}
printf("The soldier who escapes is %s\n",move->name);
getch();
}
/*A sample run of the program works as:-
        Josephus Problem
Enter the name
A
Enter end to stop entering data otherwise enter the name
B
Enter end to stop entering data otherwise enter the name
C
Enter end to stop entering data otherwise enter the name
D
Enter end to stop entering data otherwise enter the name
E
Enter end to stop entering data otherwise enter the name
end
Enter the count after which deletion is to happen and Enter the name of starting soldier
3
A
The soldier who eliminated in pass number 1 is C
The soldier who eliminated in pass number 2 is A
The soldier who eliminated in pass number 3 is E
The soldier who eliminated in pass number 4 is B
The soldier who escapes is D
*/

C Program to demonstrate operations on Matrices


/*This program performs matrix addition ,subtraction, multiplication ,finds the determinant and inverse of the entered matrices.*/
#include<stdio.h>
float **matrixA;//for the first matrix
float **matrixB;//for the second matrix
float **matrixRes;//for the results of additon,multiplication and subtraction matrix
int rowA,columnA,rowB,columnB,row,column,navigate;//rowA,columnA,rowB,columnB store sizes of A and B row and column are counters
void add()
{//function to add two matrices
if((rowA==rowB)&&(columnA==columnB))
    {
    printf("A+B\n");//Unless the dimensions are same addition not possible
    matrixRes=(float **)malloc(rowA*sizeof(float));
    for(row=0;row<rowA;row++)
    matrixRes[row]=(float *)malloc(columnA*sizeof(float));
    for(row=0;row<rowB;row++)
    {
        for(column=0;column<columnB;column++)
        {
            matrixRes[row][column]=matrixA[row][column]+matrixB[row][column];//Add corresponding elements
            printf("%.2f ",matrixRes[row][column]);
        }
        printf("\n");
    }
    for(row=0;row<rowA;row++)
        free(matrixRes[row]);
    free(matrixRes);
    }
else
printf("Incompatible for addition\n");
}
void sub()
{
if((rowA==rowB)&&(columnA==columnB))
    {//unless dimension are smae subtraction not possible
    printf("A-B\n");
    matrixRes=(float **)malloc(rowA*sizeof(float));
    for(row=0;row<rowA;row++)
    matrixRes[row]=(float *)malloc(columnA*sizeof(float));//dynamic allocation
    for(row=0;row<rowB;row++)
    {
        for(column=0;column<columnB;column++)
        {
            matrixRes[row][column]=matrixA[row][column]-matrixB[row][column];//subtracting the corresponding elements
            printf("%.2f ",matrixRes[row][column]);
        }
        printf("\n");
    }
    for(row=0;row<rowA;row++)
        free(matrixRes[row]);
    free(matrixRes);
    }
else
printf("Incompatible for subtraction\n");
}
void mult()
{
if((columnA==rowB))
    {//for two matrices to allow for multiplication number of column of first matrix should be equal to number of rows in other matrix
    printf("A*B\n");
    matrixRes=(float **)malloc(rowA*sizeof(float));
    for(row=0;row<rowA;row++)
    matrixRes[row]=(float *)malloc(columnB*sizeof(float));
    for(row=0;row<rowB;row++)
    {
        for(column=0;column<columnB;column++)
        {//code to multiply two matrices
            matrixRes[row][column]=0;
            for(navigate=0;navigate<columnA;navigate++)
            matrixRes[row][column]+=matrixA[row][navigate]*matrixB[navigate][column];
            printf("%.2f ",matrixRes[row][column]);
        }
        printf("\n");
    }
    for(row=0;row<rowA;row++)
        free(matrixRes[row]);
    free(matrixRes);
    }
else
printf("Incompatible for multiplication\n");
}
float determinant(float **matrix,int size)
{
    //A recursive function to get the determinant
    float **temp;//the temporary matrix to store subsequent smaller matrix
    float det=0;//initalise value of deteminant zero

    if(size==1)
    det=matrix[0][0];//in case the matrix passed has size 1
else
    if(size==2)
    det=matrix[0][0]*matrix[1][1]-matrix[0][1]*matrix[1][0];//in case the matrix passed has size 2
else
    {

        int cctr,ictr,ctr;
    for(column=0;column<size;column++)
    {//now we create another matrix properly exculding the first row and the element's corresponding colummn and then find its resulting determinant
        temp=(float **)malloc((size-1)*sizeof(float));
        for(ctr=0;ctr<size-1;ctr++)
        temp[ctr]=(float *)malloc((size-1)*sizeof(float));
        for(ctr=1;ctr<size;ctr++)
        {
            cctr=0;
            for(ictr=0;ictr<size;ictr++)
            {
                if(ictr==column)
                    continue;
                temp[ctr-1][cctr]=matrix[ctr][ictr];
                cctr++;
            }
        }
            det=det+pow(-1,column)*matrix[0][column]*determinant(temp,size-1);//pass the new matrix
        for(ctr=0;ctr<size-1;ctr++)
        free(temp[ctr]);
        free(temp);
    }
}
    return det;//return claculated determinant
}
void matrixInverse(float **matrix,int size,float res)
{
float **tem;//matrix to store smaller matrix whose determinant we find out
int ctr,ictr,rowT,columnT;
float **matrixCft;
matrixCft=(float **)malloc(size*sizeof(float));//matrix to store cofactor matrix
tem=(float **)malloc((size-1)*sizeof(float));
for(ctr=0;ctr<size-1;ctr++)
tem[ctr]=(float *)malloc((size-1)*sizeof(float));
for(ctr=0;ctr<size;ctr++)
matrixCft[ctr]=(float *)malloc(size*sizeof(float));
for(row=0;row<size;row++)
{
for(column=0;column<size;column++)
{//we in these loops calculate the smaller matrix which is we pass to the determinant function which allows us to calculate the cofactors
    rowT=0;
    columnT=0;
    for(ctr=0;ctr<size;ctr++)
        for(ictr=0;ictr<size;ictr++)
            if(ctr!=row&&ictr!=column)
                {
     tem[rowT][columnT++]=matrix[ctr][ictr];
                    if(columnT==size-1)
                    {
                        rowT++;
                        columnT=0;
                    }
                }
    matrixCft[row][column]=pow(-1,(row+column))*determinant(tem,size-1);//multiplying the minor obtained with appropriate power of -1 to get the cofactor
}
}
for(column=0;column<size;column++)
for(row=0;row<size;row++)
matrixCft[column][row]=matrixCft[column][row]/res;//In this step i divide the cofactor matrix with the determinant of the matrix
float **Result;
Result=(float **)malloc(size*sizeof(float));
for(ctr=0;ctr<size;ctr++)
Result[ctr]=(float *)malloc(size*sizeof(float));
for(column=0;column<size;column++)
for(row=0;row<size;row++)
Result[column][row]=matrixCft[row][column];//calulating the transpose of the cofactor matrix
for(row=0;row<size;row++)
    {
        for(column=0;column<size;column++)
        printf("%.2f ",Result[row][column]);
        printf("\n");//display the inverse
    }
for(ctr=0;ctr<size-1;ctr++)
    free(tem[ctr]);
free(tem);
for(row=0;row<size;row++)
    {
        free(Result[row]);
        free(matrixCft[row]);
    }
free(Result);
free(matrixCft);
}
int main()
{
    printf("Enter the number of rows and column in A\n");
    scanf("%d%d",&rowA,&columnA);
    printf("Enter the number of rows and column in B\n");
    scanf("%d%d",&rowB,&columnB);//entering sizes
    matrixA=(float **)malloc(rowA*sizeof(float));
    matrixB=(float **)malloc(rowB*sizeof(float));
    for(row=0;row<rowA;row++)
    matrixA[row]=(float *)malloc(columnA*sizeof(float));
    for(row=0;row<rowA;row++)
    matrixB[row]=(float *)malloc(columnB*sizeof(float));
    printf("Enter the matrix A\n");
    for(row=0;row<rowA;row++)//entering the matrices
    for(column=0;column<columnA;column++)
    scanf("%f",&matrixA[row][column]);
    printf("Enter the matrix B\n");
    for(row=0;row<rowB;row++)
    for(column=0;column<columnB;column++)
    scanf("%f",&matrixB[row][column]);
    add();//performing additon,multiplication and subtraction
    sub();
    mult();
    if(rowA==columnA)
    {//It is only possible to find detrminant and inverse for square matrix so checking that condition
    float resA=determinant(matrixA,rowA);
    printf("Determinant of matrix A is %.2f\n",resA);
    if(resA!=0)
    {//If determinant is zero than inverse can not be calculated
    printf("The matrix inverse is\n");
    matrixInverse(matrixA,rowA,resA);
    }
    else
    printf("The inverse can not be calculated\n");
    }
    else
    {
        printf("Determinant of matrix A can not be calculated\n");
        printf("Inverse of matrix A can notbe calculated\n");
    }
    if(rowB==columnB)
    {
    float resB=determinant(matrixB,rowB);
    printf("Determinant of matrix B is %.2f\n",resB);
    if(resB!=0)
    {//Similarly operate on matrix B
    printf("The matrix inverse is\n");
    matrixInverse(matrixB,rowB,resB);
    }
    else
    printf("The inverse can not be calculated");
    }
    else
    {
        printf("Determinant of matrix B can not be calculated\n");
        printf("Inverse of matrix B can not be calculated\n");
    }
    for(row=0;row<rowA;row++)
        free(matrixA[row]);
    for(row=0;row<rowB;row++)
        free(matrixB[row]);
    free(matrixA);
    free(matrixB);
    getch();
}
/*A sample run of the program is found to give rseult as:-
Enter the number of rows and column in A
3
3
Enter the number of rows and column in B
3
3
Enter the matrix A
4 5 6
4 4 7
8 9 0
Enter the matrix B
1 2 3
5 6 7
3 2 1
A+B
5.00 7.00 9.00
9.00 10.00 14.00
11.00 11.00 1.00
A-B
3.00 3.00 3.00
-1.00 -2.00 0.00
5.00 7.00 -1.00
A*B
47.00 50.00 53.00
45.00 46.00 47.00
53.00 70.00 87.00
Determinant of matrix A is 52.00
The matrix inverse is
-1.21 1.04 0.21
1.08 -0.92 -0.08
0.08 0.08 -0.08
Determinant of matrix A is 0.00
Inverse of matrix B can not be calculated
*/

C Program implementing the Newton Raphson Method (Numerical Computing)


/*This program in C illustrates the Newton Raphson method.
This program calulate the approximation to the root of x*x-5.
The maximum error between 2 succesive approximation is taken as input from the user
alongwith the maximum number of iterations and the initial approximation.
*/
#include<stdio.h>
#include<math.h>
double F(double x)
{//our function
    return ((x)*(x)-5);
}
double Fd(double x)
{//function's differentiation
    return (2*(x));
}
int main()
{
    double x0,h,err,root,x1;
    int miter,iter;
    printf("Enter the first approximation ,the max error and the maximum number of iterations\n");
    scanf("%lf%lf%d",&x0,&err,&miter);
    iter=1;
    while(iter<=miter)
    {
        h=F(x0)/Fd(x0);//calculatinf f(x)/f'(x)as we do in Newton Raphson method
        x1=x0-h;//x1=x0-f(x)/f'(x)
        printf("The approximation's value after %d iteration is %.12lf\n",iter,x1);
        if(fabs(h)<err)//If the difference between the 2 approximations is below the max error
        {
            root=x1;//then make the approximation as the root
            break;
        }
        else
        x0=x1;
        iter++;
    }
    if(root==x1)
    {//display root and the function value
        printf("The root is: %.12lf\n",root);
        double fncvalue = F(root);
        printf("Value of F(root) is: %.12lf",fncvalue);
    }
    else
    printf("The unsufficent number of iteration");//In case root!=x1 then number of iteration were insufficient
    getch();
}
/*A sample run of thje program was carried out and the results were found to be as:-
Enter the first approximation ,the max error and the maximum number of iterations
2
0.0000000001
7
The approximation's value after 1 iteration is 2.250000000000
The approximation's value after 2 iteration is 2.236111111111
The approximation's value after 3 iteration is 2.236067977916
The approximation's value after 4 iteration is 2.236067977500
The approximation's value after 5 iteration is 2.236067977500
The root is: 2.236067977500
Value of F(root) is: 0.000000000000
*/

C Program to check whether a string is a palindrome or not


/*The following program checks whether a string is plaindrome or not.*/
#include<stdio.h>
#include<string.h>
int main()
{
    char word[20];//The array to store the word entered
    char *temp;
    int ctr;
    printf("Enter the word(in lower case) to check whether it is palindrome or not(Length of the word must be below 20)\n");
    scanf("%s",word);
    int length=strlen(word);//We get the length of the string entered
    temp=(char*)malloc(length*sizeof(char));//We create a temprary array to store the word while being reversed
    for(ctr=0;ctr<=length;ctr++)
    temp[ctr]=word[length-ctr-1];
    temp[length]='\0';//terminate with null
    if(strcmp(word,temp)==0)//Then compare the initial and the reversed string
    printf("The word is a Palindrome");
    else
    printf("The word is not a Palindrome");
    getch();
}
/*This program is made keeping in mind all the characters are in the same case.
A sample run of the program is found to work as follows:-
Enter the word(in lower case) to check whether it is palindrome or not(Length of the word must be below 20)
madam
The word is a Palindrome*/

C Program to print the Pascal Triangle


/*This program prints the Pascal's triangle
The number of terms to be displayed is given as input by the user.
At the tip of Pascal's Triangle is the number 1, which makes up the zeroth row.
The first row contains two 1's, at the end both .
Do the same to create the 2nd row,make the elements at the ends as 1 and by adding the two numbers above and to the left and the right 1+1=2.
And the third: 1+2=3; 2+1=3.
In this way, the rows of the triangle go on infinitly.
A number in the triangle can also be found by nCr (n Choose r) where n is the number of the row and r is the element in that row.
*/
#include<stdio.h>
int main()
{
    int **tri;//A 2-D array is used to store the triangle
    int terms,ictr,octr;
    printf("Enter the number of terms you want to see in the triangle\n");
    scanf("%d",&terms);
    printf("\nPASCAL TRIANGLE\n");
    tri=(int **)malloc(terms*sizeof(int));
    for(ictr=0;ictr<terms;ictr++)
    {
        tri[ictr]=(int *)malloc((ictr+1)*sizeof(int));
        for(octr=0;octr<ictr+1;octr++)
        if(octr==0||octr==ictr)
            tri[ictr][octr]=1;//making elements at the ends as 1
        else
            tri[ictr][octr]=tri[ictr-1][octr-1]+tri[ictr-1][octr];//for any other element add the elemnt of previous row
    }
    for(ictr=0;ictr<terms;ictr++)
    {//display the triangle
        for(octr=0;octr<ictr+1;octr++)
        printf("%d ",tri[ictr][octr]);
        printf("\n");
        free(tri[ictr]);
    }
    free(tri);
    getch();
}
/*A sample run of the program was carried out and the results were found as:-
Enter the number of terms you want to see in the triangle
7
PASCAL TRIANGLE
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
1 6 15 20 15 6 1
*/

C Program to display Prime Numbers using the sieve of Eratosthenes


/*This is a simple program to display all the prime numbers till a given range using Eratosthenes' method:
(Adapted from wikepedia)
To find all the prime numbers less than or equal to a given integer n by Eratosthenes' method:

1.    Create a list of consecutive integers from 2 to n: (2, 3, 4, ..., n).
2.    Initially, let p equal 2, the first prime number.
3.    Starting from p, count up in increments of p and mark each of these numbers greater than p itself in the list.
      These numbers will be 2p, 3p, 4p, etc.; note that some of them may have already been marked.
4.    Find the first number greater than p in the list that is not marked.
      If there was no such number, stop. Otherwise, let p now equal this number (which is the next prime), and repeat from step 3.
*/
#include<stdio.h>
void Eratosthenes(int n)
{
int boolean[n-1];//boolean array holds 0 if the numbers is not prime
int list[n-1];//store the numbers till given range from 2 onwards
int ctr,outctr,inctr,primeassm;
for(ctr=0;ctr<n-1;ctr++)
{
    list[ctr]=ctr+2;//start storing numbers from 2 onwars
    boolean[ctr]=1;//assume all to be prime
}
for(outctr=0;outctr<n/2+1;outctr++)
{
    if(boolean[outctr]==1)
    {
    primeassm=list[outctr];//perform primality check for indivusal numbers
    for(inctr=outctr+1;inctr<n-1;inctr++)
    if(list[inctr]%primeassm==0)//if divisible set boolean to 0
    boolean[inctr]=0;
    }
}
printf("\nThe prime numbers till the given range are\n");
for(ctr=0;ctr<n-1;ctr++)
if(boolean[ctr]==1)//display the list of prime numbers
printf("%d\n",list[ctr]);
}
int main()
{
    int num;
    printf("ENTER THE RANGE WITHIN WHICH YOU WANT TO SEE THE PRIME NUMBERS\n");
    scanf("%d",&num);
    Eratosthenes(num);
    
    getch();
}
/* A sample run of the program works as:-
ENTER THE RANGE WITHIN WHICH YOU WANT TO SEE THE PRIME NUMBERS
30
The prime numbers till the given range are
2
3
5
7
11
13
17
19
23
29
*/

C Program for the Producer - Consumer Problem


/*The problem describes two processes, the producer and the consumer, who share a common, fixed-size buffer.
The producer's job is to generate a piece of data, put it into the buffer and start again.
At the same time, the consumer is consuming the data (i.e., removing it from the buffer) one piece at a time.
The problem is to make sure that the producer won't try to add data into the buffer if it's full and that the consumer won't try to remove data from an empty buffer.
The solution for the producer is to either go to sleep or discard data if the buffer is full.
The next time the consumer removes an item from the buffer, it notifies the producer, who starts to fill the buffer again.
In the same way, the consumer can go to sleep if it finds the buffer to be empty. The next time the producer puts data into the buffer, it wakes up the sleeping consumer.
*/
#include<stdio.h>
void displayContent(int size,int stack[])
 {
//This function displays the stack's of producer and consumer
  int ctr;
  if(size==0)
  printf("Empty state\n");
  else
  for(ctr=1;ctr<=size;ctr++)
  printf("\t%d",stack[ctr]);
  printf("\n");
  }
int main()
{
 int choice;
 int size;
 int sizeprod=0;//variables for size of the producer and consumer
 int sizecons=0;
 int producer[20];
 int consumer[20];
 printf("Enter Producer Consumer size :\n",size);
 scanf("%d",&size);
 while(1)
 { 
   printf("Producer Stack  (Stack Size : %d)\n",size);
   displayContent(sizeprod,producer);
   printf("Consumer Stack (Stack Size : %d)\n",size);
   displayContent(sizecons,consumer);
   printf("Enter the choice 1 to add data to buffer(Producer)\n");
   printf("Enter the choice 2 to remove data from buffer(Consumer)\n");
   printf("Enter the choice 3 to exit\n");
   scanf("%d",&choice);//Menu 
   switch(choice)
   {
    case 1:
      if(sizeprod==size)
       printf("Produer stack is full.\n");
      else//add to producer if space is there
      {
      sizeprod++;
      printf("Enter producer item :");
      scanf("%d",&producer[sizeprod]);
      }
      break;
    case 2:
      if(sizecons==size)
         {//consume one lement if not empty
                printf("Consumer Stack is full.\nReset the Cosumer Stack\n",sizecons);
                sizecons=0;
         }
      else if(sizeprod==0)
        printf("Producer stack is empty\n");
      else
       {
       sizecons++;
       consumer[sizecons]=producer[sizeprod];
       printf("Consume one item\n");
       sizeprod--;
       }
      break;
      case 3:
      return 1;

    default:
      printf("Incorrect choice enter again\n");
    }
   getch();
  }
}
/*
Enter Producer Consumer size :
3
Producer Stack (Stack Size : 3)
Empty state
Consumer Stack (Stack Size : 3)
Empty state

Enter the choice 1 to add data to buffer(Producer)
Enter the choice 2 to remove data from buffer(Consumer)
Enter the choice 3 to exit
1
Enter producer item :10
Producer Stack (Stack Size : 3)
    10
Consumer Stack (Stack Size : 3)
Empty state

Enter the choice 1 to add data to buffer(Producer)
Enter the choice 2 to remove data from buffer(Consumer)
Enter the choice 3 to exit
2
Consume one item
Producer Stack (Stack Size : 3)
Empty state
Consumer Stack (Stack Size : 3)
    10
Enter the choice 1 to add data to buffer(Producer)
Enter the choice 2 to remove data from buffer(Consumer)
Enter the choice 3 to exit
1
Enter producer item :20
Producer Stack (Stack Size : 3)
    20
Consumer Stack (Stack Size : 3)
    10
Enter the choice 1 to add data to buffer(Producer)
Enter the choice 2 to remove data from buffer(Consumer)
Enter the choice 3 to exit
3
 */

C Program for the Reader - Writer Problem


/*
The following is a very basic program to illustrate Reader Writer problem.
The reader writer problem consists of readers and writers which share a data resource.
The reader reads data from the resource, the writers writes the data to it.
There is no problem if two or more readers access the resource simultaneously.
But if a writer and a reader or two writers access the resource simultaneously, the result becomes indeterminable.
Therefore the writers must have exclusive access to the resource.
*/
#include<stdio.h>
#include<conio.h>
#include<string.h>
int choiceA,choiceB,ctr;
char c[40];
char buffer[100];
char *g;
FILE *fr,*fw;//file pointers
void readfile()
{//The function to read file contents
fr=fopen("C:\\Users\\Desktop\\Example.txt","r");
printf("\n File content is:\n");
while(!feof(fr))//read till we reach the end of the file
{
c[ctr]=getc(fr);//read the contents to array c
printf("%c",c[ctr]);
ctr++;
}
fclose(fr);//close file pointer
}
void writefile()
{//The function to write contents
printf("\nEnter your content to write:\n");
scanf("%s",buffer);
fw=fopen("C:\\Users\\Desktop\\Example.txt","w");
fprintf(fw,"%s",buffer);//writer operation
fclose(fw);//close file pointer
}
int main()
{
do
{
printf("\nEnter choice 1 to read\n \nEnter choice 2 to write\n \nEnter choice 3 to exit");//enter choice from user
printf("\nUser A enter your choice\n");
scanf("%d",&choiceA);
printf("\nUser B enter your choice\n");
scanf("%d",&choiceB);
if(choiceA==1&&choiceB==1)
{
    printf("\nBoth users can read\n");//when both users want to read then we have no ambiguity
    readfile();
}
if((choiceA==2&&choiceB==3)||(choiceA==3&&choiceB==2))
{
    printf("\nThread works for write operation\n");
    writefile();
}
if((choiceA==1&&choiceB==3)||(choiceA==3&&choiceB==1))
{
    printf("\nThread works for read operation\n");
    readfile();
}
else
printf("\nCan not do. Writers must have exclusive access to the resource.\n");
}
while(choiceA!=3&&choiceB!=3);
getch();
}
/*A sample run of the program works as:-
Enter choice 1 to read
Enter choice 2 to write
Enter choice 3 to exit
User A enter your choice
1
User B enter your choice
1
Both users can read
{The contents of the file example are diplayed}
Enter choice 1 to read
Enter choice 2 to write
Enter choice 3 to exit
User A enter your choice
1
User B enter your choice
2
Can not do. Writers must have exclusive access to the resource.
*/


C Program to demonstrate the Dining Philosopher problem


/*
The following program illustrates the dining philosopher problem in C.The problem can be described as follows(adapted from en.wikipedia.org/wiki/Dining_philosophers_problem):-
Five silent philosophers sit at a table around a bowl of rice. A spoon is placed between each pair of adjacent philosophers.
Each philosopher must alternately think and eat. Eating is not limited by the amount of rice left.
However, a philosopher can only eat while holding both the spoon to the left and the fork to the right
Each philosopher can pick up an adjacent spoon, when available, and put it down, when holding it.
These are separate actions: spoon must be picked up and put down one by one.
*/
#include<stdio.h>
char statePhil[10],self[10],spoon[10];
void test(int k)
{
if((statePhil[(k+4)%5]!='e')&&(statePhil[k]=='h')&&(statePhil[(k+1)]!='e'))
{//check whether the alternate philosopher's are eating or not and check the philosopher's state to be hungry
statePhil[k]='e';
self[k]='s';
//set alternate spoon not available
spoon[k]='n';
spoon[(k+4)%5]='n';
}
}
void pickupSpoon(int ctr)
{//This function checks whether a philosopher can pick up the spoon for eating or not
statePhil[ctr]='h';//set philospher's state to hungry
test(ctr);//check whether the alternate spoons are available or not
if(statePhil[ctr]=='h')//if the state is wtill hungy
self[ctr]='w';//change to waiting
}
void putdownSpoon(int ctr)
{
statePhil[ctr]='t';//set the state of philosopher to thinking
spoon[ctr]='s';//make the alternate spoons available
if(ctr!=0)
spoon[ctr-1]='s';
else
spoon[(ctr+4)%5]='s';
test((ctr+4)%5);//Also check if the alternate neighbour is in waiting state and if so make it eat
test((ctr+1)%5);
}
main()
{
int ch,n,ctr;
printf("\n Dining Philosopher's Problem:");
for(ctr=0;ctr<5;ctr++)
{//set all initial states as thinking all spoons as available and all philosopher satisfied
statePhil[ctr]='t';
self[ctr]='s';
spoon[ctr]='s';
}
printf("\n Initial state of each philososphers:");
printf("\n Phil No : \t Think/Eat \t Status \t\t Spoon");
for(ctr=0;ctr<5;ctr++)//Menu driven
printf("\n %d \t\t %c \t\t %c \t\t %c",ctr+1,statePhil[ctr],self[ctr],spoon[ctr]);
printf("\n Enter 1 to Exit \n Enter 2 if philosopher is Hungry \n Enter 3 if philosopher is Thinking");
printf("\n Enter your choice :");
scanf("%d",&ch);
while(ch!=1)
{
switch(ch)
{
case 1:
return 0;
case 2:
printf("\n Enter which philosophers is Hungry :");
scanf("%d",&n);
pickupSpoon(n-1);//call for pick spoon to pick the spoon up
break;
case 3:
printf("\n Enter which Philosopher is Thinking :");
scanf("%d",&n);
putdownSpoon(n-1);//put down the spoon if philospher is thinking
break;
}
printf("\n State of each Philosepher :");
printf("\n Phil no: \t Think/Eat \t Status \t\t Spoon");
for(ctr=0;ctr<5;ctr++)
printf("\n %d \t\t %c \t\t %c \t\t %c",ctr+1,statePhil[ctr],self[ctr],spoon[ctr]);
printf("\n Enter 1 to Exit \n Enter 2 if philosopher is Hungry \n Enter 3 if philosopher is Thinking");
printf("\n Enter your choice :\n");
scanf("%d",&ch);
}
getch();
}
/*A sample run of the program works as:-
Dining Philosopher's Problem:
Initial state of each philososphers:
Phil No :    Think/Eat     Status     Spoon
1           t           s       s
2           t           s       s
3           t           s       s
4           t           s       s
5           t           s       s
Enter 1 to Exit
Enter 2 if philosopher is Hungry
Enter 3 if philosopher is Thinking
Enter your choice :2
Enter which philosophers is Hungry :3
State of each Philosepher :
Phil No :    Think/Eat     Status     Spoon
1           t           s       s
2           t           s       n
3           e           s       n
4           t           s       s
5           t           s       s
Enter 1 to Exit
Enter 2 if philosopher is Hungry
Enter 3 if philosopher is Thinking
Enter your choice :2
Enter which philosophers is Hungry :2
State of each Philosepher :
Phil No :    Think/Eat     Status     Spoon
1           t           s       s
2           h           w       n
3           e           s       n
4           t           s       s
5           t           s       s
Enter 1 to Exit
Enter 2 if philosopher is Hungry
Enter 3 if philosopher is Thinking
Enter your choice :2
Enter which philosophers is Hungry :5
State of each Philosepher :
Phil No :    Think/Eat     Status     Spoon
1           t           s       s
2           h           w       n
3           e           s       n
4           t           s       n
5           e           s       n
Enter 1 to Exit
Enter 2 if philosopher is Hungry
Enter 3 if philosopher is Thinking
Enter your choice :2
Enter which philosophers is Hungry :1
State of each Philosepher :
Phil No :    Think/Eat     Status     Spoon
1           h           w       s
2           h           w       n
3           e           s       n
4           t           s       n
5           e           s       n
Enter 1 to Exit
Enter 2 if philosopher is Hungry
Enter 3 if philosopher is Thinking
Enter your choice :3
Enter which philosophers is Thinking :5
State of each Philosepher :
Phil No :    Think/Eat     Status     Spoon
1           e           s       n
2           h           w       n
3           e           s       n
4           t           s       s
5           t           s       n
Enter 1 to Exit
Enter 2 if philosopher is Hungry
Enter 3 if philosopher is Thinking
Enter your choice :3
Enter which philosophers is Thinking :3
State of each Philosepher :
Phil No :    Think/Eat     Status     Spoon
1           e           s       n
2           h           w       s
3           t           s       s
4           t           s       s
5           t           s       n
Enter 1 to Exit
Enter 2 if philosopher is Hungry
Enter 3 if philosopher is Thinking
Enter your choice :3
Enter which philosophers is Thinking :1
State of each Philosepher :
Phil No :    Think/Eat     Status     Spoon
1           t           s       n
2           e           s       n
3           t           s       s
4           t           s       s
5           t           s       s
Enter 1 to Exit
Enter 2 if philosopher is Hungry
Enter 3 if philosopher is Thinking
Enter your choice :1
*/

C Program to find the roots of Quadratic Equations

/*The following program finds out the roots of a quadriatic equation by taking the coefficents as the input
from the user.*/
#include<stdio.h>
#include<math.h>
int main()
{
double a,b,c;
printf("Enter the coefficents of the quadriatic equation of the form ax^2+bx+c\n");
scanf("%lf%lf%lf",&a,&b,&c);//We ask for the coefficents from the user
double D=pow(b,2)-4*a*c;
if(D<0)//We check the determinant whether it is greater or lesser than zero and accordingly find real or imaginary roots
{
    printf("The roots are imaginary\n");
    double real,img;
    real=(-1*b)/(2*a);//The real part of the root
    img=sqrt(-1*D)/(2*a);//The imaginary part of the root
    printf("The first root is %lf+i%lf\n",real,img);
    printf("The first root is %lf-i%lf\n",real,img);
}
if(D>=0)
{
    printf("The roots are real\n");
    if(D!=0)
{   //We find both roots if D>0
    double root1=(-1*b+sqrt(D))/(2*a);
    double root2=(-1*b-sqrt(D))/(2*a);
    printf("The first root is %lf\n",root1);
    printf("The second root is %lf\n",root2);
}
else
{   //We find the root if D==0 and display that we have equal roots
    double root=(-1*b)/(2*a);
    printf("The roots are equal\n");
    printf("The root is %lf\n",root);
}
}
getch();
}
/*A sample run of the program is found to work as follows:-
Enter the coefficents of the quadriatic equation of the form ax^2+bx+c
1 5 6
The roots are real
The first root is -2.000000
The second root is -3.000000
*/

C Program to reverse the order of words in a sentence


/* This is a program in C to reverse the order of words in a line of text.
*/
#include<stdio.h>
#include<string.h>
int main()
{
char *text=(char *)malloc(100*sizeof(char));//the array to store the entered sentence
char *temp=(char *)malloc(10*sizeof(char));//used for storing words
printf("Enter the line of text(length<100 and word length <10)\n");
gets(text);//use gets
int ctr=0;
int words=1;//initalize words as one because there would be atleast one word
int row;
while(text[ctr]!='\0')
if(text[ctr++]==' ')
words++;//count number of words by counting spaces
char **word=(char **)malloc(words*sizeof(char));//A 2-D array of words is made
for(row=0;row<words;row++)
word[row]=(char *)malloc(10*sizeof(char));
int len=0;
row=0;
while(len<strlen(text))
{
sscanf(text+len,"%s",temp);//scanf from appropriate length
strcpy(word[row++],temp);//copy the extracted word to the 2D array
len=len+strlen(temp)+1;//scan the next word so sum up the length for previous word and 1 for the space
}
char *swaptemp=(char *)malloc(10*sizeof(char));
for(row=0;row<words/2;row++)
{
strcpy(swaptemp,word[row]);//swap the first with last second with second last and so on
strcpy(word[row],word[words-row-1]);
strcpy(word[words-row-1],swaptemp);
}
strcpy(text,"");
for(row=0;row<words;row++)
{
     strcat(text,word[row]);
    strcat(text," ");//form the new text by concatenating the reverse words
}
printf("%s",text);
getch();
}
/*A sample run of the program works as:-
Enter the line of text(length<100 and word length <10)
The best place to learn is learning point
point learning is learn to place best The
*/

C Program to reverse a string


/*The following program reverses a string of length below 20 characters entered by the user*/
#include<stdio.h>
#include<string.h>
int main()
{
    char word[21];
    char *temp;//This will be our temporary array to store the string while being reversed
    int ctr;
    printf("Enter the word to reverse(Length of the word must be below 20)\n");
    scanf("%s",word);
    int length=strlen(word);//strlen function returns the length of the string. Here it returns length of the string stored in word.
    temp=(char*)malloc(length*sizeof(char));//We create a temprary array of required length
    for(ctr=0;ctr<length;ctr++)
    temp[ctr]=word[length-ctr-1];
    temp[length]='\0';//We terminate the string with null character as it is required that a string should end with null character
    printf("The reversed string is %s\n",temp);
    free(temp);//free the memory
    getch();
}
/*A sample run of the program was done and output was:-
Enter the word to reverse(Length of the word must be below 20)
rabbit
The reversed string is tibbar
*/

C Program to demonstrate the values in the series expansion of exp(x),sin(x),cos(x),tan(x)


/*The following program demonstrates the values of series expansion of
exp(x),sine(x),cosine(x) and tan(x).*/
#include<stdio.h>
#include<math.h>
int factorial(int num)
{
    int ctr;
    int fact=1;//This function calculates and returns the factorial of number num
    for(ctr=1;ctr<=num;ctr++)
    fact=fact*ctr;
    return fact;
}
int main()
{
int terms;
int ctr;
printf("Enter the number of terms till which you want to calculate the value of expansion\n");
scanf("%d",&terms);//Enter the number of terms
double sum=0.0;
double x;
printf("Enter the value for x\n");
scanf("%lf",&x);
printf("1+x+x^2/2!+x^3/3!.......This series when expanded till infinity is expansion for exp(x)\n");
for(ctr=0;ctr<terms;ctr++)
sum+=pow(x,ctr)/factorial(ctr);//finding the value for sum appropriately
printf("The value from the expansion is %.14lf\n",sum);
sum=0.0;
printf("1-x^2/2!+x^4/4!.......This series when expanded till infinity is expansion for cosine(x)\n");
for(ctr=0;ctr/2<terms;ctr+=2)
sum=sum+pow(-1,ctr/2)*pow(x,ctr)/(factorial(ctr));
printf("The value from the expansion is %.14lf\n",sum);
sum=0.0;
printf("x-x^3/3!+x^5/5!.......This series when expanded till infinity is expansion for sine(x)\n");
for(ctr=1;(ctr-1)/2<terms;ctr+=2)
sum=sum+pow(-1,(ctr-1)/2)*pow(x,ctr)/(factorial(ctr));
printf("The value from the expansion is %.14lf\n",sum);
printf("x+x^3/3+2x^5/15.......This series when expanded till infinity is expansion for tan(x)\n");
sum=0.0;
double B,temp;
int Bn,k,r;
for(ctr=1;ctr<=terms;ctr+=1)
{//This loops here calculate Bernoulli number which is further used to get the coefficient in expansion of tan x
B=0;
Bn=2*ctr;
for(k=0;k<=Bn;k++)
{
    temp=0;
for(r=0;r<=k;r++)
{
    temp=temp+pow(-1,r)*factorial(k)*pow(r,Bn)/(factorial(r)*factorial(k-r));
}
B=B+temp/((double)(k+1));
}
sum=sum+pow(-4,ctr)*(1-pow(4,ctr))*B*pow(x,2*ctr-1)/factorial(2*ctr);
}
printf("The value from the expansion is %.14lf\n",sum);
getch();
}
/* A sample run of the program works as:-
Enter the number of terms till which you want to see
6
Enter the value for x
1
1+x+x^2/2!+x^3/3!.......This series when expanded till infinity is expansion for exp(x)
The value from the expansion is 2.71666666666667
1-x^2/2!+x^4/4!.......This series when expanded till infinity is expansion for cosine(x)
The value from the expansion is 0.54030230379189
x-x^3/3!+x^5/5!.......This series when expanded till infinity is expansion for sine(x)
The value from the expansion is 0.84147098464807
x+x^3/3+2x^5/15.......This series when expanded till infinity is expansion for tan(x)
The value from the expansion is 1.55137626113259
*/

C Program to demonstrate common operations on Sets


#include<stdio.h>
int *setA,*setB;
int ctr,octr,ictr,sizeA,sizeB;
void unionsets()
{//The function to calculate union of two sets
    int *unions=(int *)malloc((sizeA+sizeB)*sizeof(int));
    ctr=0;//array unions declared to hold size of max possible union set
    for(octr=0;octr<sizeA;octr++)
    unions[ctr++]=setA[octr];//copy Set A
    for(octr=0;octr<sizeB;octr++)
    {
        int flag=0;//Copy those elements of set B which are not in set A
        for(ictr=0;ictr<sizeA;ictr++)
        {
            if(setA[ictr]==setB[octr])
            flag=1;//flag keeps track whether element is found or not
        }
        if(flag==0)
        unions[ctr++]=setB[octr];
    }
    printf("\nA Union B is \n");
    for(octr=0;octr<ctr;octr++)//display set
    printf("%d\t",unions[octr]);
    free(unions);
    
}
void intersection()
{
    int size;
    if(sizeA>=sizeB)
    size=sizeB;
    else//the sizxe of intersection set will be of the size of the smaller of two sets
    size=sizeA;
    ctr=0;
    int *intersection=(int *)malloc(size*sizeof(int));
    for(octr=0;octr<sizeA;octr++)
    {
        for(ictr=0;ictr<sizeB;ictr++)
        {
            if(setA[octr]==setB[ictr])//copy those elemts which are common to both
            intersection[ctr++]=setB[ictr];
        }
    }
    printf("\nA Intersection B is \n");
    if(ctr==0)
    {//if no elemnts are there show null and return
    printf("NULL");
    return;
    }//display
    for(octr=0;octr<ctr;octr++)
    printf("%d\t",intersection[octr]);
    free(intersection);
    
}
void difference()
{
    int *BdiffA=(int *)malloc(sizeB*sizeof(int));
    ctr=0;//the difeernce array can have size at max Of B if we find B-A
    for(octr=0;octr<sizeB;octr++)
    {
        int flag=0;
        for(ictr=0;ictr<sizeA;ictr++)
        {
            if(setA[ictr]==setB[octr])
            flag=1;//if flag=1 the elemnt is in A and in B
        }
        if(flag==0)//copy only those elemnts which are in B not A
        BdiffA[ctr++]=setB[octr];
    }
    printf("\nB - A is \n");
    if(ctr==0)
    {    printf("NULL");
    return;//if ctr=0 then NULL
    }
    for(octr=0;octr<ctr;octr++)
    printf("%d\t",BdiffA[octr]);//display
    free(BdiffA);
    
}
void CardinalProduct()
{
    int **cardinalProduct=(int **)malloc(sizeA*sizeB*sizeof(int));//There will be sizeA*sizeB rows in the cardinal product matrix
    for(ctr=0;ctr<sizeA*sizeB;ctr++)
    cardinalProduct[ctr]=(int *)malloc(2*sizeof(int));//1 cardinal product has 2 elements (a,b)
    ictr=0;
    for(ctr=0;ctr<sizeA*sizeB;ctr++)
    {
        cardinalProduct[ctr][0]=setA[ctr/sizeB];//way to fill the first element with appropriate set A element
        cardinalProduct[ctr][1]=setB[ctr%sizeB];//way to fill the second element with appropriate set B element
    }
    printf("\nA*B is \n");
    for(ctr=0;ctr<sizeA*sizeB;ctr++)
    printf("(%d,%d)\t",cardinalProduct[ctr][0],cardinalProduct[ctr][1]);//displaying in cartesian form
    for(ctr=0;ctr<sizeA*sizeB;ctr++)
    free(cardinalProduct[ctr]);
    free(cardinalProduct);
}
int main()
{
printf("Enter the size for set A\n");
scanf("%d",&sizeA);
printf("Enter the size for set B\n");
scanf("%d",&sizeB);
setA=(int *)malloc(sizeA*sizeof(int));
setB=(int *)malloc(sizeB*sizeof(int));
printf("Enter the elements of set A\n");
for(ctr=0;ctr<sizeA;ctr++)
scanf("%d",&setA[ctr]);
printf("Enter the elements of set B\n");
for(ctr=0;ctr<sizeB;ctr++)
scanf("%d",&setB[ctr]);
unionsets();
intersection();
difference();
CardinalProduct();
free(setA);
free(setB);
getch();
}
/*A sample run of the program runs as follows:-
Enter the size for set A
3
Enter the size for set B
4
Enter the elements of set A
1 2 3
Enter the elements of set B
4 5 6 7
A Union B is
1 2 3 4 5 6 7
A Intersection B is
NULL
B - A is
4 5 6 7
A*B is
(1,4) (1,5) (1,6) (1,7) (2,4) (2,5) (2,6) (2,7) (3,4) (3,5) (3,6) (3,7)
*/

C Program to solve Simultaneous Linear Equations in two variables


/*The following program finds out the solutions to simultaneous equation in two variables.The equations are of the form
ax+by=c and px+qy=r.
The coefficents of the 2 equations are taken as input and we evaluate the unknown x and y accordingly.
*/
#include<stdio.h>
int main()
{
double a,b,c,p,q,r,x,y;
printf("Enter the coefficents of the first equation of the form ax+by=c\n");
scanf("%lf%lf%lf",&a,&b,&c);//The coefficents of the first equation
printf("Enter the coefficents of the second equation of the form px+qy=r\n");
scanf("%lf%lf%lf",&p,&q,&r);//The coefficents of the second equation
if(((a*q-p*b)!=0)&&((b*p-q*a)!=0))
{//In this case we have a unique solution and display x and y
printf("The solution to the equations is unique\n");
x=(c*q-r*b)/(a*q-p*b);
y=(c*p-r*a)/(b*p-q*a);
printf("The value of x=%lf\n",x);
printf("The value of y=%lf\n",y);
}
else
if(((a*q-p*b)==0)&&((b*p-q*a)==0)&&((c*q-r*b)==0)&&((c*p-r*a)==0))//In such condition we can have infinitely many solutions to the equation.
{//When we have such a condition than mathematically we can choose any one unknown as free and other unknown can be calculated using the free variables's value.
//So we choose x as free variable and then get y
    printf("Infinitely many solutions are possible\n");
    printf("The value of x can be varied and y can be calculated according to x's value using relation\n");
    printf("y=%lf+(%lf)x",(c/b),(-1*a/b));
}
else
if(((a*q-p*b)==0)&&((b*p-q*a)==0)&&((c*q-r*b)!=0)&&((c*p-r*a)!=0))//In such condition no solutions are possible.
printf("No solutions are possible\n");
getch();
}
/*A sample run of the program was carried out and the results found were as follows:-
Enter the coefficents of the first equation of the form ax+by=c
2 4 6
Enter the coefficents of the second equation of the form px+qy=r
3 6 9
Infinitely many solutions are possible
The value of x can be varied and y can be calculated according to x's value using relation
y=1.500000+(-0.500000)x
*/


C Program to solve a Sudoku

/*The following program is an implementation of a Sudoku Solver in C.
Sudoku is a 9*9 grid in which each row,each column and each 3*3 grid contains all numbers from 1 to 9 only once.
The program uses backtracking approach to solve the sudoku. There is a recursive function to solve the sudoku.
*/
#include<stdio.h>
int sudoku[9][9];//The array which stores entries for the sudoku
void solvesudoku(int,int);
int checkrow(int row,int num)
{//This function checks whether we can put the number(num) in the row(row) of the Sudoku or not
int column;
for(column=0;column<9;column++)
    if(sudoku[row][column]==num)
        return 0 ;//If the number is found already present at certain location we return zero
return 1;//If the number is not found anywhere we return 1
}
int checkcolumn(int column,int num)
{//This function checks whether we can put the number(num) in the column(column) of the Sudoku or not
int row;
for(row=0;row<9;row++)
    if(sudoku[row][column]==num)
        return 0;//If the number is found already present at certain location we return zero
return 1;//If the number is not found anywhere we return 1
}
int checkgrid(int row,int column,int num)
{//This function checks whether we can put the number(num) in the 3*3 grid or not
//We get the starting row and column for the 3*3 grid
row=(row/3)*3 ;
column=(column/3)*3;
int r,c;
for(r=0;r<3;r++)
    for(c=0;c<3;c++)
         if(sudoku[row+r][column+c]==num)
            return 0;//If the number is found already present at certain location we return zero
return 1;//If the number is not found anywhere we return 1
}
void navigate(int row,int column)
{//Function to move to the next cell in case we have filled one cell
if(column<8)
        solvesudoku(row,column+1);
    else
       solvesudoku(row+1,0);
}
void display()
{//The function to display the solved Sudoku
int row,column;
printf("THE SOLVED SUDOKU \n");
for(row=0;row<9;row++)
{
for(column=0;column<9;column++)
printf("%d ",sudoku[row][column]);
printf("\n");
}
getch();
}
void solvesudoku(int row,int column)
{
    if(row>8)//If the row number is greater than 8 than we have filled all cells hence we have solved the sudoku
    display();
    if(sudoku[row][column]!=0)
    navigate(row,column);//If the value filled at a cell is not zero than it is filled with some value from 0 to 9 hence we move further
    else
    {
        int ctr;//This is a counter to check numbers from 1 to 9 whether the number can be filled in the cell or not
        for(ctr=1;ctr<=9;ctr++)
        {//We check row,column and the grid
        if((checkrow(row,ctr)==1)&&(checkcolumn(column,ctr)==1)&&(checkgrid(row,column,ctr)==1))
        {
            sudoku[row][column]=ctr;
             navigate(row,column);
        }
        }
        sudoku[row][column]=0;//No valid number was found so we clean up and return to the caller.
    }
    
}
int main()
{
int row,column;
printf("Enter the desired sudoku and enter 0 for unknown entries\n");
for(row=0;row<9;row++)
for(column=0;column<9;column++)
scanf("%d",&sudoku[row][column]);
solvesudoku(0,0);//We start solving the sudoku.
}
/*A sample run of the program was carried out and the results were as follows:-
1 0 3 4 0 0 7 0 9
0 5 6 0 8 9 0 2 3
0 8 9 1 0 3 4 0 6
2 1 4 0 6 5 0 9 7
3 0 0 8 0 7 0 1 4
8 0 7 0 1 4 0 6 5
0 3 1 0 4 0 9 7 8
6 4 0 9 7 0 5 3 1
0 7 8 0 0 1 0 4 2
THE SOLVED SUDOKU
1 2 3 4 5 6 7 8 9
4 5 6 7 8 9 1 2 3
7 8 9 1 2 3 4 5 6
2 1 4 3 6 5 8 9 7
3 6 5 8 9 7 2 1 4
8 9 7 2 1 4 3 6 5
5 3 1 6 4 2 9 7 8
6 4 2 9 7 8 5 3 1
9 7 8 5 3 1 6 4 2
*/

C program to display the total number of words,the number of unique words and the frequency of each word


/* The following C program displays the total number of words,the number of unique words and the frequency of each word
The program uses simple implementaion of sscanf to read from a charcater array text and scans for the frequency of word
*/
#include<stdio.h>
#include<string.h>
char *text;
int main()
{
text=(char *)malloc(100*sizeof(char));//The text array stores the entered string by the user and we assume max text size is 99
char *word=(char *)malloc(10*sizeof(char));//We create 2 more arrays word and temp to store the wors ands we assume max word size is 10
char *temp=(char *)malloc(10*sizeof(char));
printf("\nEnter the text of max length 99 and max length of any word should be 10\n");
gets(text);//use gets to input the line of text
int len=0;//works as counter variable to move through text
int words=0;//store total number of words
int unique=0;//count unique wors
while(len<strlen(text))
{
words++;
sscanf(text+len,"%s",word);//scanf from appropriate length
int ctr=0;//gives correct scanning poistion
int freq=0;//set frequency zero
while(ctr<strlen(text))
{//again scan from the start
sscanf(text+ctr,"%s",temp);
if(strcmp(word,temp)==0)//compare the words
freq++;//increment
ctr=ctr+strlen(temp)+1;//scan the next word so sum up the length for previous word and 1 for the space
}
if(freq!=1)
printf("\n<%s> is not unique and has frequency %d\n",word,freq);//the word has frequency more than 1
else
{
    printf("\nThe word <%s> is unique\n",word);//unique
    unique++;
}
len=len+strlen(word)+1;//scan the next word so sum up the length for previous word and 1 for the space
}
printf("\nThe number of unique words is %d\n",unique);
printf("\nThe total number of words are %d\n",words);
getch();
}
/*A sample run of the program works as:-
Enter the text of max length 99 and max length of any word should be 10
The Learning Point
The word <The> is unique
The word <Learning> is unique
The word <Point> is unique
The number of unique words is 3
The total number of words are 3
Enter the text of max length 99 and max length of any word should be 10
the learning point is the best
<the> is not unique and has frequency 2
The word <learning> is unique
The word <point> is unique
The word <is> is unique
<the> is not unique and has frequency 2
The word <best> is unique
The number of unique words is 4
The total number of words are 6
*/

C program to display the 
upper triangular matrix and lower triangular matrix 
for any given matrix

/*This is a program to display the
upper triangular matrix and lower triangular matrix
for any given matrix. The method used here is
LU decomposition method. This program works for matrices
of order equal to or below 10x10*/
#include<stdio.h>
int main()
{
    int size,row,column,ctr1,ctr2;
    printf("ENTER THE SIZE OF THE MATRIX(size<10)\n");
    scanf("%d",&size);
    float matrix[10][10];
    printf("ENTER THE MATRIX\n");
    for(row=0;row<size;row++)
        for(column=0;column<size;column++)
            scanf("%f",&matrix[row][column]);
    float lowertriangle[10][10];//matrices for lower and uppper triangle
    float uppertriangle[10][10];
    for(row=0;row<size;row++)
        for(column=0;column<size;column++)
            {
                if(row>column)//initialise all elements of lower triangle in upper triangular matrix as 0
                     uppertriangle[row][column]=0.0;
                if(row<column)//initialise all elements of upper triangle in lower triangular matix as 0
                    lowertriangle[row][column]=0.0;
                if(row==column)//initialise all diagonal elements of lower triangular matrix as 1
                    lowertriangle[row][column]=1.0;
            }
/*The algorithm used later is from the book Introduction to algorithms by Thomas Cormen.For a better understaning one can
read this text under chapter Matrix Operations. */
    for(ctr1=0;ctr1<size;ctr1++)
    {
        uppertriangle[ctr1][ctr1]=matrix[ctr1][ctr1];
            for(ctr2=ctr1+1;ctr2<size;ctr2++)
            {
                uppertriangle[ctr1][ctr2]=matrix[ctr1][ctr2];
                lowertriangle[ctr2][ctr1]=matrix[ctr2][ctr1]/uppertriangle[ctr1][ctr1];
            }
             for(row=ctr1+1;row<size;row++)
                for(column=ctr1+1;column<size;column++)
                    matrix[row][column]=matrix[row][column]-lowertriangle[row][ctr1]*uppertriangle[ctr1][column];
    }
    printf("UPPER TRIANGULAR MATRIX\n");
    for(row=0;row<size;row++)
    {//displays upper triangular matrix
        for(column=0;column<size;column++)
            printf("%.2f ",uppertriangle[row][column]);
        printf("\n");
    }
        printf("LOWER TRIANGULAR MATRIX\n");
    for(row=0;row<size;row++)
    {//displays lower triangular matrix
        for(column=0;column<size;column++)
            printf("%.2f ",lowertriangle[row][column]);
        printf("\n");
    }
    getch();
}
/*A sample run of the program is found to give following result
ENTER THE SIZE OF THE MATRIX
4
ENTER THE MATRIX
2.00 3.00 1.00 5.00
6.00 13.00 5.00 19.00
2.00 19.00 10.00 23.00
4.00 10.00 11.00 31.00
UPPER TRIANGULAR MATRIX
2.00 3.00 1.00 5.00
0.00 4.00 2.00 4.00
0.00 0.00 1.00 2.00
0.00 0.00 0.00 3.00
LOWER TRIANGULAR MATRIX
1.00 0.00 0.00 0.00
3.00 1.00 0.00 0.00
1.00 4.00 1.00 0.00
2.00 1.00 7.00 1.00
*/

C program for the Distance Vector Routing algorithm

/*
Distance Vector Routing in this program is implemented using Bellman Ford Algorithm:-
*/
#include<stdio.h>
struct node
{
    unsigned dist[20];
    unsigned from[20];
}rt[10];
int main()
{
    int costmat[20][20];
    int nodes,i,j,k,count=0;
    printf("\nEnter the number of nodes : ");
    scanf("%d",&nodes);//Enter the nodes
    printf("\nEnter the cost matrix :\n");
    for(i=0;i<nodes;i++)
    {
        for(j=0;j<nodes;j++)
        {
            scanf("%d",&costmat[i][j]);
            costmat[i][i]=0;
            rt[i].dist[j]=costmat[i][j];//initialise the distance equal to cost matrix
            rt[i].from[j]=j;
        }
    }
        do
        {
            count=0;
            for(i=0;i<nodes;i++)//We choose arbitary vertex k and we calculate the direct distance from the node i to k using the cost matrix
            //and add the distance from k to node j
            for(j=0;j<nodes;j++)
            for(k=0;k<nodes;k++)
                if(rt[i].dist[j]>costmat[i][k]+rt[k].dist[j])
                {//We calculate the minimum distance
                    rt[i].dist[j]=rt[i].dist[k]+rt[k].dist[j];
                    rt[i].from[j]=k;
                    count++;
                }
        }while(count!=0);
        for(i=0;i<nodes;i++)
        {
            printf("\n\n For router %d\n",i+1);
            for(j=0;j<nodes;j++)
            {
                printf("\t\nnode %d via %d Distance %d ",j+1,rt[i].from[j]+1,rt[i].dist[j]);
            }
        }
    printf("\n\n");
    getch();
}
/*
A sample run of the program works as:-
Enter the number of nodes :
3
Enter the cost matrix :
0 2 7
2 0 1
7 1 0
For router 1
node 1 via 1 Distance 0
node 2 via 2 Distance 2
node 3 via 3 Distance 3
For router 2
node 1 via 1 Distance 2
node 2 via 2 Distance 0
node 3 via 3 Distance 1
For router 3
node 1 via 1 Distance 3
node 2 via 2 Distance 1
node 3 via 3 Distance 0
*/

C program to display the Hamming Codes


C program to display the IP address

/*The following program is used to display IP address of the system using the system command */
#include<stdlib.h>

int main()
{
/*system invokes the command processor to execute a command.
Once the command execution has terminated, the processor gives the control back to the program,
returning an int value, whose interpretation is system-dependent.*/
   system("C:\\Windows\\System32\\ipconfig");

   getch();
}
/*A run of the program executes ipconfig file in the command prompt */

C program implementing the Jacobi method (Numerical Computing)


/*This program is an implementaion of the Jacobi iteration method.
The relation used is
X(k+1)=(Diagonal matrix Inverse)(RHS Coefficient-)*(Lower triangle+Upper triangle)X(k))
*/
#include<stdio.h>
float coeff[10][10];
float Dinv[10][10];
float approx[10][1];
float R[10][10];//declare the relevant matrices
float matrixRes[10][1];
float b[10][1];
float temp[10][1];
int row,column,size,navigate;
void multiply(float matrixA[][10],float matrixB[][1])
{
    int ctr,ictr;
//function to perform multiplication
for(ctr=0;ctr<size;ctr++)
{
    matrixRes[ctr][0]=0;
        for(navigate=0;navigate<size;navigate++)
            matrixRes[ctr][0]=matrixRes[ctr][0]+matrixA[ctr][navigate]*matrixB[navigate][0];
}
}
int main()
{
printf("Enter the number of unknown(below 10)\n");
scanf("%d",&size);//enter the size
printf("Enter the coefficent matrix\n");
for(row=0;row<size;row++)
    for(column=0;column<size;column++)
        scanf("%f",&coeff[row][column]);
printf("Enter the first approximation\n");
for(row=0;row<size;row++)
scanf("%f",&approx[row][0]);
printf("Enter the RHS coefficient\n");
for(row=0;row<size;row++)
scanf("%f",&b[row][0]);
for(row=0;row<size;row++)//We calculate the diagonal inverse matrix make all other entries as zero except Diagonal entries whose resciprocal we store
    for(column=0;column<size;column++)
    {    if(row==column)
        Dinv[row][column]=1/coeff[row][column];
        else
        Dinv[row][column]=0;
    }
for(row=0;row<size;row++)
    for(column=0;column<size;column++)//calculating the R matrix L+U
    {    if(row==column)
        R[row][column]=0;
        else
        if(row!=column)
        R[row][column]=coeff[row][column];
    }
int iter;
printf("Enter the number of iterations:\n");
scanf("%d",&iter);//enter the number of iterations
int ctr=1;
int octr;
while(ctr<=iter)
{
multiply(R,approx);//multiply L+U and the approximation
for(row=0;row<size;row++)
temp[row][0]=b[row][0]-matrixRes[row][0];//the matrix(b-Rx)
multiply(Dinv,temp);//multiply D inverse and (b-Rx)
for(octr=0;octr<size;octr++)
approx[octr][0]=matrixRes[octr][0];//store matrixRes value in the next approximation
printf("The Value after iteration %d is\n",ctr);
for(row=0;row<size;row++)
printf("%.3f\n",approx[row][0]);//display the value after the pass
ctr++;
}
getch();
}
/*A sample run of the program works as:-
Enter the number of unknown(below 10)
3
Enter the coefficent matrix
5 -2 3
-3 9 1
2 -1 -7
Enter the first approximation
0
0
0
Enter the RHS coefficient
-1
2
3
Enter the number of iterations:
7
The Value after iteration 1 is
-0.200
0.222  
0.429  
The Value after iteration 2 is
0.146
0.203
-0.517
The Value after iteration 3 is
0.192
0.328
-0.416
The Value after iteration 4 is
0.181
0.332
-0.421
The Value after iteration 5 is
0.185
0.329
-0.424
The Value after iteration 6 is
0.186
0.331
-0.423
The Value after iteration 7 is
0.186
0.331
-0.423*/

C program implementing the Gaussian Elimination technique (Numerical Computing)

/*This is a program to calculate area of a circle after getting the radius as input from the user*/
#include<stdio.h>
int main()
{
    double radius,area;//variables for storing radius and area
    printf("Enter the radius of the circle whose area is to be calculated\n");
    scanf("%lf",&radius);//entering the value for radius of the circle as float data type
    area=(22.0/7.0)*pow(radius,2);//Mathematical function pow is used to calculate square of radius
    printf("The area of the circle is %lf",area);//displaying the results
    getch();
}
/*A test run for the program was carried out and following output was observed
Enter the radius of the circle whose area is to be calculated
5.00
The area of the circle is 78.571429*/




/*The following program checks whether a number is armstrong number or not and also displays all armstrong numbers
from 1 to 1000. Armstrong numbers are such numbers whose sum of the cubes of digits is equal to the number itself.
For Example
371 is an Armstrong number
371=3*3*3+7*7*7+1*1*1
*/

#include<stdio.h>
#include<conio.h>
#include<math.h>
int main()
{
int numcheck;
int choice;
int rem;
int sum;
int temp;
printf("Enter Choice 1 to check whether a number is armstrong or not and Choice 2 to display all armstrong numbers from 1 to 1000\n");
scanf("%d",&choice);//It's a menu driven program and we work as per user's choice
switch(choice)
{
case 1:
    printf("Enter the number\n");
    scanf("%d",&numcheck);
    temp=numcheck;/*We create a temporary copy of the number we will require to divide the number zero which changes it
    and we need the actual number to compare after the loop operations.*/

    sum=0;//variable to hold the sum of cubes of digits
    while(temp>0)
    {
        rem=temp%10;//We find the digit at last place by finding the remainder after division by 10
        sum=sum+rem*rem*rem;
        temp=temp/10;
    }
    if(sum==numcheck)//Finally we check if the sum of the cubes of the digits equals the number or not
        printf("The Number is an armstrong number\n");
    else
        printf("The Number is not an armstrong number\n");
    break;
case 2:
    for(numcheck=1;numcheck<=1000;numcheck++)
    {//A loop which allows us to move through all numbers from 1 to 1000
    //Now we perform the same operations on all numbers
    temp=numcheck;
    sum=0;
    while(temp>0)
    {
        rem=temp%10;
        sum=sum+rem*rem*rem;
        temp=temp/10;
    }
    if(sum==numcheck)
        printf("The Number %d is an armstrong number\n",numcheck);

    }
break;
}
getch();
return 0;
}
/*A sample run of the program was carried out and it was found to give result as
Enter Choice 1 to check whether a number is armstrong or not and Choice 2 to display all armstrong numbers from 1 to 1000
2
The Number 1 is an armstrong number
The Number 153 is an armstrong number
The Number 370 is an armstrong number
The Number 371 is an armstrong number
The Number 407 is an armstrong number
*/