Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 12

 Starting Your First Program be liked: Example:

Let's break up the following code to understand it


#include <iostream>
better:
Example:
int main() {
#include <iostream>   std::cout << "Hello World!";
using namespace std;   return 0;
}
int main() {
  cout << "Hello World!";
  return 0;
}  C++ Output/ Display (Print Text):
The cout object, together with the << operator, is
Above example is explained: used to output values/print text:
Line 1: #include <iostream> is a header file #include <iostream>
library that lets us work with input and output using namespace std;
objects, such as cout (used in line 5). Header files add
functionality to C++ programs. int main() {
Line 2: using namespace std means that we can use   cout << "Hello World!";
names for objects and variables from the standard   return 0;
library. }
Don't worry if you don't understand how #include
<iostream> and using namespace std works. Just Note: You can add as many cout objects as you want.
think of it as something that (almost) always appears However, note that it does not insert a new line at
in your program. the end of the output:
Line 3: A blank line. C++ ignores white space. But we
use it to make the code more readable.  C++ New Lines:
Line 4: Another thing that always appear in a C++ To insert a new line, you can use the \n character:
program, is int main(). This is called a function. Any
#include <iostream>
code inside its curly brackets {} will be executed.
using namespace std;
Line 5: cout (pronounced "see-out") is an object used
together with the insertion operator (<<) to int main() {
output/print text. In our example it will output "Hello   cout << "Hello World! \n";
World".   cout << "I am learning C++";
Note: Every C++ statement ends with a semicolon ;.   return 0;
Note: The body of int main() could also been written }
as:
int main () { cout << "Hello World! "; return 0; } Tip: Two \n characters after each other will create a
Remember: The compiler ignores white spaces. blank line:
However, multiple lines makes the code more Another way to insert a new line, is with
readable. the endl manipulator:
Line 6: return 0 ends the main function. #include <iostream>
Line 7: Do not forget to add the closing curly using namespace std;
bracket } to actually end the main function.
int main() {
Omitting Namespace Example:   cout << "Hello World!" << endl;
You might see some C++ programs that runs without   cout << "I am learning C++";
the standard namespace library. The using   return 0;
namespace std line can be omitted and replaced with }
the std keyword, followed by the :: operator for some
objects:
Both \n and endl are used to break lines. However, \ Variables are containers for storing data values.
n is most used.
In C++, there are different types of variables (defined
But what \n is exactly? with different keywords), for example:

The newline character (\n) is called an escape  int - stores integers (whole numbers), without
sequence, and it forces the cursor to change its decimals, such as 123 or -123
position to the beginning of the next line on the  double - stores floating point numbers, with
screen. This results in a new line. decimals, such as 19.99 or -19.99
 char - stores single characters, such as 'a' or
Examples of other valid escape sequences are:
'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++ Comments: Declaring (Creating) Variable:


Comments can be used to explain C++ code, and to
make it more readable. It can also be used to prevent To create a variable, specify the type and assign it a
execution when testing alternative code. Comments
can be singled-lined or multi-lined.
 Single-line Comments:
 Single-line comments start with two forward
slashes (//). value:
 Any text between // and the end of the line is Where type is one of C++ types (such as int),
ignored by the compiler (will not be and variableName is the name of the variable (such
executed). as x or myName). The equal sign is used to assign
 This example uses a single-line comment values to the variable.
before a line of code:
To create a variable that should store a number, look
at the following example:

Example: Create a variable called myNum of


 Multi-line Comments: type int and assign it the value 15:
 Multi-line comments start with /* and ends
with */.
#include <iostream>
 Any text between /* and */ will be ignored by
the compiler: using namespace std;

int main() {
int myNum = 15;
cout << myNum;
return 0;
Note: It is up to you which you want to use. Normally, }
we use // for short comments, and /* */ for longer.
You can also declare a variable without assigning the
value, and assign the value later:

 C++ Variables
#include <iostream>
#include <iostream>
using namespace std;
using namespace std;
int main() {
int main() {
int myNum;
int myAge = 35;
myNum = 15;
cout << "I am " << myAge << " years old.";
cout << myNum;
return 0;
return 0;
}
}
Add Variables Together:
Note that if you assign a new value to an existing To add a variable to another variable, you can use
variable, it will overwrite the previous value: the + operator:
#include <iostream>
#include <iostream> using namespace std;
using namespace std;
int main() {
int main() { int x = 5;
int myNum = 15; // Now myNum is 15 int y = 6;
myNum = 10; // Now myNum is 10 int sum = x + y;
cout << myNum; cout << sum;
return 0; return 0;
} }

 C++ Declare Many Variables:


Declare Many Variables:
Other Types: To declare more than one variable of the same type,
A demonstration of other data types: use a comma-separated list:
#include <iostream>
using namespace std;

int main() {
int x = 5, y = 6, z = 50;
cout << x + y + z;
return 0;
Display Variables: }
 The cout object is used together with
the << operator to display variables.
One Value to Multiple Variables:
 To combine both text and a variable, separate
You can also assign the same value to multiple
them with the << operator:
variables in one line:
 C++ Constants
#include <iostream>
When you do not want others (or yourself) to
using namespace std;
override existing variable values, use
the const keyword (this will declare the variable as
int main() {
"constant", which means unchangeable and read-
int x, y, z;
only):
x = y = z = 50;
cout << x + y + z;
return 0;
}

 C++ Identifiers #include <iostream>


All C++ variables must be identified with unique using namespace std;
names.
These unique names are called identifiers. int main() {
Identifiers can be short names (like x and y) or more const int myNum = 15;
descriptive names (age, sum, total Volume). myNum = 10;
Note: It is recommended to use descriptive names in cout << myNum;
order to create understandable and maintainable return 0;
code:
}
#include <iostream>
You should always declare the variable as constant
using namespace std; when you have values that are unlikely to change:

int main() { #include <iostream>


// Good name using namespace std;
int minutesPerHour = 60;
int main() {
// OK, but not so easy to understand what m const int minutesPerHour = 60;
actually is const float PI = 3.14;
int m = 60; cout << minutesPerHour << "\n";
cout << PI;
cout << minutesPerHour << "\n"; return 0;
cout << m; }
return 0;
}
 C++ User Input
The general rules for naming variables are:
You have already learned that cout is used to
 Names can contain letters, digits and output (print) values. Now we will use cin to get
underscores user input.
 Names must begin with a letter or an
underscore (_) cin is a predefined variable that reads data from
 Names are case sensitive the keyboard with the extraction operator (>>).
(myVar and myvar are different variables)
 Names cannot contain whitespaces or special In the following example, the user can input a
characters like !, #, %, etc. number, which is stored in the variable x. Then
 Reserved words (like C++ keywords, such we print the value of x:
as int) cannot be used as names
#include <iostream>
#include <string>
using namespace std;
#include <iostream>
using namespace std; int main () {
// Creating variables
int main() { int myNum = 5; // Integer (whole number)
int x; float myFloatNum = 5.99; // Floating point
cout << "Type a number: "; // Type a number and number
press enter double myDoubleNum = 9.98; // Floating point
cin >> x; // Get user input from the keyboard number
cout << "Your number is: " << x; char myLetter = 'D'; // Character
return 0; bool myBoolean = true; // Boolean
} string myString = "Hello"; // String

Creating a Simple Calculator: // Print variable values


In this example, the user must input two cout << "int: " << myNum << "\n";
numbers. Then we print the sum by calculating cout << "float: " << myFloatNum << "\n";
(adding) the two numbers: cout << "double: " << myDoubleNum << "\n";
#include <iostream> cout << "char: " << myLetter << "\n";
using namespace std; cout << "bool: " << myBoolean << "\n";
cout << "string: " << myString << "\n";
int main() {
int x, y; return 0;
int sum; }
cout << "Type a number: ";
cin >> x;
Basic Data Types:
cout << "Type another number: ";
cin >> y;
sum = x + y;
cout << "Sum is: " << sum;
return 0;
}

 C++ Data Types


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

 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.

For int:
 C++ Boolean Data Types:
#include <iostream>
A boolean data type is declared with
using namespace std;
the bool keyword and can only take the
int main () { values true or false.
int myNum = 1000; When the value is returned, true = 1 and false = 0.
cout << myNum;
return 0; #include <iostream>
} using namespace std;

For Float: int main() {


bool isCodingFun = true;
#include <iostream> bool isFishTasty = false;
using namespace std; cout << isCodingFun << "\n";
cout << isFishTasty;
int main () { return 0;
float myNum = 5.75; }
cout << myNum;
return 0;  C++ Character Data Types:
}
The char data type is used to store a single character.
The character must be surrounded by single quotes,
For Double:
like 'A' or 'c':
#include <iostream>
using namespace std; #include <iostream>
using namespace std;
int main () {
double myNum = 19.99; int main () {
cout << myNum; char myGrade = 'B';
return 0; cout << myGrade;
} return 0;
}

Alternatively, you can use ASCII values to display


certain characters:

#include <iostream>
Scientific Numbers: using namespace std;
#include <iostream>
int main () {
using namespace std;
char a = 65, b = 66, c = 67;
cout << a;
int main () {
cout << b;
float f1 = 35e3;
cout << c;
double d1 = 12E4;
return 0;
cout << f1 << "\n";
}
cout << d1;
return 0;
}
#include <iostream>
 C++ String Data Types using namespace std;
The string type is used to store a sequence of
characters (text). This is not a built-in type, but it int main() {
behaves like one in its most basic usage. String values int sum1 = 100 + 50; // 150 (100 + 50)
must be surrounded by double quotes: int sum2 = sum1 + 250; // 400 (150 + 250)
int sum3 = sum2 + sum2; // 800 (400 + 400)
cout << sum1 << "\n";
cout << sum2 << "\n";
To use strings, you must include an additional header cout << sum3;
file in the source code, the <string> library: return 0;
}
#include <iostream>
#include <string>
using namespace std;

int main() {
string greeting = "Hello";
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:

#include <iostream>
 C++ Assignment Operators
using namespace std;
Assignment operators are used to assign values to
variables.
int main() {
int x = 100 + 50; In the example below, we use
cout << x; the assignment operator (=) to assign the value 10 to
return 0; a variable called x:
}
#include <iostream>
Although the + operator is often used to add together using namespace std;
two values, like in the example above, it can also be
used to add together a variable and a value, or a int main() {
variable and another variable: int x = 10;
cout << x;
return 0;
}
The addition assignment operator (+=) adds a value
to a variable:
#include <iostream>
using namespace std;

int main() {
int x = 10;
x += 5;
cout << x;
return 0;
}

 C++ Logical Operators

Logical operators are used to determine the logic


between variables or values:

 C++ Strings

Strings are used for storing text.


A string variable contains a collection of characters
surrounded by double quotes:
 C++ Comparison Operators
Comparison operators are used to compare two
values.
Note: The return value of a comparison is either true
(1) or false (0).
In the following example, we use the greater
To use strings, you must include an additional header
than operator (>) to find out if 5 is greater than 3:
file in the source code, the <string> library:

#include <iostream> #include <iostream>


using namespace std; #include <string>
using namespace std;
int main() {
int x = 5; int main() {
int y = 3; string greeting = "Hello";
cout << (x > y); // returns 1 (true) because 5 is cout << greeting;
greater than 3 return 0;
return 0; }
}
 C++ Concatenation
#include <iostream>
The + operator can be used between strings to add
#include <string>
them together to make a new string. This is
using namespace std;
called concatenation:
#include <iostream> int main () {
#include <string> string firstName = "John ";
using namespace std; string lastName = "Doe";
string fullName = firstName.append(lastName);
int main () { cout << fullName;
string firstName = "John "; return 0;
string lastName = "Doe"; }
string fullName = firstName + lastName;
cout << fullName;
 C++ Number and Strings
return 0;
}
Adding Numbers and Strings:

In the example above, we added a space after first


Name to create a space between John and Doe on
output. However, you could also add a space with If you add two numbers, the result will be a number:
quotes (" " or ' '):
#include <iostream>
#include <iostream> using namespace std;
#include <string>
using namespace std; int main () {
int x = 10;
int main () { int y = 20;
string firstName = "John"; int z = x + y;
string lastName = "Doe"; cout << z;
string fullName = firstName + " " + lastName; return 0;
cout << fullName; }
return 0;
If you add two strings, the result will be a string
}
concatenation:
#include <iostream>
Append: #include <string>
A string in C++ is actually an object, which contain using namespace std;
functions that can perform certain operations on
strings. For example, you can also concatenate strings int main () {
with the append() function: string x = "10";
string y = "20";
string z = x + y;
cout << z;
return 0;
}

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


#include <iostream>
#include <string>
using namespace std;

int main() {
string myString = "Hello";
cout << myString[0];
return 0;
 C++ String Length }
To get the length of a string, use
the length() function:

#include <iostream> This example prints the second


#include <string> character  in  myString:
using namespace std;
#include <iostream>
#include <string>
int main() {
using namespace std;
string txt = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
cout << "The length of the txt string is: " <<
int main() {
txt.length();
string myString = "Hello";
return 0;
cout << myString[1];
}
return 0;
}
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 Change String Characters:
you want to use length() or size(): To change the value of a specific character in a string,
refer to the index number, and use single quotes:
#include <iostream>
#include <string> #include <iostream>
using namespace std; #include <string>
using namespace std;
int main() {
string txt = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; int main() {
cout << "The length of the txt string is: " << string myString = "Hello";
txt.size(); myString[0] = 'J';
return 0; cout << myString;
} return 0;
}

 C++ Access String


You can access the characters in a string by referring  C++ Special Characters
to its index number inside square brackets []. Strings – Special Characters:
Because strings must be written within quotes, C++
This example prints the first character in my String:
will misunderstand this string, and generate an error:
The solution to avoid this problem, is to use
the backslash escape character.

The backslash (\) escape character turns special


characters into string characters:


 C++ User Input Strings
It is possible to use the extraction
The sequence \"  inserts a double quote in a string: operator >> on cin to display a string entered by a
user:
#include <iostream>
using namespace std;

int main() {
string txt = "We are the so-called \"Vikings\" from
the north.";
cout << txt;
return 0;
}
However, cin considers a space (whitespace, tabs,
The sequence \'  inserts a single quote in a string: etc) as a terminating character, which means that it
can only display a single word (even if you type many
#include <iostream>
words):
using namespace std;

int main() {
string txt = "It\'s alright.";
cout << txt;
return 0;
}

The sequence \\  inserts a single backslash in a string:

#include <iostream>
using namespace std;
From the example above, you would expect the
int main() { program to print "John Doe", but it only prints "John".
string txt = "The character \\ is called backslash.";
cout << txt;
That's why, when working with strings, we often use
return 0;
the getline() function to read a line of text. It
}
takes cin as the first parameter, and the string
Other popular escape characters in C++ are: variable as second:
#include <iostream>
#include <string>
using namespace std;

int main() {
string fullName;
cout << "Type your full name: ";
getline (cin, fullName);
cout << "Your name is: " << fullName;
return 0;
}

 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:
#include <iostream>
#include <string>

int main() {
std::string greeting = "Hello";
std::cout << greeting;
return 0;
}
It is up to you if you want to include the standard
namespace library or not.

You might also like