1 Roots of quadratic equation
File: quadratic.c
#include <stdio.h>
#include <math.h>
void main(){
float a,b,c,d,r1,r2;
printf("\nEnter the coefficients a b c : ");
scanf("%f%f%f" ,&a,&b,&c);
if (a==0) {
printf("\nNot a quadratic equation");
}
d=b*b-4*a*c;
r1=-b/(2*a);
if (d==0){
printf("\nThe roots are real and equal");
printf("\nThe root =%f \n",r1);
}
else if(d>0){
r2=sqrt(d)/(2*a);
printf("\nThe roots are real and distinct");
printf("\nFirst root=%f \nSecond root=%f \n",r1+r2,r1-r2);
}else {
r2= sqrt(fabs(d))/(2*a);
printf("\nThe roots are imaginary");
printf("\nFirst root =%f +i%f", r1,r2);
printf("\nSecond root=%f -i%f \n", r1,r2);
}
}
The program is compiled and executed in terminal as follows:
$ gcc quadratic.c -o quadratic -lm
$ ./quadratic
Enter the coefficients a b c : 1 2 2
The roots are imaginary
First root =-1.000000 +i1.000000
Second root=-1.000000 -i1.000000
2 Rank List
File: ranklist.c
#include <stdio.h>
#include <string.h>
#define NMAX 20
1
#define NAMELENGTH 10
struct studentType{
char name[NAMELENGTH];
int marks;
};
void main(){
int n,i,j,marks;
char name[NAMELENGTH];
struct studentType students[NMAX];
printf("\nEnter number of students (< %d): ",NMAX);
scanf("%d",&n);
for(i=0;i<n;i++){
printf("\nEnter name and marks of sudent#%d: ",i+1);
scanf("%s %d",students[i].name,&students[i].marks);
}
for(i=0;i<n-1;i++)
for(j=0;j<n-1-i;j++){
if(students[j].marks < students[j+1].marks){
strcpy(name,students[j].name);
strcpy(students[j].name,students[j+1].name);
strcpy(students[j+1].name,name);
marks=students[j].marks;
students[j].marks=students[j+1].marks;
students[j+1].marks=marks;
}
}
printf("\nRank List");
printf("\n%7s %-11s %5s","Rank","Name","Marks");
for(i=0;i<n;i++){
printf("\n%7d %-11s %5d",i+1,students[i].name,students[i].marks);
}
printf("\n");
}
Compilation and execution
$ gcc ranklist.c -o ranklist
$ ./ranklist
Enter number of students (< 20): 4
Enter name and marks of sudent#1: alpha 34
Enter name and marks of sudent#2: beta 89
Enter name and marks of sudent#3: gamma 78
2
Enter name and marks of sudent#4: epsilon 96
Rank List
Rank Name Marks
1 epsilon 96
2 beta 89
3 gamma 78
4 alpha 34
3 Print values sin(x), tan(x) and exp(−x)
File name: funcval.c
compilation command: gcc funcval.c -o funcval -lm
exection: ./funcval
#include<stdio.h>
#include<math.h>
#define PI 3.141593
void main() {
float x,xr;
printf("\n enter the value of x in degree :");
scanf("%f" ,&x );
xr= x*PI/180;
printf("\n sine(%f) =%f \t tan(%f) =%f", x,sin(xr),x,tan(xr));
printf("\n e to the power of -%f is %f",x,exp(-x));
}
4 Ploting Functions
To plot a function f (x), we will create a text file with x-values in the first
column and the corresponding f (x) in the second column. In the examples
we discuss in this section, we assume the filename to be ’data.dat’. There are
many softwares available to produce graphs from the data files. Here, we use
the program Gnuplot.
4.1 Gnuplot
This program can be invoked from the terminal using the command gnuplot.
This will start the program with the prompt gnuplot>. The terminal on gnuplot
start-up looks like the following
$ gnuplot
G N U P L O T
Version 4.6 patchlevel 6 last modified September 2014
3
Build System: Linux x86_64
Copyright (C) 1986-1993, 1998, 2004, 2007-2014
Thomas Williams, Colin Kelley and many others
gnuplot home: http://www.gnuplot.info
faq, bugs, etc: type "help FAQ"
immediate help: type "help" (plot window: hit ’h’)
Terminal type set to ’x11’
gnuplot>
Now we discuss some gnuplot-commands that are used in creating two-dimensional
graphs.
command to plot a file:
plot <filename> <xcolumn>:<ycolumn> using <linestyle>
command to set labels of X- and Y- axes:
set xlabel <xlabelname>
set ylabel <ylabelname>
Here, terms within angular brackets < > should be replaced by appropriate
values. An example is provided below.
Example
• Set X-axis label to ‘x’
• Set Y-axis label to ‘f(x)’
• Plot the ‘data.dat’ with x-data from colum 1 and f (x) data from
column 2. Set the legend of the plot-curve to be ‘function f(x)’
The following set of gnuplot commands achieve this.
gnuplot> set xlabel ’x’
gnuplot> set ylabel ’f(x)’
gnuplot> plot ’data.dat’ using 1:2 with linespoints
title ’function f(x)’
The graph will appear on a separate window.
We can also save this graph to an image file. For example, to save the current
graph to a PNG file named ’plot.png’ we use the following set of commands.
gnuplot> set terminal png
Terminal type set to ’png’
Options are ’nocrop font "/usr/share/fonts/truetype/liberation
/LiberationSans-Regular.ttf,12" fontscale 1.0 size 640,480 ’
gnuplot> set output ’sin.png’
gnuplot> replot
We can exit gnuplot using the command exit.
4
gnuplot> exit
4.2 Plot sin(x)
The C program will create a file named ’sin.dat’ with x in the first column and
sin(x) in the second column. Gnuplot can generate the graph from this file.
File: plotsin.c
#include<stdio.h>
#include<math.h>
#define PI 3.141593
void main()
{
FILE *fp;
float xstart,xend,xstep,xr,x;
printf("\n enter initial and final values of x and step in degrees :
");
scanf("%f %f %f",&xstart, &xend, &xstep);
fp=fopen("sin.dat","w");
fprintf(fp,"#x \t sin(x) ");
for(x=xstart;x<=xend;x+=xstep){
xr=x*PI/180;
fprintf(fp,"\n %f %f",x,sin(xr));
}
fclose(fp);
}
Compilation and execution of the program is done the following way.
$ gcc plotsin.c -o plotsin -lm
$ ./plotsin
enter initial and final values of x and step in degrees :
0 360 5
The contents of the file can be viewed using a texteditor, for example gedit or
scratch.
First few lines of the file: sin.dat
#x sin(x)
0.000000 0.000000
5.000000 0.087156
10.000000 0.173648
15.000000 0.258819
20.000000 0.342020
25.000000 0.422618
30.000000 0.500000
35.000000 0.573576
.
.
.
5
The graph can be plotted using the following commands in gnuplot
$ gnuplot
G N U P L O T
Version 4.6 patchlevel 6 last modified September 2014
Build System: Linux x86_64
Copyright (C) 1986-1993, 1998, 2004, 2007-2014
Thomas Williams, Colin Kelley and many others
gnuplot home: http://www.gnuplot.info
faq, bugs, etc: type "help FAQ"
immediate help: type "help" (plot window: hit ’h’)
Terminal type set to ’x11’
gnuplot> set xlabel ’x(degrees)’
gnuplot> set ylabel ’sin(x)’
gnuplot> plot ’sin.dat’ using 1:2 with linespoints
title ’sine function’
The graph looks like
The graph can be saved into a PNG file named ‘sin.png’ using the following
set of commands
gnuplot> set terminal png
Terminal type set to ’png’
Options are ’nocrop font "/usr/share/fonts/truetype/liberation
6
/LiberationSans-Regular.ttf,12" fontscale 1.0 size 640,480 ’
gnuplot> set output ’sin.png’
gnuplot> replot
4.3 Plot tan(x)
File: plottan.c
#include<stdio.h>
#include<math.h>
#define PI 3.141593
void main()
{
FILE *fp;
float xstart,xend,xstep,xr,x;
printf("\n enter initial and final values of x and step in degrees :
");
scanf("%f %f %f",&xstart, &xend, &xstep);
fp=fopen("tan.dat","w");
fprintf(fp,"#x \t tan(x) ");
for(x=xstart;x<=xend;x+=xstep){
xr=x*PI/180;
fprintf(fp,"\n %f %f",x,tan(xr));
}
fclose(fp);
}
Compilation and execution
$ gcc plottan.c -o plottan -lm
$ ./plottan
enter initial and final values of x and step in degrees :
-85 85 5
This creates the file ‘tan.dat’ from which Gnuplot creates the graph
gnuplot> set xlabel ’x’
gnuplot> set ylabel ’tan(x)’
gnuplot> plot ’tan.dat’ u 1:2 with linespoints
title ’tan function’
7
4.4 Plot exp(−x)
File: plotexp.c
#include<stdio.h>
#include<math.h>
void main()
{
FILE *fp;
float x,xstart,xend,xstep;
printf("\n enter initial and final values of x and step : ");
scanf("%f %f %f",&xstart, &xend, &xstep);
fp=fopen("exp.dat","w");
fprintf(fp,"#x \t exp(-x) ");
for(x=xstart;x<=xend;x+=xstep){
fprintf(fp,"\n %f %f",x,exp(-x));
}
fclose(fp);
}
Compilation and execution
$ gcc plotexp.c -o plotexp -lm
$ ./plotexp
enter initial and final values of x and step : 0 10 0.1
8
This creates the file ‘exp.dat’ from which Gnuplot creates the graph
gnuplot> set xlabel ’x’
gnuplot> set ylabel ’exp(-x)’
gnuplot> plot ’exp.dat’ u 1:2 with linespoints
title ’function exp(-x)’
5 Product of two matrices
File: matrix.c
#include<stdio.h>
#include<stdlib.h>
#define ROWS 10
#define COLS 10
void getmatrix(int m, int n, int a[ROWS][COLS]){
int i,j;
for(i=0;i<m;i++)
for(j=0;j<n;j++)
scanf("%d",&a[i][j]);
}
void printmatrix(int m, int n, int a[ROWS][COLS]){
int i,j;
9
for(i=0;i<m;i++){
for(j=0;j<n;j++)
printf("%d ",a[i][j]);
printf("\n");
}
}
void main(){
int a[ROWS][COLS],b[ROWS][COLS],c[ROWS][COLS];
int m,n,p,q,i,j,k;
printf("\n Enter the order of first matrix\n");
scanf("%d%d",&m,&n);
printf("\n Enter the order of the second matrix \n");
scanf("%d%d",&p,&q);
if(n!=p){
printf("\n The orders do not match,cannot multiply\n");
exit(0);
}
printf("\n Enter the elements in first matrix\n");
getmatrix(m,n,a);
printf("\n Enter the elements in second matrix\n");
getmatrix(p,q,b);
for(i=0;i<m;i++){
for(k=0;k<q;k++){
c[i][k]=0;
for(j=0;j<n;j++)
c[i][k]=c[i][k]+a[i][j]*b[j][k];
}
}
printf("\n First matrix \n");
printmatrix(m,n,a);
printf("\n second matrix \n");
printmatrix(p,q,b);
printf("\n The product of the above matrices:\n");
printmatrix(m,q,c);
}
Compilation and execution
$ gcc matrix.c -o matrix
$ ./matrix
Enter the order of first matrix
2 2
Enter the order of the second matrix
10
2 2
Enter the elements in first matrix
3 4
7 8
Enter the elements in second matrix
10 2
1 7
First matrix
3 4
7 8
second matrix
10 2
1 7
The product of the above matrices:
34 34
78 70
6 Scalar and Vector Products
File name: vecproducts.c
compilation command: gcc vecproducts.c -o vecproducts
exection: ./vecproducts
#include <stdio.h>
void main(){
float a1,a2,a3,b1,b2,b3,c1,c2,c3,scalarproduct=0;
printf("\nEnter (3D)vector a:");
scanf("%f %f %f",&a1,&a2,&a3);
printf("\nEnter (3D)vector b:");
scanf("%f %f %f",&b1,&b2,&b3);
scalarproduct=a1*b1+a2*b2+a3*b3;
c1=a2*b3-a3*b2;
c2=a3*b1-a1*b3;
c3=a1*b2-a2*b1;
printf("\nVector a: [%f \t %f \t %f]\n",a1,a2,a3);
printf("\nVector b: [%f \t %f \t %f]\n",b1,b2,b3);
printf("\nScalrproduct= %f\n",scalarproduct);
printf("\nVector product: [%f \t %f \t %f]\n",c1,c2,c3);
}
The compilation and execution in the terminal looks like the following
11
$ gcc vecproducts.c -o vecproducts
$ ./vecproducts
Enter (3D)vector a:1 3 4
Enter (3D)vector b:2 6 -3
Vector a: [1.000000 3.000000 4.000000]
Vector b: [2.000000 6.000000 -3.000000]
Scalrproduct= 8.000000
Vector product: [-33.000000 11.000000 0.000000]
7 Numerical Integration: Trapezoidal Rule
File: trapezoidal.c
#include <stdio.h>
double fn(double x){
return 1/(1+x*x);
}
double trapz(double f(double), double a, double b, int n){
double h, sumt,x;
h=(b-a)/n;
sumt=(f(a)+f(b))/2;
for(x=a+h;x<b;x+=h){
sumt=sumt+f(x);
}
return (sumt*h);
}
void main(){
int n;
double a,b;
printf("\nEnter number of intervals( >2),initial and final points:
");
scanf("%d %lf %lf",&n,&a,&b);
if((n%2)) n++;
printf("\nTrapezoidal rule: n=%d, integral=%lf\n",n,trapz(fn,a,b,n));
}
$ gcc trapezoidal.c -o trapezoidal
$ ./trapezoidal
Enter number of intervals( >2),initial and final points: 20 0 1
12
Trapezoidal rule: n=20, integral=0.785294
8 Numerical Integration: Simpson’s Rule
File: simpson.c
#include <stdio.h>
#include <math.h>
double fn(double x){
return sin(x);
}
double simpson(double f(double), double a, double b, int n){
double h,x,sums;
h=(b-a)/n;
sums=(f(a)+f(b))/2+2*f(b-h);
for(x=a+h;x<b-h;x+=2*h){
sums=sums+2*f(x)+f(x+h);
}
return (sums*h*2/3);
}
void main(){
int n;
double a,b;
printf("\nEnter number of intervals(even, >2),initial and final
points: ");
scanf("%d %lf %lf",&n,&a,&b);
if((n%2)) n++;
printf("\nSimpson rule: n=%d, Integral=%lf\n",n,simpson(fn,a,b,n));
}
Compilation and Execution:
$ gcc simpson.c -o simpson -lm
$ ./simpson
Enter number of intervals(even, >2),initial and final points:
20 0 3.14
Simpson rule: n=20, Integral=2.000006
9 Ordinary Differential Equations: Runge-Kutta
Method
File: rk2.c
13
#include <stdio.h>
float f(float y, float t){
return -y;
}
void main(){
float y,t,yout,h,tstart,tend,k1,k2;
FILE *fp;
y=10;
h=0.1;
tstart=0;
tend=10;
fp=fopen("rk2.dat","w");
fprintf(fp,"\n%f %f",tstart,y);
for(t=tstart;t<tend;t+=h){
k1=f(y,t);
k2=f(y+h*k1,t+h);
yout=y+(k1+k2)*h/2;
y=yout;
fprintf(fp,"\n%f %f",t+h,y);
}
fclose(fp);
}
Compilation and Execution:
$ gcc rk2.c -o rk2
$ ./rk2
Plotting the solution y(t) using Gnuplot:
gnuplot> set xlabel ’t’
gnuplot> set ylabel ’y(t)’
gnuplot> plot ’rk2.dat’ u 1:2 with linespoints title
’solution of dy/dt=-y, y(0)=10’
14
15