0% found this document useful (0 votes)
8 views20 pages

C++ Introduction

C++ is a cross-platform, high-performance programming language developed as an extension of C, offering control over system resources and memory. It is widely used in various applications, supports object-oriented programming, and has undergone several updates since its inception. The document covers C++ syntax, variables, data types, operators, control structures, and examples of basic programs.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views20 pages

C++ Introduction

C++ is a cross-platform, high-performance programming language developed as an extension of C, offering control over system resources and memory. It is widely used in various applications, supports object-oriented programming, and has undergone several updates since its inception. The document covers C++ syntax, variables, data types, operators, control structures, and examples of basic programs.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 20

C++ Introduction

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++ Syntax
Let's break up the following code to understand it better:
#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.
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: 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

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!";
return 0;
}
C++ Output (Print Text)
The cout object, together with the << operator, is used to output values and print
text.
Just remember to surround the text with double quotes (""):
Example
#include <iostream>
using namespace std;

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

C++ Print Numbers


You can also use cout() to print numbers.
However, unlike text, we don't put numbers inside double quotes:
Example
#include <iostream>
using namespace std;

int main() {
cout << 3;
return 0;
}
New Lines
To insert a new line in your output, you can use the \n character:
Example
#include <iostream>
using namespace std;

int main() {
cout << "Hello World! \n";
cout << "I am learning C++";
return 0;
}

C++ Comments
Comments can be used to explain C++ code, and to make it more readable. It can
also be used to prevent execution when testing alternative code. Comments can
be singled-lined or multi-lined.

Single-line Comments
Single-line comments start with two forward slashes (//).
Any text between // and the end of the line is ignored by the compiler (will not be
executed).
This example uses a single-line comment before a line of code:
Example
// This is a comment
cout << "Hello World!";
C++ Multi-line Comments
Multi-line comments start with /* and ends with */.
Any text between /* and */ will be ignored by the compiler:
Example
/* The code below will print the words Hello World!
to the screen, and it is amazing */
cout << "Hello World!";

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;

C++ Identifiers
All C++ variables must be identified with unique names.
These unique names are called identifiers.
Identifiers can be short names (like x and y) or more descriptive names (age, sum,
totalVolume).
Note: It is recommended to use descriptive names in order to create
understandable and maintainable code:
Example
// Good
int minutesPerHour = 60;

// OK, but not so easy to understand what m actually is


int m = 60;

The general rules for naming variables are:


 Names can contain letters, digits and underscores
 Names must begin with a letter or an underscore (_)
 Names are case-sensitive (myVar and myvar are different variables)
 Names cannot contain whitespaces or special characters like !, #, %, etc.
 Reserved words (like C++ keywords, such as int) cannot be used as names
 Constants
 When you do not want others (or yourself) to change existing variable
values, use the const keyword (this will declare the variable as
"constant", which means unchangeable and read-only):
 Example
 const int myNum = 15; // myNum will always be 15
myNum = 10; // error: assignment of read-only variable 'myNum'

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 (>>).
In the following example, the user can input a number, which is stored in
the variable x. Then we print the value of x:
Example
int x;
cout << "Type a number: "; // Type a number and press enter
cin >> x; // Get user input from the keyboard
cout << "Your number is: " << x; // Display the input value
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
Try it Yourself »
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

int 2 or 4 Stores whole numbers, without decimals


bytes

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


decimal digits

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


decimal digits
C++ Operators
Arithmetic Operators
Arithmetic operators are used to perform common mathematical
operations.

Operator Name Description

+ Addition Adds together two values

- Subtraction Subtracts one value from another

* Multiplication Multiplies two values

/ Division Divides one value by another

% Modulus Returns the division remainder

++ Increment Increases the value of a variable by 1

-- Decrement Decreases the value of a variable by 1

Exercise
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.
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";
}
Try it Yourself »
We can also test variables:
Example
int x = 20;
int y = 18;
if (x > y) {
cout << "x is greater than y";
}
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
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)
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
}

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++;
}
C++ "Hello World!" Program
// Your First C++ Program

#include <iostream>

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

Example: Print Number Entered by User


#include <iostream>
using namespace std;
int main() {
int number;
cout << "Enter an integer: ";
cin >> number;

cout << "You entered " << number;


return 0;
}
Example: Program to Add Two Integers
#include <iostream>
using namespace std;

int main() {

int first_number, second_number, sum;

cout << "Enter two integers: ";


cin >> first_number >> second_number;

// sum of two numbers in stored in variable sumOfTwoNumbers


sum = first_number + second_number;

// prints sum
cout << first_number << " + " << second_number << " = " << sum;

return 0;
}

Example 1: Check Whether Number is Even or Odd using if else


#include <iostream>
using namespace std;

int main() {
int n;
cout << "Enter an integer: ";
cin >> n;
if ( n % 2 == 0)
cout << n << " is even.";
else
cout << n << " is odd.";
return 0;
}
Example 1: Swap Numbers (Using Temporary Variable)
#include <iostream>
using namespace std;

int main()
{
int a = 5, b = 10, temp;

cout << "Before swapping." << endl;


cout << "a = " << a << ", b = " << b << endl;

temp = a;
a = b;
b = temp;

cout << "\nAfter swapping." << endl;


cout << "a = " << a << ", b = " << b << endl;

return 0;
}

Example 1: Find Largest Number Using if...else Statement


#include <iostream>
using namespace std;
int main() {

double n1, n2, n3;

cout << "Enter three numbers: ";


cin >> n1 >> n2 >> n3;

// check if n1 is the largest number


if(n1 >= n2 && n1 >= n3)
cout << "Largest number: " << n1;

// check if n2 is the largest number


else if(n2 >= n1 && n2 >= n3)
cout << "Largest number: " << n2;

// if neither n1 nor n2 are the largest, n3 is the largest


else
cout << "Largest number: " << n3;

return 0;
}

You might also like