0% found this document useful (0 votes)
44 views36 pages

Lecture PDF 2

Lecture pdf hahshhshshsjjssjskskskkskskwkwkbhshhshsshshshzhhzhzhhzzhhzhzhzhhxhxjhxhjdjshshshshshhshs

Uploaded by

good9761931226az
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
44 views36 pages

Lecture PDF 2

Lecture pdf hahshhshshsjjssjskskskkskskwkwkbhshhshsshshshzhhzhzhhzzhhzhzhzhhxhxjhxhjdjshshshshshhshs

Uploaded by

good9761931226az
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 36

C++ Basics

C++ is a programming language created by Bjarne Stroustrup and


his team at Bell Laboratories in 1979.

As the name implies, C++ was derived from the C language; Bjarne’s
goal was to add object-oriented programming into C, a language
well-respected for its portability and low-level functionality.

So why learn C++? Among many other things:

 It is fast and flexible.


 It is well-supported.
 It forces you to think in new and creative ways.

C++ is a powerful general-purpose programming language.


It can be used to develop operating systems, browsers, games, and
so on.
C++ supports different ways of programming like procedural,
object-oriented, functional, and so on. This makes C++ powerful as
well as flexible.

Program 1: Hello World


C++ programs are stored in files which usually have the file
extension .cpp, which simply stands for “C Plus Plus”.

Solution:
#include <iostream>
int main() {
// Write C++ code here
std::cout << "Hello world!";
return 0;
}
OR you can write the same code as:
#include <iostream>
using namespace std;
int main() {
cout << "Hello World!";
return 0;
}
Note:

C++, like most programming languages, runs line by line, from


top to bottom. Here is the structure of a C++ program
Here,
std::cout << "Hello World!\n";
 std::cout is the “character output stream”. It is pronounced
“see-out”. Here, cout is an object.
 << is an (insertion operator) operator that comes right after it.
 "Hello World!\n" is what’s being outputted here. You need
double quotes around text. The \n is a special character that
indicates a new line.
 ; is a punctuation that tells the computer that you are at the
end of a statement. It is similar to a period in a sentence.
 using namespace std means that we can use names for objects
and variables from the standard library.

We can also output multiple lines by adding more std::cout


statements:
Exercise 1: Print the following pattern using multiple std::cout
statements:
1
2 3
4 5 6
7 8 9 10
Solution 1:
Review:

 C++ is a general-purpose coding language.


 C++ runs line by line, from top to bottom.
 std::cout is how you output to the terminal.
 C++ is a cross-platform language that can be used to create
high-performance applications.

Before move on to the next step write a letter to


your future self
In letter.cpp, let’s add the following:

 Goal(s) for yourself (related to your project work completion).


 Name and date.

Hint: Here, you are writing a letter to your future programming self.
Solution 2

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.

Difference between C and C++


C++ was developed as an extension of C, and both languages have
almost the same syntax.

The main difference between C and C++ is that C++ support classes
and objects, while C does not.
C++ Get Started
To start using C++, you need two things:

 A text editor, like Notepad, to write C++ code


 A compiler, like GNU Compiler Collection, commonly known as
GCC, to translate the C++ code into a language that the
computer will understand.

There are many text editors and compilers to choose from. In this
tutorial, we will use an IDE.

C++ Install IDE


An IDE (Integrated Development Environment) is used to edit AND
compile the code.

Popular IDE's include Code::Blocks, Eclipse, and Visual Studio. These


are all free, and they can be used to both edit and debug C++ code.

Note: Web-based IDE's can work as well, but functionality is limited.

C++ Variables, Literals and Constants


In programming, a variable is a container (storage area) to hold
data.

To indicate the storage area, each variable should be given a unique


name (identifier). For example,

int age = 14;


Here, age is a variable of the int data type, and we have assigned an
integer value 14 to it.

The value of a variable can be changed, hence the name variable.

int age = 14; // age is 14

age = 17; // age is 17

Rules for naming a variable


 A variable name can only have alphabets, numbers, and the
underscore _.

 A variable name cannot begin with a number.

 It is a preferred practice to begin variable names with a


lowercase character. For example, name is preferable to Name.

 A variable name cannot be a keyword. For example, int is a


keyword that is used to denote integers.

 A variable name can start with an underscore. However, it's


not considered a good practice.

 Always give meaningful name to the variable.

C++ Literals
Literals are data used for representing fixed values. They can be
used directly in the code. For example: 1, 2.5, 'c' etc.
Here, 1, 2.5 and 'c' are literals.
1. Integers
An integer is a numeric literal (associated with numbers) without
any fractional or exponential part. There are three types of integer
literals in C programming:

 decimal (base 10)


 octal (base 8)
 hexadecimal (base 16)
For example:
Decimal: 0, -9, 22 etc
Octal: 021, 077, 033 etc
Hexadecimal: 0x7f, 0x2a, 0x521 etc

2. Floating-point Literals
A floating-point literal is a numeric literal that has either a fractional
form or an exponent form. For example:

-2.0
0.0000234
3. Characters
A character literal is created by enclosing a single character inside
single quotation marks. For example: 'a', 'm', 'F', '2', '}' etc.
4. Escape Sequences
Sometimes, it is necessary to use characters that cannot be typed or
has special meaning in C++ programming. For example, newline
(enter), tab, question mark, etc.
In order to use these characters, escape sequences are used.
Escape Sequences Characters
\b Backspace
\f Form feed
\n Newline
\r Return
\t Horizontal tab
\v Vertical tab
\\ Backslash
\' Single quotation mark
\" Double quotation mark
\? Question mark
\0 Null Character

5. String Literals
A string literal is a sequence of characters enclosed in double-quote
marks. For example:

"good" string constant


"" null string constant
"" string constant of white space
"x" string constant having a single character
"Earth is round\n" prints string with a newline
C++ Constants
In C++, we can create variables whose value cannot be changed. For
that, we use the const keyword. Here's an example:

const int LIGHT_SPEED = 299792458;


LIGHT_SPEED = 2500 // Error! LIGHT_SPEED is a constant.

C++ Data Types


In C++, data types are declarations for variables. This determines
the type and size of data associated with variables. For example,
int age = 13;
Here, age is a variable of type int. Meaning, the variable can only
store integers of either 2 or 4 bytes.

C++ Fundamental Data Types


Data Type Meaning Size (in Bytes)
int Integer 2 or 4
float Floating-point 4
double Double Floating-point 8
char Character 1
wchar_
Wide Character 2
t
bool Boolean 1
void Empty 0
1. C++ int
 The int keyword is used to indicate integers.
 Its size is usually 4 bytes. Meaning, it can store values from -
2147483648 to 2147483647.

For example: int salary = 75000;

2. C++ float and double


 float and double are used to store floating-point numbers
(decimals and exponentials).
 The size of float is 4 bytes and the size of double is 8 bytes.
Hence, double has two times the precision of float. To learn
more, visit C++ float and double.
For example:
float area = 64.74;
double volume = 134.64534;
Note: These two data types are also used for exponentials. For
example,
double distance = 45E12 // 45E12 is equal to 45*10^12

3. C++ char
 Keyword char is used for characters.
 Its size is 1 byte.
 Characters in C++ are enclosed inside single quotes ' '.
For example,
char mychar = 'a';

4. C++ wchar_t
 Wide character wchar_t is similar to the char data type, except
its size is 2 bytes instead of 1.
 It is used to represent characters that require more memory to
represent them than a single char.
For example,
wchar_t test = L'‫ 'ם‬// storing Hebrew character;

5. C++ bool
 The bool data type has one of two possible values: true or false.
 Booleans are used in conditional statements and loops (which
we will learn in later chapters).

For example,
bool isCodingFun = true;
bool isSweetTasty = false;
cout<< isCodingFun; // output 1
cout<< isSweetTasty; // output 0
6. C++ void
 The void keyword indicates an absence of data. It means
"nothing" or "no value".
 We will use void when we learn about functions and pointers.
Note: We cannot declare variables of the void type.

C++ Type Modifiers


We can further modify some of the fundamental data types by using
type modifiers. There are 4 type modifiers in C++. They are:
1. signed
2. unsigned
3. short
4. long
We can modify the following data types with the above modifiers:
 int
 double
 char
C++ Modified Data Types List

Data Type Size (in Bytes) Meaning


used for integers (equivalent to
signed int 4
int)
unsigned int 4 can only store positive integers
used for small integers (range -
short 2
32768 to 32767)
unsigned used for small positive integers
2
short (range 0 to 65,535)
used for large integers
long at least 4
(equivalent to long int)
used for large positive integers or
unsigned long 4 0 (equivalent to unsigned long
int)
used for very large integers
long long 8
(equivalent to long long int).
used for very large positive
unsigned long
8 integers or 0 (equivalent to
long
unsigned long long int)
used for large floating-point
long double 12
numbers
used for characters (guaranteed
signed char 1
range -127 to 127)
unsigned used for characters (range 0 to
1
char 255)

Example:
long b = 4523232;
long int c = 2345342;
long double d = 233434.56343;
short d = 3434233; // Error! out of range
unsigned int a = -5; // Error! can only store positive numbers or 0

Derived Data Types


Data types that are derived from fundamental data types are derived
types. For example: arrays, pointers, function types, structures, etc.
C++ Basic Input/Output

C++ Output
In C++, cout sends formatted output to standard output devices,
such as the screen. We use the cout object along with
the << operator for displaying output.

Example: String Output


#include <iostream>
using namespace std;
int main() {
// prints the string enclosed in double quotes
cout << "This is C++ Programming";
return 0;
}

How does this program work?


 We first include the iostream header file that allows us to
display output.
 The cout object is defined inside the std namespace. To use the
std namespace, we used the using namespace std; statement.
 C++ program starts with the main() function. The code
execution begins from the start of the main() function.
 cout is an object that prints the string inside quotation marks "
". It is followed by the << operator.
 return 0; is the "exit status" of the main() function. The
program ends with this statement, however, this statement is
not mandatory.
Note: If we don't include the using namespace std; statement, we
need to use std::cout instead of cout.

Example: Numbers and Characters Output


#include <iostream>
using namespace std;
int main() {
int num1 = 70;
double num2 = 256.783;
char ch = 'A';
cout << num1 << endl; // print integer
cout << num2 << endl; // print double
cout << "character: " << ch << endl; // print char
return 0;
}
Output:
70
256.783
character: A
C++ Input
In C++, cin takes formatted input from standard input devices such
as the keyboard. We use the cin object along with the >> operator
for taking input.

Example: Integer Input/Output


#include <iostream>
using namespace std;
int main() {
int num;
cout << "Enter an integer: ";
cin >> num; // Taking input
cout << "The number is: " << num;
return 0;
}
Output:
Enter an integer: 12
The number is: 12

Example: Taking Multiple Inputs


#include <iostream>
using namespace std;
int main() {
char a;
int num;
cout << "Enter a character and an integer: ";
cin >> a >> num;
cout << "Character: " << a << endl;
cout << "Number: " << num;
return 0;
}

Output:
Enter a character and an integer: x 1
Character: x
Number: 1

C++ Type Conversion


C++ allows us to convert data of one type to that of another. This is
known as type conversion.
There are two types of type conversion in C++.
 Implicit Conversion
 Explicit Conversion (also known as Type Casting)
Implicit Type Conversion
The type conversion that is done automatically done by the compiler
is known as implicit type conversion.
This type of conversion is also known as automatic conversion.

Example: Conversion from int to double


#include <iostream>
using namespace std;
int main() {
// assigning an int value to num_int
int num_int = 9;
// declaring a double type variable
double num_double;
// implicit conversion
// assigning int value to a double variable
num_double = num_int;
cout << "num_int = " << num_int << endl;
cout << "num_double = " << num_double << endl;
return 0;
}
Output:
num_int = 9
num_double = 9
Example: Automatic Conversion from double to int
#include <iostream>
using namespace std;
int main() {
int num_int;
double num_double = 9.99;
// implicit conversion
// assigning a double value to an int variable
num_int = num_double;
cout << "num_int = " << num_int << endl;
cout << "num_double = " << num_double << endl;
return 0;
}
Output:
num_int = 9
num_double = 9.99
Note: Since int cannot have a decimal part, the digits after the
decimal point are truncated in the above example.
Data Loss During Conversion:
Conversion from one data type to another is prone to data loss. This
happens when data of a larger type is converted to data of a smaller
type.
C++ Explicit Conversion

When the user manually changes data from one type to another, this
is known as explicit conversion. This type of conversion is also
known as type casting.
There are three major ways in which we can use explicit conversion
in C++. They are:

1. C-style type casting (also known as cast notation)


2. Function notation (also known as old C++ style type casting)
3. Type conversion operators
C-style Type Casting
As the name suggests, this type of casting is favored by the C
programming language. It is also known as cast notation.
The syntax for this style is:

(data_type) expression;

Example:

// initializing int variable

int num_int = 26;

// declaring double variable

double num_double;

// converting from int to double

num_double = (double)num_int;

Function-style Casting
We can also use the function like notation to cast data from one type
to another.

The syntax for this style is:

data_type(expression);
Example:

// initializing int variable

int num_int = 26;

// declaring double variable

double num_double;

// converting from int to double

num_double = double(num_int);

cout<< num_double;

Example:
#include <iostream>
using namespace std;
int main() {
// initializing a double variable
double num_double = 3.56;
cout << "num_double = " << num_double << endl;

// C-style conversion from double to int


int num_int1 = (int)num_double;
cout << "num_int1 = " << num_int1 << endl;
// function-style conversion from double to int
int num_int2 = int(num_double);
cout << "num_int2 = " << num_int2 << endl;
return 0;
}
Output
num_double = 3.56
num_int1 = 3
num_int2 = 3

C++ Operators
Operators are symbols that perform operations on variables and
values.
Operators in C++ can be classified into 6 types:
1. Arithmetic Operators
2. Assignment Operators
3. Relational Operators
4. Logical Operators
5. Bitwise Operators
6. Other Operators

1. C++ Arithmetic Operators


Arithmetic operators are used to perform arithmetic operations on
variables and data. For example: a + b;
Operator Operation

+ Addition

- Subtraction

* Multiplication

/ Division

Modulo Operation
%
(Remainder after division)

Example:
#include <iostream>
using namespace std;
int main() {
int a, b;
a = 7;
b = 2;
// printing the sum of a and b
cout << "a + b = " << (a + b) << endl;
// printing the difference of a and b
cout << "a - b = " << (a - b) << endl;
// printing the product of a and b
cout << "a * b = " << (a * b) << endl;
// printing the division of a by b
cout << "a / b = " << (a / b) << endl;
// printing the modulo of a by b
cout << "a % b = " << (a % b) << endl;
return 0;
}
Output:
a+b=9
a-b=5
a * b = 14
a/b=3
a%b=1

/ Division Operator
Note the operation (a / b) in our program. The / operator is the
division operator.
In the above example, if an integer is divided by another integer, we
will get the quotient.
However, if either divisor or dividend is a floating-point number, we
will get the result in decimals.
In C++,
7/2 is 3
7.0 / 2 is 3.5
7 / 2.0 is 3.5
7.0 / 2.0 is 3.5
1.1 Increment and Decrement Operators
C++ also provides increment and decrement operators: ++ and --
respectively.
++ increases the value of the operand by 1
-- decreases it by 1
Example:
#include <iostream>
using namespace std;
int main() {
int a = 10, b = 100, result_a, result_b;
// incrementing a by 1 and storing the result in result_a
result_a = ++a;
cout << "result_a = " << result_a << endl;
// decrementing b by 1 and storing the result in result_b
result_b = --b;
cout << "result_b = " << result_b << endl;
return 0;
}
Output
result_a = 11
result_b = 99
Note: In the above program, we have used the ++ and -- operators as
prefixe (++a and --b). However, we can also use these operators as
postfix (a++ and b--).
2. C++ Assignment Operators
In C++, assignment operators are used to assign values to variables.

Operator Example Equivalent to

= a = b; a = b;

+= a += b; a = a + b;

-= a -= b; a = a - b;

*= a *= b; a = a * b;

/= a /= b; a = a / b;

%= a %= b; a = a % b;

Example:
#include <iostream>
using namespace std;
int main() {
int a, b;
// 2 is assigned to a
a = 2;
// 7 is assigned to b
b = 7;
cout << "a = " << a << endl;
cout << "b = " << b << endl;
cout << "\nAfter a += b;" << endl;
// assigning the sum of a and b to a
a += b; // a = a +b
cout << "a = " << a << endl;
return 0;
}
Output
a=2
b=7
After a += b;
a=9

3. C++ Relational Operators


A relational operator is used to check the relationship between two
operands. For example,
// checks if a is greater than b
a > b;
Here, > is a relational operator. It checks if a is greater than b or not.
If the relation is true, it returns 1 whereas if the relation is false, it
returns 0.
Operator Meaning Example
3 == 5 gives us
== Is Equal To
false

3 != 5 gives us
!= Not Equal To
true

3 > 5 gives us
> Greater Than
false

3 < 5 gives us
< Less Than
true

Greater Than 3 >= 5 give us


>=
or Equal To false

Less Than or 3 <= 5 gives us


<=
Equal To true

Example 4: Relational Operators


#include <iostream>
using namespace std;
int main() {
int a, b;
a = 3;
b = 5;
bool result;
result = (a == b); // false
cout << "3 == 5 is " << result << endl;
result = (a != b); // true
cout << "3 != 5 is " << result << endl;
result = a > b; // false
cout << "3 > 5 is " << result << endl;

result = a < b; // true


cout << "3 < 5 is " << result << endl;

result = a >= b; // false


cout << "3 >= 5 is " << result << endl;

result = a <= b; // true


cout << "3 <= 5 is " << result << endl;

return 0;
}

Output:
3 == 5 is 0
3 != 5 is 1
3 > 5 is 0
3 < 5 is 1
3 >= 5 is 0
3 <= 5 is 1
Note: Relational operators are used in decision-making and loops.

4. C++ Logical Operators

Logical operators are used to check whether an expression


is true or false. If the expression is true, it returns 1 whereas if
the expression is false, it returns 0.
Operator Example Meaning
Logical AND.
True only if
expression1
&& all the
&& expression2
operands are
true.
Logical OR.
True if at least
expression1
|| one of the
|| expression2
operands is
true.
Logical NOT.
True only if
! !expression
the operand is
false.

In C++, logical operators are commonly used in decision making. To


further understand the logical operators, let's see the following
examples,

Suppose,
a=5
b=8
Then,
(a > 3) && (b > 5) evaluates to true
(a > 3) && (b < 5) evaluates to false
(a > 3) || (b > 5) evaluates to true
(a > 3) || (b < 5) evaluates to true
(a < 3) || (b < 5) evaluates to false
!(a < 3) evaluates to true
!(a > 3) evaluates to false

Example 5: Logical Operators

#include <iostream>

using namespace std;

int main() {

bool result;

result = (3 != 5) && (3 < 5); // true

cout << "(3 != 5) && (3 < 5) is " << result << endl;

result = (3 == 5) && (3 < 5); // false

cout << "(3 == 5) && (3 < 5) is " << result << endl;
result = (3 == 5) && (3 > 5); // false

cout << "(3 == 5) && (3 > 5) is " << result << endl;

result = (3 != 5) || (3 < 5); // true

cout << "(3 != 5) || (3 < 5) is " << result << endl;

result = (3 != 5) || (3 > 5); // true

cout << "(3 != 5) || (3 > 5) is " << result << endl;

result = (3 == 5) || (3 > 5); // false

cout << "(3 == 5) || (3 > 5) is " << result << endl;

result = !(5 == 2); // true

cout << "!(5 == 2) is " << result << endl;

result = !(5 == 5); // false

cout << "!(5 == 5) is " << result << endl;

return 0;

}
Output

(3 != 5) && (3 < 5) is 1
(3 == 5) && (3 < 5) is 0
(3 == 5) && (3 > 5) is 0
(3 != 5) || (3 < 5) is 1
(3 != 5) || (3 > 5) is 1
(3 == 5) || (3 > 5) is 0
!(5 == 2) is 1
!(5 == 5) is 0

5. C++ Bitwise Operators


In C++, bitwise operators are used to perform operations on individual
bits. They can only be used alongside char and int data types.
Operator Description
& Binary AND
| Binary OR
^ Binary XOR
Binary One's
~
Complement
<< Binary Shift Left
>> Binary Shift Right
6. Other C++ Operators
Operator Description Example
returns the size of
sizeof sizeof(int); // 4
data type
string result = (5
returns value based
?: > 0) ? "even" :
on the condition
"odd"; // "even"
represents memory
&num; // address
& address of the
of num
operand
accesses members
. of struct variables s1.marks = 92;
or class objects

used with pointers


-> to access the class ptr->marks = 92;
or struct variables

prints the output


<< cout << 5;
value

>> gets the input value cin >> num;

C++ Comments
C++ comments are hints that a programmer can add to make their
code easier to read and understand. They are completely ignored by
C++ compilers.

There are two ways to add comments to code:

// - Single Line Comments


/* */ -Multi-line Comments
Single Line Comments
In C++, any line that starts with // is a comment. For example,

// declaring a variable

int a;

// initializing the variable 'a' with the value 2

a = 2;

Multi-line comments

In C++, any line between /* and */ is also a comment.


/* declaring a variable
to store salary to employees
*/
int salary = 2000;

This syntax can be used to write both single-line and multi-line


comments.

Why use Comments?


If we write comments on our code, it will be easier for us to
understand the code in the future. Also, it will be easier for your
fellow developers to understand the code.

You might also like