Author: admin

  • C++ if-else-if ladder statement

    This statement allows the user to have multiple options to check for different conditions. Here, if one of the if or else-if condition is true then that part of the code will be executed and the rest will be skipped. if none of the conditions are true then the final else statement present at the end will be executed.

    The syntax of the if-else-if ladder statement in C++:

     if(condition1)
     {  
       //code to be executed if condition1 is true  
     }
     else if(condition2){  
       //code to be executed if condition2 is true  
     }  
     else if(condition3){  
       //code to be executed if condition3 is true  
     }  
       ...  
     else{  
        //final else if all the above condition are false 
     }

    Flowchart diagram for if-else if statement:

    if elseif statement

    Example of C++ if-else-if ladder statement

    #include <iostream>
    using namespace std;
    
    int main()
    {
       int a = 100;
    
      	// check condition
       if (a > 50)
       {
          cout << "Value of a less than 10." << endl;
       }
       else if (a == 10)
       {
          cout << "Value of a is equal to 20." << endl;
       }
       else if (a < 30)
       {
          cout << "Value of a is greater than 30." << endl;
       }
       else
       {
          cout << "None of the condition is true" << endl;
       }
    
       cout << "Value of a: " << a << endl;
    
       return 0;
    }

    Output:

    Value of a less than 10.
    Value of a: 100

  • C++ nested if statement

    This statement allows the user to use if block inside the other if block. And the inner if statement is executed only if the outer if statement’s condition is true.

    The syntax of the nested if statement in C++:

    if(condition1)
    {    
       //block of code to be executed    
       if(condition2)
       {  
         //block of code to be executed    
       }    
    } 

    You can also nest the if..else statement in same manner as shown below.

    //Nested if....else statement
    
    if(condition1)
    {
        if(condition2)
        {
            //block of statement;
        }
        else 
        {
            //block of statement;
        }
    }
    else
    {
        //block of statement;
    }

    nested if statement Flowchart:

    nested if

    Example of nested if statement in C++

    #include <iostream>
    using namespace std;
    
    int main()
    {
       int a = 50;
       int b = 110;
    
      	// check condition
       if (a < 100)
       {
         	// agian the use of if
          if (b < 200)
          {
             cout << "Value of a and b are 50 and 110 respectively" << endl;
          }
       }
    
       cout << "Value of a is: " << a << endl;
       cout << "Value of b is: " << b << endl;
    
       return 0;
    }
    
    

    Output:

    Value of a and b are 50 and 110 respectively
    Value of a is: 50
    Value of b is: 110

    Example of C++ nested if…else statement

    #include <iostream>
    using namespace std;
    
    int main()
    {
       int a, b, c;
    
       cout << "Enter 3 integers: ";
       cin >> a >> b >> c;
    
       if (a > b)
       {
          if (a > c)
          {
             cout << a << " is greatest of all.";
          }
          else
          {
             cout << c << " is greatest of all.";
          }
       }
       else
       {
          if (b > c)
          {
             cout << b << " is greatest of all.";
          }
          else
          {
             cout << c << " is greatest of all.";
          }
       }
    }

    Output:

    Enter 3 integers: 2 5 4
    5 is greatest of all.

  • C++ if…else statement

    If the Boolean expression is true then the code inside the if statement block is executed or if it is false then the code inside else statement will be executed. Hence if..else statement.

    The syntax of the if..else statement in C++:

     if (condition) 
     {
      //code executed if condition true 
     }
     else
     {
      //code executed if condition false 
     }

    If…else Flowchart:

    if…else

    Example of if…else statement in C++

    #include <iostream>
    using namespace std;
    
    int main()
    {
       int x = 50;
    
       // check condition
       if (x < 20)
       {
          //condition is true
          cout << "x is less than 20;" << endl;
       }
       else
       {
          //condition is false
          cout << "x is not less than 20;" << endl;
       }
    
       cout << "value of x: " << x << endl;
    
       return 0;
    }

    The output of if…else statement in C++.

    x is not less than 20;
    value of x: 50

  • C++ if Statement

    An if statement consists of a Boolean expression followed by one or more statements. If the Boolean expression is true, the block of code inside the if statement will be executed else not. This is most simple of all the decision making statements.

    The syntax of the if statement in C++:

    if (condition) 
    {
       //block of statement
    }
    • If the condition is evaluated true, block of statement is executed.
    • If the condition is evaluated false, block of statement is skipped.

    if statement Flowchart:

    if statement

    Example of C++ if statement:

    #include <iostream>
    using namespace std;
    
    int main()
    {
       int x = 100;
    
       //check the Boolean condition
       if (x < 200)
       {
          //if true, following will be displayed
          cout << "x is less than 200;" << endl;
       }
    
       cout << "value of x: " << x << endl;
    
       return 0;
    }

    Output:

    x is less than 200;
    value of x: 100

  • C# Keywords and Identifiers

    It is important that before programming you should know the C# Keywords and Identifiers. You need to know that keywords cannot be used as identifiers and more.

    C# Keywords

    There are some predefined and reserved words that have special meanings to the compiler. These words are called Keywords. The meaning of the keywords in C# cannot be changed nor can you use them as an identifier. Some of the keywords that you see in a program are int, float, public, etc.

    For Example:

    //Valid way to write keyword
    int phNumber;
    long cardNumber;
    float @float;
    
    //Invalid way to write keyword
    int int;
    float double;

    There are 79 keywords in C#. All the keywords are written in lowercase.

    List of C# keywords

    abstractasbasebool
    breakbytecasecatch
    charcheckedclassconst
    continuedecimaldefaultdelegate
    dodoubleelseenum
    eventexplicitexternfalse
    finallyfixedfloatfor
    foreachgotoifimplicit
    inin (generic modifier)intinterface
    internalislocklong
    namespacenewnullobject
    operatoroutout (generic modifier)override
    paramsprivateprotectedpublic
    readonlyrefreturnsbyte
    sealedshortsizeofstackalloc
    staticstringstructswitch
    thisthrowtruetry
    typeofuintulongunchecked
    unsafeushortusingusing static
    voidvolatilewhile 

    Contextual Keywords

    Aside from the above keywords, C# has 25 other keywords which are called contextual keywords. They have some specific meaning in a program. Unlike the above 79 regular keywords, contextual keywords are not reserved, they can be used as an identifier.

    addaliasascending
    asyncawaitdescending
    dynamicfromget
    globalgroupinto
    joinletorderby
    partial (type)partial (method)remove
    selectsetvalue
    varwhen (filter condition)where (generic type constraint)
    yield  

    You may go through each of them, Click Here.


    C# Identifiers

    Identifiers are nothing but the name assigned to the entities such as variables, functions in a program, Union, classes, etc. They are tokens that has a unique name so that they can be uniquely identified in a program.

    Example: int number;, number being an identifier.

    Rules for Naming an Identifiers:

    • Identifiers are case-sensitive that is uppercase and lowercase letters are distinct.
    • The first letter of identifiers must be a letter or underscore or symbols. After the first letter, you can use digits.
    • White spaces are not allowed.
    • A keyword cannot be used as an identifier.

    Some valid and invalid identifiers:

    //Valid
    Number  
    result1  
    _multiply  
    S2C
    @number
    @int
    
    //Invalid
    Number-2   //special character '-' is present.  
    3Sum    //started with digit   
    int    // int is a keyword      

  • Type Casting in C#

    C# allows us to convert the variables of one data type to another. This conversion referred to as type conversion or type casting. There are various ways to typecast variables, casting can be between a larger size type to a smaller size type or vice-versa.

    There are two types of casting in C#:

    • Implicit Casting (automatic casting): Conversion of smaller type to a larger.
      char -> int -> long -> float -> double
    • Explicit Casting (manual casting): Conversion of a larger type to a smaller size type.
      double -> float -> long -> int -> char

    Implicit Casting

    For this kind of conversion, there is no need for special syntax. Implicit includes the conversion of a smaller data type to a larger size data type and conversions from derived classes to base classes, so there is no loss of data here. It is also known as Automatic Type Conversion.

    Although the two data types need to be compatible with each other that is the numeric data types are compatible with each other but the automatic conversion is not supported to the conversion of numeric type to char or boolean.

    //Example
    int num1 = 20;  
    int num2 = 30;  
    long result;  
    result = num1 + num2;

    As the Implicit conversion is done by the compiler itself, compiler first checks the type compatibility before the conversion. The compatibility is checked in the following order:

    byte -> short -> int -> long -> float -> double

    The following shows the implicit types of conversion that is supported by C#:

    Convert fromConvert to
    byteshort, int, long, float, double
    shortint, long, float, double
    intlong, float, double
    longfloat, double
    floatdouble

    Example of implicit type casting in C# programming.

    using System;
    
    namespace Conversion
    {
       class ImplicitConversion
       {
          static void Main(string[] args)
          {
             int num1 = 20;
             int num2 = 30;
             long result;
    
             result = num1 + num2;
    
             Console.WriteLine("Result: {0}", result);
          }
       }
    }

    Output:

    Result: 50

    Explicit Casting

    Explicit conversion is a manual conversion that it is done by the user themselves. We specifically do the explicit conversion to prevent data loss or maybe when the conversion is not succeeded and it is done by using a cast operator ().

    This conversion is useful for incompatible data types where above automatic conversion cannot be done. This happens when data of a larger type is converted to data of a smaller type.

    long double - > double -> float -> long -> short -> char

    Example of explicit type casting in C# programming.

    using System;
    
    namespace Conversion
    {
       class ExplicitConversion
       {
          public static void Main(String[] args)
          {
             double db = 165.15;
    
             //Explicit Casting
             int num = (int) db;
    
             Console.WriteLine("Value of i: {0}", num);
          }
       }
    }

    Output:

    Value of i: 165

    C# Type Conversion Methods

    There are some built-in conversion methods provided by the C#.

    MethodsDescription
    ToBooleanThis converts a type to a Boolean value,
    ToByteIt will convert a type to a byte.
    ToCharIt will convert a type to a single Unicode character.
    ToDateTimeIt will convert a type (integer or string type) to date-time structures.
    ToDecimalIt will convert a floating-point or integer type to a decimal type.
    ToDoubleIt will convert a type to a double type.
    ToInt16It will convert a type to a 16-bit integer.
    ToInt32It will convert a type to a 32-bit integer.
    ToInt64It will convert a type to a 64-bit integer.
    ToSbyteIt will convert a type to a signed byte type.
    ToSingleIt will convert a type to a small floating-point number.
    ToStringIt will convert a type to a string.
    ToTypeIt will convert a type to a specified type.
    ToUInt16It will convert a type to an unsigned int type.
    ToUInt3It will convert a type to an unsigned long type.
    ToUInt64It will convert a type to an unsigned big integer.

    C# program to demonstrate some the built-in type conversion methods

    using System;
    namespace Conversion
    {
       class MethodConversion
       {
          public static void Main(String[] args)
          {
             int i = 20;
             double d = 465.19;
             float f = 77.154 F;
    
            	//uilt- In Type Conversion
             Console.WriteLine(Convert.ToDouble(i));
             Console.WriteLine(Convert.ToString(f));
             Console.WriteLine(Convert.ToInt32(d));
             Console.WriteLine(Convert.ToUInt32(f));
    
          }
       }
    }

    Output:

    20
    77.154
    465
    77

  • C# Bitwise Operators

    Bitwise operators are used to perform a bit-level operation on operands. They are used in testing, setting, or shifting the actual bits in a program.

    You can see the truth table below.

    pqp & qp | qp ^ q~p
    000001
    010111
    111100
    100110

    Below are the list of Bitwise operators:

    OperatorsName of operators
    &Bitwise AND
    |Bitwise OR
    ^Bitwise XOR
    ~Bitwise complement
    <<Shift left
    >>Shift right

    Example of C# Bitwise Operators

    using System;
    
    namespace Operator
    {
       class Bitwise
       {
          static void Main(string[] args)
          {
             int a = 60;  //60 = 0011 1100
             int b = 13;  //13 = 0000 1101
             int result = 0;
    
             result = a &b;	//12 = 0000 1100
             Console.WriteLine("'&' Operator, Result: {0}", result);
    
             result = a | b;  //61 = 0011 1101
             Console.WriteLine("'|' Operator, Result: {0}", result);
    
             result = a ^ b;	//49 = 0011 0001
             Console.WriteLine("'^' Operator, Result: {0}", result);
    
             result = ~a;  //-61 = 1100 0011
             Console.WriteLine("'~' Operator, Result: {0}", result);
    
             result = a << 2;   //240 = 1111 0000
             Console.WriteLine("'<<' Operator, Result: {0}", result);
    
             result = a >> 2;   //15 = 0000 1111
             Console.WriteLine("'>>' Operator, Result: {0}", result);
    
          }
       }
    }

    Output:

    '&' Operator, Result: 12
    '|' Operator, Result: 61
    '^' Operator, Result: 49
    '~' Operator, Result: -61
    '<<' Operator, Result: 240
    '>>' Operator, Result: 15

  • C# Unary Operators (Increment and Decrement)

    Unary Operators are the Increment and Decrement Operators. They operate on a single operand. They are ++ and -- operators. ++ is used to increase the value by 1 and — is used to decrease the value by 1.

    • Post-Increment or Post-Decrement:
      First, the value is used for operation and then incremented or decremented. Represented as a++ or a–.
    • Pre-Increment Pre-Decrement:
      Here First the value is incremented or decremented then used for the operation. Represented as ++a or –a.

    Example of Unary Operators in C#

    using System;
    
    namespace Operator
    {
       class Unary
       {
          public static void Main(string[] args)
          {
             int num = 10, result;
    
             result = ++num;
             Console.WriteLine("'++num' Result: {0}", result);
    
             result = --num;
             Console.WriteLine("'--num' Result: {0}", result);
    
          }
       }
    }

    Output:

    '++num' Result: 11
    '--num' Result: 10

    Example of Post and Pre Increment operators in C#

    using System;
    
    namespace Operator
    {
       class Unary
       {
          public static void Main(string[] args)
          {
             int num = 10;
    
             Console.WriteLine("Post and Pre INCREMENT");
             Console.WriteLine((num++));
             Console.WriteLine((num));
    
             Console.WriteLine((++num));
             Console.WriteLine((num));
    
             Console.WriteLine("Post and Pre DECREMENT");
             num = 10;
             Console.WriteLine((num--));
             Console.WriteLine((num));
    
             Console.WriteLine((--num));
             Console.WriteLine((num));
          }
       }
    }

    Output:

    Post and Pre INCREMENT
    10
    11
    12
    12
    Post and Pre DECREMENT
    10
    9
    8
    8

  • C# Logical Operators

    Logical Operators are used to compute the logical operation in a program such as &&|| and !. They are used to evaluate the condition.

    The following are the C# Logical Operators. Assume X holds the value 1 and Y holds 0

    OperatorDescriptionExample
    && (logical and)If both the operands are non-zero, then the condition becomes true.(X && Y) is false
    || (logical or)If any of the two operands are non-zero, then the condition becomes true.(X || Y) is true
    ! (logical not)Use to reverses the logical state of its operand. If a condition is true then Logical NOT operator will make false.!(X && Y) is true

    Example of Logical Operators in C#

    using System;
    
    namespace Operators
    {
       class Logical
       {
          static void Main(string[] args)
          {
             bool a = true;
             bool b = false;
    
             Console.WriteLine("'!' Operator: {0}", !b);
             Console.WriteLine("'||' Operator: {0}", a || b);
             Console.WriteLine("'&&' Operator: {0}", a && b);
          }
       }
    }

    Output:

    '!' Operator: True
    '||' Operator: True
    '&&' Operator: False

  • C# Relational Operators

    Relational Operators are used in a program to check the relationship between two operands and accordingly, it returns boolean values, true or false. These operators are used with loops and Decision-Making Statements during condition checking.

    List of relational operators in C#:

    OperatorNameExample
    ==Equal to.A == B
    !=Not equal.A != B
    >Greater than.A > B
    <Less than.A < B
    >=Greater than or equal to.A >= B
    <=Less than or equal to.A <= B

    Example of Relational Operators in C#

    using System;
    
    namespace Operators
    {
       class Relational
       {
          static void Main(string[] args)
          {
             int a = 11;
             int b = 10;
    
            	//Gives true and false value
             Console.WriteLine("'==' operator: {0}", a == b);
             Console.WriteLine("'<' operator: {0}", a < b);
             Console.WriteLine("'>' operator: {0}", a> b);
             Console.WriteLine("'!=' operator: {0}", a != b);
    
             /*Now if we change the value*/
             a = 5;
             b = 20;
             Console.WriteLine("'<=' operator: {0}", a <= b);
             Console.WriteLine("'>=' operator: {0}", a>= b);
          }
       }
    }

    Output:

    '==' operator: False
    '<' operator: False
    '>' operator: True
    '!=' operator: True
    '<=' operator: True
    '>=' operator: False