You are viewing our Forum Archives. To view or take place in current topics click here.
Basic C++ Tutorial (Updated with downloadable E-Book)
Posted:

Basic C++ Tutorial (Updated with downloadable E-Book)Posted:

skatertg
  • Winter 2022
Status: Offline
Joined: Jan 20, 201014Year Member
Posts: 8,013
Reputation Power: 2165
Status: Offline
Joined: Jan 20, 201014Year Member
Posts: 8,013
Reputation Power: 2165
This tutorial is to basically teach you about the basics of C++ syntax such as declaring functions, variables, etc and how to use basic IO functions (Input/Output).

If you want to learn C++ in more detail here the download to an e-book that has helped me when I started learning: [ Register or Signin to view external links. ]


Credits go to [ Register or Signin to view external links. ] of course.





Basics

First of all we want to write the infamous and sometimes irritating Hello World program.
Please have a look at the code below.


1.   #include <iostream>
2.   
3.   // using namespace std;
4.   
5.   int main()
6.   {
5.        std::cout << Hello World! << std::endl;
6.
7.      return 0;
8.     }


Now, on line 1 you will see #include. In C++ this is how in include header files which contains functions that we can use in our programs.

The iostream header is used for input and output in console applications.

On line 3 you will notice that there are two forward slashes. This is how we specify a comment.
You can also specify multi-line comments but I will show you how to do that later.
Now On line 3 I have commented out using namespace std if I hadnt commented out that line we would not need to add std:: to the front of cout on line five.

The reason why I have commented this line is so I can still explain that it is considered bad programming practice to actually use some namespaces as they could declare a function that has the same name as another function.

The function main starts on line 5 and has a return value of type integer. I will explain this in more detail a little later.

Inside main() on line 5 you can see std::cout << Hello World!;. This is the heart of our application. This line prints the string Hello Word to the console screen.

cout stands for Console output thus meaning that this command will print whatever you have behind the << symbols.

Think of it this way, the << symbols point towards cout meaning you are passing Hello World! to the screen.

std::endl is just a simple way of placing a newline character (\n) at the end to make a new line.
You can also do this by replacing Hello World! with Hello World!\n or replace std::endl with a newline character in single quotation marks (\n).

To receive input from a user you would use std::cin >> variable_name;
I will explain this in more detail later on as well as variable declarations..

Line 7 is the most important line in the program as it defines whether the application throws an error or closes properly.

Also all the code that is in the function main() must be enclosed in a pair of curly brackets.
Recieving input from a user is quite easy. In the next example I will show you how to declare variables and how to add give those variables a value.


1.   #include <iostream>
2.   
3.    int main()
4.   {
5.       std::string first, last;
6.       std::cout << Please enter your first and last name: ;
7.       std::cin >> first >> last;
8.   
9.       std::cout << \n << It is nice to meet you  << first <<   << last << . << std::endl;
10.   
11.       return 0;
12.     }


On line 5 you can see std::string, this is how we declare a variable of type string and seeing as string is a member of the std namespace we must have the std:: in front of string unless we type using namespace std under the #include statement.

You can declare other variable types such as int, float, long, char, etc.

On line 7 we pass user input to the variables first and last from std::cin (Console Input).
The way this works is when the user types something int the first word will be placed in first and when the program runs into a space character it will start putting the rest of a variable into last.

The only problem with this approach is that if you put a space after the last name and keep typing everything you type will be discarded.

So what do you do if you want to pass a whole sentence to a variable? We use std::getline.

1.   #include <iostream>
2.   
3.   int main()
4.   {
5.       std::string name;
6.   
7.       std::cout << Please enter your full name: ;
8.       std::getline(std::cin, name);
9.   
10.       std::cout << \n << Its nice to meet you  << name << . << std::endl;
11.       return 0;
12.   }


To use std::geline you need to give it some sort of input. On line 8 you can see that the first argument for std::getline is std::cin and the second argument is the variable that it will pass the line to.

This program will accept all input and place it in name.




For Loop

A for loop in C++ is much more difficult than its relatives in other programming languages.
Once you become more adept with the C++ language you will realise multiple ways that you can utilize a for loop in any program.

The example below shows you how to write a simple program that counts to 20 and prints out every number along the way.


1.   #include <iostream>
2.   
3.   int main()
4.   {
5.       for (int i = 1; i <= 20; i++)
6.       {
7.          std::cout << i;
8.       }
9.       
10.       return 0;
11.    }


Now there are three parts of a for loop.
The initialization, condition and the increment.

The initialization is used to declare a variable used in the loop.
While the condition is non-zero the loop will continue.
The increment is just how you want to change the variable in such a way to make the for loop move.

In the example above I created an integer that holds the value of 1. Then I add a condition that tests if the integer i is less than or equal to 20 and then for the increment I have made it add 1 to the integer i on every loop with i++.

When you run this program it will print the value of i to the screen until i equals 20.




While Loop

The while loop is the same as in any other programming language, it only accepts a single condition.
The example below is the same as the one above but it uses a while loop instead of a for loop.


1.   #include <iostream>
2.   
3.   int main()
4.   {
5.       int i = 1;
6.       while (i <= 20)
7.       {
8.          std::cout  << i;
9.          I++;
10.       }
11.   
12.       return 0;
13.   }


As you can see with a while loop you need to add an incrimination in the loop to make it so it will count up, unlike the for loop where you add the incrimination to the actual declaration of the for loop.




If, Else If and Else Statements.

The if statement can be useful for a great amount of situations. Lets say you want to write a program that has multiple stuff it can do and you would like the user to select what they would like to do.

The else if statement is used to check if something else is true if only the first if statement returns false.

The else statement will be only work if the preceding if and else if statements all return false.

Have a look at the example below.


1.   #include <iostream>
2.   
3.   int main()
4.   {
5.       int choice, x, y;
6.   
7.       std::cout << Please enter an integer as your choice. << \n
8.            << [1] Print Hello. << \n
9.            << [2] Add two integers. << \n
10.            << [3] Multiply two integers. << \n
11.            << Choice > ;
12.   
13.       std::cin >> choice;
14.       std::cout << std::endl;
15.   
16.       if (choice == 1)
17.       {
18.          std::cout << Hello! << std::endl;
19.       }
20.       else if (choice == 2)
21.       {
22.          std::cout << Integer 1: ;
23.          std::cin >> x;
24.          std::cout << \n << Integer 2: ;
25.          std::cin >> y;
26.          std::cout << \n << x <<  +  << y <<  =  << x+y << std::endl;
27.       else if (choice == 3)
28.       {
29.          std::cout << Integer 1: ;
30.          std::cin >> x;
31.          std::cout << \n << Integer 2: ;
32.          std::cin >> y;
33.          std::cout << \n << x <<  *  << y <<  =  << x*y << std::endl;
34.       }
35.       else
36.       {
37.          std::cout << You can only enter an integer between 1 and 3! << std::endl;
38.       }
39.   
40.       return 0;
41.   }


As you can see in the example above, The use is prompted with a menu of things the program can do and they have a choice between three different things.

If they choose 1 the program will print Hello! and exit,
if they choose 2 the program will prompt them for two numbers and it will add them and print the result to the screen,
if they choose 3 the program will do the same as if they typed 2 put it multiplies the numbers that the user types.

If the user types anything that isnt a 1, 2 or 3 it will print a message letting them know that they can only enter one of the three numbers and then exit.




Arrays and Switches

An array is a variable that can hold multiple values. One thing to remember when working with arrays is that in programming everything starts as a zero.

Here is an example of how to declare an array.


1.   #include <iostream>
2.   
3.   int main()
4.   {
5.       int int_array[10]; // Declaring an array with a size of 10
6.    /*
7.         Give int_array[a] the value of a + 1.
8.         So int_array[3] will be 4.
9.   */
10.       for (int a = 0; a <= 9; a++)
11.       {
12.          int_array[a] = a + 1;
13.       }
14.   
15.       for (int b = 0; b < =9; b++)
16.       {
17.          std::cout << int_array[ << b << ] =  << int_array[b] << std::endl;
18.       }
19.   
20.       return 0;
21.   }


The program above is to show you how an array works.
This is the output of the program.


int_array[0] = 1
int_array[1] = 2
int_array[2] = 3
int_array[3] = 4
int_array[4] = 5
int_array[5] = 6
int_array[6] = 7
int_array[7] = 8
int_array[8] = 9
int_array[9] = 10


As you can see the array starts at 0 and ends at 9 but it still has 10 places.
Arrays can be useful for many different reasons so remember to use them.

Switches are case statements and are a cleaner version of a if statement when you want to check the value of a variable and do something depending on that value.
The example below is the same as the one we had for the if statements when we had a menu.


1.   #include <iostream>
2.   
3.   int main()
4.   {
5.       int choice, x, y;
6.   
7.       std::cout << "Please enter an integer as your choice." << '\n'
8.            << "[1] Print Hello." << '\n'
9.            << "[2] Add two integers." << '\n'
10.            << "[3] Multiply two integers." << '\n'
11.            << "Choice > ";
12.   
13.       std::cin >> choice;
14.      std::cout << std::endl;
15.   
16.       switch (choice)
17.       {
18.          case 1:
19.          {
20.             std::cout << "Hello!" << std::endl;
21.          }
22.          case 2:
23.          {
24.             std::cout << "Integer 1: ";
25.             std::cin >> x;
26.             std::cout << '\n' << "Integer 2: ";
27.            std::cin >> y;
28.            std::cout << '\n' << x << " + " << y << " = " << x + y << std::endl;
29.          }
30.          case 3:
31.          {
32.            std::cout << "Integer 1: ";
33.            std::cin >> x;
34.            std::cout << "Integer 2: ";
35.            std::cin >> y;
36.            std::cout << '\n' << x << " * " << y << " = " << x * y << std::endl;
37.          }
38.          default:
39.          {
40.            std::cout << "You can only enter an integer between 1 and 3!\n";
41.          }
42.       }
43.   
44.       return 0;
45.   }


For each number in the menu we have added a case to deal with it but where we had an else statement in the other example we have added a default case.
The default case will only execute if none of the cases above are true.




Writing your own functions.

Writing your own functions can be very useful so I thought I would chuck this little bit into the tutorial.

If you have been paying attention to the main() functions in all the example programs have the word int in front of them and that there is always a return function at the end of main then you are already on your way to understanding functions.

When you start to write bigger programs functions will come in handy and making functions that return a value will become more so.
In the example below I have created the function Addition that has an integer return value.

NOTE:
If you are to place functions below the main() in your source you must declare a prototype for that function. Seeing as I followed that rule when I was learning C++ I will try to encourage you guys/girls to do it as well.


1.   #include <iostream>
2.   
3.   /* Prototype Declarations */
4.    int addition(int x, int y);  // Addition accepts two arguments of type integer.
5.   
6.   int main() // Return value of type integer.
7.   {
8.       int result, x, y;
9.   
10.       std::cout << Enter integer 1: ;
11.       std::cin >> x;
12.       std::cout << \n << Enter integer 2: ;
13.       std::cin >> y;
14.   
15.       result = addition(x, y); // Pass the return value of addition to result.
16.       
17.       std::cout << x <<  +  << y <<  =  << result << std::endl;
18.   }
19.   
20.   int addition(int x, int y)
21.   {
22.       return x + y;
23.   }


In the example above we declare a function of return type integer that returns the sum of x and y.

The user enters two integers and we call addition with the two integers as arguments.
Then addition returns x + y and is passed to the variable result and we print the string x + y = result.

Quite simple yes?

Credits to vb-board.com


I will be updating when i get the time


Last edited by skatertg ; edited 4 times in total

The following 23 users thanked skatertg for this useful post:

SovietRussia (02-18-2013), Leak (09-23-2012), Odin (06-27-2012), rghmodz (06-14-2012), DrAzzazzin (04-27-2012), JackM97 (04-03-2012), Oahu (02-28-2012), Coolinator89 (01-10-2012), Lucario- (12-13-2011), Overfield (11-17-2011), DiamondMoDZz (10-07-2011), Matt (07-24-2011), ElusivePatches (05-22-2011), TTGxFreeB00T_Fanboy (03-28-2011), Kr3wModz (03-02-2011), TTG_Yankees (03-01-2011), HiTideHax (02-19-2011), vary (01-24-2011), CoNdEmR (01-04-2011), Fiberzz (01-02-2011), -ADayToRemember (01-01-2011), G_Man (12-01-2010), PossibleDerp (12-01-2010)
#2. Posted:
Maximilian
  • TTG Fanatic
Status: Offline
Joined: Jul 05, 201013Year Member
Posts: 4,077
Reputation Power: 195
Status: Offline
Joined: Jul 05, 201013Year Member
Posts: 4,077
Reputation Power: 195
Thanks skater, you are awesome.


~ Respect the rules.
#3. Posted:
_iTBAG_TTG_
  • TTG Addict
Status: Offline
Joined: Aug 02, 201013Year Member
Posts: 2,516
Reputation Power: 124
Status: Offline
Joined: Aug 02, 201013Year Member
Posts: 2,516
Reputation Power: 124
Did i ever mention "Youre awsome?"
#4. Posted:
TTG_Gold_Jake
  • TTG Destroyer
Status: Offline
Joined: Jun 25, 201013Year Member
Posts: 7,353
Reputation Power: 336
Status: Offline
Joined: Jun 25, 201013Year Member
Posts: 7,353
Reputation Power: 336
I never really got C++
Always too complex for me
VB FTW! xD
#5. Posted:
3OH3
  • Summer 2018
Status: Offline
Joined: Feb 21, 201014Year Member
Posts: 5,715
Reputation Power: 279
Status: Offline
Joined: Feb 21, 201014Year Member
Posts: 5,715
Reputation Power: 279
Good tut. But you may want to include how some very small things can be different depending on what kind of compiler you use. For instance on my compiler I would write something along the lines of #include <Iostream> but on different compilers one might use #include <iostream.h>

But anyways, very good tut for people wanting/thinking about learning C++.... I love using that language.... Although sometimes it gets kind of irritating that the compiler I use is always so picky at what I type :p

Also, since when did we have a programming fourm lol?
#6. Posted:
skatertg
  • V5 Launch
Status: Offline
Joined: Jan 20, 201014Year Member
Posts: 8,013
Reputation Power: 2165
Status: Offline
Joined: Jan 20, 201014Year Member
Posts: 8,013
Reputation Power: 2165
3OH3 wrote Good tut. But you may want to include how some very small things can be different depending on what kind of compiler you use. For instance on my compiler I would write something along the lines of #include <Iostream> but on different compilers one might use #include <iostream.h>

But anyways, very good tut for people wanting/thinking about learning C++.... I love using that language.... Although sometimes it gets kind of irritating that the compiler I use is always so picky at what I type :p

Also, since when did we have a programming fourm lol?


It doesn't really cause much of an issue as to put it in imo, i have only added in stuff to do with learning the basics, although i guess you could say its a basic people can read your comment and figure it out

What compiler are you using?

And since yesterday
#7. Posted:
ktwizzle13
  • 2 Million
Status: Offline
Joined: Mar 24, 201014Year Member
Posts: 5,407
Reputation Power: 289
Status: Offline
Joined: Mar 24, 201014Year Member
Posts: 5,407
Reputation Power: 289
thanks skater once again your posts are always helpful
#8. Posted:
G_Man
  • Retired Staff
Status: Offline
Joined: Mar 24, 201014Year Member
Posts: 5,367
Reputation Power: 547
Status: Offline
Joined: Mar 24, 201014Year Member
Posts: 5,367
Reputation Power: 547
Brings back memories of computing in high school

spent two months doing programming - fun but frustrating as hell

Very nice topic, i myself was going to post something similar until i saw this, maybe sticky it?
#9. Posted:
Canning87
  • TTG Commander
Status: Offline
Joined: May 17, 201013Year Member
Posts: 6,839
Reputation Power: 311
Status: Offline
Joined: May 17, 201013Year Member
Posts: 6,839
Reputation Power: 311
can i have your account info so i can sticky this nice post skater
#10. Posted:
xKryptic
  • Retired Staff
Status: Offline
Joined: Jun 24, 200914Year Member
Posts: 11,065
Reputation Power: 1528
Status: Offline
Joined: Jun 24, 200914Year Member
Posts: 11,065
Reputation Power: 1528
Nice tutorial.

I never really got into C++.

I'll probably learn it in the future, but for now I'll stick to java.
Jump to:
You are viewing our Forum Archives. To view or take place in current topics click here.