Search

Thursday, April 30, 2020

C++

Learn C++   Programming 1


C++ Variables, Literals and Constants

In this tutorial, we will learn about variables, literals, and constants in C++ with the help of examples.

C++ Variables

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.
Note: The int data type suggests that the variable can only hold integers. Similarly, we can use the double data type if we have to store decimals and exponentials.
We will learn about all the data types in detail in the next tutorial.
The value of a variable can be changed, hence the name variable.
int age = 14; // age is 14
age = 17; // age is 17

  •  
    Note: We should try to give meaningful names to variables. For example, first_name is a better variable name than fn.

C++ Literals

Literals are data used for representing fixed values. They can be used directly in the code. For example: 12.5'c' etc.
Here, 12.5 and 'c' are literals. Why? You cannot assign different values to these terms.
Here's a list of different literals in C++ programming.

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:
For example:
Decimal: 0, -9, 22 etc
Octal: 021, 077, 033 etc
Hexadecimal: 0x7f, 0x2a, 0x521 etc
In C++ programming, octal starts with a 0, and hexadecimal starts with a 0x.

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
-0.22E-5
Note: E-5 = 10-5

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 SequencesCharacters
\bBackspace
\fForm feed
\nNewline
\rReturn
\tHorizontal tab
\vVertical tab
\\Backslash
\'Single quotation mark
\"Double quotation mark
\?Question mark
\0Null 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 six white space
"x"string constant having a single character
"Earth is round\n"prints string with a newline
We will learn about strings in detail in the C++ string tutorial.

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.
Here, we have used the keyword const to declare a constant named LIGHT_SPEED. If we try to change the value of LIGHT_SPEED, we will get an error.
A constant can also be created using the #define preprocessor directive. We will learn about it in detail in the C++ Macros tutorial.

C++ Data Types

In this tutorial, we will learn about basic data types such as int, float, char, etc. in C++ programming with the help of examples.

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

The table below shows the fundamental data types, their meaning, and their sizes (in bytes):
Data TypeMeaningSize (in Bytes)
intInteger2 or 4
floatFloating-point4
doubleDouble Floating-point8
charCharacter1
wchar_tWide Character2
boolBoolean1
voidEmpty0
Now, let us discuss these fundamental data types in more detail.

1. float area = 64.74;

double volume = 134.64534;
As mentioned above, these two data types are also used for exponentials. For example,
double distance = 45E12    // 45E12 is equal to 45*10^12

3. C++ char

char test = 'h';
Note: In C++, an integer value is stored in a char variable rather than the character itself. To learn more, visit C++ characters.

4. C++ wchar_t

  • wchar_t test = L'ם' // storing Hebrew character;

Note: There are also two other fixed-size character types char16_t and char32_t introduced in C++11.




5. C++ bool



  • For example,
bool cond = false;

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


C++ Modified Data Types List

Data TypeSize (in Bytes)Meaning
signed int4used for integers (equivalent to int)
unsigned int4can only store positive integers
short2used for small integers (range -32768 to 32767)
longat least 4used for large integers (equivalent to long int)
unsigned long4used for large positive integers or 0 (equivalent to unsigned long int)
long long8used for very large integers (equivalent to long long int).
unsigned long long8used for very large positive integers or 0 (equivalent to unsigned long long int)
long double8used for large floating-point numbers
signed char1used for characters (guaranteed range -127 to 127)
unsigned char1used for characters (range 0 to 255)
Let's see a few examples.
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

In this tutorial, we will learn to use the cin object to take input from the user, and the cout object to display output to the user with the help of examples.

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 1: String Output

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

Example 2: Numbers and Characters Output

To print the numbers and character variables, we use the same cout object but without using quotation marks.
#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: ANo

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 3: 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: 70
The number is: 70
In the program, we used
cin >> num;
to take input from the user. The input is stored in the variable num. We use the >> operator with cin to take input.
Note: If we don't include the using namespace std; statement, we need to use std::cin instead of cin.

C++ 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: F
23 Character: F
Number: 23

C++ Operators

In this tutorial, we will learn about the different types of operators in C++ with the help of examples. In programming, an operator is a symbol that operates on a value or a variable.

Operators are symbols that perform operations on variables and values. For example, + is an operator used for addition, while - is an operator used for subtraction.
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;
Here, the + operator is used to add two variables a and b. Similarly there are various other arithmetic operators in C++.
OperatorOperation
+Addition
-Subtraction
*Multiplication
/Division
%Modulo Operation (Remainder after division)

Example 1: Arithmetic Operators

#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
Here, the operators +- and * compute addition, subtraction, and multiplication respectively as we might have expected.
/ Division Operator
Note the operation (a / b) in our program. The / operator is the division operator.
As we can see from 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
% Modulo Operator
The modulo operator % computes the remainder. When a = 9 is divided by b = 4, the remainder is 1.
Note: The % operator can only be used with integers.

Increment and Decrement Operators

C++ also provides increment and decrement operators: ++ and -- respectively. ++ increases the value of the operand by 1, while -- decreases it by 1.
For example,
int num = 5;
// increasing num by 1
++num;
Here, the value of num gets increased to 6 from its initial value of 5.

Example 2: Increment and Decrement Operators

// Working of increment and decrement operators
#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
In the above program, we used ++ and -- operator as prefixes. We can also use these operators as postfix.
There is a slight difference when these operators are used as a prefix versus when they are used as a postfix.

2. C++ Assignment Operators

In C++, assignment operators are used to assign values to variables. For example,
// assign 5 to a
a = 5;
Here, we have assigned a value of 5 to the variable a.
OperatorExampleEquivalent 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 2: Assignment Operators

#include <iostream>
using namespace std;
int main() {
int a, b, temp;
// 2 is assigned to a
a = 2;
// 7 is assigned to b
b = 7;
// value of a is assigned to temp
temp = a; // temp will be 2
cout << "temp = " << temp << endl;
// assigning the sum of a and b to a
a += b; // a = a +b
cout << "a = " << a << endl;
return 0;
}
Output
temp = 2
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.
OperatorMeaningExample
==Is Equal To3 == 5 gives us false
!=Not Equal To3 != 5 gives us true
>Greater Than3 > 5 gives us false
<Less Than3 < 5 gives us true
>=Greater Than or Equal To3 >= 5 give us false
<=Less Than or Equal To3 <= 5 gives us 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 1
3 > 5 is 0 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.
OperatorExampleMeaning
&&expression1 && expression 2Logical AND. True only if all the operands are true.
||expression1 || expression 2Logical OR. True if at least one of the operands is true.
!!expressionLogical NOT. True only if 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 1
(3 == 5) && (3 > 5) is 0 (3 != 5) || (3 > 5) is 1
!(5 == 5) is 0
(3 == 5) || (3 < 5) is 0
!(5 == 2) is

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.
OperatorDescription
&Binary AND
|Binary OR
^Binary XOR
~Binary One's Complement
<<Binary Shift Left
>>Binary Shift Right