C++ Important Knowledge Gathered All Together

Arithmetic Operator


#include <iostream>

using namespace std;

int main()
{
    //+,-,*,/,%= binary operators
    cout <<5+2<< endl;
    cout<<5/2.0<<endl; //2
    cout<<5%2<<endl;

    //++,-- unary operators

    int counter=7;
    counter++;
    cout<<counter<<endl;

    counter--;
    cout<<counter<<endl;

    int counter2=7;
    cout<<++counter2<<endl;
    cout<<counter2--<<endl;
    cout<<counter2<<endl;

    cout<<--counter2<<endl;
    cout<<counter2<<endl;

    //system("cls");


    //< > <= >= == != // comparison operator
    int a=5, b=5;
    cout<<(a!=b)<<endl;
    system("cls");

    //&&, ||, ! //logical operator
    cout<<!(a==5 && b==5+3)<<endl;
    cout<<(a==5 || b==5)<<endl;

    //=,+=,-=,*=,/=,%= //assignment operator
    int x = 5;

    //x+=7;
    //x=x+7; //priority/precedence also applies

    x-=7;
    //x=x-7;

    cout<<x<<endl;


    //other operators

    //member access operator


    //special operator

    //conversion

    //memory allcoation


    //https://en.cppreference.com/w/cpp/language/expressions


    system("pause>0");
    return 0;
}

Datatypes

#include<iostream>
using namespace std;

int main(){

    int yearOfBirth=1995;
    char gender = 'f';
    bool isOlderThan18 = true;

    float averageGrade=4.5; //4 bytes
    double balance = 4567894563; //8 bytes

    cout<<"Size of int is "<<sizeof(int)<<"bytes\n";
    //-1,-2,-3,-4,......,-2147483648
    cout<<"Int min value is "<<INT_MIN<<endl;

    //+0,+1+2,.......+2147483647
    cout<<"Int max value is "<<INT_MAX<<endl;

    cout<<"Size of unsigned int is"<<sizeof(unsigned int)<<"bytes\n";
    cout<<"UInt max value is "<<UINT_MAX<<endl; //it is always positive hobe

    cout<<"Size of bool is "<<sizeof(bool)<<" bytes\n"<<endl;
    cout<<"Size of float is "<<sizeof(float)<<" bytes\n"<<endl;
    cout<<"Size of double is "<<sizeof(double)<<" bytes"<<endl;




}

Data Type conversion

#include <iostream>

using namespace std;

int main()
{
    cout<<(int)'a'<<endl;
    cout<<int('a')<<endl;
    cout<<int('A')<<endl;
    cout<<char(65)<<endl;

//    char c1;
//    char c2;
//    char c3;
    char c1,c2,c3,c4,c5;
    cout<<"Enter 5 letters:";
    cin>>c1>>c2>>c3>>c4>>c5;
    cout<<"ASCII message:"<<int(c1)<<" "<<int(c2)<<" "<<int(c3);

    int number;
    cout<<"Enter number to check odd or even:"<<endl;
    cin>>number;

    if(number%2==0)
        cout<<"Even";
    else
        cout<<"Odd";

    system("pause>0");
//    return 0;
}

Datatype Overflow

#include<iostream>
using namespace std;

int main(){
    int intMax = INT_MAX;
    cout<<intMax<<endl;

    cout<<intMax+1;



    return 0;
}

Enum data structure

//https://www.youtube.com/watch?v=08DZPaJupdk&list=PL43pGnjiVwgTnNmcPuhvSUcSgpNfR48ui&index=15
#include <iostream>

using namespace std;
enum EyeColor{
    Brown=1,
    Blue=2,
    Green=3,
    Gray,
    Heterochromia,
    Other
};

void getEyeColorDetails2(int myEyeColor){
    switch(myEyeColor){
        case 1: cout<<"70% population"<<endl; break;
        case 2: cout<<"Second common population"<<endl;  break;
        case 3: cout<<"Estimated 2% common population"<<endl; break;
        case 4: cout<<"Close to 3% common population"<<endl; break;
        case 5: cout<<"Not really"<<endl; break;
//        case Brown: cout<<"70% population"<<endl; break;
//        case Blue: cout<<"Second common population"<<endl;  break;
//        case Green: cout<<"Estimated 2% common population"<<endl; break;
//        case Gray: cout<<"Close to 3% common population"<<endl; break;
//        case Heterochromia: cout<<"Not really"<<endl; break;
    }

}

//void getEyeColorDetails3(string myEyeColor){
//    switch(myEyeColor){
//            case "Brown": cout<<"70% population"<<endl; break;
//            case "Blue": cout<<"Second common population"<<endl;  break;
//            case "Green": cout<<"Estimated 2% common population"<<endl; break;
//            case "Gray": cout<<"Close to 3% common population"<<endl; break;
//            case "Heterochromia": cout<<"Not really"<<endl; break;
//    }

//}

int main()
{
    //getEyeColorDetails(Blue);
    getEyeColorDetails2(2);
//    getEyeColorDetails3("Blue"); // it is not allowed in c++

//    int userInput;
//    cin>>userInput;

//    EyeColor myEyeColor;
//    myEyeColor=(EyeColor)userInput;
   // cout<<myEyeColor;

//    for(int myEyeColor=Brown; myEyeColor!=Other; myEyeColor++)
//    {


//    }

    return 0;
}

Enum to Enum Conversion

#include <iostream>

using namespace std;

enum Scale{
    SINGLE=1,
    DOUBLE=2,
    QUAD=4
};

int main()
{
//    Scale s1=1;
    Scale s2=static_cast<Scale>(2);
    Scale s3=static_cast<Scale>(4);
    Scale s4=static_cast<Scale>(8.56);
    cout << s3 << endl;
    return 0;
}

&Reference

#include<iostream>
using namespace std;

int main(){

    int luckyNumbers[5]={2,3,5,7,9};
    cout<<luckyNumbers<<endl;
    cout<<&luckyNumbers[0]<<endl; //& eta adress er location bujhay


    cout<<luckyNumbers[2]<<endl;
    cout<<*(luckyNumbers+2)<<endl; //eta oi &address e thaka value bujhay

    for(int i=0; i<=4; i++){
        cout<<"Number:";
        cin>>luckyNumbers[i];
}
    for(int i=0; i<=4; i++){
        cout<<(luckyNumbers+i)<<endl;
}


return 0;
}

Array

#include<iostream>

using namespace std;

int main()
{
//    char vowels [] {'a','e','i','o','u'};
//    cout<<"The first vowel is:"<<vowels[0]<<endl;
//    cout<<"The last vowel is."<<vowels[4]<<endl;
//    cin>>vowels[5]; //out of bounds , don't do this
//    
//    
//    
//    int test_scores[5] {100,95,99,87,88};
//
//    
//    cout<<"First score at index 0: "<<test_score[0]<<endl;
//    cout<<"Second score at index 1: "<<test_score[1]<<endl;
//    cout<<"Fifth score at index 1: "<<test_score[4]<<endl;
//    
    
    
    
    double hi_temps [] {90.1,89.8,77.5,81.6};
    cout<<"The first high temperature is :"<<hi_temps[0]<<endl;
    hi_temps[0]=100.7; 
    cout<<"The first high temperature is now:"<<hi_temps[0]<<endl;


    int test_score[5] {100,90};
    cout<<"first score t index 0: "<<test_score[2]<<endl;

    return 0;
}

Function

#include <iostream>

using namespace std;

void function();

int main()
{
    cout<<"Hello form main()\n";
    function();
    function();
    function();
    return 0;
}

void function(){
    cout<<"Hello from function()"<<endl;
}

Function Return

#include <iostream>

using namespace std;

bool isPrimeNumber(int number){
    //bool isPrimeFlag=true;
    for(int i=2; i<number; i++)
    {
        if(number%i==0)
 //           isPrimeFlag=false;
 //           break;
            return false;

    }
    return true;
}

//prime number divisible by this number and 1
int main()
{
//    int number;
//    cout<<"Number: ";
//    cin>>number;

   // bool isPrimeFlag=true;

//    for(int i=2; i<number; i++)
//    {
//        if(number%i==0){
//            isPrimeFlag=false;
//            break;
//        }
//    }
//    bool isPrimeFlag=isPrimeNumber(number);

//    if(isPrimeFlag){
//        cout<<"Prime number"<<endl;
//    }
//    else{
//        cout<<"Not prime number"<<endl;
//    }
for(int i =1; i<=100000000; i++){
    bool isPrime=isPrimeNumber(i);
    if(isPrime)
        cout<<i<<" is prime number"<<endl;
//    else
//        cout<<i<<" is not prime number"<<endl;
}
    return 0;
}

Function Parameter:

#include <iostream>

using namespace std;

void introduceMe(string name, string city="default", int age=0){

    cout<<"My name is: "<<name<<endl;
    cout<<"I am from: "<<city<<endl;
    if(age!=0)
        cout<<"I am "<<age<<" years old"<<endl;
    cout<<endl;

}

int main()
{
//   introduceMe("Zaki", "Dhaka", 4);
//   introduceMe("Salina","Bosnia");
   string name,city;
   int age;

   cout<<"Please enter name: "<<endl;
   cin>>name;
   cout<<"Please enter city: "<<endl;
   cin>>city;
   cout<<"Please enter age: "<<endl;
   cin>>age;
   introduceMe(name, city, age);
   return 0;
}

Function Overloading

#include <iostream>

using namespace std;

int sum(int a, int b);
double sum(double a, double b);
float sum(float a, float b, float c);

int main()
{
    cout<<sum(4,3)<<endl;
    cout<<sum(4.4,3.3)<<endl;
    cout<<sum(3.3,3.3,2.2)<<endl;


}

int sum(int a, int b)
{
    return a+b;
}

double sum(double a, double b){
    return a+b;
}

float sum(float a, float b, float c)
{
    return a+b+c;
}

Function Overloading Another Examples:

//multiple function with same name
//but different parameters

#include<iostream>
using namespace std;

int add(int x, int y){

    cout<<"Sum of x and y="<<x+y<<endl;

}

float add(float x, float y, float z){

    cout<<"Average of three numbers="<<(x+y+z)/3;
}

int main(){

    add(20,30);
    add(10.90,20,30);


    return 0;
}
#include<iostream>
using namespace std;

int abst(int x){

    if(x<0)
        x=-x;
    return x;

}

float abst(float x){

    if(x<0)
        x=-x;
    return x;
}

int main(){

    cout<<"Absolute value of -5 is:"<<abst(-5)<<endl;
    cout<<"Absolute value of -5.5 is: "<<abst(-5.5f)<<endl;

    return 0;

}


Recursive function

#include <iostream>
using namespace std;

int recursive_sum(int m, int n){//m=2, n=4
    if(m==n)
        return m;
    return m+recursive_sum(m+1,n);//2+(2+1,4)
}

//Sum numbers between m and n
int main()
{
    int m=2, n=4;
    cout<<"Sum = "<<recursive_sum(m,n);

//    int sum=0;
//    for(int i=m; i<=n; i++)
//    {
//        sum+=i;
//    }
//    cout<<"Sum="<<sum<<endl;

    return 0;
}

Evolution of Generic Function

#include <iostream>

using namespace std;

void swap(int a, int b)
{
    int temp=a;
    a=b;
    b=temp;
}

int main()
{
    int a=5;
    cout<<a<<" - "<<b<<endl;
    swap(a,b);
    cout << "Hello World!" << endl;
    return 0;
}

For any type this below generic function can work.

#include <iostream>
using namespace std;

template<class Type> //generic function

void Swap(Type& a, Type& b){ //bepar ta ekhane & diye address e value save kore agaise, kheyal koira
    Type temp=a;
    a=b;
    b=temp;
}

//void swap(char &a, char &b){
//    char temp=a;
//    a=b;
//    b=temp;
//}

int main()
{
    int a=5, b=7;
    cout<<a<<" "<<b<<endl;
    Swap<int>(a, b);
    cout<<a<<" "<<b<<endl;

    char c='c', d='d';
    cout<<c<<" "<<d<<endl;
    Swap<char>(c, d);
    cout<<c<<" "<<d<<endl;

    return 0;
}
#include<iostream>
#include<string>

using namespace std;


template <typename T>
T min(T a, T b){
    return (a<b) ? a:b;
}


template<typename T1, typename T2>
void func(T1 a , T2 b)
{
    std::cout<<a<<" "<<b<<std::endl;
    
}

struct Person{
    std::string name;
    int age;
    bool operator<(const Person &rhs) const{
        return this -> age<rhs.age;
    }
};

int main()
{
    Person p1{"Curly", 50 };
    Person p2{"Moe", 50 };
    
    Person p3=min(p1,p2);
    
   // std::cout<<min<int>(2,3)<<std::endl;
    std::cout<<min(2,3)<<std::endl;
    std::cout<<min('A', 'B')<<std:.endl;
    
    
    return 0;
}

Ternary

#include <iostream>

using namespace std;

int main()
{
    int hostUserNum, guestUserNum;
    cout<<"Host: "<<endl;
    cin>>hostUserNum;

    system("cls");

    cout<<"Guest: "<<endl;
    cin>>guestUserNum;

    (hostUserNum==guestUserNum)? cout<<"Correct"<<endl: cout<<"Failed!"<<endl;


//    if(hostUserNum==guestUserNum)
//        cout<<"Correct"<<endl;
//    else
//        cout<<"Failed"<<endl;





}

If else

#include <iostream>

using namespace std;

int main()
{
    float a,b,c;

    cout << "a, b, c" << endl;
    cin>>a>>b>>c;

    if(a==b && b==c)
        cout<<"Equilateral triangle"<<endl;

    else
        if(a!=b && a!=c && b!=c)
            cout<<"Scalene triangle"<<endl;
        else
            cout<<"Isoscalene triangle"<<endl;

    return 0;
}

For loop

#include <iostream>

using namespace std;

int main()
{
    //multiplication table
    for(int i=1; i<=2000; i++)
    {
        for(int j=1; j<=2000; j++)
        {
            cout<<i<<"*"<<j<<" = "<<i*j<<endl;
        }
        cout<<endl;
    }

    return 0;
}

Range based for loop:

//range based for loop

for(type variable: collection){

	//body of loop
}
#include<iostream>
using namespace std;
int main(){

	int num_array[]={1,2,3,4,5,6,7};
	
	for(int n: num_array){
		cout<<n<<endl;
	}
	return 0;
}

Factorial with For Loop

#include <iostream>
using namespace std;

int main()
{

    //Factorial of a number
    //6!=1*2*3*4*5*6=720
    int number;
    cout<<"Number:";
    cin>>number;
    int factorial=1;

//    for(int i=1; i<=number; i++){
//        factorial=factorial*i;
//    }


    if(number!=0){
        if(number<0)
            number=-1*number;
        //6*5*4*3*2*1
        for(int i = number; i>=1 ; i--){
            factorial=factorial*i;
        }
    }

    cout<<"Factorial of "<<number<<"! = "<<factorial<<endl;

    return 0;
}

Do While

#include <iostream>
using namespace std;

int main()
{
    int grade, sum=0;
    for(int i=0; i<3; i++){

        do{
            cout<<"Enter grade "<<i+1<<":";
            cin>>grade;

        }while(grade<1 || grade>5);
            sum+=grade;
    }

    cout<<"Sum="<<sum<<endl;
    cout<<"Avg grade= "<<(float)sum/3<<endl;

    return 0;
}

While

#include <iostream>

using namespace std;

int main()
{
    //write out all the number between 100 and 500 that are divisible by 3 and 5

    int counter = 100;

    while(counter<=500){
        if(counter%3==0 && counter%5==0)
            cout<<counter<<"is divisible\n";
        counter++;
    }

    return 0;
}

Exceptions:

#include <iostream>

using namespace std;

class Printer{
    string _name;
    int _availablePaper;

public:
    Printer(string name, int paper)
    {
        _name=name;
        _availablePaper=paper;
    }
    void Print(string txtDoc){
        int requiredPaper=txtDoc.length()/10; //40/10=4

        if(requiredPaper>_availablePaper){
            //throw "No Paper";
            //throw 101;
            throw 10.6;
        }

        cout<<"Printing..."<<txtDoc<<endl;
        _availablePaper-=requiredPaper;
    }
};

int main()
{
    Printer myPrinter("HP Deskjet", 10);
    try {
        myPrinter.Print("Hello I am Zaki, I am a sofwtare engineer");
        myPrinter.Print("Hello I am Zaki, I am a sofwtare engineer");
        myPrinter.Print("Hello I am Zaki, I am a sofwtare engineer");
    } catch (const char * txtException) {
        cout<<"Exception:"<<txtException<<endl;
    }
    catch(int exCode){
        cout<<"Exception"<<exCode<<endl;

    }catch(...){
        cout<<"Exception happened"<<endl;
    }



    return 0;
}

Programming Problems:

Swapping two numbers

#include <iostream>

using namespace std;

int main()
{


    //program for swapping variables of two variables
    int a = 20;
    int b = 10;

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


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

    system("cls");
    //system("pause>0");


    //without third variable how to
    a=a+b; //30
    b=a-b; //20
    a=b-a; //10

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


    return 0;
}

Reverse a number

#include <iostream>

using namespace std;

int main()
{

    //Reversing a number
    int number; int reversedNumber=0;//321
    cout<<"Number:";
    cin>>number;

    while(number!=0){
        reversedNumber*=10;
        reversedNumber+=number%10;
        number/=10;
    }

    cout<<"Reversed: "<<reversedNumber<<endl;
    return 0;

}

Inverse a triangle

#include <iostream>
#include<iomanip>

using namespace std;

int main()
{
    int length;
    cout<<"Length:";
    cin>>length;
    char symbol;
    cout<<"Symbol:";
    cin>>symbol;

//    for(int i=1; i<=length; i++){
//        for(int j=1; j<=i; j++){
//            cout<<setw(2)<<symbol;
//           }
//        cout<<endl;
//    }

    cout<<endl<<endl;

    for(int i=length; i>=1; i--){
        for(int j=1; j<=i; j++){
            cout<<setw(2)<<symbol;
           }
        cout<<endl;
    }



    //cout << "Hello World!" << endl;
    return 0;
}

drawing a shape with C++

#include<iostream>
#include<iomanip>
using namespace std;

int main()
{
    int height,width;
    char symbol;

    cout<<"Height:";
    cin>>height;
    cout<<"Width:";
    cin>>width;
    cout<<"Symbol:";
    cin>>symbol;

    for(int h = 0; h < height; h++)
    {
        for(int w = 0; w < width; w++)
        {
            cout<<setw(3)<<symbol;
        }
        cout<<endl;
    }

    return 0;
}

Input taking basic APP


int main(){
    std::cout<<"Hello WorlD"<<std::endl;

    //float annualSalary = 50000.99;
    float annualSalary;
    std::cout<<"Please enter your annual salary";
    std::cin>>annualSalary;

    float monthlySalary = annualSalary/12;

    std::cout<<"Your monthly salary is "<<monthlySalary<<std::endl;
    std::cout<<"In 10 years you will earn"<<annualSalary*10;

    char character='a';


    return 0;
}

Digits Counter

#include <iostream>

using namespace std;

int main()
{

    int number;
    //Counter digits of a number
    cout<<"Number:";
    cin>>number;

    if(number==0)
        cout<<"You have entered 0.\n";
    else{
        //1325
        //counter=0, counter=1, counter=2, counter=3
        if(number<0)
            number=-1*number;

        int counter=0;

        while(number>0)
        {
            //number=number/10;
            number/=10;
            counter++;
        }

        cout<<"The number contains "<<counter<<" digits\n";
    }

    return 0;
}

Check number of days in a month

#include <iostream>

using namespace std;

int main()
{
    // leap year or not (year % 4 == 0 && year % 100!=0 || year % 400 ==0)
    int year, month;
    cout<<"Year, Month:";
    cin>>year>>month;

    switch(month){
        case 2:(year % 4 == 0 && year % 100!=0 || year % 400 ==0)?
                    cout<<"29 days month."<<endl:cout<<"28 days a month."<<endl;break;
        case 4:
        case 6:
        case 9:
        case 11: cout<<"30 days month"<<endl; break;
        case 1:
        case 3:
        case 5:
        case 7:
        case 8:
        case 10:
        case 12:cout<<"31 days month."<<endl;break;
        default:cout<<"Not valid!";

    }

    system("pause>0");

}

Calculator APP

#include <iostream>

using namespace std;

int main()
{
    float num1, num2;
    char operation;
    cout<<"**CodeBeauty Calculator**"<<endl;
    cin>>num1>>operation>>num2;

    switch(operation)
    {
        case '_':
            cout<<num1<<operation<<num2<<"="<<num1-num2<<endl;
            //break;
        case '+':
            cout<<num1<<operation<<num2<<"="<<num1+num2<<endl;
            break;
        case '*':
            cout<<num1<<operation<<num2<<"="<<num1*num2<<endl;
            break;
        case '%':
            bool isNum1Int, isNum2Int; // as a programmer/engineer you should find the solution as your own, no one is here to help you

           //goal is to check if the value user enter is integer or not
            isNum1Int = ((int)num1==num1);            //casting data type is use to convert one data type to another
            isNum2Int = ((int)num2==num2);  //to check if it is integer or not
            system("cls");
            cout<<isNum1Int<<endl;
            if(isNum1Int&&isNum2Int)
                //cout<<isNum1Int;
                cout<<num1<<operation<<num2<<"="<<(int)num1%(int)num2<<endl;
            else
                cout<<"Not valid!"<<endl;
            break;
        case '/':
            cout<<num1<<operation<<num2<<"="<<num1/num2;
            break;
        default:
            cout<<"Not valid operation!"<<endl;
    }

}

Calculate APP 2

#include<iostream>

using namespace std;

class Calculate{

    public:
        int choose, num1, num2, result;
    
    void option(){
        cout<<"Please choose your option to calculate"<<endl;
        cout<<"Enter 1 for addition."<<endl;
        cout<<"Enter 2 for subtraction."<<endl;
        cout<<"Enter 3 for multiplication."<<endl;
        cout<<"Enter 4 for division."<<endl;
        cout<<"Enter 0 for exit."<<endl;
    
        cout<<"Please enter your option = ";
        cin>>choose;
    }

    void input(){
        cout<<"Please enter 2 numbers"<<endl;
        cin>>num1>>num2;

    }

    void calc_inside(){

        switch(choose)
        {
        case 1:
            result=num1+num2;
            cout<<"Addition of "<<num1<<" and "<<num2<<" = "<<result;
            break;

        case 2:
        
            if(num1>num2)
                result=num1-num2;
            else
                result=num2-num1;
            cout<<"Subtraction of "<<num1<<" and "<<num2<<" = "<<result;
            break;
        
        case 3:
            result=num1*num2;
            cout<<"Multiplciation of "<<num1<<" and "<<num2<<" = "<<result;
            break;

        case 4:
            result=num1/num2;
            cout<<"Division of "<<num1<<" and "<<num2<<" = "<<result;
            break;

        default:
            break;
        }
    }


};


int main(){

    Calculate calc;

    calc.option();
    calc.input();
    calc.calc_inside();

    return 0;
}

ATM app

#include <iostream>

using namespace std;

void showMenu(){
    cout<<"****Menu****"<<endl;
    cout<<"1. Check balance"<<endl;
    cout<<"2. Deposit"<<endl;
    cout<<"3. Withdraw"<<endl;
    cout<<"4. Exit"<<endl;
    cout<<"*************"<<endl;
}

int main()
{
    //check balance, deposit, withdraw, show menu
    int option;
    double balance=0;

    do{
    showMenu();
    cout<<"Option: ";
    cin>>option;
    system("cls");
    switch(option){
       case 1: cout<<"Balance is:"<<balance<<" $"<<endl; break;
       case 2: cout<<"Deposit amount:"<<endl;
            double depositAmount;
            cin>>depositAmount;
            balance+=depositAmount;
            break;
       case 3: cout<<"Withdraw amount:"<<endl;
            double withdrawAmount;
            cin>>withdrawAmount;

            if(withdrawAmount<=balance)
                balance-=withdrawAmount;
            else
                cout<<"Not enough money"<<endl;
            break;
    }
    }while(option!=4);

    return 0;
}

BMI Calculator

#include <iostream>

using namespace std;
//BMI calculator
//weigth(kg)/height*height(meter)
//underweight<18.5
//normal weight 18.5-24.9
//overweight > 25


int main()
{

    float weight, height, bmi;
    cout<<"weight(kg),height(m):";
    cin>>weight>>height;
    bmi=weight/(height*height);

    if(bmi<18.5)
        cout<<"underweight";
    else
        if(bmi>25)
            cout<<"overweight";
        else
            cout<<"normal weight";


    /*if(bmi<18.5)
        cout<<"underweight";
      else if(bmi>25)
        cout<<"overweight";
      else
        cout<<"normal weight";
*/
    cout<<"Your bmi is"<<bmi;

    return 0;
}

PIN Validation

#include <iostream>

using namespace std;

int main()
{

    int usersPin=1234, pin, errorCounter=0;
    do{
       cout<<"PIN: ";
       cin>>pin;

       if(pin!=usersPin){
           errorCounter++;
       }

    }while(errorCounter<3 && pin!=usersPin);


    if(errorCounter<3)
        cout<<"Loading.."<<endl;
    else
        cout<<"Blocked.."<<endl;

    return 0;
}

Find Average of numbers:

#include<iostream>
using namespace std;
//write a c++ program to find average of 2 number using class and object
class Program{

    public:
        int num1,num2;

};

int main()
{
    Program p;
    p.num1=10;
    p.num2=20;
    
    int avg=(p.num1+p.num2)/2;

    cout<<"Average="<<avg<<endl;

    return 0;
}

toString()

iterator()

OOP Concepts:

Object creation:

#include<iostream>
#include<list>
using namespace std;

class YouTubeChannel{
public:
   string Name;
   string OwnerName;
   int SubscribersCount;
   list<string> PublishedVideoTitles;

   YouTubeChannel(string name, string ownerName){
        Name=name;
        OwnerName=ownerName;
        SubscribersCount=0;
   }
};

int main(){
 YouTubeChannel ytChannel1("Zaki Code","Zaki");
//    YouTubeChannel ytChannel;
//    ytChannel.Name="Zaki Code";
//    ytChannel.OwnerName="Zaki";
//    ytChannel.SubscribersCount=1800;
//    ytChannel.PublishedVideoTitles={"Python Realtime", "Paris Visit", "Biycyle Louvre"};

    cout<<"Name: "<<ytChannel1.Name<<endl;
    cout<<"OwnerName: "<<ytChannel1.OwnerName<<endl;
    cout<<"SubsscribersCount: "<<ytChannel1.SubscribersCount<<endl;
    for(string videoTitle : ytChannel1.PublishedVideoTitles){
        cout<<videoTitle<<endl;
    }

    cout<<endl<<endl;
    YouTubeChannel ytChannel2("AmySings", "Amy");
//    YouTubeChannel ytChannel2;
//    ytChannel2.Name="AmySings";
//    ytChannel2.OwnerName="Amy";
//    ytChannel2.SubscribersCount=2000;
//    ytChannel2.PublishedVideoTitles={"Johny B-Cover", "Lorelei-Cover"};

    cout<<"Name: "<<ytChannel2.Name<<endl;
    cout<<"OwnerName: "<<ytChannel2.OwnerName<<endl;
    cout<<"SubsscribersCount: "<<ytChannel2.SubscribersCount<<endl;
    for(string videoTitle : ytChannel2.PublishedVideoTitles){
        cout<<videoTitle<<endl;
    }


}

Another object creation example:

//Basic understanding of OOP
#include<iostream>

using namespace std;

class Car{

    public:
    string brand;
    string modelname;
    int price;

    private:
    string region;

};

int main(){

    Car obj1;
    obj1.brand="Toyota";
    obj1.modelname="Corolla";
    obj1.price=20000;

    Car obj2;
    obj2.brand="Mercedez";
    obj2.modelname="Coyo";
    obj2.price=30000;

    Car obj3;
    obj3.brand="Tesla";
    obj3.modelname="S3";
    obj3.price=50000;


    cout<<"Object1 details:"<<endl;
    cout<<"Brand name:"<<obj1.brand<<endl;
    cout<<"Model name:"<<obj1.modelname<<endl;
    cout<<"Price:"<<obj1.price<<endl;

    cout<<"----------------"<<endl;
    
    cout<<"Object2 details:"<<endl;
    cout<<"Brand name:"<<obj2.brand<<endl;
    cout<<"Model name:"<<obj2.modelname<<endl;
    cout<<"Price:"<<obj2.price<<endl;

    cout<<"----------------"<<endl;
    
    cout<<"Object3 details:"<<endl;
    cout<<"Brand name:"<<obj3.brand<<endl;
    cout<<"Model name:"<<obj3.modelname<<endl;
    cout<<"Price:"<<obj3.price<<endl;

    return 0;
}

Constructor:

#include<list>
#include <iostream>

using namespace std;


class YouTubeChannel{
private:
    string Name;
    string OwnerName;
    int SubscriberCount;
    list<string> publishedVideoTitles;
public:
    YouTubeChannel(string name, string ownerName)
    {
        Name=name;
        OwnerName=ownerName;
        SubscriberCount=0;
    }

    void getInfo(){
        cout<<"Name:"<<Name<<endl;
        cout<<"Owner Name:"<<OwnerName<<endl;
        cout<<"Subscriber:"<<SubscriberCount<<endl;
        cout<<"Video titles:"<<endl;
        for(string VideoTitle: publishedVideoTitles){
            cout<<VideoTitle<<endl;
        }
        cout<<endl;
    }
    void Subscribe(){
        SubscriberCount++;

    }
    void Unsubscribe(){
        if(SubscriberCount>0)
                SubscriberCount--;

    }
    void PublishVideo(string title){
        publishedVideoTitles.push_back(title);
    }
};

int main()
{
    YouTubeChannel ytChanel1("Zaki Channel", "Zaki");
    ytChanel1.PublishVideo("C++");
    ytChanel1.PublishVideo("OOP books");
    //ytChanel1.SubscriberCount=1000000;
//    ytChanel1.Subscribe();
//    ytChanel1.Subscribe();
//    ytChanel1.Subscribe();
    ytChanel1.Unsubscribe();
    ytChanel1.getInfo();


    YouTubeChannel ytChanel2("Emi Channel", "Emi");
    ytChanel2.getInfo();

    return 0;
}

Class and Object creation in C++17:#cpp17_object

#include<iostream>
#include<vector>
#include<string>

using namespace std;

class Player{
public:
        //attributes
        string name {"Player"}; //eta initialize korte hoy naile garbage choile ashey but jokhon call kore oitar value show kore :D
        int health {100};
        int xp {3}; //experience
        
        //methods
        void talk(string text_to_say){ cout<<"\n"<<name<<" says " <<text_to_say<<endl; }
        bool is_dead;
};

class Accounts{
    
public:
    // attributes
    string name{"Account just initiliaze"};
	double balance {0.0};
    
    //methods
    bool showBalance() { cout<<"\n"<<name<<" has "<<balance<<" euro in his account"<<endl; }
	bool deposit(double bal) {balance += bal; cout<<"In deposit "<<bal<<" euro for "<<name<<endl;}
    bool withdraw(double bal) {balance -= bal; cout<<"In withdraw "<<bal<<" euro for "<<name<<endl;} 
};

int main()
{
//    Accounts frank_account;
//    Accounts zaki_account;
//    
    Accounts frank_account;

    frank_account.name="Frank's Account";
    frank_account.balance=5000;
    frank_account.showBalance();
    frank_account.deposit(1000.0);
    frank_account.withdraw(500.0);
    
    Accounts *zaki=new Accounts;
    zaki->name="Zaki Live";
    zaki->balance=8900;
    zaki->showBalance();
    (*zaki).deposit(500);
    (*zaki).withdraw(100);
    
    
    Player frank;
    frank.name="Frank Man";
    frank.health=100;
    frank.xp=12;
    frank.talk("Hi there");
    
    Player *enemy=new Player;
    (*enemy).name="enemy";
    (*enemy).health=100;
    enemy->xp=50;
    
    enemy->talk("I will destory you");
    
    
    
//    Player hero;
//    Player zaki;
//    
//    Player players[] {frank,hero};
//    
//    vector <Player> player_vec{frank};
//    player_vec.push_back(hero);
//    
//    
//    
//    
//    Player *enemy{nullptr};
//    enemy=new Player;
//    
//    delete enemy;
    
    
    return 0;
}

Friends Class:

Constructor Overload:

#include<string>
using namespace std;

class Player{

private:
	std::string name_val;
	int health;
	int age;
	
public:
	//Constructor overloading
	Player();
	Player(age);
	Player(std::string name_val, health, age);
	Player(std::string name_val);
};


Player::Player():Player{"None",0,0}{
    cout<<"No args constructor"<<endl;
    }
Player::Player(std::string name_val):Player{name_val,0,0}{
    cout<<"One-args constructor"<<endl;
    }
Player::Player(std::string name_val,health_val,age_val):name{name_val},health{health_val},age{age_val}{}


int main(){
    
    Player empty;
    Player zaki{"Zaki"};
    Player enemy{"Enemy",100,55};
    
    return 0;
}
//we are studying about operator overloading
#include<iostream>

using namespace std;

class Player{
private:
    std::string name;
    int xp;
    int health;
public:
//overloaded constructor
    Player();
    Player(std::string name_value);
    Player(std::string name_value, int xp_val, int health_val );

};

Player::Player(){
    name="None";
    xp=0;
    health=0;
}
Player::Player(std::string name_value){
    name=name_value;
    xp=0;
    health=0;
}


Player::Player(std::string name_value, int xp_val, int health_val ){
    name=name_value;
    xp=xp_val;
    health=health_val;
}



int main()
{
    //classes can have many constructors as necessary
    //each must have unique signature
    //default constructor is no longer compiler gegnerated
    Player empty;
    Player hero{"Hero"};
    Player villain{"Villain"};
    
    Player frank{"Frank", 100, 4};
    
    Player *enemy = new Player("Enemy",1000,0); //dynamically in heap
    
    
    return 0;
}

Destructor:

#include<iostream>

using namespace std;

class Base{
private:
    int value;
    
public:
	Base(): value{0} { cout<<"Base no -args Constructor"<<endl; }
    Base(int x): value{x} {cout<<"Base(int) overloaded constructor"<<endl;}
    ~Base() {cout<<"Base destructor"<<endl;}
};

class Derived: public Base{
private:    
    int doubled_value;
public:
	Derived(): Base {}, doubled_value {0} { cout<<"Derived Constructor"<<endl; }
    Derived(int x): doubled_value{x*2} {cout<<"Derived(int) overloaded constructor"<<endl;}
    ~Derived() {cout<<"Derived constructor"<<endl;}
};

int main()
{
   // Base b;
   // Base b{100};
    Derived d {1000};
    return 0;
}

Header, Main:

#ifndef _ACCOUNT_H_
#define _ACCOUNT_H_
#include<string>

class Account{
private:
        std::string name;
		double balance;
	public:
		void set_balance(double bal){balance=bal;}
		double get_balance(){return balance;}
            
        //method will be declared outside the class declaration
        void set_name(std::string n);
        std::string get_name();
        
        bool deposit(double amount);
        bool withdraw(double amount);
};

#endif // _ACCOUNT_H_
#include "Account.h"

void Account::set_name(std::string n)
{
	name=n;
}

std::string Account::get_name(){
    return name;
}

bool Account::deposit(double amount){
    balance+=amount;
    return true;
}

bool Account::withdraw(double amount)
{
    if(balance-=amount>=0){
        balance-=amount;
        return true;
    }else{
        return false;
    }
    
}
#include<iostream>
#include<Account.h>
using namespace std;

int main()
{
    Account zaki_account;
    zaki_account.set_name("Zaki's Account");
    zaki_account.set_balance(1000.0);
    
    if(zaki_account.deposit(200.0))
        cout<<"Deposit Ok"<<endl;
    else
        cout<<"Deposit not allwoed"<<endl;
        
    if(zaki_account.withdraw(500.0))
        cout<<"Withdrawal ok"<<endl;
    else
        cout<<"Not sufficient funds"<<endl;
        
    if(zaki_account.withdraw(1500.0))
        cout<<"Withdraw ok"<<endl;
    else 
        cout<<"Not sufficient funds"<<endl;
    
    return 0;
}

Access Specifier:

//Ref: cppreference.com c++17
#include<iostream>
using namespace std;


class Example{

    public:
        void add(int x)
        {
            n=n+x;
        }   
    private:
        int n=0;

};

int main()
{
    Example e;
    //e.n=8;

    return 0;
}

Protected

#include <iostream>

using namespace std;

class Base
{
    // Note friends of Base has access to all
public:
    int a {0};
    void display() { std::cout << a <<"," << b << "," << c << endl; } // member method has access to all

protected:
    int b { 0 };

private:
    int c { 0 };
};

class Derived : public Base
{

    // a will be public
    // b will be protected
    // c will not be accessible
public:
    void access_base_members()
    {

        a = 100; // ok
        b = 200; // Ok
        // c=300; //not accessible
    }
};

int main()
{
    Base base1;
    base1.a = 100; // ok
    base1.b = 200; // compiler error
    base1.c = 300; // compiler error

    Derived d;
    d.a = 100; // Ok
    d.b = 200; // Error
    d.c = 300; // Error

    return 0;
}

get, set:

#include<iostream>

using namespace std;


class A{
private:
    int _value=0;
public:
    void setval(const int a){
        _value=a;
    };
    int getval();
    int getval() const;

//    int getval() const {
//        return _value;
//    }

};

int A::getval(){
    puts("mutable getv");
    return _value;
}

int A::getval() const{
    puts("const getv");
    return _value;
}

int main()
{

    A a;
    a.setval(5);
    printf("It is %d\n",a.getval());


    const A b=a;
    printf("It is also %d\n",b.getval());

    return 0;
}

Data Members: Access inside Struct and Class

#include<iostream>

using namespace std;


struct A{ // in class it is private but here it is public
    int ia;
    const char *sb="";
    int ic;
};

class B{
public:
    int i1;
    const char *s="";
    int i2;
};

int main(){
    A a;
    a.ia=1;
    a.sb="two";
    a.ic=3;

    printf("On struct A == ia is %d, sb is %s , ic is %d\n",a.ia,a.sb,a.ic);

    B bb;
    bb.i1=1;
    bb.s="testing";
    bb.i2=3;


    printf("On class B == i1 is %d and s is %s and i2 is %d",bb.i1,bb.s,bb.i2);

    return 0;

}

Polymorphism, Overriding, Inheritance:

//Poly = many morphism= forms 
//We use this to reusuabitly
//One method in different tasks

#include<iostream>
using namespace std;

class Animal{

public:
    void animalSound(){

        std::cout<<"Animal makes sound\n"<<std::endl;;
    
    }

};


//Overriding the animalSound() method with other text
class Pig: public Animal{

    public:
        void animalSound(){

            std::cout<<"The pig says: wee see\n"<<std::endl;
        
        }

};

class Dog: public Animal{
    public:
        void animalSound(){

            std::cout<<"The dog says: bow bow\n"<<std::endl;
        
        }

};


int main(){
    Animal a;
    Pig p;
    Dog d;


    a.animalSound();
    p.animalSound();
    d.animalSound();




    return 0;
}

Polymprphism and pointer:

#include<list>
#include <iostream>

using namespace std;

class YouTubeChannel{

private:
    string Name;
    list<string> publishedVideoTitles;
protected:
    string OwnerName;
    int ContentQuality;
public:
    //constructor
    YouTubeChannel(string name, string ownerName)
    {
        Name=name;
        OwnerName=ownerName;
        ContentQuality=0;
    }

    void CheckAnalytics(){
        if(ContentQuality<5)
            cout<<Name<<" has bad quality content."<<endl;
        else
            cout<<Name<<" has great content"<<endl;
    }
};

class CookingYoutubeChannel: public YouTubeChannel{
public:
    CookingYoutubeChannel(string name, string ownername): YouTubeChannel(name, ownername){

    }
    void Practice(){
        cout<<OwnerName<<" is practicing cooking, learning new recipes, experimenting with spices..."<<endl;
        ContentQuality++;
    }
};

class SingersYoutubeChannel: public YouTubeChannel{
public:
    SingersYoutubeChannel(string name, string ownername): YouTubeChannel(name, ownername){

    }
    void Practice(){
        cout<<OwnerName<<" is taking singing classes, learning new songs, learning how to dance...."<<endl;
        ContentQuality++;
    }
};


int main()
{

    CookingYoutubeChannel cookingYtChannel("Amy's kitchen", "Amy");
    SingersYoutubeChannel singersYtChannel("John Sings", "John");

    cookingYtChannel.Practice();
    singersYtChannel.Practice();
    singersYtChannel.Practice();
    singersYtChannel.Practice();
    singersYtChannel.Practice();
    singersYtChannel.Practice();
    singersYtChannel.Practice();

    YouTubeChannel yy=cookingYtChannel;
    yy.CheckAnalytics();
    YouTubeChannel zz=singersYtChannel;
    zz.CheckAnalytics();

    YouTubeChannel *yt1=&cookingYtChannel;
    yt1->CheckAnalytics();
    YouTubeChannel *yt2=&singersYtChannel;
    yt2->CheckAnalytics();

//    YouTubeChannel* yt1=&cookingYtChannel;
//    YouTubeChannel* yt2=&singersYtChannel;

//    yt1->CheckAnalytics();
//    yt2->CheckAnalytics();

    return 0;
}

c++17:

#include "Savings_Account.h"
#include <iostream>

Savings_Account::Savings_Account()
    : int_rate { 3.0 }
{
}

Savings_Account::~Savings_Account()
{
}

void Savings_Account::deposit(double amount)
{

    std::cout << "Savings account deposit called with " << amount << std::endl;
}

void Savings_Account::withdraw(double amount)
{

    std::cout << "Savings account withdraw called with " << amount << std::endl;
}
#ifndef SAVINGS_ACCOUNT_H
#define SAVINGS_ACCOUNT_H
#include "Account.h"

class Savings_Account : public Account
{
public:
    double int_rate;
    Savings_Account();
    ~Savings_Account();
    void deposit(double amount);
    void withdraw(double amount);
};

#endif // SAVINGS_ACCOUNT_H
#include "Account.h"
#include "Savings_Account.h"
#include <iostream>

using namespace std;

int main()
{
    // Use the account class

    cout << "\n== Account ==" << endl;
    Account acc {};
    acc.deposit(2000.0);
    acc.withdraw(500.0);

    cout << endl;

    Account* p_acc { nullptr };
    p_acc = new Account();

    p_acc->deposit(1000.0);
    p_acc->withdraw(500.0);
    delete p_acc;

    // use the savings account class
    cout << "\n == Savings Account ===" << endl;
    Savings_Account sav_acc {};
    sav_acc.deposit(2000.0);
    sav_acc.withdraw(500.0);

    cout << endl;

    Savings_Account* p_sav_Acc { nullptr };
    p_sav_Acc = new Savings_Account();
    p_sav_Acc->deposit(1000.0);

    p_sav_Acc->withdraw(500.0);

    delete p_sav_Acc;

    cout << "\n =====" << endl;

    return 0;
}
#ifndef ACCOUNT_H
#define ACCOUNT_H
#include <string>

class Account
{
public:
    double balance;
    std::string name;

    Account();
    ~Account();
    void deposit(double amount);
    void withdraw(double amount);
};

#endif // ACCOUNT_H
#include "Account.h"
#include <iostream>

Account::Account()
    : balance { 0.0 }
    , name { "An Account" }
{
}

Account::~Account()
{
}

void Account::deposit(double amount)
{
    std::cout << "Account deposit called with " << amount << std::endl;
}

void Account::withdraw(double amount)
{
    std::cout << "Account withdraw called with " << amount << std::endl;
}

Programming Problems with OOP:

Class Object Method Working together:

//Program to find average alongside odd or even in different modular function with OOP paradigm

#include<iostream>
using namespace std;

class Calculate{

    public:
        int num1, num2, avg, total;

    void takeInput(){

        cout<<"Please enter two number : "<<endl;
        cin>>num1>>num2;

    }

    void avgNumber()
    {   
        total=num1+num2;
        avg=total/2;
        cout<<"Average is: "<<avg<<endl;
    }

    void findOdd(){
        if(total%2!=0)
            cout<<"Odd"<<endl;
    }


    void findEven(){

        if(total%2==0)
           cout<<"Even"<<endl;
    }
};

int main(){
    Calculate c;
    c.takeInput();
    c.avgNumber();
    c.findEven();
    c.findOdd();

    return 0;
}
#include<iostream>
# define M_PI  
#include<cmath>
using namespace std;


class Circle{

    public:
        float radius,diameter,circumference,area;

    void takeInput(){
        cout<<"Enter radius:"<<endl;
        cin>>radius;
    }

    void calcCircle(){

        diameter=2*radius;
        area=M_PI*radius*radius;
        circumference=2*M_PI*radius;
        cout<<diameter<<endl;
        cout<<area<<endl;
        cout<<circumference<<endl;
    }


};

int main(){
    Circle c;
    c.takeInput();
    c.calcCircle();


    return 0;
}

Another one

#include<iostream>
# define M_PI  
#include<cmath>
using namespace std;


class Circle{

    public:
        float diam,radius,circumference,area;


    void diameter(float x){
        diam=2*x;
        cout<<"Diameter="<<diam<<endl;
    }

    void findCircumference(float x){
        circumference=2*M_PI*x;
        cout<<"Circumference="<<circumference<<endl;
    }

    int findArea(float x){
        area=M_PI*x*x;
        cout<<"Area="<<area<<endl;
    }


};

int main(){
    
    float radius;
    cout<<"Enter radius of your circle"<<endl;
    cin>>radius;

    Circle c;
    c.diameter(radius);
    c.findCircumference(radius);
    c.findArea(radius);


    return 0;
}

Some concepts from C++ 17 and higher:

Primitive Data Type/ Variable Initialization:

//PrimitiveTypes
#include<iostream>

using namespace std;

int main()
{
    char middle_initial {'J'}; // double quotes is string and single quote is character
    cout<<"My middle initial is "<<middle_initial<<endl;
    
    //integer types
    unsigned short int exam_score {55};
    cout<<"My exam score was "<<exam_score<<endl;
    
    int countries_represented {65};
    cout<<"There were "<<countries_represented<<" countries represnted in my meeting"<<endl;
    
    long people_in_flora {20610000};
    cout<<"There are about "<<people_in_flora<<" people in Florida"<<endl;
    
    long people_on_earth = 7'600'000'000;
    cout<<"There are about "<<people_on_earth<<" people on Earth"<<endl;
    
    float car_payment {401.23};
    cout<<"My car payment is "<<car_payment<<endl;
    
    double pi {3.14159};
    cout<<"PI is "<<pi<<endl;
    
    
    long double large_amount_number {2.7e120};
    cout<<large_amount_number<<" is a very big number"<<endl;
    
    


    long long distance_to_alpha_centauri {9'461'000'000'000};
    cout<<"The distace to alpha centauri is "<<distance_to_alpha_centauri<<" kilometers"<<endl;
    
    
    bool game_over {false};
    cout<<"the value of gameOver is "<<game_over<<endl;
    
    short value1 {30000};
    short value2 {1000};
    
    short product {value1*value2};
    
    
    cout<<"The multiply of  "<<value1<<" and "<<value2<<" is "<<product<<endl;
    
    cout<<"hello\tthere\nmy friend\n";

    return 0;
}
#include<iostream>

using namespace std;

int main()
{
    cout<<"Enter the width of the room:";
    int room_width {0};
    cin>>room_width;
    
    cout<<"Enter the length of the room:";
    int room_length {0};
    cin>>room_length;
     
    cout<<"The area of the room is "<<room_width*room_length<<" square feet"<<endl;
    
    return 0;
}
#include<iostream>

using namespace std;
//we have usued pesudocode here for the equation from the requirements

int main()
{
    cout<<"Hello, welcome to Software based cleaning service"<<endl;
    
    int number_of_small_rooms {0};
    cout<<"How many small rooms would you like to clean?"<<endl;
    cin>>number_of_small_rooms;
    
    int number_of_large_rooms {0};    
    cout<<"How many large rooms would you like to clean?"<<endl;
    cin>>number_of_large_rooms;
    
    const double price_per_small_room {25};
    const double price_per_large_room {35};
    
    const double sales_tax {0.06};
    const int estimate_expiry {30}; //days
    
    cout<<"Estimated carpet cleaning service"<<endl;
    cout<<"Number of small rooms: "<<number_of_small_rooms<<endl;
    cout<<"Number of large rooms: "<<number_of_large_rooms<<endl;

    cout<<"Price per small room: $"<<price_per_small_room<<endl;
    cout<<"Price per large room: $"<<price_per_large_room<<endl;
    
    double cost_of_room=(price_per_small_room*number_of_small_rooms)+(price_per_large_room*number_of_large_rooms);    
    cout<<"Cost of room:$"<<cost_of_room<<endl;
    
    double tax_calculation=cost_of_room*sales_tax;
    cout<<"Tax:$"<<tax_calculation<<endl;
    
    cout<<"==========================="<<endl;
    cout<<"Total estimate:$"<<cost_of_room+tax_calculation<<endl;
    cout<<"This estimate is valid for "<<estimate_expiry<<" days"<<endl;
    
    return 0;
}

String Initialization and Overloading(Amar arektu bujhte hobe):

#include <cstring>
#include<iostream>
#include "Mystring.h"

//No-args constructor
Mystring::Mystring():str{nullptr}
{
    str=new char[1];
    *str='\0';
}

//overloaded cosnrtuctor
Mystring::Mystring(const char *s)
:str{nullptr}{
    if(s==nullptr){
        str=new char[1];
        *str='\0';
    }else{
        str=new char[std::strlen(s)+1];
        std:strcpy(str,s);
    }
        
    }


//copy constructor
Mystring::Mystring(const Mystring &source):str{nullptr}
{
    str=new char[std::strlen(source.str)+1];
    std::strcpy(str,source.str);
}

Mystring::~Mystring()
{
}

#ifndef MYSTRING_H
#define MYSTRING_H

class Mystring
{
private:
     char *str;
public:
    Mystring(); //No-args constructor
    ~Mystring(const char *s); //Overloaded constructor
    Mystring(const Mystring &source) //copy constructor
    ~Mystring();    //Destructor
    void display() const;
    int get_length const; //getters
    const char *get_str() const;

};

#endif // MYSTRING_H

const:

pointer and reference(*, &):

#include <iostream>

using namespace std;

int main()
{

    int n=5; //pointer should be same type
    cout<<&n<<endl; //we use meaningful name instead of address location
    int * ptr=&n;

    cout<<ptr<<endl; //ptr is keeping the address of n variable
    //so to access ptr we need *ptr, the star symbol to reference the value of the address
    cout<<*ptr<<endl;
    *ptr=10;
    cout<<*ptr<<endl;
    cout<<n<<endl; // the n is automatically pointing to ptr

    int v;
    int *ptr2=&v;
    *ptr2=7; //dereferencing our pointer
    cout<<"v="<<v<<endl;


    return 0;
}

Playing with pointer:

#include <iostream>

using namespace std;

int main()
{
    int luckyNumbers[5];
//    cout<<luckyNumbers<<endl;
//    cout<<&luckyNumbers[0]<<endl; //here [o] is dereferencing
//    cout<<luckyNumbers[2]<<endl;
//    cout<<*(luckyNumbers+2)<<endl;

    for (int i=0; i<=4; i++)
    {
        cout<<"Number: ";
        cin>>luckyNumbers[i];
    }

    for (int i=0; i<=5; i++)
    {
        cout<<*(luckyNumbers+i)<<" ";
    }
    system("pause>0");
    return 0;
}

Return value form function using pointer:

#include <iostream>

using namespace std;

int getMin(int numbers[], int size){
    int min=numbers[0];
    for(int i=0; i<=size; i++)
    {
        if(numbers[i]<min)
            min=numbers[i];

    }
    return min;
}

int getMax(int numbers[], int size){
    int max=numbers[0];
    for(int i=0; i<=size; i++)
    {
        if(numbers[i]>max)
            max=numbers[i];

    }
    return max;
}

void getMinAndMax(int numbers[], int size, int *min, int *max){
    for(int i=0; i<size; i++)
    {
        if(numbers[i]>*max)
            *max=numbers[i];
        if(numbers[i]<*min)
            *min=numbers[i];
    }
}

int main()
{
    int numbers[5]={5,4,-2,29,6};
//    cout<<"min is:"<<getMin(numbers,5)<<endl;
//    cout<<"max is:"<<getMax(numbers,5)<<endl;

    int min=numbers[0];
    int max=numbers[0];
    getMinAndMax(numbers, 5, &min, &max);

    cout<<"Min is:"<<min<<endl;
    cout<<"Max is:"<<max<<endl;

    system("pause>0");
    return 0;
}

Dynamic Array:

#include <iostream>

using namespace std;

int main()
{
//  int myArray[5];
    int size;
    cout<<"Size: ";
    cin>>size;

   //int myArray[size]; // have to declare in compile time not in runtime
   int *myArray=new int[size]; //new keyword allocate memory for us //when we allocate memory like this we have to deallocate it after usage as it is //it is dynamic array

   for(int i=0;i<size;i++)
   {
       cout<<"Array["<<i<<"] ";
       cin>>myArray[i];
   }

   for(int i=0;i<size;i++)
   {
       //we can do dereferencing in two ways
//       cout<<myArray[i]<<" "; //either this way
       cout<<*(myArray+i)<<endl; //or this way

   }

  delete[] myArray; //we have deleted the dynamic array
  myArray=NULL; //we have to declare it is not pointing to anything in memory

   system("pause>0");
   return 0;
}

Multidimensional Array(Valo bujhinai :p):

#include <iostream>

using namespace std;

int main()
{
    int rows, cols;
    cout<<"rows, cols:";
    cin>>rows>>cols;

    int **table=new int*[rows];
    for(int i=0; i<rows; i++)
    {
        table[i]=new int[cols];
    }

    table[1][2]=88;

    for(int i = 0; i<rows; i++)
    {
        delete[] table[i];
    }

    delete[] table;
    table=NULL;

    system("pause>0");
    return 0;
}

Memeory leak:

#include <iostream>

using namespace std;

void myFunction(){
    int *ptr = new int[50000];
    ptr[2] = 10;
    cout<<"Hi i am ="<<ptr[2]<<endl;
    delete[] ptr; //checked with pvs studio from Codebeauty, if we don't use this it is memory leak
}

int main()
{
    myFunction();

    return 0;
}

Void pointer:

#include <iostream>

using namespace std;

void printNumber(int *numberPtr){
    cout<<*numberPtr<<endl;
}

void printNumber(char *charPtr){
    cout<<*charPtr<<endl;
}

void print(void *ptr,char type){
    switch(type){
        case 'i':cout<<*((int*)ptr)<<endl;//handle int*
            break;
        case 'c':cout<<*((char*)ptr)<<endl;//handle char*
            break;

    }
}

int main()
{
    int number=5;
    char letter='a';
//    printNumber(&number);
 //  printNumber(&letter);
   print(&number,'i');
   print(&letter,'c');
    return 0;
}

smart_pointer:

auto:

operator++:

#include<iostream>

using namespace std;



class Num{

    int value = 0;
public:
    num()int x 0 0): value(x) {};
    int getvalue() const{return value;};
    void setvallue(int x){value=x;}

    num & operator ++ ();
    num & iperator ++(int);
    num & operator -- ();
    num operator -- (int);

}

//pre-increment
num & num:: operator ++(){
    cout<<"pre-increment: ";
    value+=1;
    return *this;
}

//post-increment
num num::operator++(int){

    cout||"post-increment:";
    num temp=*this;
    value+=1;
    return temp;


}

//pre-decrement



int main()
{
    num n(42);
    cout<<"value is "<<n<endl;
    cout<<"value is" <<++n<<endl;
    cout<<"value is "<<n<<endl;
    return 0;
}

STL:

https://leetcode.com/problems/keep-multiplying-found-values-by-two/discuss/1733130/java-and-c-solutions-using-hashsetunordered_set

Set in STL:

http://geeksquiz.com/set-associative-containers-the-c-standard-template-library-stl/

#include <iostream>
#include<set>
using namespace std;

int main()
{
    set<char> a;
    a.insert('G');
    a.insert('F');
    a.insert('G');

    for(auto see: a)
        cout << see <<' ';

    return 0;
}
#include <iostream>
#include <iterator>
#include <set>

using namespace std;

int main()
{
    //empty set container
    set<int, greater<int>> s1;

    s1.insert(40);
    s1.insert(30);
    s1.insert(50);

    s1.insert(50);


    //printing set s1
    set<int, greater<int>>::iterator itr;
    for(itr=s1.begin(); itr!=s1.end(); itr++){
        cout<<*itr<<" ";
    }

    return 0;
}

Unordered Set STL:

#include <bits/stdc++.h>

using namespace std;

int main()
{
    unordered_set <string> stringSet;

    stringSet.insert("code");
    stringSet.insert("in");
    stringSet.insert("c++");
    stringSet.insert("is");
    stringSet.insert("fast");

    for(auto see: stringSet){
        cout<<see<<endl;
    }
    string key="slow";
    if(stringSet.find(key)==stringSet.end())
        cout<<key<<" not found"<<endl<<endl;
    else
        cout<<"Found "<<key<<endl;

    key="c++";
    if(stringSet.find(key)==stringSet.end())
        cout<<key<<" not found"<<endl<<endl;
    else
        cout<<"Found "<<key<<endl;

    //now iterating over whole set and printing its content
    cout<<"All elements"<<endl;
    unordered_set <string> :: iterator itr;
    for(itr = stringSet.begin(); itr!=stringSet.end(); itr++)
        cout<<*itr<<endl;


    return 0;
}

Lambda:

this,->,:: https://arstechnica.com/civis/viewtopic.php?t=492371

underlying_type:(Aro bujhte hobe)
https://en.cppreference.com/w/cpp/types/underlying_type
https://riptutorial.com/cplusplus/example/19366/underlying-type–and-hence-size–of-an-enum

https://www.geeksforgeeks.org/stdunderlying_type-in-c-with-example/

#include <iostream>
#include<type_traits>

using namespace std;

enum E{
    RED,
    GREEN,
    BLUE,


};



int main()
{
   std::underlying_type<E>(type);

    return 0;
}

Vectors:

#include<iostream>
#include<vector>
using namespace std;

int main()
{
    vector <int> test_scores {100, 98, 89};
    cout<<"Test score using array syntax"<<endl;
    cout<<test_scores[0]<<endl;
    cout<<test_scores[1]<<endl;
    cout<<test_scores[2]<<endl;
    
    cout<<"\nTest scores using vector syntax"<<endl;
    cout<<test_scores.at(0)<<endl;
    cout<<test_scores.at(1)<<endl;
    cout<<test_scores.at(2)<<endl;
    cout<<"There are:"<<test_scores.size()<<" scores in the vector"<<endl;


    
    
    cout<<"Enter a test score to add to the vector:";
    cin>>test_scores.at(0);
    cin>>test_scores.at(1);
    cin>>test_scores.at(2);
    
    cout<<"Updated test score:";
    cout<<test_scores.at(0)<<endl;
    cout<<test_scores.at(1)<<endl;
    cout<<test_scores.at(2)<<endl;
    
    
    
    
    return 0;
}

Implicit/Explicit Casting:

#include<iostream>

using namespace std;

int main(){

//    int number1;
//    double number2=9.760;
//    number2=number1;
//    cout<<"Integer value ="<<number1<<endl;
//    cout<<"double value="<<number2<<endl;


int num1=7, num2=3;
float result;

//conversation done by compiler is implicit
cout<<"This is implicit conversion"<<endl;
cout<<"Result:"<<num1/num2<<endl;


//(type)expression
cout<<"This is explicit conversion"<<endl;
result=(float)num1/num2;
cout<<"Result:"<<result<<endl;


}

Static Casting:

#include<iostream>

using namespace std;

int main(){

    //it is not compile time
    double multiplication = 3.6*1.7;
    int result;
    result = multiplication;
    cout<<"Result:"<<result<<endl;


    //static_casting is compile time, it is done by
    //syntax: static_cast<new_data_type> (expression);

    result=static_cast<int>(multiplication);
    cout<<"Result:"<<result<<endl;

}

Dynamic Casting:

#include<iostream>

using namespace std;



class Base{
    virtual void message(){

    }
};


class derived : public Base{

};

int main(){
    Base b;
    derived d;

    Base *ptr = new derived;
    derived *pd = dynamic_cast<derived*>(ptr);

    if(pd!=NULL)
    {
        cout<<"Dynamic casting is done successfully"<<endl;
    }
    else{
        cout<<"Dynamic casting has failed"<<endl;
    }

    return 0;
}

SQL Project:

Today I have Worked with some SQL from Codebeauty here it is
ref: https://www.youtube.com/watch?v=LCs_gbsRaCA 
create table Users(
	id int,
	name varchar(30), 
	age int
);

insert into users(id, name, age)
values('1', 'zucker berg', '28')
values('2', 'elon musk', '35')

select * from users
*W3schools is always best for that

Some SQL refresh: w3schools, tutorialspoint, CRUD, Join

UPDATE Customers
SET ContactName='Alfred Schmidt', City='Frankfurt'
WHERE CustomerID=1

foreign key refers to primary key in another table

CREATE TABLE Orders(
	OrderID int NOT NULL,
	OrderNumber int NOT NULL,
	PersonID int,
	PRIMARY KEY(OrderID),
	FOREIGN KEY(PersonID) REFERENCES Persons(PersonID)
);

CREATE TABLE Persons(
	ID int not null,
	LastName varchar(255) NOT NULL,
	FirstName varchar(255),
	Age int,
	PRIMARY KEY(ID)

)

Primary Key is a constraint: Only once in a table
Unique is also but many times: https://www.w3schools.com/sql/sql_unique.asp


EKta jinish already create hoye jawar pore ALTER Command use kora hoye
DROP mane hocche delete kora, eta TABLE hoite parey eta Database hoite parey

SQL join gula janao important

SELECT ID, NAME, AGE, AMOUNT
FROM CUSTOMERS, ORDERS
WHERE CUSTOMERS.ID=ORDERS.CUSTOMER_ID

SOLID Implementation:

QT/QML project:

Ref:

Codebeauty, The Cherno, UDemy C++17 course, CPPreference, FAANG Problem solving, A good QT cook book

https://riptutorial.com/cplusplus/example/18751/enum-conversions

IDE: QT, CodeLite

Approach: Do it and run , revise frequently

It would be a great help, if you support by sharing :)
Author: zakilive

Leave a Reply

Your email address will not be published. Required fields are marked *