Sie sind auf Seite 1von 15

SHAIK SRINADH 12-10-2020

NARASARAOPETA ENGINEERING COLLEGE

1.Value types and Reference Types


Value Types:
A Data type that holds a data value within its own memory space is called Value Type. It means
variables of these data type directly contain their values in stack.
Variables that store data are called value types. Value types are stored on stack. They contain actual
values. They cannot contain null values. However, this can be achieved by nullable types. Examples of
value types are int, enum, structs etc.,
Reference Types:
Variables that store reference to actual data are called reference types. Data stored in Heap. But they
contain reference on stack which points to data on Heap memory. Reference can hold values.
Examples of reference types are class, interface, string, object etc.,

2. Conditional operator and its Syntax


It is also called ternary operator. Its function is similar to simple if else block. It evaluates the condition
and based on that it returns result.
Syntax :
<condition>? Expression1(if true): Expression2(if false)
First it evaluates the condition, if condition is satisfied it returns the expression1 otherwise it returns
expression2.
Example:
int num1 = 50;
int num2 = 30;
int bigNum = (num1 > num2) ? num1 : num2;
Console.WriteLine(bigNum)
output is : 50

3.Conditional Statements in C#
Conditional statements are used when we want to execute a certain action based on the condition. It
means decision making statements require a few conditions, if the condition evaluates as true certain
statements executed otherwise some other statements gets executed. The different conditional
statements are following
If statement
If(condition)
{
statements executed if condition evaluates to true.
}
e.g.
int a = 10, b= 10;
if(a==b)
{
Console.WriteLine(“Both are equal”); // if a equals to b
}

If Else Statement
It is basically an “if” statement with an optional “else” statement if the condition evaluates to false.
If(condition)
{
Statements executed if condition is true.
}
else
{
Statements executed if the condition is false.
}

e.g.
int a=10, b= 20;
if (a == b)
{
Console.WriteLine(“Print Both are Equal”); // if condition is true a equals b
}
else
{
Console.WriteLine(“Print Both are not equal”); // if condition is false
}

If Else If Statement:
Similar to if else statement but with else if statement we can check multiple conditions. That is each
“else if” represents a separate condition.
If(condition1)
{
Statements executed if condition1 is true.
}
else if(condition2)
{
Statements executed if condition2 is true.
}
else
{
Statements executed if both conditions are false.
}

Nested If statements
Nested means making conditions inside other conditions. That is using “if” or “else if” inside another if
statements.
Int num = 30;
If(num > 10)
{
If(num == 20)
{
Console.WriteLine (“Print num is 20”);
}
Else
{
Console.WriteLine (“Print num is not 20”);
}
}
else
{
Print num is not greater than 10;
}
4. Difference between if and switch statement
In case of multi-conditional processing, basically there come two statements in thought they are switch
case and else if ladder. You can do whatever you want to do with both these statements but using
switch statement is an elegant solution to if-else if and nested if.
The if statements runs for a true value i.e. if you something get displayed on the screen you can simply
use it with any valid arguments, you can use it in looks for break, continue functions simply, but when
you go with switch, it just compares cases and executes the statement under the case provided by
switch expression. We can put a range expression while using if statements, but when we go with
switch, we can’t use range of an expression, we need to provide a single expression whatever it is
either integer etc.,
“If” is difficult to understand if number of conditions are more. The switch statement is easy to edit as
it has created the separate cases for different statements.

If(condition1)
{
Body of if
}
else if (condition2)
{
Body
}
else if(condition3)
{
Body
}
----------------more conditions----

Switch(expression)
{
Case1: statements; // if expression matches with the case1
Break;
Case2: statements; // if expression matches with the case1
Break;
Default:
Statements;// if no case match
}
5. Array and its types.
We can define Array as a collection of similar type of values which are stored in sequential order i.e.,
they stored in a contiguous memory location.
C# supports 2 types of arrays. They are
1. Single dimensional array
2. Multi-dimensional array

In the Single dimensional array, the data is arranged in the form of a row whereas in the Multi-
dimensional arrays the data is arranged in the form of rows and columns. Again, the multi-dimensional
arrays are of two types
Jagged array: whose rows and columns are not equal
Rectangular array: whose rows and columns are equal
We can access the values of an array using the index positions whereas the array index starts from 0
which means the first item of an array will be stored at 0th position and the position of the last item of
an array will be the total number of the item – 1.
Syntax:
// single-dimensional array of 10 integers.
int[] array1 = new int[10];

// Declaring and setting array element values.


int[] array2 = new int[] { 1, 3, 5, 7, 9,4,5,6 };

// Another Alternative syntax.


int[] array3 = { 3,2,1,1, 2, 3, 4, 5, 6 };

// Declaration of a two-dimensional array.


int[,] multiDimensionalArray1 = new int[3, 3]; // 3 rows and 3 columns

// Declaring and setting array element values.


int[,] multiDimensionalArray2 = { { 1, 2, 3 }, { 4, 5, 6 } };

// Declare a jagged array.


int[][] jarray = new int[2][]; // 2 arrays

// Setting the values of the first array in the jagged array structure.
jarray[0] = new int[4] { 1, 2, 3, 4 }
jarray[1] = new int[3] { 5,6,7 }

6.Jagged Array
A jagged array can be defined as an array consisting of arrays. They are used to store arrays instead of
other data types. It is initialized by using two square brackets, where the first square bracket denotes
the size of the array that is being defined and the second bracket denotes the array dimension that is
going to be stored inside the jagged array.
Jagged Array Declaration
string[ ][ ] stringArr = new string[2][ ];
A jagged array can store multiple arrays with different lengths.
arrayJag[0] = new string [2] ;
arrayJag[1] = new string [3] ;
In the above example, we have initialized a string type jagged array with index “0” and “1” containing
an array of size defined inside the square bracket. The 0th index contains a string type array of length 2
and the index “1” contains a string type array of length 3.
Initialization at the time of declaration
arrayJag[0] = new string [2] {“apple”, “mango”};
arrayJag[1] = new string [3] {“orange”, “banana”, “guava”};
Finally we can say that a Jagged array is unique in itself as it stores arrays as values. These arrays are
quite similar to other arrays with the only difference being the type of value it stores.
7.Static and Non static Members
A class is a collection of members like variables, methods, Constructors etc. These
members will be of two different categories.
1) Non-static (or) Instance Methods
2) Static members
The members of a class which requires the object of a class for initialization or execution are known as
Instance members where as members of a class which do not require object of a class for initialization
or execution are known as static members.
Instance variables Vs Static Variables
1) A variable under a static block or a variable declared using static modifier are static variables, rest of
all are instance variables only.
e.g.
class Sample{
int x = 100; //instance variable
statc int y = 100; // static variable
static void Main()
{
int z=100; // static variable
Sample obj = new Sample(); // object creation
Console.WriteLine(obj.x) // accessing instance variable through object;
Console.WriteLine(Sample.y) // accessing static variable using class name
}
}
2)The initialization of a static variable gets done, if we execute the class in which the variable is
declared whereas instance variable gets initialized after creating the object of class either within the
class or in other class also.
3) The minimum and maximum number of times a static variable gets initialized will be one and only
one time whereas in 'n' case of instance it will be '0' if no objects are created or 'n' if 'n' objects are
created.
Note: -To access an instance member we use object of the class whereas to access static members we
use name of the class.

8.Constructor and types of Constructors


1) Constructor a special method that is available to every class responsible for initializing the variables
of a class
2) Every class requires a Constructor in it, if at all it has to execute. Without a Constructor any class
can't execute.
Note: - Because Constructors are mandatory for a class to execute when the program is getting
compile. The compiler if doesn't finds a Constructor in that class will take the responsibility of defining
a Constructor to the class.
Compiler define Constructor will always be "public". A Constructor will have the same name of your
class and moreover they are non-value returning methods.
class ConDemo
{
public ConDemo() // Constructor of class
{
Console.WriteLine("Constructor of class");
}
void Demo()
{
Console.WriteLine("Method of class");
}
static void Main()
{
ConDemo cd1 = new ConDemo(); //object creation and calling constructor
ConDemo cd2 = new ConDemo(); (); //object creation and calling
constructor
cd1.Demo(); // calling demo method
cd2.Demo(); // calling demo method
}
}
In the above program each time we create an object of the class it will internally invoke the
Constructor
of that class, which is then responsible for allocation of the Memory for the required class.
Constructors are of two types
1) Zero Argument (or) Default Constructors
2) Parameterized Constructors
A Constructor without any parameters is a Zero argument of Default Constructor where as a
Constructor with parameter is a parameterized constructor. Parameters can be either input or output
also.
If a class contains parameterized Constructors in it values to the parameters has to be sent while
creating the object of a class. Because a Constructor call should always match a Constructor signature.
e.g.
ConDemo(int x)
{
Console.WriteLine("Constructor of class:"+x);
}
//Pass values to the Constructor while creating the object under Main as following.
Main()
{
ConDemo cd1=new ConDemo(10); // passing value 10 to the constructor
ConDemo cd2=new ConDemo(20); // passing value 20 to the constructor
}
Constructors are used in a class for initializing variables of a class. So, using a parameterized
Constructor we can send all the initialization values that are required for a class to execute.

9. Logical and relational Operators

C# has a so many operators such as Arithmetic operators, Relational operators, Assignment operators,
Logical operators, Unary operators, etc. They can be used to evaluate a variable or perform an
operation on a variable to make a proper expression.
Relational Operators:
Any relation between the two operands is validated by using relational operators. Relational operators
return Boolean values. If the relation between two operands is successfully validated then it will return
“true” and if the validation fails then “false” will be returned. Relational operators are mainly used in
decision making or for defining conditions for loops.
Greater than operator: (denoted by “>”): Validates greater than the relation between operands.
Less than operator: (denoted by “<“): Validates less than the relation between operands.
Equals To operator: (denoted by “==”): Validates the equality of two operands.
Greater than or equals to (denoted by “>=”): Validates greater than or equals to the relation between
the two operands.
Less than or equals to (denoted by “<=”): Validates less than or equals to the relations between the
two operands.
Not equal: (denoted by “!=”): Validates not an equal relationship between the two operands.
int a = 10;
int b = 5;
bool validate;
validate = a > b; //1
Console.WriteLine(validate);
validate = a < b; //2
Console.WriteLine(validate);
validate = a == b; //3
Console.WriteLine(validate);
validate = a >= b; //4
Console.WriteLine(validate);
validate = a <= b; //5
Console.WriteLine(validate);
validate = a != b; //6
Console.WriteLine(validate);
Logical Operators
Logical operators are used for performing logical operations. Logical operators work with Boolean
expressions and return a Boolean value. Logical operators are used with the conditional operators in
loops and decision-making statements.
1) Logical AND Operator
Symbol: “&&”
AND operator returns true when both the values are true. If any of the value is false then it will return
false.

For example, A && B will return true if both A and B are true, if any or both of them are false then it
will return false.
2)Logical OR Operator
Symbol: “||”
OR operator returns true if any of the condition/operands is true. It will return false when both of the
operands are false.
For example, A || B returns true if the value of either of A or B is true. It will return false if both A and
B have false values.
3)Logical NOT Operator
Symbol: “!”
NOT operator is used to reverse the logical conclusion of any condition. If the condition is true then it
will return false and if the condition is false then it will return true.
Example, !(A||B) returns false if “A||B” returns true and will return true if “A||B” returns false.

10. Difference between string and string builder


The main difference is String is Immutable and StringBuilder is Mutable.
Immutability of string object means, if any of your operation on the string instance changes its value, it
will end up in the creation of new instance in a different address location with modified value.
Mutability of StringBuilder is just opposite for this. It won’t create new instance when their content
changes as string does. Instead it makes the new changes in the same instance.

using System; //for String Class


using System.Text;/for StringBuilder Class
class Program
{
static void Main(string[] args)
{
String str = "My first string was ";
str += "Hello World";

//Now str="My first string was Hello World"


//content of str changes, so new instance is created in a different memory location with
new value

StringBuilder sbr = new StringBuilder("My Favourite Programming is ");


sbr.Append("C#");

//Now sbr="My Favourite Programming Font is C#"


//Changes the value of stringbuilder variable sbr it won’t create a new instead it will keep
appending new strings to existing instance.
}
}
B-1) Write an algorithm to find out whether given number is prime or not?
function prime(n)
if n less than or equal to 1
return False
else if n equals to 2
return True
else
flag = 1
for i = 2 to n/2
if n % i equals to 0
flag = 0
break
if flag equals to 1
return True
else
return False

B-2) Write an algorithm to find out whether given string is palindrome or not?
function palindrome(string)
start = 0
end = length of string - 1
while start less than end
if string[start] == string[end]
increment start by 1
decrement end by 1
else
return False
return True

C-1) Write a program to copy values from one array to another array using a loop?
using System;
namespace ArraysPractice
{
class CopyingArray
{
static void Main()
{
Console.WriteLine("Enter the Elements in Array ");

// Taking the array elements as a string in a single line separated with space

string[] sarr1 = Console.ReadLine().Split(' ');


int[] arr1 = new int[sarr1.Length];

// converting each element into integer and copying into new array.
for (int i = 0; i < sarr1.Length; i++)
{
arr1[i] = int.Parse(sarr1[i]);
}
// Printing the copied array
for (int i = 0; i < arr1.Length; i++)
{
Console.Write(arr1[i] + " ");
}
}
}
}
output
Enter the Elements in Array
5734189
The new array is
5734189
Press any key to continue . . .
C-2) Write a function with reference arguments to reverse the given number?
using System;
namespace Practice
{
class ReverseNumber
{
static void ReverseNum(ref int num)
{
int sum = 0;
while(num > 0)
{
sum = sum * 10 + num % 10;
num /= 10;
}
num = sum;
}
static void Main()
{
Console.WriteLine("Enter a number ");
int number = int.Parse(Console.ReadLine());
ReverseNum(ref number); // passing reference of a variable
Console.WriteLine(number);
}
}
}

Enter a number
2456
6542
Press any key to continue . . .
C-3)Write a program using do..while to implement a menu drive program? .
using System;
namespace Practice
{
class Class1
{
static void Main()
{
int choice, n1=0 , n2=0 ;
do
{
Console.WriteLine("=== Menu ===\n");
Console.WriteLine("1. Addition\n");
Console.WriteLine("2. Subtraction\n");
Console.WriteLine("3. Exit\n");

Console.WriteLine("Enter your choice:");


choice = int.Parse(Console.ReadLine());
if (choice != 3)
{
Console.WriteLine("Enter 1st number");
n1 = int.Parse(Console.ReadLine());
Console.WriteLine("Enter 2nd number");
n2 = int.Parse(Console.ReadLine());
}
switch (choice)
{
case 1:
Console.WriteLine("The addition = {0}", n1 + n2);
break;
case 2:
Console.WriteLine("The subtraction = {0}", n1 - n2);
break;
case 3:
Console.WriteLine("Goodbye\n");
break;
default:
Console.WriteLine("Wrong Choice. Enter again\n");
break;
}
} while (choice != 3);
}
}
}
output
=== Menu ===
1. Addition
2. subtraction
3. Exit
Enter your choice:
1
Enter 1st number
12
Enter 2nd number
13
The addition = 25
=== Menu ===
1. Addition
2. substruction
3. Exit
Enter your choice:
3
Goodbye
Press any key to continue . . .

C-4)Program to find out biggest of 4 numbers using conditional operator?


using System;
namespace Practice
{
class BigOfFour
{
static void Main()
{
// Program to find biggest among four numbers
Console.WriteLine("Enter 1st Number");
int num1 = int.Parse(Console.ReadLine());
Console.WriteLine("Enter 2nd Number");
int num2 = int.Parse(Console.ReadLine());
Console.WriteLine("Enter 3rd Number");
int num3 = int.Parse(Console.ReadLine());
Console.WriteLine("Enter 4th Number");
int num4 = int.Parse(Console.ReadLine());
int max = (num1 > num2 && num1 > num3 && num1 > num4) ?
num1 :
((num2 > num3 && num2 > num4) ? // logic to find biggest among four numbers
num2 :
(num3 > num4 ? num3 : num4));
Console.WriteLine($"The biggest number is {max}");
}
}
}

Output:

Enter 1st Number


60
Enter 2nd Number
72
Enter 3rd Number
43
Enter 4th Number
22
The biggest number is 72
Press any key to continue . . .

THE END

Das könnte Ihnen auch gefallen