100% found this document useful (1 vote)
21 views36 pages

S1 Introduction To C++

The document provides a comprehensive overview of C++ programming concepts including header files, variables, data types, operators, control structures, loops, and arrays. It explains how to use input/output, declare variables, perform arithmetic operations, and implement conditional statements and loops. Additionally, it covers string manipulation, user input, and the structure of C++ 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
100% found this document useful (1 vote)
21 views36 pages

S1 Introduction To C++

The document provides a comprehensive overview of C++ programming concepts including header files, variables, data types, operators, control structures, loops, and arrays. It explains how to use input/output, declare variables, perform arithmetic operations, and implement conditional statements and loops. Additionally, it covers string manipulation, user input, and the structure of C++ 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/ 36

via.

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)

● using namespace std means that we can use names for


objects and variables from the standard library. (always
appear in program)

● C++ ignores white space.

● int main() is called a function. Any code inside its curly


brackets {} will be executed.

● cout is an object used together with the insertion


operator (<<) to output/print text.

● Every C++ statement ends with a semicolon ;

● return 0 ends the main function.

Omitting Namespace

● The using namespace std line can be omitted and


replaced with the std keyword, followed by the ::
operator for some objects:

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

● It is up to you if you want to include the standard


namespace library or not.

New Lines

● To insert a new line, you can use the \n character:

#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++

● Two \n characters after each other will create a blank


line:

#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

the next line on the screen. This results in a new line.


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

● 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:

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).
● To create a variable that should store a number, look at the following
example:

variable called myNum type int assigned value 15

int myNum = 15; output:

cout << myNum; 15

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

Add Variables Together


● To add a variable to another variable, you can use the + operator:
int x = 5; OUTPUT:
int y = 6; 11
int sum = x + y;
cout << sum;

C++ User Input


cin is a predefined variable that reads data from the keyboard with the
extraction 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.

bool isCodingFun = true; Output:


bool isFishTasty = false; 10
cout << isCodingFun;
cout << isFishTasty;
● Boolean values are used for conditional testing.

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.

string greeting = "Hello"; Output:

cout << greeting; Hello

● 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

● 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
❖ 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:

int y = 3; 1[returns 1 (true) cause 5 is

cout << (x > y); greater than 3]


Logical Operators
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 x < 5 && x < 10


statements are true

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


statements is true

! 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 firstName = "John "; Output:


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

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:

● 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
if (condition) {
// block of code to be executed if the condition is true
}

The else Statement


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
}

The else if Statement


Use the else if statement to specify a new condition if the first condition is
false.

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
}

ShortHand If...Else (Ternary Operator)


● Aka 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

variable = (condition) ? expressionTrue : expressionFalse;

Example:

int time = 9;

string result = (time < 12) ? "Good day." : "Good evening.";

cout << result;

C++ Switch Statements


● The switch statement is used to select one of many code blocks to be
executed.

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

● 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 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.
● 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 is used to specify some code to run if there is no case
match.

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.

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:

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

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

do {

// code block to be executed

while (condition);

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

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

cout << i << "\n";

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.

string cars[4]; //a variable that holds an array of four strings

string cars[4] = {"Volvo", "BMW", "Ford", "McLaren"};

int myNum[3] = {10, 20, 30}; //an array of three integers

Access the Elements of an Array


You access an array element by referring to the index number inside square
brackets [].

string cars[4] = {"Volvo", "BMW", "Ford", "Mazda"};


cout << cars[0];

OUTPUT
Volvo

⭐Array indexes start with 0: [0] is the first element. [1] is the
second element, etc.⭐

Change an Array Element

string cars[4] = {"Volvo", "BMW", "Ford", "Mazda"};


cars[0] = "Audi";
cout << cars[0];

OUTPUT
Audi

Loop Through an Array


You can loop through the array elements with the for loop.

Outputs the index of each element together with its value:

string cars[5] = {"Volvo", "BMW", "Ford", "Mazda", "Tesla"};


for (int i = 0; i < 5; i++) {
cout << i << " = " << cars[i] << "\n";
}
OUTPUT
0 = Volvo
1 = BMW
2 = Ford
3 = Mazda
4 = Tesla

Loop through an array of integers:

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


for (int i = 0; i < 5; i++) {
cout << myNumbers[i] << "\n";
}
OUTPUT
10
20
30
40
50

The Foreach Loop


Used exclusively to loop through elements in an array.

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

Outputs all elements in an array, using a "for-each loop":

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


for (int i : myNumbers) {
cout << i << "\n";
}
OUTPUT
10
20
30
40
50

Omit Elements on Declaration


It is also possible to declare an array without specifying the elements on
declaration, and add them later:

string cars[5];
cars[0] = "Volvo";
cars[1] = "BMW";

Get the Size of an Array


Use the sizeof() operator:

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


cout << sizeof(myNumbers);

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:

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


int getArrayLength = sizeof(myNumbers) / sizeof(int);
cout << getArrayLength;

OUTPUT
5

Loop Through an Array with sizeof()

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


for (int i = 0; i < sizeof(myNumbers) / sizeof(int); i++) {
cout << myNumbers[i] << "\n";
}
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" }
};

This array has 2 dimensions.

● Each set of square brackets in an array declaration adds another


dimension to an array.

Example:
string letters[2][2][2] = {
{
{ "A", "B" },
{ "C", "D" }
},
{
{ "E", "F" },
{ "G", "H" }
}
};

This array has 3 dimensions.

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:

Commonly used literals in C++ :

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.

2. Floating-point Numbers (double)

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.

Print Multiple Strings


We can print multiple strings in a single statement by separating them with
the << operator.
We use a semicolon ; to indicate the end of a statement.

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.

Once we declare a variable, we can assign a value to it.


Declare and Assign Value Together
We can also assign values to variables during their declaration.

Output
19

Here, we have created a variable named salary and assigned a value to it in


a single statement.

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.

Use single quotes ( ‘ ‘ ) to represent characters.

A character variable can only store a single character data.

Output
s

Here,
‘char’ = data type
‘myinitial’ = variable
‘s’ = value stored in variable

Changing Values Stored in Variables


Output
19
18

Value of One Variable to Another


Output
74
243

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.

Create Multiple Variables Together


Output
24
132
Via Book C++ Programming Basics

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

Braces and the Function Body


Body of a function is surrounded by braces ( { } ) . They surround or delimit
a block of program statements. Every function must use this pair of braces
around the function body.

Always Start with main()


The program may consist of many functions, classes, and other program
elements, but on startup control always goes to main(). If there is no
function called main() in your program, an error will be reported when you
run the program.

Program Statements
The program statement is the fundamental unit of C++ programming. There
are two statements
in the FIRST program:

cout << “Every age has a language of its own\n”;


The first statement tells the computer to display the quoted phrase. Most
statements tell the
computer to do something.
A semicolon signals the end of the statement.

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.

Output Using cout


The identifier cout is actually an object.It is predefined in C++ to correspond
to the standard output stream. A stream refers to a flow of data.
The operator << is called the insertion or put to operator. It directs the
contents of the variable
on its right to the object on its left. In FIRST it directs the string constant
“Every age has a
language of its own\n” to cout, which sends it to the display.

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.

● A preprocessor directive is an instruction to the compiler.


● A part of the compiler called the preprocessor deals with these
directives before it begins the real compilation process.
● The preprocessor directive #include tells the compiler to insert
another file into your source file.
● In effect, the #include directive is replaced by the contents of the file
indicated.
● The type file usually included by #include is called a header file.

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.

The using Directive


A C++ program can be divided into different namespaces. A namespace is
a part of the pro-
gram in which certain names are recognized; outside of the namespace
they’re unknown. The directive

using namespace std;

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.

Defining Integer Variables

Here’s a program that defines and uses several variables of type int:
The statements:
● int var1;
● int var2;

define two integer variables, var1 and var2.


The keyword int signals the type of variable.
The INTVARS program are definitions, as well as declarations, because
they set aside memory for var1 and var2.
The program INTVARS uses variables named var1 and var2.
These statements, which are called declarations, must terminate with a
semicolon, like other
program statements.
You must declare a variable before using it.

Declarations and Definitions


A declaration introduces a variable’s name (such as var1) into a program
and specifies its type
(such as int). However, if a declaration also sets aside memory for the
variable, it is also
called a definition.

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

You can’t use a C++ keyword as a variable name. A keyword is a


predefined word with a spe-
cial meaning. int, class, if, and while are examples of keywords. A complete
list of key-
words can be found in Appendix B, “C++ Precedence Table and
Keywords,” and in your

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

Insertion sort is a simple sorting algorithm that works by iteratively


building a sorted portion of the array or listing one element at a time. It
is called "insertion sort" because it inserts each element into its correct
position within the already sorted portion of the array.
● In this code, the insertionSort function takes an array arr and its
size n as input. It iterates over the array starting from the second
element (i=1) and compares each element with the elements in
the already sorted portion of the array (arr[0] to arr[i-1]).
If an element is smaller, it shifts the greater elements one
position to the right to make space for the current element.Once
the correct position is found, the current element is inserted into
that position.

● The printArray function is used to print the elements of the array.

● In the main function, an example array is initialized, and the


original and sorted arrays are printed by calling the appropriate
functions.

You might also like