2018

C program to find value using Bisection Method | C Programming

#include<stdio.h>
#include<conio.h>
#include<math.h>
#define EST 0.05
#define F(x) pow(x,3)-x-3
int main()
{
int i=1;
float xl,xu,xm,f1,f2,f3,error;
printf("Enter the values for xl and xu respectively\n");
scanf("%f%f",&xl,&xu);
printf("Iteration\tXl\t Xu\t f(Xm)\t Error\n");
do
{
xm=(xl+xu)/2;
f1=F(xl);
f2=F(xu);
f3=F(xm);
error=fabs((xl-xu)/xu);
if((f1*f3)<0)
{
xu=xm;
}
else
{
xl=xm;
}
f3=F(xm);
error=fabs((xl-xu)/xu);
printf("%d\t %.4f\t %.4f\t%.4f\t %.4f\n",i,xl,xu,xm,error);
i++;
}while (error>=EST);

}

C program to find value using secant method | C programming


#include<stdio.h>
#include <math.h>
#include<conio.h>
#define EST 0.05
#define F(x) x-exp(x)+2
int main()
{
int i = 1;
float x0,x1,a,b,c,d,f1,x2,f0,error;
printf("\nEnter the value of x0: ");
scanf("%f",&x0);
printf("\nEnter the value of x1: ");
scanf("%f",&x1);
printf("\n__________________________________________________________________\n");
printf("\niteration\tx0\t x1\t f0\t f1\t x2\t\terror");
printf("\n___________________________________________________________________\n");
f0=F(x0);
f1=F(x1);
x2=x1-((f1*(x1-x0))/(f1-f0));
printf("%f",x2);
error=fabs((x2-x1)/x2);
printf("\n %d \t %.2f\t %.2f\t %.2f \t %.3f \t %.3f \t %.3f", i, x0,x1,f0,f1,x2,error);
do{
i++;
x0=x1;
f0= f1;
x1=x2;

f0=F(x0);
f1=F(x1);
x2=x1-((f1*(x1-x0))/(f1-f0));
error=fabs((x2-x1)/x2);
printf("\n %d \t %.2f\t %.2f\t %.2f \t %.4f \t %.4f \t %.4f", i, x0,x1,f0,f1,x2,error);
}while(error>EST);
printf("\n__________________________________________________________\n");
printf("\n\nApp.root = %f",x2);
return 0;
}

C program to find the value using Newton Raphson

Before starting with the program let us learn something about Newton Raphson Method

Newton Raphson Method is open method and starts with one initial guess for finding real root of non-linear equations. In other Words, Newton Raphson method, also called the Newton’s method, is the fastest and simplest approach of all methods to find the real root of a nonlinear function. It is an open bracket approach, requiring only one initial guess. This method is quite often used to improve the results obtained from other iterative approaches




C program to find the value using Newton Raphson

#include<stdio.h>
#include <math.h>
#include<conio.h>
#define EST 0.05
#define F(x) 4*(x)*(x)*(x) - 2*(x) - 6
#define F1(x) 12*(x)*(x) - 2
int main()
{
int i = 1;
float xl;
double f1,fm,f0,error;
printf("\nEnter the value of x0: "); scanf("%f",&xl);
printf("\n__________________________________________________________________\n");
printf("\niteration\tx0\tf0\t f1\t fm\t error");
printf("\n___________________________________________________________________\n");
do
{
f0=F(xl); f1=F1(xl); fm=xl-(f0/f1);
error=(fabs((fm-xl)/fm));
printf("\n %d \t%.2lf\t %.2lf\t %.2lf\t %.4lf \t %.4lf", i,xl,f0,f1,fm,error);
if(error>EST)
{
 xl=fm; f0=F(xl); f1=F1(xl); fm=xl-(f0/f1);
error=(fabs((fm-xl)/fm));
i++;
printf("\n %d \t%.2lf\t %.2lf\t %.2lf\t %.4lf \t %.4lf", i,xl,f0,f1,fm,error);
}
else
{
printf("\n__________________________________________________________\n");
printf("\n\nApp.root = %f",fm);
}
}while(error>EST);
return 0;
}


C program to calculate the Chinese remainder theorem 

#include <stdio.h>
int main()
{
    int user_num[2];
    int numbers[4];
    int a[10][10];
    int i, j, sum[4];
    printf("\nEnter two numbers of seven digits: \n");
    for (i = 0; i <= 1; i++)
    {
        scanf("%d", &user_num[i]);
    }
    printf("\n\nEnter four relative prime numbers:\n");
    for (i = 0; i < 4; i++)
    {
        scanf("%d", &numbers[i]);
    }
    for (i = 0; i < 2; i++)
    {
        for (j = 0; j < 4; j++)
        {
            a[i][j] = user_num[i] % numbers[j];
        }
    }
    for (i = 0; i < 4; i++)
    {
        j = 0;
        sum[i] = (a[j][i] + a[j + 1][i]) % numbers[i];
    }
    printf("\n\n The tuple of 4 numbers is: \n\n");
    printf("(");
    for (i = 0; i < 4; i++)
    {
        printf("%d , ", sum[i]);
    }
    printf(")");
    printf("\n\n");
}

C Program To Generate Permutation

#include <stdio.h>
long int fact(int x)
{
    long int f = 1;
    int i;
    for (i = 1; i <= x; i++)
        f = f * i;
    return (f);
}
int main()
{
    int n, r, i, p;
    printf("Enter value of n and r : ");
    scanf("%d %d", &n, &r);
    if (n >= r)
    {
        p = fact(n) / fact(n - r);
        printf("Permutation P(%d , %d) = %d", n, r, p);
    }
    else
    {
        printf("Wrong Input ! Enter n>=1 .");
    }
    return 0;
}


C Programming To Generate Combination | C Programming

#include <stdio.h>
long int fact(int x)
{
    long int f = 1;
    int i;
    for (i = 1; i <= x; i++)
        f = f * i;
    return (f);
}
int main()
{
    int n, r, i, ncr;
    printf("Enter value of n and r : ");
    scanf("%d %d", &n, &r);
    if (n >= r)
    {
        ncr = fact(n) / (fact(r) * fact(n - r));
        printf("Combination C(%d , %d) = %d", n, r, ncr);
    }
    else
    {
        printf("Wrong Input ! Enter n>=1 .");
    }
    return 0;
}
no image

Implication:-

The statement “p implies q” means that if p is true, then q must also be true. The statement “p implies q” is also written “if p then q” or sometimes “q if p.” Statement p is called the premise of the implication and q is called the conclusion.


C++ program to find implication

#include<iostream>
#include<iomanip>
using namespace std;
int main()
{
bool p[8]= {true, true,true, true,false,false,false,false};
bool q[8] = {true, true,false,false,true,true,false,false};
bool r[8] = {true,false,true,false,true,false,true,false};
cout<<"Truth Table of p Implies q is: \n";
cout<<"p"<<setw(15)<<"q"<<setw(20)<<"p --> q" <<endl;
cout<<"_______________________________________________"<<endl;
for(int i=0; i<8; i++)
{
cout<<p[i]<<setw(15)<<q[i]<<setw(15)<<(!(p[i]) || q[i])<<endl;
}
cout<<"\n\nTruth Table of q Implies r is: \n";
cout<<"q"<<setw(15)<<"r"<<setw(20)<<"q --> r" <<endl;
cout<<"_______________________________________________"<<endl;
for(int i=0; i<8; i++)
{
cout<<q[i]<<setw(15)<<r[i]<<setw(15)<<(!(q[i]) || r[i])<<endl;
}
cout<<"\n\nTruth Table of p Implies r is: \n";
cout<<"p"<<setw(15)<<"r"<<setw(20)<<"p --> r" <<endl;
cout<<"_______________________________________________"<<endl;
for(int i=0; i<8; i++)
{
cout<<p[i]<<setw(15)<<r[i]<<setw(15)<<(!(p[i]) || r[i])<<endl;
}
cout<<"\nHence, above arguments are tested.";
}

C++ Program for modular search and linear search using recursion function


Before starting with the program to find binary search and linear search using recursion function let us know about recursion function and Modular Search.


Recursion Function

Recursion is a process by which a function call itself repeatedly until some specified condition has been satisfied.
                
The process is used for repetitive computation in which action is stated in terms of previous result.
                
In order to solve a problem recursively two condition must be satisfied.
  • The problem must be written in a recursive form.
  • The problem statement must include a problem stopping condition.


Modular Search

It is the type of search in which we use mod recursively to find the item which is searched in the program.


C++ Program for linear search using recursion function


#include<iostream>
using namespace std;

int recursiveLinearSearch(int array[],int key,int size)
{
size=size-1;
if(size <0)
{
return -1;
}
else if(array[size]==key){
return 1;
}
else{
return recursiveLinearSearch(array,key,size);
}
}


int main()
{

cout<<"Enter The Size Of Array: ";
int size;
cin>>size;
int array[size], key,i;

// Taking Input In Array
for(int j=0;j<size;j++)
{
cout<<"Enter "<<j<<" Element : ";
cin>>array[j];
}
//Your Entered Array Is
for(int a=0;a<size;a++)
{
cout<<"array[ "<<a<<" ] = ";
cout<<array[a]<<endl;
}
cout<<"Enter Key To Search in Array";
cin>>key;
int result;
result=recursiveLinearSearch(array,key,size--);
if(result==1)
{
cout<<"Key Found in Array ";
}
else{
cout<<"Key NOT Found in Array ";
}
return 0;
}


C++ Program for modular search and using recursion function

#include <iostream>
using namespace std;
int mod (int x, int y, int a)
{
if (x == 0)
return 0;
if (y == 0)
return 1;
// If y is even
long temp;
if (y % 2 == 0) {
temp = mod(x, y / 2, a);
temp = (temp * temp) % a;
}
// If y is odd
else {
temp = x % a;
temp = (temp * mod(x, y - 1, a) % a) % a;
}
return (int)((temp + a) % a);
}
int main()
{
int x,y,a;
cout<<"x^y (mod a)"<<endl;
cout<<"Enter Base Value: ";
cin>>x;
cout<<"Enter Exponent: ";
cin>>y;
cout<<"Enter Modular Value: ";
cin>>a;
long temp;
temp= mod(x,y,a);
cout<<x <<" ^ "<<y <<" (mod "<<a<<")"<<" = "<<temp;
}

C Program To Compute A Power N

#include <stdio.h>
int power(int a, int n)
{
    if (n == 0)
    {
        return 1;
    }
    else
    {
        return a * power(a, n - 1);
    }
}
int main()
{
    int a, n, x;
    printf("Enter a non-zero real number: ");
    scanf("%d", &a);
    printf("Enter positive power: ");
    scanf("%d", &n);
    x = power(a, n);
    printf("The value of %d ^ %d = %d ", a, n, x);
}


C Program To Find GCD Using Recursion

#include <stdio.h>
int hcf(int n1, int n2);
int main()
{
    int n1, n2;
    printf("Enter values of a and b : ");
    scanf("%d %d", &n1, &n2);

    printf("G.C.D (%d , %d) = %d.", n1, n2, hcf(n1, n2));
    return 0;
}

int hcf(int n1, int n2)
{
    if (n2 != 0)
        return hcf(n2, n1 % n2);
    else
        return n1;
}

C Program for Binary Search and Merge Search using recursion function

Before starting with the program to find binary search and linear search using recursion function let us know about recursion function.

Recursion Function

Recursion is a process by which a function call itself repeatedly until some specified condition has been satisfied.
                
The process is used for repetitive computation in which action is stated in terms of previous result.
                
In order to solve a problem recursively two condition must be satisfied.
  • The problem must be written in a recursive form.
  • The problem statement must include a problem stopping condition.


C Program for Binary Search and using recursion function

#include <stdio.h>
int binarysearch(int a[], int low, int high, int x)
{
    int mid = (low + high) / 2;
    if (low > high)
        return -1;
    if (a[mid] == x)
        return mid;
    if (a[mid] < x)
        return binarysearch(a, mid + 1, high, x);
    else
        return binarysearch(a, low, mid - 1, x);
}
int main(void)
{
    int a[100];
    int len, pos, search_item;
    printf("Enter the length of the array\n");
    scanf("%d", &len);
    printf("Enter the array elements\n");
    for (int i = 0; i < len; i++)
        scanf("%d", &a[i]);
    printf("Enter the element to search\n");
    scanf("%d", &search_item);
    pos = binarysearch(a, 0, len - 1, search_item);
    if (pos < 0)
        printf("Cannot find the element %d in the array.\n", search_item);
    else
        printf("The position of %d in the array is %d.\n", search_item, pos + 1);
    return 0;
}

C Program for Merge Search using recursion function
#include <iostream>
 
using namespace std;

// A function to merge the two half into a sorted data.
void Merge(int *a, int low, int high, int mid)
{
    // We have low to mid and mid+1 to high already sorted.
    int i, j, k, temp[high - low + 1];
    i = low;
    k = 0;
    j = mid + 1;

    // Merge the two parts into temp[].
    while (i <= mid && j <= high)
    {
        if (a[i] < a[j])
        {
            temp[k] = a[i];
            k++;
            i++;
        }
        else
        {
            temp[k] = a[j];
            k++;
            j++;
        }
    }

    // Insert all the remaining values from i to mid into temp[].
    while (i <= mid)
    {
        temp[k] = a[i];
        k++;
        i++;
    }

    // Insert all the remaining values from j to high into temp[].
    while (j <= high)
    {
        temp[k] = a[j];
        k++;
        j++;
    }

    // Assign sorted data stored in temp[] to a[].
    for (i = low; i <= high; i++)
    {
        a[i] = temp[i - low];
    }
}

// A function to split array into two parts.
void MergeSort(int *a, int low, int high)
{
    int mid;
    if (low < high)
    {
        mid = (low + high) / 2;
        // Split the data into two half.
        MergeSort(a, low, mid);
        MergeSort(a, mid + 1, high);

        // Merge them to get sorted output.
        Merge(a, low, high, mid);
    }
}

int main()
{
    int n, i;
    cout << "\nEnter the number of data element to be sorted: ";
    cin >> n;

    int arr[n];
    for (i = 0; i < n; i++)
    {
        cout << "Enter element " << i + 1 << ": ";
        cin >> arr[i];
    }

    MergeSort(arr, 0, n - 1);

    // Printing the sorted data.
    cout << "\nSorted Data ";
    for (i = 0; i < n; i++)
        cout << "->" << arr[i];

    return 0;
}


Program Explanation

  1. Take input of data.
  2. Call MergeSort() function.
  3. Recursively split the array into two equal parts.
  4. Split them until we get at most one element in both half.
  5. Combine the result by invoking Merge().
  6. It combines the individually sorted data from low to mid and mid+1 to high.
  7. Return to main and display the result.
  8. Exit.

Compound Preposition

One that can be broken down into more primitive propositions. E.g.,
If it is sunny outside then I walk to work; otherwise I drive, and if it is raining then I carry my umbrella.

This consists of several primitive propositions:
  • p = “It is sunny outside”
  • q = “I walk to work”
  • r = “I drive”                       
  • s = “It is raining”
  • t = “I carry my umbrella”

Connectives: “if… then” , “ otherwise” , “ and”
If it is sunny outside then I walk to work; otherwise I drive, and if it is raining then I carry my umbrella.
  • p= “It is sunny outside”
  • q = “I walk to work”
  • r= “I drive”
  • s = “It is raining”
  • t = “I carry my umbrella”

If p then q; otherwise r and if s then t.
If p then q and (if not p then (r and (if s then t))).
p implies q and ((not p) implies (r and (s implies t))).



C++ Program To Generate Compound Preposition



#include<iostream>
#include<iomanip>
#include <cstdlib>
using namespace std;
class Proposition
{
private:
int p[4],q[4];
public:
void get_data();
void display_input();
void display_output();
};
void Proposition::get_data()
{
cout<<"Enter value of p(assume in LHS) and q(assume in RHS) of table simultaenously"<<endl;
for(int i=0;i<4;i++)
{
cout<<" p = " ; cin>>p[i];
cout<<" q = "; cin>> q[i];
}
}
void Proposition::display_input()
{
for(int i=0;i<4;i++)
{

if(!((p[i]==0 && q[i]== 0) || (p[i] == 1 && q[i]== 1) || (p[i] == 0 && q[i]== 1) || (p[i] == 1 && q[i]== 0)))
{
cout<<"\nWRONG INPUT ! Enter binary values of p and q "<<endl;
exit(0);
}
}
cout<<"\nInput given : "<<endl;
cout<<"p"<<setw(15)<<"q"<<endl;
cout<<"_____________________________________"<<endl;
for(int i=0;i<4;i++)
{
cout<<p[i]<<setw(15)<<q[i]<<endl;
}
}
void Proposition::display_output()
{
cout<< "\nCompound Proposition Output :"<<endl;
cout<<"p"<<setw(15)<<"q"<<setw(30)<<"(p V ¬q) --> (p ^ q)"<<endl;
cout<<"____________________________________________________"<<endl;

for(int i=0;i<4;i++)

{
cout<<endl<<p[i]<<setw(15)<<q[i];

if((p[i]==1 && q[i] == 1) || (p[i]==0 && q[i]==1))
{
cout<<setw(15)<<"1"<<endl;
}

if((p[i]==1 && q[i] == 0) || (p[i]==0 && q[i]==0))
{
cout<<setw(15)<<"0"<<endl;
}
}

}
int main()
{
Proposition obj;
obj.get_data();
obj.display_input();
obj.display_output();
}

C Program To Implement Dijkstra's Algorithm For Finding Shortest Path | C Programming

#include "stdio.h"

#include "conio.h"

#define infinity 999

void dij(int n, int v, int cost[10][10], int dist[])

{

    int i, u, count, w, flag[10], min;

    for (i = 1; i <= n; i++)

        flag[i] = 0, dist[i] = cost[v][i];

    count = 2;

    while (count <= n)

    {

        min = 99;

        for (w = 1; w <= n; w++)

            if (dist[w] < min && !flag[w])

                min = dist[w], u = w;

        flag[u] = 1;

        count++;

        for (w = 1; w <= n; w++)

            if ((dist[u] + cost[u][w] < dist[w]) && !flag[w])

                dist[w] = dist[u] + cost[u][w];
    }
}

int main()

{

    int n, v, i, j, cost[10][10], dist[10];

    printf("Enter the number of nodes:");

    scanf("%d", &n);

    printf("\n Enter the cost matrix:\n");

    for (i = 1; i <= n; i++)

        for (j = 1; j <= n; j++)

        {

            scanf("%d", &cost[i][j]);

            if (cost[i][j] == 0)

                cost[i][j] = infinity;
        }

    printf("\n Enter the source matrix:");

    scanf("%d", &v);

    dij(n, v, cost, dist);

    printf("\n Shortest path:n");

    for (i = 1; i <= n; i++)

        if (i != v)

            printf("%d->%d,cost=%dn", v, i, dist[i]);

    return 0;
}

C Program To Find Minimum Spanning Tree Using Kruskal's Algorithm 

#include <stdio.h>
#include <conio.h>
#include <stdlib.h>
int i, j, k, a, b, u, v, n, ne = 1;
int min, mincost = 0, cost[9][9], parent[9];
int find(int);
int uni(int, int);
int main()
{
    printf("\n\tImplementation of Kruskal's Algorithm\n");
    printf("\nEnter the no. of vertices:");
    scanf("%d", &n);
    printf("\nEnter the cost adjacency matrix:\n");
    for (i = 1; i <= n; i++)
    {
        for (j = 1; j <= n; j++)
        {
            scanf("%d", &cost[i][j]);
            if (cost[i][j] == 0)
                cost[i][j] = 999;
        }
    }
    printf("The edges of Minimum Cost Spanning Tree are\n");
    while (ne < n)
    {
        for (i = 1, min = 999; i <= n; i++)
        {
            for (j = 1; j <= n; j++)
            {
                if (cost[i][j] < min)
                {
                    min = cost[i][j];
                    a = u = i;
                    b = v = j;
                }
            }
        }
        u = find(u);
        v = find(v);
        if (uni(u, v))
        {
            printf("%d edge (%d,%d) =%d\n", ne++, a, b, min);
            mincost += min;
        }
        cost[a][b] = cost[b][a] = 999;
    }
    printf("\n\tMinimum cost = %d\n", mincost);
    getch();
}
int find(int i)
{
    while (parent[i])
        i = parent[i];
    return i;
}
int uni(int i, int j)
{
    if (i != j)
    {
        parent[j] = i;
        return 1;
    }
    return 0;
}

C++ Program To Represent The Graph Using Adjacency Matrix 

#include<iostream>

#include<iomanip>

using namespace std;

// A function to print the adjacency matrix.

void PrintMat(int mat[][20], int n)

{

    int i, j;

     cout<<"\n\n"<<setw(4)<<"";

     for(i = 0; i < n; i++)

      cout<<setw(3)<<"("<<i+1<<")";

     cout<<"\n\n";

// Print 1 if the corresponding vertexes are connected otherwise 0.

    for(i = 0; i < n; i++)

     {

          cout<<setw(3)<<"("<<i+1<<")";

          for(j = 0; j < n; j++)

          {

               cout<<setw(4)<<mat[i][j];

          }

          cout<<"\n\n";

     }

}

int main()

{

    int i, j, v;

     cout<<"Enter the number of vertexes: ";

     cin>>v;

     int  mat[20][20];

     cout<<"\n";

// Take input of the adjacency of each pair of vertexes.

    for(i = 0; i < v; i++)

     {

          for(j = i; j < v; j++)

          {

               if(i != j)

               {

                cout<<"Enter 1 if the vertex "<<i+1<<" is adjacent to "<<j+1<<", otherwise 0: ";

                cin>>mat[i][j];

                 mat[j][i] = mat[i][j];

               }

               else

                mat[i][j] = 0;

          }

     }

     PrintMat(mat, v);

     return 0;

}

OUTPUT

C++ Program To Represent The Graph Using Adjacency Matrix


Difference Between Procedure Oriented Programming (POP) & Object-Oriented Programming (OOP) | C++ Programming


Procedure Oriented ProgrammingObject-Oriented Programming
Divided IntoIn POP, the program is divided into small parts called functions.In OOP, the program is divided into parts called objects.
ImportanceIn POP, Importance is not given to data but to functions as well as the sequence of actions to be done.In OOP, Importance is given to the data rather than procedures or functions because it works as a real world.
ApproachPOP follows Top-Down approach.OOP follows Bottom-Up approach.
Access SpecifiersPOP does not have any access specifier.OOP has access specifiers named Public, Private, Protected, etc.
Data MovingIn POP, Data can move freely from function to function in the system.In OOP, objects can move and communicate with each other through member functions.
ExpansionTo add new data and function in POP is not so easy.OOP provides an easy way to add new data and functions.
Data AccessIn POP, the Most function uses Global data for sharing that can be accessed freely from function to function in the system.In OOP, data can not move easily from function to function,it can be kept public or private so we can control the access of data.
Data HidingPOP does not have any proper way for hiding data so it is less secure.OOP provides Data Hiding so it provides more security.
OverloadingIn POP, Overloading is not possible.In OOP, overloading is possible in the form of Function Overloading and Operator Overloading.
ExamplesExample of POP are : C, VB, FORTRAN, Pascal.Example of OOP are : C++, JAVA, VB.NET, C#.NET.