Thread Rating:
  • 1 Vote(s) - 5 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Learn C++ (The Correct Way) - Lesson 2
#1
Hi, this is lesson 2 in learning C++ the proper way. We will discuss basic math operations and converting data. So you should have an IDE setup and ready and know the basics of input and output from lesson 1. We will use the skills we learnt there and apply them here into making programs that could be useful to someone. This tutorial is split up into two sections: Section 1 – Maths Basics, Section 2 – Conversion Basics. First I will show you a simple application and explain line by line then i will post source code for real world programs that can be customised by you to perform a different operation, so let’s begin. (Note: I welcome all criticism and comments on this tutorial).
Basic Maths
First open up the IDE of your choice and create a new source file with a .cpp extension, for the purpose of the tutorial I will call it BasicMath.cpp. So like last time we will have the same program structure:

1. Include Files
2. Declare Standard Namespace
3. Start the main program loop
4. Then our application code
5. Then code to prevent application from ending before we see the results
6. Then tell the compiler to stop executing the main loop


For simple maths like +,-,*,/ you don’t need any extra includes. So our first line is the same as lesson 1:

Code:
#include <iostream>
So we know want to say which namespace where using which is the standard library:

Code:
using namespace std;
Like all of our applications so far we will then use the in main() to tell the compiler where our program actually starts.

Code:
int main(){
So how are we going to some basic math operations, well its actually very simple:

Code:
cout << "3 + 4 = " << 3 + 4 << "" << endl;
So what’s different in this cout statement than in the ones we have seen previously? Well after our string we have the cout insertion operators then our some in this case its 3+4 and we would expect it to output 7 to the screen, which it would if we were to end our program here, but let’s add some more operations.

Code:
cout << "3 - 4 = " << 3 - 4 << "" << endl;
cout << "3 * 4 = " << 3 * 4 << "" << endl;
cout << "12 / 4 = " << 12 / 4 << "" << endl;
cout << "3 / 4 = " << 3.0 / 4.0 << "" << endl;
So we have added the minus, times and divide operator. You may have asked why i have done to divide twice. Well the first one 12/4 is just simply 3 and is a whole number but if we do 3 / 4 then we get a decimal, if you replaced the 3.0/4.0 with 3/4 and ran the program you will get 0. How can we combat this? Simply actually by placing a decimal place we can get the correct answer of 0.75.
This program does not require any input using the cin function so we can use cin.ingore(); instead of system(“PAUSE”);. If you try using the cin.ignore(); or cin.get(); with a program using the cin function then it will prevent the program from working correctly.

Code:
cin.ignore();
So like usual we will finish main loop off with our return 0; and then add the closing curly brace.

Code:
return 0;
}
So if we now compile and run or debug the program you should see the calculations being performed and the correct answers being produced.
Full source code listing for BasicMath.cpp

Code:
#include <iostream>
using namespace std;
int main()
{
    cout << "3 + 4 = " << 3 + 4 << "" << endl;
    cout << "3 - 4 = " << 3 - 4 << "" << endl;
    cout << "3 * 4 = " << 3 * 4 << "" << endl;
    cout << "12 / 4 = " << 12 / 4 << "" << endl;
    cout << "3 / 4 = " << 3.0 / 4.0 << "" << endl;
    cin.ignore();
    return 0;
}
So now that we can perform calculations in C++, its about time we created a program that could be useful to someone. I decided a good application to make would be a program to find the length of the Hypotenuse using Pythagoras. It should retrieve the lengths of the adjacent and opposite from the user and then calculate the length. In this program some new concepts are introduced like extra includes, different data types and multi step calculations. So first create a new .cpp file and it call it want you want. For this program we will require two includes: the first like usual handles input and output, the second is for advanced maths functions.
So our first two lines are:

Code:
#include <iostream> // Basic Input/Output
#include <math.h> // Square root function
The next two lines should be obvious:

Code:
[code]using namespace std;
int main(){
So let’s look at another new item:

Code:
float opposite;
float adjacent;[/code]
In the previous lesson we used int age;, this is the same thing but with a different data type. So why did I choose to use float over int. Well as seen earlier int does not allow for decimal places but that’s where our friend Mr. Float comes in handy. A float is a data type just like int but can handle decimal places. So we can define our floats to be any number and not receive any wrong numbers. So let’s get some numbers in which to work with from the user.

Code:
cout << "Please enter the opposite length" << endl;
cin >> opposite;    
cout << "Please enter the adjacent length" << endl;
cin >> adjacent;
These lines are self explanatory, it asks the user to define the two sides.
Pythagoras is defined as a2=b2+c2 if we want to find the hypotenuse, if we want to find b or c then we can jus rearrange the equation to fit our needs but for this program we are going to find A (hypotenuse). So how can we write a2=b2+c2 in a way that our C++program can used to calculate A. Well we can use the sqrt() function from the math.h we included earlier. But first we need to do b2+c2, then square root our answer. This can be done by the following line:

Code:
cout << "The length of the hypotenuse is " << sqrt(((opposite*opposite) + (adjacent*adjacent))) << "" << endl;
Then finish off the program with:

Code:
system(“PAUSE”);
return 0;
}
That’s all there is to it.
Complete source code:

Code:
#include <iostream>
#include <math.h>
using namespace std;
int main(){
    float opposite;
    float adjacent;
    cout << "Please enter the opposite length" << endl;
    cin >> opposite;
    cout << "Please enter the adjacent length" << endl;
    cin >> adjacent;
    cout << "The length of the hypotenuse is " << sqrt(((opposite*opposite) + (adjacent*adjacent))) << "" << endl;
    system("PAUSE");
    return 0;
}
Conversion
So now we can do maths and we can create math based programs. We can now move onto just as practical programs that involve calculations.
Conversion can be done exactly like how we the pythag solver but may not always require the math.h include. Instead of saying what each line of code does I will just add a comment after the line of code. This program will convert degrees to radians, the equation to do so is:

Code:
Pi Radians = Degrees * (Pi/180)
e.g. 360 * (Pi/180) = 2 Pi Radians
There is one thing that is new in the code is the use of #define, this allows the programmer to define variablename value, where going to use this for our value of PI.

Code:
#include <iostream> // Include standard input/output functions
using namespace std; // Declare which namespace we are using, in this case its standard
#define PI 3.1415926535897932384626433832795 // Define our value for Pi
int main(){ // start the main program loop
    float degrees; // float with degrees variable
    cout << "Please enter your degrees value" << endl; // Output string message
    cin >> degrees; // Ask user to input a value
    cout << "" << (degrees * (PI / 180)) << " pi radians" << endl; // Output answer
    system("PAUSE"); // Wait for system to press any key
    return 0; // End program loop
}

So in this lesson you should have learned basic maths and the use of the math.h file for calculations beyond iostream. Also you should have learned that you can define values yourself so they can be used later. Also that it is simple to convert one number to another using a multi step math calculation.
Lesson 3 will be about if and else statements and will use things from what we have learned in lesson 1 and 2.
Thanks for reading
Quote:Who has two thumbs and doesn't give a crap.......Bob Kelso......Have we met?
[Image: BobKelso.jpg]
Reply
#2
uuhoo Smile wonderful tut. Thanks dude ;)
Reply
#3
Really helpful.. Loving your tuts. Helped me out a lot.
Reply
#4
Hey doc, thanks.
Quote:Who has two thumbs and doesn't give a crap.......Bob Kelso......Have we met?
[Image: BobKelso.jpg]
Reply
#5
Did you write your lesson on the pointers yet ?
Reply
#6
nice code king very good code
Reply
#7
gud details

thax
[Image: 2d75599e9a.png]:superman:
Reply
#8
make lesson 3 man.
i like your tut, good job!
Reply
#9
Very good for beginners, Keep Going!
Reply
#10
hard to learn if ur not doing hands on
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Learn C++ (The Correct Way) - Lesson 1 Code King 43 16,592 08-09-2012, 10:47 AM
Last Post: Rwkeith
  At What Age Did You Learn C++ Win 66 17,583 12-11-2011, 02:52 PM
Last Post: Neel

Forum Jump:


Users browsing this thread: 1 Guest(s)