Some Useful Tricks In C++ (Part II)

Some Useful Tricks In C++ (Part II)

2 min read

Let’s start with the second part of useful tricks in C++

1.) To find minimum :- Normally to find minimum among few elements we use like this . Ex:- int a = min(x1,min(x2,min(x3,min(x4,x5))));

Instead of this we can use this. Ex:- int a= min({x1,x2,x3,x4,x5});

2.) The swap function :- swap function is already available in C++

 int a=3; 
 int b=4;
 swap(a,b);

3.)Using auto :- Auto automatically determines the datatype of the variable at run time and hence you need not to specify the datatype of the variable.Ex:-

auto a=1;           // a will become "int" type
auto b=1.0;      // b will become" double"
auto c="variable" ;         // c will become "string"

4.) Bitwise operator:- No need to use % for checking if the number is even or odd . Just use “&” operator.Ex:-

if(x&1)
      cout<<"odd";
else
       cout<<"even";

5.) Inbuilt functions :- Some inbuilt algorithms are there in C++ , that can check the following conditions:

all_of(left, left+n , isPositive());             // check all are positive or not
any_of(left, left+n , isPositive());           //check atleast one positive or not
none_of(left, left+n, isPositive());          // check no elements are positive

6.) Using conditional operators :- using conditional operators can make the code clean and efficient .Ex:-

if(a&1){
      a = a*2;
        }
else {
      a = a +1
       }
// with conditional operators
a&1?a*=2:a+=1;

7.) Change the text and background color of the screen :- To change the text and background color of the screen in TurboC++ :-

#include <iostream.h>
#include <conio.h>
void main() {
    textcolor(RED);
    textbackground(WHITE);
    clrscr();
    cout<<"Hello world";
    getch();
 }
    

8.) Create a password before the execution of your program :- If you want to create a password in the starting of execution of the program.

#include <iostream.h>
#include<conio.h>
void main() {
{
     clrscr();
     int p;
     do{
       cin>>p;
       if(p!=123)  {
          cout<<"enter again"<<endl;
        }
      else if(p=123) {
                            // password for your code
        cout<<"welcome to the world"<<endl;
         }
     }while(p!=123);
      cout<<"hello"<<endl;
     getch();
}

9.) Maximum size of array inside main function is 10^6 , but if you declare it globally , you can even declare it upto 10^7.

10.)(i)- Create inline functions and use them during contests.

(ii)- while loop is used where we do not know how many times loop needs to be executed. for loop is used where we already know about the number of times loop needs to be executed.

THANK YOU

Tags:
Choose your Reaction!
Leave a Comment