Users Online

· Guests Online: 110

· Members Online: 0

· Total Members: 188
· Newest Member: meenachowdary055

Forum Threads

Newest Threads
No Threads created
Hottest Threads
No Threads created

Latest Articles

C Programming Examples on Numerical Problems & Algorithms

1. C Programming examples on “Solving Linear Equations

C Program to Solve any Linear Equation in One Variable

This C program solves linear equation in one variable.
Here is the source code of the C program to solve any linear equation in one variable. The C program is successfully compiled and run on a Linux system. The program output is also shown below.

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

float solve_for_y(float a, float b, float c)
{
float Y = Y = -(b + c) / a;
return Y;
}
main()
{
float a, b, c, Y;
printf("\nEnter a linear equation in one variable of the form aY + b + c = 0 ");
printf("\nEnter the value of a, b, c respectively: ");
scanf("%f%f%f", &a, &b, &c);
Y = solve_for_y(a, b, c);
printf("\nSolution is Y = %f", Y);

}

$ gcc linear_equation.c -o linear_equation
$ ./linear_equation

Enter a linear equation in one variable of the form aY + b + c = 0
Enter the value of a, b, c respectively: 2 4 8
Solution is Y = -6.000000

---------------------------------------------------------------------------

C Program to Find Inverse of a Matrix

This C program sorts a given array of integer numbers using Bubble Sort technique. The algorithm gets its name from the way smaller elements “bubble” to the top of the list. Because it only uses comparisons to operate on elements, it is a comparison sort. Time Complexity of this algorithm is O(n2).
Here is the source code of the C program to sort and display the integer array. The C program is successfully compiled and run on a Linux system. The program output is also shown below.

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

float determinant(float [][25], float);
void cofactor(float [][25], float);
void transpose(float [][25], float [][25], float);
int main()
{
float a[25][25], k, d;
int i, j;
printf("Enter the order of the Matrix : ");
scanf("%f", &k);
printf("Enter the elements of %.0fX%.0f Matrix : \n", k, k);
for (i = 0;i < k; i++)
{
for (j = 0;j < k; j++)
{
scanf("%f", &a[i][j]);
}
}
d = determinant(a, k);
if (d == 0)
printf("\nInverse of Entered Matrix is not possible\n");
else
cofactor(a, k);
}

/*For calculating Determinant of the Matrix */
float determinant(float a[25][25], float k)
{
float s = 1, det = 0, b[25][25];
int i, j, m, n, c;
if (k == 1)
{
return (a[0][0]);
}
else
{
det = 0;
for (c = 0; c < k; c++)
{
m = 0;
n = 0;
for (i = 0;i < k; i++)
{
for (j = 0 ;j < k; j++)
{
b[i][j] = 0;
if (i != 0 && j != c)
{
b[m][n] = a[i][j];
if (n < (k - 2))
n++;
else
{
n = 0;
m++;
}
}
}
}
det = det + s * (a[0][c] * determinant(b, k - 1));
s = -1 * s;
}
}

return (det);
}

void cofactor(float num[25][25], float f)
{
float b[25][25], fac[25][25];
int p, q, m, n, i, j;
for (q = 0;q < f; q++)
{
for (p = 0;p < f; p++)
{
m = 0;
n = 0;
for (i = 0;i < f; i++)
{
for (j = 0;j < f; j++)
{
if (i != q && j != p)
{
b[m][n] = num[i][j];
if (n < (f - 2))
n++;
else
{
n = 0;
m++;
}
}
}
}
fac[q][p] = pow(-1, q + p) * determinant(b, f - 1);
}
}
transpose(num, fac, f);
}
/*Finding transpose of matrix*/
void transpose(float num[25][25], float fac[25][25], float r)
{
int i, j;
float b[25][25], inverse[25][25], d;

for (i = 0;i < r; i++)
{
for (j = 0;j < r; j++)
{
b[i][j] = fac[j][i];
}
}
d = determinant(num, r);
for (i = 0;i < r; i++)
{
for (j = 0;j < r; j++)
{
inverse[i][j] = b[i][j] / d;
}
}
printf("\n\n\nThe inverse of matrix is : \n");

for (i = 0;i < r; i++)
{
for (j = 0;j < r; j++)
{
printf("\t%f", inverse[i][j]);
}
printf("\n");
}
}

$ gcc inverse_matrix.c -o inverse_matrix
$ ./inverse_matrix

Enter the order of the Square Matrix : 3

Enter the elements of 3X3 Matrix : 3 5 2 1 5 8 3 9 2

The inverse of matrix is :
0.704545 -0.090909 -0.340909
-0.250000 -0.000000 0.250000
0.068180 0.136364 -0.113636


C Program to Perform Encoding of a Message Using Matrix Multiplication

This C program encodes a message using matrix multiplication. One type of code, which is extremely difficult to break, makes use of a large matrix to encode a message. The receiver of the message decodes it using the inverse of the matrix. This first matrix is called the encoding matrix and its inverse is called the decoding matrix.
Here is the source code of the C program to encode and decode a message using matrix multiplication technique. The C program is successfully compiled and run on a Linux system. The program output is also shown below.

/*
Restriction: Input string has to be in lower case without any special characters
*/
#include <stdio.h>
#include <string.h>


void mul(int first[3][3], int second[3][10], int result[3][10])
{
int c, d, sum, k;
int i, j;
for ( c = 0 ; c < 3 ; c++ )
{
for ( d = 0 ; d < 10 ; d++ )
{
sum = 0;
for ( k = 0 ; k < 3 ; k++ )
{
sum = sum + first[c][k] * second[k][d];
}
result[c][d] = sum;
}
}

}
int main()
{
char str[29] = "this message is to be encoded";
int len;
int i, j;
int result[3][10] = {0};
int key[3][3] = {
{-3, -3, -4},
{0, 1, 1},
{4, 3, 4}
};
int inv_key[3][3] = {
{1, 0, 1},
{4, 4, 3},
{-4, -3, -3}
};
int encode[3][10] = {32};
int decode[3][10] = {0};
len = strlen(str);

for (i = 0; i < 10; i++)
{
for(j = 0; j < 3; j++)
{
if (str[j + i*3] >='a' && str[j + i*3] <='z')
{
encode[j][i] = str[j + i*3] - 96;

}
if (str[j + i*3] == 32)
{
encode[j][i] = 32;
}
if (str[j + i*3] == '\0')
break;
}
if (str[j + i*3] == '\0')
break;
}
mul( key, encode, result);
printf("\nEncoded message to be sent: ");
for (i = 0; i < 10; i++)
{
for ( j = 0 ; j < 3; j++)
printf("%d, ", result[j][i]);
}
printf("\nDecoded message is: ");
mul(inv_key, result, decode);
for (i = 0; i < 10; i++)
{
for ( j = 0; j < 3; j++)
{
if ( ((decode[j][i]+96)) >= 97 && ((decode[j][i]+96) <= 123))
printf("%c", (decode[j][i] + 96) );
else if ( decode[j][i] == 32)
printf(" ");
else
return;
}
}
return 0;
}

$ gcc encode.c -o encode
$ ./encode

Encoded message to be sent: -120, 17, 140, -205, 45, 224, -148, 38, 153, -44, 12, 45, -199, 28, 231, -216, 35, 248, -122, 7, 154, -167, 19, 199, -70, 19, 73, -27, 4, 32,
Decoded message is: this message is to be encoded



C Program to Perform LU Decomposition of any Matrix

This is a C Program to perform LU decomposition of a given matrix. Every square matrix A can be decomposed into a product of a lower triangular matrix L and a upper triangular matrix U, as described in LU decomposition.
A = LU
Here is source code of the C Program to Perform LU Decomposition of any Matrix. The C program is successfully compiled and run on a Linux system. The program output is also shown below.

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

#define foreach(a, b, c) for (int a = b; a < c; a++)
#define for_i foreach(i, 0, n)
#define for_j foreach(j, 0, n)
#define for_k foreach(k, 0, n)
#define for_ij for_i for_j
#define for_ijk for_ij for_k
#define _dim int n
#define _swap(x, y) { typeof(x) tmp = x; x = y; y = tmp; }
#define _sum_k(a, b, c, s) { s = 0; foreach(k, a, b) s+= c; }

typedef double **mat;

#define _zero(a) mat_zero(a, n)
void mat_zero(mat x, int n) {
for_ij
x[i][j] = 0;
}

#define _new(a) a = mat_new(n)
mat mat_new(_dim) {
mat x = malloc(sizeof(double*) * n);
x[0] = malloc(sizeof(double) * n * n);

for_i
x[i] = x[0] + n * i;
_zero(x);

return x;
}

#define _copy(a) mat_copy(a, n)
mat mat_copy(void *s, _dim) {
mat x = mat_new(n);
for_ij
x[i][j] = ((double(*)[n]) s)[i][j];
return x;
}

#define _del(x) mat_del(x)
void mat_del(mat x) {
free(x[0]);
free(x);
}

#define _QUOT(x) #x
#define QUOTE(x) _QUOT(x)
#define _show(a) printf(QUOTE(a)" =");mat_show(a, 0, n)
void mat_show(mat x, char *fmt, _dim) {
if (!fmt)
fmt = "%8.4g";
for_i {
printf(i ? " " : " [ ");
for_j {
printf(fmt, x[i][j]);
printf(j < n - 1 ? " " : i == n - 1 ? " ]\n" : "\n");
}
}
}

#define _mul(a, b) mat_mul(a, b, n)
mat mat_mul(mat a, mat b, _dim) {
mat c = _new(c);
for_ijk
c[i][j] += a[i][k] * b[k][j];
return c;
}

#define _pivot(a, b) mat_pivot(a, b, n)
void mat_pivot(mat a, mat p, _dim) {
for_ij
{
p[i][j] = (i == j);
}
for_i {
int max_j = i;
foreach(j, i, n)
if (fabs(a[j][i]) > fabs(a[max_j][i]))
max_j = j;

if (max_j != i)
for_k {
_swap(p[i][k], p[max_j][k]);
}
}
}

#define _LU(a, l, u, p) mat_LU(a, l, u, p, n)
void mat_LU(mat A, mat L, mat U, mat P, _dim) {
_zero(L);
_zero(U);
_pivot(A, P);

mat Aprime = _mul(P, A);

for_i {
L[i][i] = 1;
}
for_ij
{
double s;
if (j <= i) {
_sum_k(0, j, L[j][k] * U[k][i], s)
U[j][i] = Aprime[j][i] - s;
}
if (j >= i) {
_sum_k(0, i, L[j][k] * U[k][i], s);
L[j][i] = (Aprime[j][i] - s) / U[i][i];
}
}

_del(Aprime);
}

double A3[][3] = { { 1, 3, 5 }, { 2, 4, 7 }, { 1, 1, 0 } };
double A4[][4] = { { 11, 9, 24, 2 }, { 1, 5, 2, 6 }, { 3, 17, 18, 1 }, { 2, 5,
7, 1 } };

int main() {
int n = 3;
mat A, L, P, U;

_new(L);
_new(P);
_new(U);
A = _copy(A3);
_LU(A, L, U, P);
_show(A);
_show(L);
_show(U);
_show(P);
_del(A);
_del(L);
_del(U);
_del(P);

printf("\n");

n = 4;

_new(L);
_new(P);
_new(U);
A = _copy(A4);
_LU(A, L, U, P);
_show(A);
_show(L);
_show(U);
_show(P);
_del(A);
_del(L);
_del(U);
_del(P);

return 0;
}

Output

$ gcc LUDecomposition.cpp
$ ./a.out

A

1 3 5
2 4 7
1 1 0

L

1.00000 0.00000 0.00000
0.50000 1.00000 0.00000
0.50000 -1.00000 1.00000

U

2.00000 4.00000 7.00000
0.00000 1.00000 1.50000
0.00000 0.00000 -2.00000

P

0 1 0
1 0 0
0 0 1

------------------------------------------------------------------------------------------------------------



C Program to Implement Gauss Jordan Elimination Method

This C program implements Gauss Jordan Elimination method. In linear algebra, Gaussian elimination is an algorithm for solving systems of linear equations.
Here is the source code of the C program to find solution of a system of linear equations. The C program is successfully compiled and run on a Linux system. The program output is also shown below.

#include <stdio.h>

void solution( int a[][20], int var );
int main()
{

int a[ 20 ][ 20 ], var, i, j, k, l, n;
printf( "\nEnter the number of variables:\n" );
scanf( "%d", &var );

for ( i = 0;i < var;i++ )
{
printf( "\nEnter the equation%d:\n", i + 1 );

for ( j = 0;j < var;j++ )
{
printf( "Enter the coefficient of x%d:\n", j + 1 );
scanf( "%d", &a[ i ][ j ] );
}

printf( "\nEnter the constant:\n" );
scanf( "%d", &a[ i ][ var] );
}

solution( a, var );
return 0;
}



void solution( int a[ 20 ][ 20 ], int var )
{
int k, i, l, j;

for ( k = 0;k < var;k++ )
{
for ( i = 0;i <= var;i++ )
{
l = a[ i ][ k ];

for ( j = 0;j <= var;j++ )
{
if ( i != k )
a[i][j] = (a[k][k]*a[i][j])-(l*a[k][j]);
}
}
}

printf( "\nSolutions:" );

for ( i = 0;i < var;i++ )
{
printf( "\nTHE VALUE OF x%d IS %f\n", i + 1, ( float ) a[ i ][ var ] / ( float ) a[ i ][ i ] );
}

}

Output

$ gcc bubblesort.c -o bubblesort
$ ./bubblesort

Enter the number of variables: 3

Enter the equation 1:
Enter the coefficient of x1: 1
Enter the coefficient of x2: 0
Enter the coefficient of x3: 0

Enter the constant: 2

Enter the equation 2:
Enter the coefficient of x1: 0
Enter the coefficient of x2: 1
Enter the coefficient of x3: 0

Enter the constant: 0

Enter the equation 3:
Enter the coefficient of x1: 0
Enter the coefficient of x2: 0
Enter the coefficient of x3: 1

Enter the constant: -1

Solutions:
THE VALUE OF x1 IS 2.000000

THE VALUE OF x2 IS 0.000000

THE VALUE OF x3 IS -1.000000

--------------------------------------------------------------------------------------------------------------

C Program to Implement Gauss Seidel Method

This C program implements iterative version of Gauss Seidel Method. In this method, a system of linear equations is solved by iteration, using a brute-force kind of technique, to reach the actual solution.
Here is the source code of the C program to solve a system of linear equations. The C program is successfully compiled and run on a Linux system. The program output is also shown below.

#include <stdio.h>

int main() {
//a sparse way of representing the equations
float eq[3][4];
int i;
float x ,y , z;
x = 1; y = 1; z = 2; //initial guess
eq[0][0] = 7/4.0;
eq[0][1] = 0;
eq[0][2] = 1/4.0;
eq[0][3]= -1/4.0;
eq[1][0] = 21/8.0;
eq[1][1] = 4/8.0;
eq[1][2] = 0;
eq[1][3]= 1/8.0;
eq[2][0] = 15/5.0;
eq[2][1] = 2/5.0;
eq[2][2] = -1/5.0;
eq[2][3]= 0;



//10 iterations of gauss-seidel
for (i = 0;i < 10; i++) {
x = eq[0][0] + eq[0][2] * y + eq[0][3] * z;
y = eq[1][0] + eq[1][1] * x + eq[1][3] * z;
z = eq[2][0] + eq[2][1] * x + eq[2][2] * y;
printf("Output: \n%f %f %f\n", x, y, z);
}

return 0;
}

$ gcc gauss_seidel.c -o gauss_seidel
$ ./gauss_seidel

1.500000 3.625000 2.875000
1.937500 3.953125 2.984375
1.992188 3.994141 2.998047
1.999023 3.999268 2.999756
1.999878 3.999908 2.999969
1.999985 3.999989 2.999996
1.999998 3.999999 3.000000
2.000000 4.000000 3.000000
2.000000 4.000000 3.000000
2.000000 4.000000 3.000000
-------------------------------------------------------------------------------------------------------------

C Program to Represent Linear Equations in Matrix Form


This is a C Program to represent a set of linear equations in matrix form. This is c program to convert the system of linear equations to matrix form. The input is the coefficient of each variable and constant. Program rearranges them and converts them into matrix form, which aids solving them.
Here is source code of the C Program to Represent Linear Equations in Matrix Form. The C program is successfully compiled and run on a Linux system. The program output is also shown below.

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

int main(void) {
char var[] = { 'x', 'y', 'z', 'w' };
printf("Enter the number of variables in the equations: ");
int n;
scanf("%d", &n);
printf("\nEnter the coefficients of each variable for each equations");
printf("\nax + by + cz + ... = d");
int mat[n][n];
int constants[n][1];
int i,j;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
scanf("%d", &mat[i][j]);
}
scanf("%d", &constants[i][0]);
}

printf("Matrix representation is: ");
for (i = 0; i < n; i++) {
for (j = 0; j < n; j++) {
printf(" %f", mat[i][j]);
}
printf(" %f", var[i]);
printf(" = %f", constants[i][0]);
printf("\n");
}
return 0;
}

Output:

$ gcc MatRepOfEquation.cpp
$ ./a.out

Enter the number of variables in the equations: 3

Enter the coefficients of each variable for each equations
ax + by + cz + ... = d
1 2 3 4
1 2 6 8
2 3 9 8
Matrix representation is:
1 2 3 x = 4
1 2 6 y = 8
2 3 9 z = 8

---------------------------------------------------------------------------------------------------------------

C Program to Perform Matrix Multiplication

This C program performs matrix multiplication. In matrix multiplication, we take two matrices of order m*n and p*q respectively to find a resultant matrix of the order m*q where n is equal to p . Time Complexity of this algorithm is O(n3).
Here is the source code of the C program to perform matrix multiplication. The C program is successfully compiled and run on a Linux system. The program output is also shown below.

#include

int main()
{
int m, n, p, q, c, d, k, sum = 0;
int first[10][10], second[10][10], multiply[10][10];

printf("Enter the number of rows and columns of first matrix\n");
scanf("%d%d", &m, &n);
printf("Enter the elements of first matrix\n");

for ( c = 0 ; c < m ; c++ )
for ( d = 0 ; d < n ; d++ )
scanf("%d", &first[c][d]);

printf("Enter the number of rows and columns of second matrix\n");
scanf("%d%d", &p, &q);

if ( n != p )
printf("Matrices with entered orders can't be multiplied with each other.\n");
else
{
printf("Enter the elements of second matrix\n");

for ( c = 0 ; c < p ; c++ )
for ( d = 0 ; d < q ; d++ )
scanf("%d", &second[c][d]);

for ( c = 0 ; c < m ; c++ )
{
for ( d = 0 ; d < q ; d++ )
{
for ( k = 0 ; k < p ; k++ )
{
sum = sum + first[c][k]*second[k][d];
}

multiply[c][d] = sum;
sum = 0;
}
}

printf("Product of entered matrices:-\n");

for ( c = 0 ; c < m ; c++ )
{
for ( d = 0 ; d < q ; d++ )
printf("%d\t", multiply[c][d]);

printf("\n");
}
}

return 0;
}

Output

$ gcc matrix_multiply.c -o matrix_multiply
$ ./matrix_multiply

Enter the number of rows and columns of first matrix 3 3
Enter the elements of first matrix
1 2 0
0 1 1
2 0 1
Enter the number of rows and columns of second matrix 3 3
Enter the elements of second matrix
1 1 2
2 1 1
1 2 1
Product of entered matrices:-
5 3 4
3 3 2
3 4 5

-----------------------------------------------------------------------------------------
C Program to Check if a Matrix is a Sparse Matrix

This C program is used to check if a matrix is a sparse Matrix. If the number of zeros in a matrix exceeds (n*m)/2, where n, m is the dimension of the matrix, matrix is sparse matrix. Sparse matrix has more zero elements than nonzero elements.
Here is the source code of the C program to find out is a given matrix is a sparse matrix. The C program is successfully compiled and run on a Linux system. The program output is also shown below.

/*
* C Program to check if a Matrix is a Sparse Matrix
*/
#include

void main ()
{
int matrix[10][10];
int i, j, m, n;
int sparse_counter = 0;

printf("Enter the order of the matix \n");
scanf("%d %d", &m, &n);
printf("Enter the elements of the matix \n");
for (i = 0; i < m; ++i)
{
for (j = 0; j < n; ++j)
{
scanf("%d", &matrix[i][j]);
if (matrix[i][j] == 0)
{
++sparse_counter;
}
}
}
if (sparse_counter > ((m * n) / 2))
{
printf("The given matrix is Sparse Matrix !!! \n");
}
else
printf("The given matrix is not a Sparse Matrix \n");
printf("There are %d number of Zeros.", sparse_counter);
}

Output

$ gcc sparse_matrix.c -o sparse_matrix
$ ./sparse_matrix

Enter the order of the matix 3 3
Enter the elements of the matix
1 2 3
4 0 0
0 0 0
The given matrix is Sparse Matrix !!!
There are 5 number of Zeros.

-------------------------------------------------------------------------------------------------------------

Comments

No Comments have been Posted.

Post Comment

Please Login to Post a Comment.

Ratings

Rating is available to Members only.

Please login or register to vote.

No Ratings have been Posted.
Render time: 1.12 seconds
10,836,951 unique visits