0% found this document useful (0 votes)
13 views

C++ Note

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views

C++ Note

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 20

C++ PROGRAMMING NOTE

What is C++?

C++ is a cross-platform language that can be used to create high-performance


applications.

C++ was developed by Bjarne Stroustrup, as an extension to the C language.

C++ gives programmers a high level of control over system resources and
memory.

The language was updated 5 major times in 2011, 2014, 2017, 2020, and
2023 to C++11, C++14, C++17, C++20, and C++23.

Why Use C++

C++ is one of the world's most popular programming languages.

C++ can be found in today's operating systems, Graphical User Interfaces,


and embedded systems.

C++ is an object-oriented programming language which gives a clear


structure to programs and allows code to be reused, lowering development
costs.

C++ is portable and can be used to develop applications that can be adapted
to multiple platforms.

C++ is fun and easy to learn!

As C++ is close to C, C# and Java, it makes it easy for programmers to


switch to C++ or vice versa.

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

C++ Operators

Operators are used to perform operations on variables and values.

C++ divides the operators into the following groups:

 Arithmetic operators
 Assignment operators
 Comparison operators
 Logical 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

x%
% Modulus Returns the division remainder
y
++ Increment Increases the value of a variable by 1 ++x

-- Decrement Decreases the value of a variable by 1 --x

Assignment Operators

Assignment operators are used to assign values to variables.

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.

Logical Operators

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

C++ Syntax

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

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.

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: C++ is case-sensitive: "cout" and "Cout" has different meaning.

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.
Example:

1. Write a C++ program that will print your first and last name

#include <iostream>
using namespace std;

int main() {

string firstName = "John ";


string lastName = "Doe";
cout << firstname << lastname <<endl;
return 0;
}

C++ User Input

You have already learned that cout is used to output (print) values. Now we
will use cin to get user input.

cin is a predefined variable that reads data from the keyboard with the
extraction operator (>>).

Example2. Write a C++ program that ask a user to input your first name and
display the output.

#include <iostream>
using namespace std;

int main() {
string firstName;
cout << "Type your first name: ";
cin >> firstName;
cout << "Your name is: " << firstName;

return 0;
}

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

Example:

#include <iostream>

using namespace std;

int main() {

bool isCodingFun = true;


bool isFishTasty = false;
cout << isCodingFun;
cout << isFishTasty;

return 0;

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 execute

The if Statement

Use the if statement to specify a block of C++ code to be executed if a


condition is true.

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

EXAMPLE:

#include <iostream>

using namespace std;

int main() {

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

return 0;
}

The else Statement

Use the else statement to specify a block of code to be executed if the


condition is false.

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:

#include <iostream>

using namespace std;

int main(){

int age;

cout << “Input Your Age” <<endl;

cin>> age;

if (age < 17){

cout<< “You are not eligible to vote” <<

Else {
Cout<< “You are eligible to vote” << endl;

return 0;

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 condition2 is
false
}

Example:

#include <iostream>

using namespace std;

int main(){

int time = 22;


if (time < 10) {
cout << "Good morning.";
} else if (time < 20) {
cout << "Good day.";
} else {
cout << "Good evening.";
}return 0;

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
 The break and default keywords are optional, and will be described
later in this chapter

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

#include <iostream>
using namespace std;

int main() {

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;
}

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
while (condition) {
// code block to be executed
}
EXAMPLE: 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:

#include <iostream>

using namespace std;

int main(){

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

return 0;

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);
EXAMPLE: 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:

#include <iostream>

using namespace std;

int main(){

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

return 0;

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.

EXAMPLE:

#include <iostream>

using namespace std;

int main(){

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


cout << i << "\n";
}

return 0;

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.

C++ Arrays

Arrays are used to store multiple values in a single variable, instead of


declaring separate variables for each value.

To declare an array, define the variable type, specify the name of the array
followed by square brackets and specify the number of elements it should
store:
- One-Dimensional Array Example

#include <iostream>

using namespace std;

int main() {

int numbers[5] = {10, 20, 30, 40, 50};

cout << "One-Dimensional Array Elements:" << endl;

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

cout << "numbers[" << i << "] = " << numbers[i] <<

endl;

return 0;

- Array of Strings Example

#include <iostream>

#include <string>

using namespace std;

int main() {

// Declare and initialize an array of strings

string fruits[3] = {"Apple", "Banana", "Cherry"};

// Display the elements of the string array

cout << "Array of Strings:" << endl;


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

cout << "fruits[" << i << "] = " << fruits[i] <<

endl;

return 0;

- Dynamic Array Example

#include <iostream>

using namespace std;

int main() {

int size;

// Ask user for array size

cout << "Enter the size of the array: ";

cin >> size;

// Dynamically allocate an array

int* array = new int[size];

// Initialize array with values

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

array[i] = i + 1;

// Display array elements


cout << "Dynamic Array Elements:" << endl;

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

cout << "array[" << i << "] = " << array[i] <<

endl;

// Free dynamically allocated memory

delete[] array;

return 0;

- C++ Code for 2D Array

#include <iostream>

using namespace std;

int main() {

// 1. Declare and initialize a 2D array

int array[3][3] = {

{1, 2, 3},

{4, 5, 6},

{7, 8, 9}

};

// 2. Display the 2D array elements

cout << "2D Array Elements:" << endl;


for (int i = 0; i < 3; i++) { // Iterate over rows

for (int j = 0; j < 3; j++) { // Iterate over

columns

cout << array[i][j] << " ";

cout << endl; // Move to the next line after each

row

// 3. Modify an element in the 2D array

array[1][1] = 10; // Change the middle element to 10

// 4. Display the updated array

cout << "\nUpdated 2D Array Elements:" << endl;

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

for (int j = 0; j < 3; j++) {

cout << array[i][j] << " ";

cout << endl;

return 0;

You might also like