S1 Introduction To C++
S1 Introduction To C++
W3Schools
● #include <iostream> is a header file library that lets us
work with input and output objects, such as cout,cin .
Header files add functionality to C++ programs. (always
appear in program)
Omitting Namespace
#include <iostream>
int main() {
std::cout << "Hello World!";
return 0;
}
New Lines
#include <iostream>
using namespace std;
int main() {
cout << "Hello World! \n";
cout << "I am learning C++";
return 0;
}
OUTPUT:
Hello World!
I am learning C++
#include <iostream>
using namespace std;
int main() {
cout << "Hello World! \n\n";
cout << "I am learning C++";
return 0;
}
OUTPUT:
Hello World!
I am learning C++
What is \n ?
The newline character (\n) is called an escape sequence, and
it forces the cursor to change its position to the beginning of
● char - stores single characters, such as 'a' or 'B'. Char values are
surrounded by single quotes
● To combine both text and a variable, separate them with the <<
operator.
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.
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'.
String Types
● The string type is used to store a sequence of characters (text).
● 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:
#include <string> Output:
string greeting = "Hello"; Hello
cout << greeting;
C++ Operators
❖ Arithmetic operators
❖ Assignment operators
❖ Comparison operators
❖ Logical operators
❖ Bitwise operators
Arithmetic Operators
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.
● 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
int x = 5; Output:
! Logical not Reverse the result, returns !(x < 5 && x < 10)
false if the result is true
C++ Strings
String Concatenation
The + operator can be used between strings to add them together to make a
new string. This is called concatenation.
String Length
To get the length of a string, use the length() function:
Output:
15
Access Strings
You can access the characters in a string by referring to its index number
inside square brackets [].
Output:
m
C++ Conditions and If Statements
C++ has the following conditional statements:
The if Statement
if (condition) {
// block of code to be executed if the condition is true
}
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:
int time = 9;
switch(expression) {
case x:
// code block
break;
case y:
// code block
break;
default:
// code block
}
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.
while (condition) {
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:
int i = 0;
while (i < 5) {
cout << i << "\n";
i++;
}
do {
while (condition);
Statement 1 is executed (one time) before the execution of the code block.
Statement 3 is executed (every time) after the code block 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.
OUTPUT
Volvo
⭐Array indexes start with 0: [0] is the first element. [1] is the
second element, etc.⭐
OUTPUT
Audi
SYNTAX
for (type variableName : arrayName) {
// code block to be executed
}
string cars[5];
cars[0] = "Volvo";
cars[1] = "BMW";
…
OUTPUT
20
(20 because the sizeof() operator returns the size of a type in bytes.
An int type is usually 4 bytes, so 4 x 5 (4 bytes x 5 elements) = 20
bytes.)
To find out how many elements an array has, divide the size of the array by
the size of the data type it contains:
OUTPUT
5
Multi-Dimensional Arrays
● A multi-dimensional array is an array of arrays.
● To declare a multidimensional array, define the variable type, specify
the name of the array followed by square brackets which specify how
many elements the main array has, followed by another set of square
brackets which indicates how many elements the sub-arrays have.
Example:
string letters[2][4] = {
{ "A", "B", "C", "D" },
{ "E", "F", "G", "H" }
};
Example:
string letters[2][2][2] = {
{
{ "A", "B" },
{ "C", "D" }
},
{
{ "E", "F" },
{ "G", "H" }
}
};
2 Dimensional Array
3 Dimensional Array
Multi-dimensional arrays are great at representing grids.
Programiz
Every C++ program we will write will follow this structure:
1. Integers (int)
Integers are numbers without decimal parts. For example: 5, -11, 0, 12, etc.
For now, let's refer to integers as simply int.
Floating-point numbers contain decimal parts. For example: 2.5, 6.76, 0.0, -
9.45, etc. For now, let's refer to floating-point numbers as double.
3. Strings (string)
In C++, texts wrapped inside double quotation marks are called strings.
"This is a string."
We use the cout << “output”; statement to print output on the screen.
Declare Variables
The syntax to declare variables in C++ is:
int age;
Here,
● age - a variable
● int - data type of age
The age variable can only store integer values because we have used the
data type int to declare it.
Output
19
Printing Variables
Output
19
age
Data Types
Data types determine the type of data
associated with variables.
1. int type - used for integer values without decimal. Ex. 4, -43, etc.
2. double type - used for floating-point numbers with decimal. Ex. 34.9,
98.26, etc.
Output
2.1
Here,
‘double’ = data type
‘decimalnumber’ = variable
‘2.1’ = value stored in variable
3. char type - used for characters. Ex. 'g', '(', '-', etc.
Output
s
Here,
‘char’ = data type
‘myinitial’ = variable
‘s’ = value stored in variable
Output
123
456
Selecting Proper Variable Names
● If the name consists of two or more words, use the snake case ( _ )
formatting to separate them.
● You cannot use spaces or other symbols (except alphabets, numbers
and underscore) as variable names.
#include <iostream>
using namespace std;
int main()
{
cout << “Every age has a language of its own\n”;
return 0;
}
Function Name
The parentheses ( ) following the word main are the distinguishing feature
of a function. Without
the parentheses the compiler would think that main refers to a variable or to
some other pro-
gram element.
We’ll put parentheses following the function name.
The word int preceding the function name indicates that this particular
function has a return
value of type int.
Program Statements
The program statement is the fundamental unit of C++ programming. There
are two statements
in the FIRST program:
return 0;
The last statement in the function body is return 0;. This tells main() to
return the value 0 to
whoever called it, in this case the operating system or compiler.
Whitespace
The compiler ignores whitespace. Whitespace is defined as spaces,
carriage returns, line-
feeds, tabs, vertical tabs, and formfeeds.
String Constants
● The phrase in quotation marks
● Cannot be given a new value as the program runs.
● Its value is set when the program is written.
● The ‘\n’ character at the end of the string constant is an example of
an escape sequence.
● It causes the next text output to be displayed on a new line.
Directives
● The two lines that begin the FIRST program are directives.
● They are:
1. Preprocessor directive
2. Using directive
Preprocessor Directives
The first line of the FIRST program
#include <iostream>
● It’s called a preprocessor directive.
● Can be identified by the initial # sign.
Header Files
● In the FIRST example, the preprocessor directive #include tells the
compiler to add the source file IOSTREAM to the FIRST.CPP source
file before compiling.
● IOSTREAM is an example of a header file.
● It’s concerned with basic input/output operations, and contains
declarations that are needed by the cout identifier and the <<
operator.
says that all the program statements that follow are within the std
namespace. Various program components such as cout are declared within
this namespace.
Comments
They help the person writing a program, and anyone else who must read
the source file, understand what’s going on.
The compiler ignores comments.
Comment Syntax ( // )
// comments.cpp
// demonstrates comments
#include <iostream> //preprocessor
directive
using namespace std; //”using”
directive
int main() //function
name “main”
{ //start function
body
cout << “Every age has a language of its own\n”; //statement
return 0; //statement
} //end function
body
Comments start with a double slash symbol (//) and terminate at the end of
the line.
Integer Variables
A variable has a symbolic name and can be given a variety of values.
Variables are located in particular places in the computer’s memory. When
a variable is given a value, that value is actually placed in the memory
space assigned to the variable. Integer variables represent integer
numbers like 1, 30,000, and –27.
Here’s a program that defines and uses several variables of type int:
The statements:
● int var1;
● int var2;
Variable Names
The names given to variables (and other program features) are called
identifiers.
Rules for writing identifiers:
You can use upper- and lowercase letters, and the digits from 1 to 9, the
underscore (_),
The first character must be a letter or underscore.
The compiler distinguishes between upper- and lowercase letters,
You can’t use a C++ keyword as a variable name.
(A keyword is a predefined word with a special meaning. int, class, if, and
while are examples of keywords.)
compiler’s documentation.
Many C++ programmers follow the convention of using all lowercase letters
for variable
names. Other programmers use a mixture of upper- and lowercase, as in
IntVar or dataCount.
Still others make liberal use of underscores. Whichever approach you use,
it’s good to be con-
sistent throughout a program. Names in all uppercase are sometimes
reserved for constants
(see the discussion of const that follows). These same conventions apply to
naming other pro-
gram elements such as classes and functions.
A variable’s name should make clear to anyone reading the listing the
variable’s purpose and
how it is used. Thus boilerTemperature is better than something cryptic like
bT or t.
Assignment Statements
The statements
var1 = 20;
var2 = var1 + 10;
assign values to the two variables. The equal sign (=), as you might guess,
causes the value on
the right to be assigned to the variable on the left. The = in C++ is
equivalent to the := in
Pascal or the = in BASIC. In the first line shown here, var1, which
previously had no value, is
given the value 20.
Insertion Sort