C++ (BEGINNER_TO_BEYOND) --- (Part-1)
BASICS:
Build: Compiling linking together external libraries and
external files if we need to and creating an executable file.
Compiler: Convert (a program) into a machine-code (0's and 1's)
or lower-level form in which the program can be executed. When we compile a
program an object file is created that is in the extension .exe or .o.
Compile Errors: Syntax errors (Something wrong with the structure).
Semantic errors (Something wrong with the
meaning).
Compiler
Warning: The compiler has
recognized an issue with your code that could lead to a potential problem; it's
only a warning because the compiler is still able to generate correct machine
code.
Linker errors: The error generated when all the parts that make up a program
cannot be put together because one or more are missing is called a linker
error. The linker is having a trouble linking all the objects
files together to create an executable, usually there is library or object file
that is missing.
Runtime Errors: Error that occurs when the program is executing, exception handling
can help deal with runtime errors. Ex: Divide by zero, file not found, out of
memory etc..
Logic Errors: Errors or bug in your code that cause your program to run incorrectly, logic errors are mistakes made by programmer.
STRUCTURE OF C++:
Keywords: Keywords are pre-defined; reserved words used in programming that
have special meanings to the compiler. Keywords are part of the syntax and they cannot be used as an
identifier.
https://en.cppreference.com/w/cpp/keyword
Pre-processor: Pre-processor is a program that processes your
source code before
actual compilation starts.
Preprocessor Directive: Are lines in the source
code with '#' or ' " 'symbol.
Iostream: iostream provides basic input and output
services for C++ programs. iostream uses the
objects cin, cout, cerr, and clog for sending data to and from the standard
streams input, output, error (un-buffered), and log (buffered) respectively.
Main function: Every c++ program must have exactly one main
function, it return 0 that means successful execution of the program. int
main() function always returns an integer.
Namespaces:
It is used to organize code into
logical groups and to prevent name collisions that can occur especially when
your code base includes multiple libraries.
All the files in the C++ standard library declare all of its entities within the std namespace. That’s why we have generally includ the using namespace std; statement in all programs that used any entity defined in iostream.
:: is called scope resolution
operator, it is used to resolve which name we want to use.
using namespace std; it means use the entire std namespace.
iostream
library includes cout, cin, cerr and clog.
cout: standard
output stream, console.
cin: standard
input stream.
<<:
insertion operator, output stream.
>>:
extraction operator, input stream.
All C++ variables must be identified with unique names, these unique names are called identifiers.
VARIABLES AND CONSTANTS:
Variable is an abstraction for a
memory location, allows the coder to use meaningful names rather than memory
addresses.
C++ is case sensitive.
Declaration and initialization:
#include<iostream>
using namespace std;
#include<iostream>
using namespace std;
int main()
{
int num1; //declaration
(these are local variables)
int fav_num1 {10}; //initializing
int fav_num2 = 20; //initializing
cout<<"number:"<<num1<<endl; //will return garbage value
cout<<"Fav_number1:"<<fav_num<<endl;
cout<<"Fav_number2:"<<fav_num<<endl;
}
Global Variable:
The program will print 15 in fav_num because when the programs runs the the compiler checks fav_num locally if it’s not found there then it will go to check globally, in this case the compiler finds it locally.
#include<iostream>
using namespace std;
int
fav_num {10}; //Global variable
int
main()
{
int num1;
int fav_num {15};
cout<<"Fav_number:"<<fav_num<<endl;
cout<<"number:"<<num1<<endl;
}
Primitive
data types:
Fundamental data types implemented directly by the language:
1. int: 4 bytes
2. char: 1byte(8 bits),
char16_t: 16 bits, char32_t: 32 bits
3. float: non integer number
containing (7 decimal digits), double(15 decimal dig), long double(19 decimal dig)
4. boolean: used to represent true and false (8 bits)
Sizeof operator:
sizeof()
operator is used to determine the size of bytes of a type or variable.
sizeof operator gets it's information from climits(integeral points) and cfloat (floating points) include files.
Constant:
The value of constant cannot be changed once declared.
Types of constant:
1. Literal constants
2. Declared constants ---
const keyword
3. Constant expressions ---
constexpr keyword
4. Enumerated constants ---
enum keyword
5. Defined constants --- #define
ARRAY
AND VECTORS:
Array is a compound data type or data structure,
collection of elements.
All elements are of same data type, each element can be accessed directly, fixed in size.
Vector is an array that can grow and shrink at
runtime, container in the C++ Standard Template Library.
Vector is dynamic in nature.
Declaring
and Initializing Array:
#include
<iostream>
using
namespace std;
int
main()
{
int test_score1[5]; //declaration
int test_score2[10] {1,2,3,4,5}; //Initializing of array, init to 1 to 5 rest
is 0
int another_array[] {1,2,3,4,5}; //size
automatically calculated
return 0;
}
Accessing
and Modifying Array Elements:
#include<iostream>
using
namespace std;
int
main()
{
char vowels[] {'a','e','i','o','u'};
cout<<"First
Vowel:"<<vowels[0]<<endl;
//accessing
cout<<"Last
Vowel:"<<vowels[4]<<endl;
vowels[0] = 'A'; //modifying
cout<<"First Vowel is:
"<<vowels[0]<<endl;
cout<<"Array is
:"<<vowels<<endl; //it
gives us the address were the array is stored of first array index
return 0;
}
Multidimensional
Array:
#include<iostream>
using namespace std;
int
main()
{
int row = 3;
int col = 4;
int arr1[row][col]; //declaring
int arr2[row][col]
{
{0,1,2,3},
{4,5,6,7},
{8,9,10,11}
} ; //Initializing
return 0;
}
Declaring
and Initializing Vectors:
#include<iostream>
#include<vector>
using
namespace std;
int
main()
{
vector <char> vowels; //declaring
vector <int> test_score 1(10); //declaring and saying to be 10 elements in
array all initialized to 0
vector <int> test_score2 {10,20,30,40,50}; //initializing
vector <double> temperature
(365,80.0); //vector having 365 elements all have 80.0 as their value
return 0;
}
Accessing
and Modifying Vector Elements:
#include<iostream>
#include<vector>
using
namespace std;
int
main()
{
vector<char> vowels
{'a','e','i','o','u'};
cout<<vowels[0]<<endl; //accessing
cout<<vowels[4]<<endl;
vector<int> scores {2,43,13,52,13};
cout<<scores.at(0)<<endl; //accessing
cout<<"Size of score vector:
"<<scores.size()<<endl;
//getting size of vector
cout<<"Enter any value at index 0: ";
cin>>scores.at(0); //modifying
cout<<"updated score vector at
index 0 is: "<<scores.at(0)<<endl;
scores.push_back(34); //appending a new element at the back of
vector
cout<<"Updated size of score
vector: "<<scores.size()<<endl;
cout<<scores.at(5)<<endl;
vector<vector<int>> ratings
{
{1,2,3},
{4,5,6},
{7,8,9}
};
//Multidimensional vector
cout<<ratings[0][2]<<endl;
cout<<ratings .at(1).at(0)<<endl;
return 0;
}
STATEMENTS
AND OPERATORS:
Expressions are building blocks of a program
(sequence of operators and operands that specifies a computation).
Statement is a complete line of code that performs some action, usually terminates with semi colon, usually contain expression. Ex:-expression, null, iteration, jump, try blocks etc...
Assignment
Operator:
#include<iostream>
using namespace std;
int
main()
{
int num {10};
num = 100;
//'=' is assignment operator
cout<<num<<endl;
int num1,num2 {20};
num1 = num2;
cout<<num1<<endl;
return 0;
}
Arithmetic
Operator:
#include<iostream>
using namespace std
int
main()
{
int num1 {100};
int num2 {200};
int add,sub,mul,div;
add = num1 + num2; //arithmetic operation
sub =
num1 - num2;
mul = num1 * num2;
div = num1 / num2;
cout<<num1<<"+"<<num2<<"="<<add<<endl;
cout<<num1<<"-"<<num2<<"="<<sub<<endl;
cout<<num1<<"*"<<num2<<"="<<mul<<endl;
cout<<num1<<"/"<<num2<<"="<<div<<endl;
return 0;
}
Increment
and Decrement Operator:
#include<iostream>
using namespace std;
int
main()
{
int
count1 {10},count2 {20};
int result1,result2;
//pre-increment, increment counter before
we use it
result1 = ++count1; //count is incremented then it is assigned to
result
cout<<"Count1: "<<count1<<endl;
//print 11
cout<<"Result1:
"<<result1<<endl;
//print 11
//post-increment,increment the counter
after we use it
result2 = count2++; //count is incremented after it is assigned
cout<<"Count2:
"<<count2<<endl; //print 21
cout<<"Result2:
"<<result2<<endl;
//print 20
return 0;
}
Mixed
Expression and Conversions:
C++ operation occurs on same type of operands, if operand are of different type then C++ will convert one operand.
#include<iostream>
using
namespace std;
int
main()
{
int a {},b {},c {};
int total {0};
const int count {3};
cout<<"Enter 3 numbers seperated
by space: ";
cin>>a>>b>>c;
total = a+b+c;
double avg {0.0};
//since it performs a integer summation we
have to convert it to a double type to get the decimal places after the average
//if we will not type cast the total the
average will give an integer type output
avg = static_cast<double>
(total)/count;
cout<<"Average is:
"<<avg<<endl;
return 0;
}
Testing
for equality:
#include<iostream>
using
namespace std;
int
main()
{
int a {},b {};
bool equal {false};
bool not_equal {false};
equal = (a == b);
not_equal = (a != b);
cout<<boolalpha; //will display true or false rather than 1 or
0
cout<<"Enter 2 numbers: ";
cin>>a>>b;
cout<<"Equal:
"<<equal<<endl;
cout<<"Not equal:
"<<not_equal<<endl;
return 0;
}
Relational
Operators:
#include<iostream>
using
namespace std;
int
main()
{ int a {},b {};
cout<<boolalpha;
cout<<"Enter 2 numbers: ";
cin>>a>>b;
cout<<a<<">"<<b<<(a>b)<<endl; //relational operator
cout<<a<<"<"<<b<<(a<b)<<endl;
cout<<a<<">="<<b<<(a>=b)<<endl;
cout<<a<<"<="<<b<<(a<=b)<<endl;
return 0;
}
Logical
Operators:
Precedence order (not > and > or).
not is unary operator ,and ,or is binary operator.
#include<iostream>
using
namespace std;
int
main()
{
int a {10},b {20},c {};
bool inside_bound {};
cout<<boolalpha;
cout<<"Enter number: ";
cin>>c;
inside_bound = (c>a && c<20); //and operator
cout<<"Inside Bound:
"<<inside_bound<<endl;
bool outside_bound {};
outside_bound = (c<a || c>b); //or operator
cout<<"Outside Bound: "<<outside_bound<<endl;
bool on_bound {};
on_bound = (c == a || c == b);
cout<<"On Bound:
"<<on_bound<<endl;
return 0;
}
CONTROLLING
PROGRAM FLOW:
The conditional operator is also known as a ternary operator. The conditional statements are the
decision-making statements which depend upon the output of the expression. It
is represented by two symbols, i.e., '?' and ':'.
It is a
ternary operator, similar to if else.
((condition)? if_statement : else_statement;
#include
<iostream>
using
namespace std;
int
main()
{
int num{};
cout<<"Enter the number: ";
cin>>num;
cout<<"The number is result
"<<((num % 2 == 0)?"even":"odd")<<endl; //conditional operator
return 0;
}
For
Loop:
A loop statement allows us to
execute a statement or
group of statements multiple
times and following is the general from of a loop statement in most of the programming languages.
for(initialize ; condition ;
increment/decrement)
statements;
#include
<iostream>
using
namespace std;
int
main()
{
for(int i{0};i<10;i++) //increment
{
cout<<i<<endl;
}
for(int i{10};i>0;i--) //decrement
{
cout<<i<<endl;
}
for(int i{0};i<100;i++) //print
divisible by 5
{
if(i % 5 == 0)
cout<<i<<endl;
}
vector<int> nums{10,20,30,40,50};
for(int i{0};i<nums.size();++i)
{
cout<<nums[i]<<endl;
}
return 0;
}
Ranged Based For-Loop:
auto
keyword used to check data type it self.
for(var_type var_name : sequence)
{
statements;
}
#include
<iostream>
#include<vector>
using
namespace std;
int
main()
{
int
score[] {10,20,30};
for(auto i : score)
{
cout<<i<<endl;
}
vector<double>
temp{86.8,43.89,90.64,67.89};
double avg{};
double total{};
for(auto i : temp)
{
total += i;
}
if(temp.size() != 0)
avg = total/temp.size();
cout<<"Avg Temp:
"<<avg<<endl;
return 0;
}
While Loop:
Condition
runs until condition is true.
while(condition)
{
statements:
}
#include
<iostream>
using
namespace std;
int
main()
{
int num{5};
while(num > 0)
{
cout<<num<<endl;
num--;
}
int a{};
cout<<"Enter a number less than
100: "<<endl;
cin>>a;
while(a > 100) // same as !(number > 100)
{
cout<<"Please enter a number
less than 100: "<<endl;
cin>>a;
}
return 0;
}
do-while Loop:
In
this we use to execute the body of the loop and then test the condition.
do
{
Statements;
}
while(condition);
#include
<iostream>
using namespace
std;
int main()
{
int num{5};
while(num > 0)
{
cout<<num<<endl;
num--;
}
int a{};
cout<<"Enter a number less than
100: "<<endl;
cin>>a;
while(a > 100) // same as !(number > 100)
{
cout<<"Please enter a number
less than 100: "<<endl;
cin>>a;
}
return 0;
}
Continue & Break:
Continue: no
further statements in the body of the loop executed, control immediately go the
beginning of the loop for the next iteration.
Break: no further statements in the body of the loop executed, loop is immediately terminated.
Nested Loops:
Loop inside a loop is called a nested loop, very
useful in multi-dimensional data structures.
First the inside loop will run ‘n’ number of times then it will go to the outer loop ‘i is incremented’ then we go inside the loop again inner loop will run ‘n’ number of times and so on.
#include
<iostream>
using namespace
std;
int main()
{
for(int i{1};i<=5;i++)
{
for(int j{1};j<=10;j++)
{
cout<<i<<" *
"<<j<<" = "<<i*j<<endl;
}
cout<<"=================="<<endl;
}
return 0;
}
STRINGS:
Character Function:
#include<cctype>
Funtion testing characters(returns True or False), functions for
converting character case.
Converting Character : tolower(c) and toupper(c).
C++ Strings:
C++ strings are objects. std::string is a class in the standard template library.
#include<string>, dynamic
size, contiguous memory, works with input output stream, contains lots of
useful memory function.
#include<string>
using namespace
std;
int main()
{
string s0;
//declaring
string s1{"Apple"}; //initializing
string s2{"Banana"};
string s3{"Kiwi"};
string s4{"apple"};
string s5{s1}; //it will print Apple
string s6{s1,0,3}; //print App, starting with index 0 to index 2
i.e. excluding 3
string s7{10,'X'}; //it will print XXXXXXXXXX
cout<<s1<<endl;
cout<<"Size of s1:
"<<s1.size()<<endl;
cout<<boolalpha; //print true or false rather than 0 or 1
cout<<s1<<" ==
"<<s1<<" "<<(s1 == s1)<<endl; //comparison
cout<<s1<<" ==
"<<s2<<" "<<(s1 > s2)<<endl;
s3 = "Anubhav"; //Assigning, from Kiwi to Anubhav
cout<<"Print s3:
"<<s3<<endl;
s3.at(2) = 'X'; //at index 2 of s3 change the value to X
cout<<"Now s3 is:
"<<s3<<endl;
s0 = "Watermelon";
s0 = s1 + " and " + "
juice"; //there are two c-style
string literals so it will give an error
s0 = s1 + " and " + s2 + "
juice"; //string concatenation
cout<<"Print s0:
"<<s0<<endl;
for(size_t i{0};i<s0.length();i++) //loop through string
{
cout<<s0.at(i)<<endl;
}
cout<<"Substring of s0: "<<s0.substr(0,6)<<endl; //substr(including start index,excluding last
return 0;
}
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
Comments
Post a Comment