0% found this document useful (0 votes)
24 views36 pages

Overview of CPP

The document discusses the basic syntax of a C++ program by breaking down the components of a sample program line-by-line. It covers header files, the main function, namespaces, blocks and braces, semicolons, identifiers, keywords, and basic input/output using cout.

Uploaded by

Jemuel Herrera
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
24 views36 pages

Overview of CPP

The document discusses the basic syntax of a C++ program by breaking down the components of a sample program line-by-line. It covers header files, the main function, namespaces, blocks and braces, semicolons, identifiers, keywords, and basic input/output using cout.

Uploaded by

Jemuel Herrera
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 36

EXCELLENCE AND VIRTUE

Basic Syntax of a C++ Program


Learn about basic C++ Syntax using the following program.

The image above shows the basic C++ program that contains header files, main
function, namespace declaration, etc. Let’s try to understand them one by one.

1. Header File

The header files contain the definition of the functions and macros are using in
our program. They are defined on the top of the C++ program.
In line #1, we used the #include <iostream> statement to tell the compiler to
include an iostream header file library which stores the definition of the cin and
cout methods that used for input and output. #include is a preprocessor
directive using which we import header files.
Syntax:
#include <library_name>
To know more about header files, please refer to the article – Header Files in
C/C++.

CS102-1L 1T.23.24 ASDS


EXCELLENCE AND VIRTUE

2. Namespace

A namespace in C++ is used to provide a scope or a region where it define


identifiers. It is used to avoid name conflicts between two identifiers as only
unique names can be used as identifiers.
In line #2, the using namespace std statement for specifying the standard
namespace where all the standard library functions are defined.
Syntax:
using namespace std;
To know more about namespaces in C++, please refer to the article
– Namespaces in C++.

3. Main Function

Functions are basic building blocks of a C++ program that contains the
instructions for performing some specific task. Apart from the instructions
present in its body, a function definition also contains information about its
return type and parameters. To know more about C++ functions, please refer to
the article Functions in C++.
In line #3, it defined the main function as int main(). The main function is the
most important part of any C++ program. The program execution always starts
from the main function. All the other functions are called from the main function.
In C++, the main function is required to return some value indicating the
execution status.
Syntax:
int main() {

... code ....


return 0;
}

CS102-1L 1T.23.24 ASDS


EXCELLENCE AND VIRTUE

4. Blocks

Blocks are the group of statements that are enclosed within { } braces. They
define the scope of the identifiers and are generally used to enclose the body of
functions and control statements.

The body of the main function is from line #4 to line #9 enclosed within { }.
Syntax:
{

// Body of the Function

return 0;
}

5. Semicolons

Each statement in the above code is followed by a ( ; ) semicolon symbol. It is


used to terminate each line of the statement of the program. When the compiler
sees this semicolon, it terminates the operation of that line and moves to the
next line.
Syntax:
any_statement ;

6. Identifiers

The identifiers for the naming of variables, functions, and other user-defined
data types. An identifier may consist of uppercase and lowercase alphabetical
characters, underscore, and digits. The first letter must be an underscore or an
alphabet.
Example:
int num1 = 24;
int num2 = 34;
num1 & num2 are the identifiers and int is the data type.

7. Keywords

CS102-1L 1T.23.24 ASDS


EXCELLENCE AND VIRTUE

In the C++ programming language, there are some reserved words that are
used for some special meaning in the C++ program. It can’t be used for
identifiers.
For example, the words int, return, and using are some keywords used in our
program. These all have some predefined meaning in the C++ language.
There are total 95 keywords in C++. These are some keywords.
int void if while for
auto bool break
this static new true false
case char class
To know more about Identifiers and Keywords in C++, refer to the article C/C++
Tokens.

8. Basic Output cout

In line #7, the cout method which is the basic output method in C++ to output
the sum of two numbers in the standard output stream (stdout).

Syntax:
cout << result << endl;

To know more about basic input and output in C++, please refer to the article
– Basic Input and Output in C.
Now, we have a better understanding of the basic syntax structure of the above
C++ program. Let’s try to execute this program and see if it works correctly.
Sample C++ Program:
// C++ program to demonstrate the basic syntax
// Header File Library
#include <iostream>

// Standard Namespace
using namespace std;

// Main Function
int main()
{

// Body of the Function

// Declaration of Variable
int num1 = 24;

CS102-1L 1T.23.24 ASDS


EXCELLENCE AND VIRTUE

int num2 = 34;

int result = num1 + num2;

// Output
cout << result << endl;

// Return Statement
return 0;
}

References : https://www.geeksforgeeks.org/cpp-basic-syntax

C++ Syntax
Let's break up the following code to understand it better:

Example
#include <iostream>
using namespace std;

int main() {
cout << "Hello World!";
return 0;
}

Example explained
Line 1: #include <iostream> is a header file library that lets us work with
input and output objects, such as cout (used in line 5). Header files add
functionality to C++ programs.

Line 2: using namespace std means that we can use names for objects and
variables from the standard library.

CS102-1L 1T.23.24 ASDS


EXCELLENCE AND VIRTUE

Don't worry if you don't understand how #include <iostream> and using
namespace std works. Just think of it as something that (almost) always
appears in your program.

Line 3: A blank line. C++ ignores white space. But we use it to make the
code more readable.

Line 4: Another thing that always appear in a C++ program, is int main().
This is called a function. Any code inside its curly brackets {} will be
executed.

Line 5: cout (pronounced "see-out") is an object used together with


the insertion operator (<<) to output/print text. In our example it will output
"Hello World!".

Note: Every C++ statement ends with a semicolon ;.

Note: The body of int main() could also been written as:
int main () { cout << "Hello World! "; return 0; }

Remember: The compiler ignores white spaces. However, multiple lines


makes the code more readable.

Line 6: return 0 ends the main function.

Line 7: Do not forget to add the closing curly bracket } to actually end the
main function.

Omitting Namespace
You might see some C++ programs that runs without the standard namespace
library. The using namespace std line can be omitted and replaced with
the std keyword, followed by the :: operator for some objects:

Example
#include <iostream>

int main() {
std::cout << "Hello World!";

CS102-1L 1T.23.24 ASDS


EXCELLENCE AND VIRTUE

return 0;
}

It is up to you if you want to include the standard namespace library or not.

C++ Data Types


As explained in the Variables chapter, a variable in C++ must be a specified
data type:

Example
int myNum = 5; // Integer (whole number)
float myFloatNum = 5.99; // Floating point number
double myDoubleNum = 9.98; // Floating point number
char myLetter = 'D'; // Character
bool myBoolean = true; // Boolean
string myText = "Hello"; // String

Basic Data Types


The data type specifies the size and type of information the variable will store:

Data Type Size Description

boolean 1 byte Stores true or false values

char 1 byte Stores a single character/letter/number, or ASCII values

CS102-1L 1T.23.24 ASDS


EXCELLENCE AND VIRTUE

int 2 or 4 Stores whole numbers, without decimals


bytes

float 4 bytes Stores fractional numbers, containing one or more decimals.

Sufficient for storing 6-7 decimal digits

double 8 bytes Stores fractional numbers, containing one or more decimals.

Sufficient for storing 15 decimal digits

C++ Numeric Data Types


Numeric Types
Use int when you need to store a whole number without decimals, like 35 or
1000, and float or double when you need a floating point number (with
decimals), like 9.99 or 3.14515.

int
int myNum = 1000;
cout << myNum;

float
float myNum = 5.75;
cout << myNum;

CS102-1L 1T.23.24 ASDS


EXCELLENCE AND VIRTUE

double
double myNum = 19.99;
cout << myNum;

float vs. double


The precision of a floating point value indicates how many digits the value can
have after the decimal point. The precision of float is only six or seven decimal
digits, while double variables have a precision of about 15 digits. Therefore it is
safer to use double for most calculations.

Scientific Numbers
A floating point number can also be a scientific number with an "e" to indicate
the power of 10:

Example
float f1 = 35e3;
double d1 = 12E4;
cout << f1;
cout << d1;

C++ Boolean Data Types


Boolean Types
A boolean data type is declared with the bool keyword and can only take the
values true or false.

When the value is returned, true = 1 and false = 0.

Example
bool isCodingFun = true;
bool isFishTasty = false;
cout << isCodingFun; // Outputs 1 (true)
cout << isFishTasty; // Outputs 0 (false)

CS102-1L 1T.23.24 ASDS


EXCELLENCE AND VIRTUE

Boolean values are mostly used for conditional testing, which you will learn
more about in a later chapter.

C++ Character Data Types


Character Types
The char data type is used to store a single character. The character must be
surrounded by single quotes, like 'A' or 'c':

Example
char myGrade = 'B';
cout << myGrade;

Alternatively, you can use ASCII values to display certain characters:

Example
char a = 65, b = 66, c = 67;
cout << a;
cout << b;
cout << c;

Tip: A list of all ASCII values can be found in our ASCII Table Reference.

C++ String Data Types


String Types
The string type is used to store a sequence of characters (text). This is not a
built-in type, but it behaves like one in its most basic usage. String values must
be surrounded by double quotes: To use strings, you must include an additional
header file in the source code, the <string> library:

Example

CS102-1L 1T.23.24 ASDS


EXCELLENCE AND VIRTUE

string greeting = "Hello";


cout << greeting;

To use strings, you must include an additional header file in the source code,
the <string> library:

Example
// Include the string library
#include <string>

// Create a string variable


string greeting = "Hello";

// Output string value


cout << greeting;

C++ String Concatenation


String Concatenation
The + operator can be used between strings to add them together to make a
new string. This is called concatenation:

Example
string firstName = "John ";
string lastName = "Doe";
string fullName = firstName + lastName;
cout << fullName;

In the example above, we added a space after firstName to create a space


between John and Doe on output. However, you could also add a space with
quotes (" " or ' '):

CS102-1L 1T.23.24 ASDS


EXCELLENCE AND VIRTUE

Example
string firstName = "John";
string lastName = "Doe";
string fullName = firstName + " " + lastName;
cout << fullName;

Append
A string in C++ is actually an object, which contain functions that can perform
certain operations on strings. For example, you can also concatenate strings
with the append() function:

Example
string firstName = "John ";
string lastName = "Doe";
string fullName = firstName.append(lastName);
cout << fullName;

C++ Numbers and Strings


Adding Numbers and Strings
WARNING!

C++ uses the + operator for both addition and concatenation.

Numbers are added. Strings are concatenated.

If you add two numbers, the result will be a number:

Example
int x = 10;
int y = 20;
int z = x + y; // z will be 30 (an integer)

If you add two strings, the result will be a string concatenation:

CS102-1L 1T.23.24 ASDS


EXCELLENCE AND VIRTUE

Example
string x = "10";
string y = "20";
string z = x + y; // z will be 1020 (a string)

If you try to add a number to a string, an error occurs:

Example
string x = "10";
int y = 20;
string z = x + y;

C++ String Length


String Length
To get the length of a string, use the length() function:

Example
string txt = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
cout << "The length of the txt string is: " << txt.length();

C++ Access Strings


Access Strings
You can access the characters in a string by referring to its index number inside
square brackets [].

CS102-1L 1T.23.24 ASDS


EXCELLENCE AND VIRTUE

This example prints the first character in myString:

Example
string myString = "Hello";
cout << myString[0];
// Outputs H

Note: String indexes start with 0: [0] is the first character. [1] is the second
character, etc.

This example prints the second character in myString:

Example
string myString = "Hello";
cout << myString[1];
// Outputs e

Change String Characters


To change the value of a specific character in a string, refer to the index
number, and use single quotes:

Example
string myString = "Hello";
myString[0] = 'J';
cout << myString;
// Outputs Jello instead of Hello

Tip: You might see some C++ programs that use the size() function to get the
length of a string. This is just an alias of length(). It is completely up to you if
you want to use length() or size():

Example
string txt = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
cout << "The length of the txt string is: " << txt.size();

CS102-1L 1T.23.24 ASDS


EXCELLENCE AND VIRTUE

C++ String Namespace


Omitting Namespace
You might see some C++ programs that runs without the standard namespace
library. The using namespace std line can be omitted and replaced with
the std keyword, followed by the :: operator for string (and cout) objects:

Example
#include <iostream>
#include <string>

int main() {
std::string greeting = "Hello";
std::cout << greeting;
return 0;
}

C++ Operators
Operators are used to perform operations on variables and values.

In the example below, we use the + operator to add together two values:

Example
int x = 100 + 50;

Although the + operator is often used to add together two values, like in the
example above, it can also be used to add together a variable and a value, or a
variable and another variable:

Example
int sum1 = 100 + 50; // 150 (100 + 50)
int sum2 = sum1 + 250; // 400 (150 + 250)
int sum3 = sum2 + sum2; // 800 (400 + 400)

C++ divides the operators into the following groups:

CS102-1L 1T.23.24 ASDS


EXCELLENCE AND VIRTUE

• Arithmetic operators
• Assignment operators
• Comparison operators
• Logical operators
• Bitwise operators

Arithmetic Operators
Arithmetic operators are used to perform common mathematical operations.

Operator Name Description Example

+ Addition Adds together two values x+y

- Subtraction Subtracts one value from another x-y

* Multiplication Multiplies two values x*y

/ Division Divides one value by another x/y

Assignment Operators
Assignment operators are used to assign values to variables.

In the example below, we use the assignment operator (=) to assign the
value 10 to a variable called x:

CS102-1L 1T.23.24 ASDS


EXCELLENCE AND VIRTUE

Example
int x = 10;

The addition assignment operator (+=) adds a value to a variable:

Example
int x = 10;
x += 5;

A list of all assignment operators:

Operator Example Same As

= x=5 x=5

+= x += 3 x=x+3

-= x -= 3 x=x-3

*= x *= 3 x=x*3

/= x /= 3 x=x/3

CS102-1L 1T.23.24 ASDS


EXCELLENCE AND VIRTUE

%= x %= 3 x=x%3

&= x &= 3 x=x&3

|= x |= 3 x=x|3

^= x ^= 3 x=x^3

>>= x >>= 3 x = x >> 3

<<= x <<= 3 x = x << 3

Comparison Operators
Comparison operators are used to compare two values (or variables). This is
important in programming, because it helps us to find answers and make
decisions.

The return value of a comparison is either 1 or 0, which means true (1)


or false (0). These values are known as Boolean values, and you will learn
more about them in the Booleans and If..Else chapter.

In the following example, we use the greater than operator (>) to find out if 5
is greater than 3:

Example

CS102-1L 1T.23.24 ASDS


EXCELLENCE AND VIRTUE

int x = 5;
int y = 3;
cout << (x > y); // returns 1 (true) because 5 is greater than 3

A list of all comparison operators:

Operator Name Example

== Equal to x == y

!= Not equal x != y

> Greater than x>y

< Less than x<y

>= Greater than or equal to x >= y

<= Less than or equal to x <= y

C++ Logical Operators


Logical Operators

CS102-1L 1T.23.24 ASDS


EXCELLENCE AND VIRTUE

As with comparison operators, you can also test for true (1) or false (0) values
with logical operators.

Logical operators are used to determine the logic between variables or values:

Operator Name Description Example

&& Logical and Returns true if both statements are true x < 5 && x < 10

|| Logical or Returns true if one of the statements is true x < 5 || x < 4

! Logical not Reverse the result, returns false if the result is true !(x < 5 && x < 10)

C++ Booleans
Very often, in programming, you will need a data type that can only have one of
two values, like:

• YES / NO
• ON / OFF
• TRUE / FALSE

For this, C++ has a bool data type, which can take the values true (1)
or false (0).

Boolean Values
A boolean variable is declared with the bool keyword and can only take the
values true or false:

CS102-1L 1T.23.24 ASDS


EXCELLENCE AND VIRTUE

Example
bool isCodingFun = true;
bool isFishTasty = false;
cout << isCodingFun; // Outputs 1 (true)
cout << isFishTasty; // Outputs 0 (false)

Boolean Expression
A Boolean expression returns a boolean value that is either 1 (true)
or 0 (false).

This is useful to build logic, and find answers.

You can use a comparison operator, such as the greater than (>) operator, to
find out if an expression (or variable) is true or false:

Example
int x = 10;
int y = 9;
cout << (x > y); // returns 1 (true), because 10 is higher than 9

Or even easier:

Example
cout << (10 > 9); // returns 1 (true), because 10 is higher than 9

In the examples below, we use the equal to (==) operator to evaluate an


expression:

Example
int x = 10;
cout << (x == 10); // returns 1 (true), because the value of x is equal
to 10

Example

CS102-1L 1T.23.24 ASDS


EXCELLENCE AND VIRTUE

cout << (10 == 15); // returns 0 (false), because 10 is not equal to 15

Real Life Example


Let's think of a "real life example" where we need to find out if a person is old
enough to vote.

In the example below, we use the >= comparison operator to find out if the age
(25) is greater than OR equal to the voting age limit, which is set to 18:

Example
int myAge = 25;
int votingAge = 18;

cout << (myAge >= votingAge); // returns 1 (true), meaning 25 year olds
are allowed to vote!

Cool, right? An even better approach (since we are on a roll now), would be to
wrap the code above in an if...else statement, so we can perform different
actions depending on the result:

Example
Output "Old enough to vote!" if myAge is greater than or equal to 18. Otherwise
output "Not old enough to vote.":

int myAge = 25;


int votingAge = 18;

if (myAge >= votingAge) {


cout << "Old enough to vote!";
} else {
cout << "Not old enough to vote.";
}

// Outputs: Old enough to vote!

Booleans are the basis for all C++ comparisons and conditions.

CS102-1L 1T.23.24 ASDS


EXCELLENCE AND VIRTUE

C++ Variables
Variables are containers for storing data values.

In C++, there are different types of variables (defined with different


keywords), for example:

• int - stores integers (whole numbers), without decimals, such as 123 or -


123
• double - stores floating point numbers, with decimals, such as 19.99 or -
19.99
• char - stores single characters, such as 'a' or 'B'. Char values are
surrounded by single quotes
• string - stores text, such as "Hello World". String values are surrounded
by double quotes
• bool - stores values with two states: true or false

Declaring (Creating) Variables


To create a variable, specify the type and assign it a value:

Syntax
type variableName = value;

Where type is one of C++ types (such as int), and variableName is the name of
the variable (such as x or myName). The equal sign is used to assign values
to the variable.

To create a variable that should store a number, look at the following example:

Example
Create a variable called myNum of type int and assign it the value 15:

int myNum = 15;


cout << myNum;

You can also declare a variable without assigning the value, and assign the
value later:

CS102-1L 1T.23.24 ASDS


EXCELLENCE AND VIRTUE

Example
int myNum;
myNum = 15;
cout << myNum;

Note that if you assign a new value to an existing variable, it will overwrite the
previous value:

Example
int myNum = 15; // myNum is 15
myNum = 10; // Now myNum is 10
cout << myNum; // Outputs 10

Other Types
A demonstration of other data types:

Example
int myNum = 5; // Integer (whole number without decimals)
double myFloatNum = 5.99; // Floating point number (with decimals)
char myLetter = 'D'; // Character
string myText = "Hello"; // String (text)
bool myBoolean = true; // Boolean (true or false)

You will learn more about the individual types in the Data Types chapter.

Display Variables
The cout object is used together with the << operator to display variables.

To combine both text and a variable, separate them with the << operator:

Example
int myAge = 35;
cout << "I am " << myAge << " years old.";

CS102-1L 1T.23.24 ASDS


EXCELLENCE AND VIRTUE

Add Variables Together


To add a variable to another variable, you can use the + operator:

Example
int x = 5;
int y = 6;
int sum = x + y;
cout << sum;

C++ Conditions and If Statements


You already know that C++ supports the usual logical conditions from
mathematics:

• Less than: a < b


• Less than or equal to: a <= b
• Greater than: a > b
• Greater than or equal to: a >= b
• Equal to a == b
• Not Equal to: a != b

You can use these conditions to perform different actions for different decisions.

C++ has the following conditional statements:

• Use if to specify a block of code to be executed, if a specified condition is


true
• Use else to specify a block of code to be executed, if the same condition
is false
• Use else if to specify a new condition to test, if the first condition is
false
• Use switch to specify many alternative blocks of code to be executed

The if Statement
Use the if statement to specify a block of C++ code to be executed if a
condition is true.

CS102-1L 1T.23.24 ASDS


EXCELLENCE AND VIRTUE

Syntax
if (condition) {
// block of code to be executed if the condition is true
}

Note that if is in lowercase letters. Uppercase letters (If or IF) will generate an
error.

In the example below, we test two values to find out if 20 is greater than 18. If
the condition is true, print some text:

Example
if (20 > 18) {
cout << "20 is greater than 18";
}

We can also test variables:

Example
int x = 20;
int y = 18;
if (x > y) {
cout << "x is greater than y";
}

Example explained

In the example above we use two variables, x and y, to test whether x is


greater than y (using the > operator). As x is 20, and y is 18, and we know that
20 is greater than 18, we print to the screen that "x is greater than y".

C++ Else
The else Statement
Use the else statement to specify a block of code to be executed if the condition
is false.

CS102-1L 1T.23.24 ASDS


EXCELLENCE AND VIRTUE

Syntax
if (condition) {
// block of code to be executed if the condition is true
} else {
// block of code to be executed if the condition is false
}

Example
int time = 20;
if (time < 18) {
cout << "Good day.";
} else {
cout << "Good evening.";
}
// Outputs "Good evening."

Example explained

In the example above, time (20) is greater than 18, so the condition is false.
Because of this, we move on to the else condition and print to the screen "Good
evening". If the time was less than 18, the program would print "Good day".

C++ Else If
The else if Statement
Use the else if statement to specify a new condition if the first condition
is false.

Syntax
if (condition1) {
// block of code to be executed if condition1 is true
} else if (condition2) {
// block of code to be executed if the condition1 is false and
condition2 is true
} else {
// block of code to be executed if the condition1 is false and

CS102-1L 1T.23.24 ASDS


EXCELLENCE AND VIRTUE

condition2 is false
}

Example
int time = 22;
if (time < 10) {
cout << "Good morning.";
} else if (time < 20) {
cout << "Good day.";
} else {
cout << "Good evening.";
}
// Outputs "Good evening."

Example explained

In the example above, time (22) is greater than 10, so the first
condition is false. The next condition, in the else if statement, is also false, so
we move on to the else condition since condition1 and condition2 is
both false - and print to the screen "Good evening".

However, if the time was 14, our program would print "Good day."

C++ Short Hand If Else


Short Hand If...Else (Ternary Operator)
There is also a short-hand if else, which is known as the ternary
operator because it consists of three operands. It can be used to replace
multiple lines of code with a single line. It is often used to replace simple if else
statements:

Syntax
variable = (condition) ? expressionTrue : expressionFalse;
Instead of writing:

Example

CS102-1L 1T.23.24 ASDS


EXCELLENCE AND VIRTUE

int time = 20;


if (time < 18) {
cout << "Good day.";
} else {
cout << "Good evening.";
}

You can simply write:

Example
int time = 20;
string result = (time < 18) ? "Good day." : "Good evening.";
cout << result;

C++ Switch
C++ Switch Statements
Use the switch statement to select one of many code blocks to be executed.

Syntax
switch(expression) {
case x:
// code block
break;
case y:
// code block
break;
default:
// code block
}

This is how it works:

• The switch expression is evaluated once


• The value of the expression is compared with the values of each case
• If there is a match, the associated block of code is executed

CS102-1L 1T.23.24 ASDS


EXCELLENCE AND VIRTUE

• The break and default keywords are optional, and will be described later
in this chapter

The example below uses the weekday number to calculate the weekday name:

Example
int day = 4;
switch (day) {
case 1:
cout << "Monday";
break;
case 2:
cout << "Tuesday";
break;
case 3:
cout << "Wednesday";
break;
case 4:
cout << "Thursday";
break;
case 5:
cout << "Friday";
break;
case 6:
cout << "Saturday";
break;
case 7:
cout << "Sunday";
break;
}
// Outputs "Thursday" (day 4)

The break Keyword


When C++ reaches a break keyword, it breaks out of the switch block.

This will stop the execution of more code and case testing inside the block.

When a match is found, and the job is done, it's time for a break. There is no
need for more testing.

CS102-1L 1T.23.24 ASDS


EXCELLENCE AND VIRTUE

A break can save a lot of execution time because it "ignores" the execution of
all the rest of the code in the switch block.

The default Keyword


The default keyword specifies some code to run if there is no case match:

Example
int day = 4;
switch (day) {
case 6:
cout << "Today is Saturday";
break;
case 7:
cout << "Today is Sunday";
break;
default:
cout << "Looking forward to the Weekend";
}
// Outputs "Looking forward to the Weekend"

C++ Loops
Loops can execute a block of code as long as a specified condition is reached.

Loops are handy because they save time, reduce errors, and they make code
more readable.

C++ While Loop


The while loop loops through a block of code as long as a specified condition
is true:

Syntax

CS102-1L 1T.23.24 ASDS


EXCELLENCE AND VIRTUE

while (condition) {
// code block to be executed
}

In the example below, the code in the loop will run, over and over again, as
long as a variable (i) is less than 5:

Example
int i = 0;
while (i < 5) {
cout << i << "\n";
i++;
}

Note: Do not forget to increase the variable used in the condition, otherwise
the loop will never end!

The Do/While Loop


The do/while loop is a variant of the while loop. This loop will execute the code
block once, before checking if the condition is true, then it will repeat the loop
as long as the condition is true.

Syntax
do {
// code block to be executed
}
while (condition);
The example below uses a do/while loop. The loop will always be executed at
least once, even if the condition is false, because the code block is executed
before the condition is tested:

Example
int i = 0;
do {
cout << i << "\n";
i++;
}

CS102-1L 1T.23.24 ASDS


EXCELLENCE AND VIRTUE

while (i < 5);


Do not forget to increase the variable used in the condition, otherwise the loop
will never end!

C++ For Loop


When you know exactly how many times you want to loop through a block of
code, use the for loop instead of a while loop:

Syntax
for (statement 1; statement 2; statement 3) {
// code block to be executed
}

Statement 1 is executed (one time) before the execution of the code block.

Statement 2 defines the condition for executing the code block.

Statement 3 is executed (every time) after the code block has been executed.

The example below will print the numbers 0 to 4:

Example
for (int i = 0; i < 5; i++) {
cout << i << "\n";
}

Try it Yourself »

CS102-1L 1T.23.24 ASDS


EXCELLENCE AND VIRTUE

Example explained

Statement 1 sets a variable before the loop starts (int i = 0).

Statement 2 defines the condition for the loop to run (i must be less than 5). If
the condition is true, the loop will start over again, if it is false, the loop will
end.

Statement 3 increases a value (i++) each time the code block in the loop has
been executed.

Another Example
This example will only print even values between 0 and 10:

Example
for (int i = 0; i <= 10; i = i + 2) {
cout << i << "\n";
}

Nested Loops
It is also possible to place a loop inside another loop. This is called a nested
loop.

The "inner loop" will be executed one time for each iteration of the "outer loop":

Example
// Outer loop
for (int i = 1; i <= 2; ++i) {
cout << "Outer: " << i << "\n"; // Executes 2 times

// Inner loop
for (int j = 1; j <= 3; ++j) {
cout << " Inner: " << j << "\n"; // Executes 6 times (2 * 3)
}

CS102-1L 1T.23.24 ASDS


EXCELLENCE AND VIRTUE

The foreach Loop


There is also a "for-each loop" (introduced in C++ version 11 (2011), which is
used exclusively to loop through elements in an array (or other data sets):

Syntax
for (type variableName : arrayName) {
// code block to be executed
}

The following example outputs all elements in an array, using a "for-


each loop":

Example
int myNumbers[5] = {10, 20, 30, 40, 50};
for (int i : myNumbers) {
cout << i << "\n";
}

C++ Break and Continue


C++ Break
You have already seen the break statement used in an earlier chapter of this
tutorial. It was used to "jump out" of a switch statement.

The break statement can also be used to jump out of a loop.

This example jumps out of the loop when i is equal to 4:

Example

CS102-1L 1T.23.24 ASDS


EXCELLENCE AND VIRTUE

for (int i = 0; i < 10; i++) {


if (i == 4) {
break;
}
cout << i << "\n";
}

C++ Continue
The continue statement breaks one iteration (in the loop), if a specified condition
occurs, and continues with the next iteration in the loop.

This example skips the value of 4:

Example
for (int i = 0; i < 10; i++) {
if (i == 4) {
continue;
}
cout << i << "\n";
}

Reference: https://www.w3schools.com/cpp/cpp_pointers.asp

CS102-1L 1T.23.24 ASDS

You might also like