C++ Tutorial in Linux
An introduction to C++, is very beneficial to the research group.
I have written these
tutorials so programming resources are available. In this section I
will
write a little more about programming and give an example that will
enable you to work, and learn c++ programming. In any programming
language we always get an structure to how the program is build onto.
One example of this is how we by in building a source code, what
does it take to have a program. Here is program structure that shows
how a program works.
The problem that we have is the following.
You want to find the roots of a quadratic equation, given that, the
standard equation for a quadratic equation is
Ax^2+Bx+C=0.
We we want to start design a program that would find the solutions to
the quadratic equations,
because what we want to do is find a good solution based on our
knowledge of quadratic equations.
Here is brief of how to configurate your Unix or Linux machine,
depeninng from what you are working from.
I am particular working from the webster server.
If you are at teminal, make a directory that you can save all your
work on: type
>mkdir practice
>cd practice
> emacs -nw quadratic_roots.cpp
My screen shot looks like this.
Type the following code in this file:
//******************************************************************
//Quadratic Root Finder: This program finds the roots of any
//quadratic equation. Using the equation x=-b+or-sqrt(b^2-4*a*c)/2*a
//******************************************************************
//Header Files
#include<iostream>
#include<cmath>
using namespace std;
int main()
{
//declare variables
int a=0, b=0, c=0;
double discriminant=0, x_1=0, x_2=0;
cout<<"Enter a, b, and c.";
cin>>a>>b>>c;
//Calculations
discriminant = b*b-4*a*c;
if (discriminant > 0)
x_1=((-b)+sqrt(discriminant))/(2*a);
x_2=((-b)-sqrt(discriminant))/(2*a);
cout<<"The two real roots are "<<x_1<<" and
"<<x_2<<" ."<<endl;
if (discriminant < 0)
cout<<"The roots are complex."<<endl;
else if (discriminant == 0)
x_1=(-b)/(2*a);
cout<<"The only root is "<<x_1<<endl;
return 0;
}
*Note you can also copy and paste it in your file. To compile this file
what we need to do is the following: In the prompth. Type the following
comand.
>g++ quadratic_roots.cpp -o quadratic_roots.exe
What this command does is compiles the file quadratic_roots.cpp and
turns that in an exacutable file. To execute the file, type what is
shown below:
>./quadratic_roots.exe
It should run just fine. Even though we might find some problems trying
to understand what it is doing.
Things you have learn:
1. Edit a new c++ file
2. Compile a c++ file and execute it.