Chapter 2: Basics of Csharp

Chapter 2: Basics of Csharp

C# By Pavan

Topics Covered:

  • Operators

  • Control Structures

  • Functions

  • Access Modifiers

  • Few Basic Programs on the above topics

  • Interview Questions on the above topics


Operators

OperatorExample
Arithmetic Operators+, -, *, /, %
Comparison Operators==, !=, >, <, >=, <=
Logical Operators&&
Bitwise Operators&
Assignment Operators=, +=, -=, *=, /=, %=
Conditional Operatorscondition ? value1 : value2
Type Operatorsis, as, sizeof, typeof
Member Access Operators. , ->

Brief Explanation:

  1. Arithmetic Operators: These operators perform mathematical operations such as addition (+), subtraction (-), multiplication (*), division (/), and modulus (%).

    Example, x + y will add the value of x and y.

  2. Comparison Operators: These operators compare the values of two operands and return a Boolean result. The comparison operators include == (equal to), != (not equal to), > (greater than), < (less than), >= (greater than or equal to), and <= (less than or equal to).

    Example, x > y will return true if the value of x is greater than the value of y.

  3. Logical Operators: These operators combine multiple Boolean expressions and return a Boolean result. The logical operators include && (logical AND), || (logical OR), and ! (logical NOT).

    Example, x > y && x < z will return true if the value of x is greater than the value of y and less than the value of z.

  4. Bitwise Operators: These operators perform operations at the bit level. The bitwise operators include & (bitwise AND), | (bitwise OR), ^ (bitwise exclusive OR), ~ (bitwise complement), << (left shift), and >> (right shift).

    Example, x & y will perform a bitwise AND operation on the values of x and y.

  5. Assignment Operators: These operators assign values to variables or modify their values. The assignment operators include = (simple assignment), += (addition assignment), -= (subtraction assignment), *= (multiplication assignment), /= (division assignment), and %= (modulus assignment).

    Example, x += y is equivalent to x = x + y.

  6. Conditional Operators: These operators return one value or another based on a Boolean expression. The conditional operator is expressed as

    condition ? value1 : value2, where the condition is evaluated first and, if true, value1 is returned; otherwise, value2 is returned.

    Example, (x > y) ? x : y will return the value of x if it is greater than y, and y otherwise.

  7. Type Operators: These operators check the compatibility or identity of types. The type operators include is (type compatibility), as (type conversion), sizeof (size of a type), and typeof (type of an object).

    Example, x is string will return true if x is a string.

  8. Member Access Operators: These operators access members of a class or structure. The member access operators include . (dot) and ->. The dot operator is used to access members of an object or class, while the -> operator is used to access members of a pointer to an object or class.

    Example, myObject.MyProperty will access the value of the MyProperty property of the myObject object.


Control Structures/Control Statements

Clear Light Bulb · Free Stock Photo

These are used to divert the flow of execution of the program.

C# has three main types of control structures:

  1. Conditional Statements

  2. Looping Statements

  3. Jump Statements


Conditional Statements

These help in executing a block of code based on certain conditions.

There are two types of conditional statements in C#: if-else statements and switch statements.

  • If-else statements:

    These statements evaluate a condition and execute a block of code if the condition is true. If the condition is false, an alternative block of code is executed.

    Example:

int a = 10;
if (a < 5)
{
   Console.WriteLine("a is less than 5");
}
else
{
   Console.WriteLine("a is greater than or equal to 5");
}

  • Switch statements:

    These statements evaluate a variable or expression and execute a block of code based on its value.

    Example:

int day = 3;
switch (day)
{
   case 1:
      Console.WriteLine("Monday");
      break;
   case 2:
      Console.WriteLine("Tuesday");
      break;
   case 3:
      Console.WriteLine("Wednesday");
      break;
   default:
      Console.WriteLine("Invalid day");
      break;
}


Looping Statements

These statements help in executing a block of code repeatedly as long as a certain condition is true.

There are three types of looping statements in C#: while loops, do-while loops, and for loops.

  • While loops:

    These statements execute a block of code as long as a condition is true.

    Example:

int i = 0;
while (i < 5)
{
   Console.WriteLine(i);
   i++;
}

  • Do-while loops:

    These statements execute a block of code at least once and then repeatedly execute it as long as a condition is true.

    Example:

int i = 0;
do
{
   Console.WriteLine(i);
   i++;
} while (i < 5);

  • For loops:

    These statements execute a block of code a specific number of times.

    Example:

for (int i = 0; i < 5; i++)
{
   Console.WriteLine("Wednesday");
}


Jump Statements:

These statements help in altering the normal flow of execution of a program.

There are three types of jump statements in C#: break statements, continue statements, and goto statements.

  • Break statements:

    These statements break out of a loop or switch statement.

    Example:

for (int i = 0; i < 5; i++)
{
   if (i == 3)
   {
      break;
   }
   Console.WriteLine(i);
}

  • Continue statements:

    These statements skip the current iteration of a loop and move to the next iteration.

    Example:

for (int i = 0; i < 5; i++)
{
   if (i == 3)
   {
      continue;
   }
   Console.WriteLine(i);
}

  • Goto statements:

    These statements transfer control to a labeled statement in the program.

    Example:

goto label;
Console.WriteLine("This statement is skipped");
label:
Console.WriteLine("This statement is executed");

Note: The goto statement is generally not preferred to use in C# because it can make the code harder to read and maintain. The goto statement allows you to jump to a different section of code, which can make it difficult to follow the flow of the program and can make debugging more challenging.


Functions

C# Method (With Examples)

Functions in C# are blocks of code that can be called by other parts of the program. A function is a self-contained unit of code that performs a specific task and returns a value to the caller.

The reason behind the usage of Functions in programming:

  1. Reusability: Functions can be written once and used multiple times in a program.

  2. Modularity: Functions break the program down into smaller, more manageable pieces.

  3. Encapsulation: Functions provide a way to hide the details of the implementation of the code from the caller.

Functions in C# are defined using the following syntax:

access_modifier return_type function_name (parameter_list) {
    // function body
}

where:

  • access_modifier: The access level of the function, such as public, private, or protected.

  • return_type: The data type of the value that the function returns, such as int, string, or void (if the function does not return any value).

  • function_name: The name of the function.

  • parameter_list: A list of variables that the function accepts as input parameters.

Example:

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

This function takes two integer values a and b as input parameters and returns their sum. The public access modifier indicates that the function can be accessed from anywhere in the program.

To call this function, we can simply use the function name and pass the required parameters:

int result = Add(2, 3);
Console.WriteLine(result); // output: 5

Functions can be used to perform many different tasks, from simple calculations to complex data manipulations. Understanding how to write and use functions is an essential part of programming in C#.

Access Modifiers

Access modifiers are keywords used in C# to set the accessibility of classes, methods, variables, and other members of a program.

They determine which parts of the program can access these members and modify their values.

There are five access modifiers in C#:

  1. Public: A public member can be accessed from any part of the program.

  2. Private: A private member can only be accessed within the same class in which it is declared.

  3. Protected: A protected member can be accessed within the same class or any derived class.

  4. Internal: An internal member can be accessed within the same assembly or namespace.

  5. Protected internal: A protected internal member can be accessed within the same assembly or any derived class, regardless of the namespace.

In general, it is recommended to use the most restrictive access modifier possible to ensure proper encapsulation and security of the program's data.


Few Basic Programs

Program on Arithmetic Operators:

using System;
class ArthProgram
{
    static void Main(string[] args)
    {
        int a = 10;
        int b = 20;
        int sum = a + b;
        int diff = a - b;
        int product = a * b;
        int quotient = a / b;
        int remainder = a % b;

        Console.WriteLine("Sum: " + sum);
        Console.WriteLine("Difference: " + diff);
        Console.WriteLine("Product: " + product);
        Console.WriteLine("Quotient: " + quotient);
        Console.WriteLine("Remainder: " + remainder);

        Console.ReadKey();
    }
}

Program on Relational Operators:

using System;

class RelProgram
{
    static void Main(string[] args)
    {
        int a = 10;
        int b = 20;

        Console.WriteLine("a < b: " + (a < b));
        Console.WriteLine("a > b: " + (a > b));
        Console.WriteLine("a <= b: " + (a <= b));
        Console.WriteLine("a >= b: " + (a >= b));
        Console.WriteLine("a == b: " + (a == b));
        Console.WriteLine("a != b: " + (a != b));

        Console.ReadKey();
    }
}

Program on If-else Statement:

using System;

class IfElseProgram
{
    static void Main(string[] args)
    {
        int a = 10;

        if (a > 0)
        {
            Console.WriteLine("a is positive.");
        }
        else if (a < 0)
        {
            Console.WriteLine("a is negative.");
        }
        else
        {
            Console.WriteLine("a is zero.");
        }

        Console.ReadKey();
    }
}

Program on For Loop:

using System;

class ForProgram
{
    static void Main(string[] args)
    {
        for (int i = 1; i <= 10; i++)
        {
            Console.WriteLine(i);
        }

        Console.ReadKey();
    }
}

Program on Function:

using System;
class FactorialProgram
{
    static void Main(string[] args)
    {
        Console.Write("Enter a number: ");
        int n = int.Parse(Console.ReadLine());
        int result = Factorial(n);
        Console.WriteLine(n + "! = " + result);
    }
    static int Factorial(int n)
    {
        if (n == 0)
        {
            return 1;
        }
        else
        {
            return n * Factorial(n - 1);
        }
    }
}

Even or Odd:

using System;
class EvenorOddProgram
{
    static void Main(string[] args)
    {
        Console.Write("Enter a number: ");
        int n = int.Parse(Console.ReadLine());
        if (IsEven(n))
        {
            Console.WriteLine(n + " is even.");
        }
        else
        {
            Console.WriteLine(n + " is odd.");
        }
    }

    static bool IsEven(int n)
    {
        return n % 2 == 0;
    }
}

Interview Questions

Control Structures:

  1. What are control structures in C#?

  2. Explain the difference between if and switch statements in C#.

  3. What is the purpose of a loop in C#?

  4. Explain the difference between a for loop and a while loop in C#.

  5. How can you exit from a loop prematurely in C#?

  6. Explain the do-while loop in C#.

Operators:

  1. What are operators in C#?

  2. Explain the difference between arithmetic and logical operators in C#.

  3. What is the purpose of the ternary operator in C#?

  4. Explain the difference between the ++ and -- operators in C#.

  5. How can you overload an operator in C#?

  6. Explain the concept of operator precedence in C#.

Functions:

  1. What is a function in C#?

  2. What is the purpose of a return statement in a function in C#?

  3. Explain the difference between a parameter and an argument in C#.

  4. What is the purpose of function overloading in C#?

  5. Explain the concept of recursion in C# functions.

  6. How can you pass a function as an argument in C#?

Access Modifiers:

  1. What are access modifiers in C#?

  2. Explain the difference between public, private, and protected access modifiers in C#.

  3. What is the default access modifier for a class in C#?

  4. How can you access a private member of a class from outside the class in C#?

  5. Explain the internal access modifier in C#.

  6. What is the purpose of the sealed keyword in C# access modifiers?


thanks for following me | Thank you wallpaper, Wallpaper powerpoint, Thank  you images

Thank you for reading my Blog. I hope you have learned something from it!

If you find this blog helpful, please like, share, and follow me for more interesting posts like this in the future.

Pavan Kumar R

LinkedIn Link