In this tutorial you will learn the basics of C++ and how to use operators and loops. 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
Not what you are looking? Try the next tutorial – Functions
Lab 1: Operators
Lab 1: Operators
Arithmetic Operators
Basic binary operators
a + b (addition)
a – b (subtraction)
a * b (multiplication)
a / b (division)
a % b (modulo, i.e. remainder)
Basic unary operators
+a (unary plus)
-a (unary negation)
a++ (postfix increment by 1)
++a (prefix increment by 1)
a– (postfix decrement by 1)
–a (prefix increment by 1)
Conditional Operator
The conditional operatoris like an in-situ if test – (condition) ? trueResult : falseResult
Example: bool isMale;
int age;
...
int togo = (isMale) ? (65 - age) : (60 - age);
cout << "You have " << togo << " years to retirement";
Assignment Operators
Basic assignment operator
a = b (assign b to a)
Performs widening conversion implicitly, if needed (see later)
Example: int a = 100;
int b = 200;
b = 42;
a = b;
// OR
int a, b, c;
...
a = b = c = 0;
Compound assignment operators:
a += b (calculate a + b, then assign to a)
a -= b (calculate a – b, then assign to a)
a *= b (calculate a * b, then assign to a)
a /= b (calculate a / b, then assign to a)
etc…
Example: // Use *= compound operator:
x *= a + b;
// Equivalent to the following (note the precedence):
x = x * (a + b);
Casting
Implicit conversions:
C++ implicitly converts less-precise expns to more-precise expns
char -> short -> int -> long -> float -> double
Explicit conversions (aka casting):
You can explicitly cast an expression into a compatible other type
(type)expression –or– type(expression)
Might result in a loss of precision
Explain the following example: What would happen? can you do this without explicit casting? int judge1Score;
int judge2Score;
int judge3Score;
...
double averageScore = (double) (judge1Score + judge2Score + judge3Score) / 3;
Relational Operators
There are 6 relational operators (all return bool):
== (equality)
!= (inequality)
>(greater-than)
>= (greater-than-or-equal)
< (less-than)
<= (less-than-or-equal)
Logical Operators
There are 3 relational operators (all return bool):
&& (logical AND)
|| (logical OR)
! (logical NOT)
Note:
&& and || perform short-circuit evaluation
Bitwise Operators
Bitwise AND and OR binary operators
& (bitwise AND)
^ (bitwise exclusive OR)
| (bitwise inclusive OR)
Bitwise NOT unary operator
~ (bitwise NOT)
Bitwise shift operators
<< (shift bits left)
>> (shift bits right)
Order of Precedence
Operators have the following precedence (use parens to override this precedence):
`
Lab
Using operators
Start Visual Studio, and create a new C++ project named Dates in the student folder. Write code to manipulate day, month, and year values using operators. Suggestions and requirements:
To start off with, declare 3 integers with hard-coded values for the day, month, and year. // Declare 3 variables, for a hard-coded date.
int day = 3, month = 12, year = 2011;
Use a conditional operator (?:) to determine if it’s a leap year. A leap year is: (evenly divisible by 4 AND NOT evenly divisible by 100); Use the remainder operator (%) to help you out here // Is the date a leap year?
bool isLeapYear = ((year % 4 == 0) && !(year % 100 == 0)) || (year % 400 == 0);
cout << "Is " << year << " a leap year? " << isLeapYear << endl;
Test whether your “is-leap-year” algorithm works for various years.
Lab 2: Conditional statements
Lab 2: Conditional statements
Using if Tests
Basic if tests if (test) {
body
}
if-else tests if (test) {
body1
} else {
body2
}
if-else-if tests if (test1) {
body1
}
else if (test2) {
body2
}
else if (test3) {
body3
}
...
else {
lastBody
}
Notes:
Test conditions don’t have to be bool
{} are optional if you want a 1-line statement
Nesting if Tests
You can nest if tests inside each other
Use {} to ensure correct logic, as needed
Use indentation for readability int age = ... ;
string gender = ... ;
if (age < 18) {
if (gender == "Male") {
cout << "boy" << endl;
} else {
cout << "girl" << endl;
}
} else {
if (age >= 100) {
cout << "centurion ";
}
if (gender == "Male") {
cout << "man" << endl;
} else {
cout << "woman" << endl;
}
}
Using switch Tests
The switch statement is useful if you want to test a single expression against a finite set of expected values
General syntax: switch (expression) {
case constant1:
branch1Statements;
break;
case constant2:
branch2Statements;
break;
...
default:
defaultBranchStatements;
break;
}
Expression must be:
Integral type (or enum)
Note, strings are NOT allowed!
Cases:
Must be (different) constants
If you omit break:
Fall-through occurs
The default branch:
Is optional
Doesn’t have to be at the end!
Lab
Using conditional logic
Validate the day, month, and year. Output a single message saying if the date is valid. If the date is valid, output it in the format dd/mm/yyyy. Suggestions and requirements:
Write an if-statement to validate the month (it must be 1-12). // Is the date valid?
bool isValid;
if (month < 1 || month > 12)
{
isValid = false;
}
Write an if-statement to validate the year (let’s say the year must be 1900…2099). else if (year < 0 || year > 2099)
{
isValid = false;
}
Write an if-statement to ensure the day is 1 or higher. else if (day < 1)
{
isValid = false;
}
Write a switch-statement to ensure the day isn't too big. The max value is 28, 29, 30, or 31, depending on the month (and if the month is February, whether it's a leap year). else
{
int maxDay;
switch (month)
{
case 2:
maxDay = (isLeapYear) ? 29 : 28;
break;
case 4:
case 6:
case 9:
case 11:
maxDay = 30;
break;
default:
maxDay = 31;
break;
}
isValid = (day <= maxDay);
}
cout << day << "/" << month << "/" << year << " is valid? " << isValid << endl;
for (initialization; test; update) {
...
if (someCondition)
break;
...
if (someOtherCondition)
continue;
...
Note: C++ also has a goto statement...
Lab
Using loops
Refactor your application so that it gets a series of dates from the user, rather than having a single hard-coded date. Suggestions and requirements:
Write a do-while loop that allows the user to enter a series of different dates. Each time round the loop, ask the user whether he/she wants to continue (use string here); if the user says "Yes" or "yes", keep on iterating int day, month, year;
string response;
do
{
// Get a date from the user and Error check
...
// Ask the user whether he/she wants to enter another date.
cout << endl << "Enter another date? ";
cin >> response;
}
while (response == "yes");
cout << "The End." << endl;
Inside the loop, ask the user to enter a new day, month, and year cout << "Day: ";
cin >> day;
cout << "Month: ";
cin >> month;
cout << "Year: ";
cin >> year;
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.