In this tutorial you will learn the basics of C++ and how to use functions. This will allow you to write a simple C++ program that you will then compile. The program will be a Visual Studio console application
About this Tutorial –
Objectives –
This course is aimed at students who need to get up to speed in C++. The course introduces object-oriented concepts and shows how they are implemented in C++. The course does not require awareness or familiarity with object-oriented programming techniques, but programming experience would be useful but not necessarily required.
Audience
Students who are new to object orientation (or programming) and need to learn C++.
Prerequisites
No previous experience in C++ programming is required. But any experience you do have in programming will help. Also no experience in Visual Studio is required. But again any experience you do have with programming development environments will be a valuable.
Experience using a contemporary OO language such as Java or C# would be useful but is not required.
Contents
The C++ course covers these topics and more:
Introduction to C++: Key features of C++; Defining variables; Formulating expressions and statements; Built-in data types; Console input/output
Operators and types: Assignment; Compound Assignment; Increment and decrement operators; Const declarations; Type conversions
Going Further with Data Types: Enumerations; Arrays; Using the standard vector class; Using the standard string class; Structures
You can also split functionality into multiple functions
Aids modularity
Each function has a specific purpose
C++ allows global functions…
But OO dictates that most functions should be defined in classes – these are known as “methods”
We’ll discuss this in the “Defining and Using Classes” chapter
Lab 1: Defining and calling functions
Lab 1: Defining and calling functions
Declaring Function Prototypes
There’s a key rule in C++:
You must declare an item before you can use it
i.e. the compiler has to know what you’re talking about
This is relevant for functions
You have to declare what a function looks like, before you call it
Function declarations are also known as “function prototypes”
A function prototype specifies:
The name of a function, its parameter types, and its return type
It’s common to place function prototypes in a header file
You can #include the header file in any source file it’s needed
Here’s an example of a header file that declares several function prototypes
Note: parameter names are optional (but desirable) in a prototype void displayWelcome();
int calcSum(int a, int b);
bool isValidMonth(int m);
To include a header file in another source file, there are 2 possible syntaxes: #include <iostream> //Standard header files, located in the compiler system folder
#include "MyHeader.h" //User-defined header files, located in your own folder
Place function definitions in a source file (.cpp)
Also #include the header file, to ensure the function signature matches what you promised in the prototype #include <iostream>
#include "MyHeader.h"
using namespace std;
void displayWelcome()
{
cout << "Hello mate!" << endl;
}
int calcSum(int a, int b)
{
return a + b;
}
bool isValidMonth(int m)
{
return (m >= 1) && (m <= 12);
}
Calling Functions
To call a function:
Specify the function name
Pass any parameter values needed by the function
Use the return value, if there is one (and if you want to)
Simple client code: #include <l;iostream>
#include "MyHeader.h"
using namespace std;
int main()
{
displayWelcome();
int sum = calcSum(10, 20);
cout << "Sum is " << sum;
bool flag = isValidMonth(12);
cout << "Is month valid? " << flag;
return 0;
}
Here's another client example
Shows how to use variables, rather than constants
Shows how to use function return values in-situ #include <iostream>
#include "MyHeader.h"
using namespace std;
int main()
{
int num1, num2;
cout << "Enter two numbers: ";
cin >> num1 >> num2;
cout << "Sum is " << calcSum(num1, num2) << endl;
int month;
cout << "Enter a month number: ";
cin >> month;
if (isValidMonth(month))
cout << "Month is valid" << endl;
else
cout << "Month is invalid" << endl;
return 0;
}
Pass-By-Value
By default, functions always take a copy of the value passed in from the client
Except for arrays, which are passed by address (see later)
For other types, you can use pointers or references if you want the function to work on the original value (see later)
Example of pass-by-value: int n = 10;
cout << "Here are 5 numbers, starting at " << n << endl;
displayNumberRange(n, 5);
cout << "Did you notice the first number was " << n << endl
// FUNCTION
void displayNumberRange(int num, int count)
{
int lastNum = num + count;
while (num < lastNum)
cout << num++ << endl;
}
Lab
Determining whether a number is prime
Start Visual Studio, and create a new C++ project named MathApp in the student folder. Write a function named IsPrime(). The function needs to take an integer parameter and return a boolean, to indicate whether the number is prime (a number is prime if it has no other factors than 1 and itself). bool IsPrime(int number)
{
for (int i=2; i < number; i++)
{
if (number % i == 0)
{
return false;
}
}
return true;
}
In main(), ask the user to enter a number, and pass it into your IsPrime()function to determine if it's a prime number. Display a result message in main(). cout << "Enter a number: ";
int number;
cin >> number;
if (IsPrime(number))
{
cout << number << " is prime." << endl;
}
else
{
cout << number << " is not prime." << endl;
}
It's conventional to wrap the innards of a header file in a "header guard"
Enables the compiler to detect whether the same header file has been included several times whilst compiling a given .cpp file
Prevents declarations from being parsed multiple times during a "compilation unit" (i.e. whilst compiling a given .cpp file)
Here's the traditional way to define a header guard: #if !defined __BANKACCOUNT_HEADER__
#define __BANKACCOUNT_HEADER__
// BankAccount declarations, e.g. function prototypes, structures, classes, etc.
#endif
Lab
Finding all prime numbers in a range
Write a function named DisplayPrimeNumbersInRange(). The function should take 2 integer parameters (representing lower and upper bounds), and return nothing. The function should display all the prime numbers in the range (lowerBound...upperBound-1). Note, it's quite common for the lower bound to be inclusive, but the upper bound exclusive. void DisplayPrimeNumbersInRange(int lower, int upper)
{
cout << "The following numbers between " << lower << " and " << upper << " are prime" << endl;
for (int i = lower; i < upper; i++)
{
if (IsPrime(i))
{
cout << i << endl;
}
}
}
In main(), ask the user to enter the lower and upper bounds, and then call your function. cout << endl << "Enter a lower number: ";
int lower;
cin >> lower;
cout << "Enter an upper number: ";
int upper;
cin >> upper;
DisplayPrimeNumbersInRange(lower, upper);
If you liked this post, please comment with your suggestions to help others.
If you would like to see more content like this in the future, please fill-in our quick survey.
Manage cookie consent
You can view this website without consenting to extra cookies. However you will need to accept the 'marketing' cookies to send messages via the contact forms & see any maps displayed on the site
Functional
Always active
Cookies necessary for the website to work.
Preferences
The technical storage or access is necessary for the legitimate purpose of storing preferences that are not requested by the subscriber or user.
Statistics
The technical storage or access that is used exclusively for statistical purposes.Cookies used to track user interaction on the site, which helps us to evaluate & improve the website.
Marketing: Forms & additional content (Marketing)
We need your permission to place ‘marketing’ cookies, so you are able to use the contact forms & see embedded content e.g. videos and maps. - - - - We have added protection to our contact forms to help prove that a human (rather than a spambot) is filling
If you would like to see more content like this in the future, please fill-in our quick survey.