We consider N electric charges of values \(q_i\) located in a plane at the points \(Q_i\) of coordinates \(x_i, y_i\).
The \(q_i, x_i\) and \(y_i\) values are stored in a one dimensional array. The potential energy of these N charges is: \(\frac{1}{4\pi\epsilon_0}\sum_{i=0}^{i=N-1}\sum_{j>i}^{j=N-1}\frac{q_iq_j}{|\overrightarrow{Q_iQ_j}|}\)
We have \(\frac{1}{4\pi\epsilon_0}=9.10^9 SI\).
Write a program that calculates this potential energy. In the case where two charges are at the same position, the following instructions shall be executed:
printf("Two charges are at the same position\n");
exit(0);
the second instruction serving to interrupt the execution of the program.
Use the following set fo data:
double x[N]={1.5,2.7,-6.3},y[N]={-5.3,3.9,4.1},q[N]={1.7,4.2,3.8};
Difficulty level
This exercise is mostly suitable for students
#include<conio.h>
#include<stdio.h>
#include<stdlib.h>
#include<math.h>
#define N 3
void main()
{
int i,j;
double x[N]={1.5,2.7,-6.3},y[N]={-5.3,3.9,4.1},q[N]={1.7,4.2,3.8};
double a,b,d,ee;
const double cc=9.e9;
for(ee=0,i=0;i<N;i++)
{
for(j=i+1;j<N;j++)
{
a=x[i]-x[j];
b=y[i]-y[j];
d=sqrt(a*a+b*b);
if(d==0.)
{
printf("Two charges are at the same position\n");
exit(0);
}
ee+=q[i]*q[j]/d;
}
}
ee*=cc;
printf("Energy=%lf Joules\n",ee);
getch();
}
Back to the list of exercises
Looking for a more challenging exercise, try this one !!
Lagrange form of the polynomial interpolation