Chap2.. Main Method
Chap2.. Main Method
Control Statements –
1) If Statement -
If the boolean expression evaluates to true, then the block of code inside the if statement is executed.
If boolean expression evaluates to false, then the first set of code after the end of the if
statement(after the closing curly brace) is executed.
Flow Diagram
Example-
using System;
namespace DecisionMaking {
class Program {
static void Main(string[] args) {
/* local variable definition */
int a = 10;
Syntax −
if(boolean_expression) {
/* statement(s)
} else {
/* statement(s)
}
If the boolean expression evaluates to true, then the if block of code is executed, otherwise else
block of code is executed.
Flow Diagram
Example-
using System;
namespace DecisionMaking {
class Program {
static void Main(string[] args) {
/* local variable definition */
int a = 100;
Syntax
if(boolean_expression 1) {
/* Executes when the boolean expression 1 is true */
}
else if( boolean_expression 2) {
/* Executes when the boolean expression 2 is true */
}
else if( boolean_expression 3) {
/* Executes when the boolean expression 3 is true */
} else {
/* executes when the none of the above condition is true */
}
Example-
using System;
namespace DecisionMaking {
class Program {
static void Main(string[] args) {
/* local variable definition */
int a = 100;
4) switch statement-
A switch statement allows a variable to be tested for equality against a list of values. Each value is
called a case, and the variable being switched on is checked for each switch case.
Syntax
switch(expression) {
case constant-expression1 :
statement(s);
break;
case constant-expression2 :
case constant-expression3 :
statement(s);
break;
default : /* Optional */
statement(s);
Flow Diagram -
Example-
using System;
namespace DecisionMaking {
class Program {
static void Main(string[] args) {
/* local variable definition */
char grade = 'B';
switch (grade) {
case 'A':
Console.WriteLine("Excellent!");
break;
case 'B':
case 'C':
Console.WriteLine("Well done");
break;
case 'D':
Console.WriteLine("You passed");
break;
case 'F':
Console.WriteLine("Better try again");
break;
default:
Console.WriteLine("Invalid grade");
break;
}
Console.WriteLine("Your grade is {0}", grade);
Console.ReadLine();
}
}
}
result −
Well done
Your grade is B
Syntax
switch(ch1) {
case 'A':
switch(ch2) {
case 'A':
break;
break;
}
Example
using System;
namespace DecisionMaking {
class Program {
static void Main(string[] args) {
int a = 100;
int b = 200;
switch (a) {
case 100:
Console.WriteLine("This is part of outer switch ");
switch (b) {
case 200:
Console.WriteLine("This is part of inner switch ");
break;
}
break;
}
Console.WriteLine("Exact value of a is : {0}", a);
Console.WriteLine("Exact value of b is : {0}", b);
Console.ReadLine();
}
}
}
result −
Loops Statements-
There may be a situation, when you need to execute a block of code several number of times. In
general, the statements are executed sequentially: The first statement in a function is executed first,
followed by the second, and so on.
Programming languages provide various control structures that allow for more complicated execution
paths.
A loop statement allows us to execute a statement or a group of statements multiple times and
following is the general from of a loop statement in most of the programming languages −
1) While Loop -
A while loop statement in C# repeatedly executes a target statement as long as a given condition is
true.
Syntax
while(condition) {
statement(s);
}
Flow Diagram
Here, key point of the while loop is that the loop might not ever run. When the condition is tested and
the result is false, the loop body is skipped and the first statement after the while loop is executed.
Example
using System;
namespace Loops {
class Program {
static void Main(string[] args) {
/* local variable definition */
int a = 10;
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 15
value of a: 16
value of a: 17
value of a: 18
value of a: 19
Syntax
for ( init; condition; increment ) {
statement(s);
}
Here is the flow of control in a for loop −
The init step is executed first, and only once. This step allows you to declare and initialize any
loop control variables. You are not required to put a statement here, as long as a semicolon
appears.
Next, the condition is evaluated. If it is true, the body of the loop is executed. If it is false, the
body of the loop does not execute and flow of control jumps to the next statement just after
the for loop.
After the body of the for loop executes, the flow of control jumps back up to
the increment statement. This statement allows you to update any loop control variables. This
statement can be left blank, as long as a semicolon appears after the condition.
The condition is now evaluated again. If it is true, the loop executes and the process repeats
itself (body of loop, then increment step, and then again testing for a condition). After the
condition becomes false, the for loop terminates.
Flow Diagram
Example
using System;
namespace Loops {
class Program {
static void Main(string[] args) {
/* for loop execution */
for (int a = 10; a < 20; a = a + 1) {
Console.WriteLine("value of a: {0}", a);
}
Console.ReadLine();
}
}
}
result −
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 15
value of a: 16
value of a: 17
value of a: 18
value of a: 19
3) do...while loop –
Unlike for and while loops, which test the loop condition at the start of the loop, the do...while loop
checks its condition at the end of the loop.
A do...while loop is similar to a while loop, except that a do...while loop is guaranteed to execute at
least one time.
Syntax
do {
statement(s);
} while( condition );
Flow Diagram
Example
using System;
namespace Loops {
class Program {
static void Main(string[] args) {
/* local variable definition */
int a = 10;
/* do loop execution */
do {
Console.WriteLine("value of a: {0}", a);
a = a + 1;
}
while (a < 20);
Console.ReadLine();
}
}
}
result −
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 15
value of a: 16
value of a: 17
value of a: 18
value of a: 19
break statement –
The break statement in C# has following two usage −
When the break statement is encountered inside a loop, the loop is immediately terminated
and program control resumes at the next statement following the loop.
It can be used to terminate a case in the switch statement.
If you are using nested loops (i.e., one loop inside another loop), the break statement will stop the
execution of the innermost loop and start executing the next line of code after the block.
Syntax
break;
Example
using System;
namespace Loops {
class Program {
static void Main(string[] args) {
/* local variable definition */
int a = 10;
if (a > 15) {
/* terminate the loop using break statement */
break;
}
}
Console.ReadLine();
}
}
}
result −
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 15
continue statement –
The continue statement in C# works somewhat like the break statement. Instead of forcing
termination, however, continue forces the next iteration of the loop to take place, skipping any code in
between.
For the for loop, continue statement causes the conditional test and increment portions of the loop to
execute. For the while and do...while loops, continue statement causes the program control passes to
the conditional tests.
Syntax
continue;
Flow Diagram
Example
using System;
namespace Loops {
class Program {
static void Main(string[] args) {
/* local variable definition */
int a = 10;
/* do loop execution */
do {
if (a == 15) {
/* skip the iteration */
a = a + 1;
continue;
}
Console.WriteLine("value of a: {0}", a);
a++;
}
while (a < 20);
Console.ReadLine();
}
}
}
result −
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 16
value of a: 17
value of a: 18
value of a: 19
Array -
An array stores a fixed-size sequential collection of elements of the same type. An array is used to store
a collection of data, but it is often more useful to think of an array as a collection of variables of the
same type stored at contiguous memory locations.
Instead of declaring individual variables, such as number0, number1, ..., and number99, you declare one
array variable such as numbers and use numbers[0], numbers[1], and ..., numbers[99] to represent
individual variables. A specific element in an array is accessed by an index.
All arrays consist of contiguous memory locations. The lowest address corresponds to the first element
and the highest address to the last element.
datatype[] arrayName;
where,
[ ] specifies the rank of the array. The rank specifies the size of the array.
For example,
double[] balance
Example -
using System;
namespace ArrayApplication {
class MyArray {
int i,j;
n[ i ] = i + 100;
}
/* output each array element's value */
Console.ReadKey();
result −
Element[0] = 100
Element[1] = 101
Element[2] = 102
Element[3] = 103
Element[4] = 104
Element[5] = 105
Element[6] = 106
Element[7] = 107
Element[8] = 108
Element[9] = 109
Multidimensional Array -
C# allows multidimensional arrays. Multi-dimensional arrays are also called rectangular array. You can
declare a 2-dimensional array of strings as −
int [ , , ] m;
using System;
namespace ArrayApplication {
class MyArray {
static void Main(string[] args) {
int i, j;
Console.ReadKey();
When the above code is compiled and executed, it produces the following result −
a[0,0]: 0
a[0,1]: 0
a[1,0]: 1
a[1,1]: 2
a[2,0]: 2
a[2,1]: 4
a[3,0]: 3
a[3,1]: 6
a[4,0]: 4
String -
In C#, you can use strings as array of characters, However, more common practice is to use the string
keyword to declare a string variable. The string keyword is an alias for the System.String class.
example
using System;
namespace StringApplication {
class Program {
C# applications have an entry point called Main Method. It is the first method which gets
invoked whenever an application started and it is present in every C# executable file. The
application may be Console Application or Windows Application. The most common entry point
of a C# program is static void Main() or static void Main(String []args).
1. With command line arguments: This can accept n number of array type parameters
during the runtime.
Example:
using System;
class GFG {
// Main Method
static public void Main(String[] args)
{
Console.WriteLine("Main Method");
}
}
Output:
Main Method
Example:
using System;
class GFG {
// Main Method
static public void Main()
{
Console.WriteLine("Main Method");
}
}
Output:
Main Method
Example:
using System;
class GFG {
// Main Method
protected static void Main()
{
Console.WriteLine("Main Method");
}
}
Output:
Main Method
Example:
using System;
class GFG {
// Main Method
private protected static void Main()
{
Console.WriteLine("Main Method");
}
}
Compiler Error:
4. Without any access modifier: The default access modifier is private for a Main()
method.
Example:
using System;
class GFG {
Console.WriteLine("Main Method");
}
}
Output:
Main Method
5. Order of Modifiers: The user can also swap positions of static and applicable modifiers
in Main() method.
Example:
using System;
class GFG {
// Main Method
public static void Main()
{
Console.WriteLine("Main Method");
}
}
Output:
Main Method
Example:
using System;
class GFG {
Console.WriteLine("Main Method");
}
}
Output:
Main Method
6. Return Type: The Main Method can also have integer return type. Returning an integer
value from Main() method cause the program to obtain a status information. The value
which is returned from Main() method is treated as the exit code for the process.
Example:
using System;
class GFG {
Console.WriteLine("Main Method");
Output:
Main Method
Example:
using System;
class GFG {
Console.WriteLine("Main Method");
Output:
Main Method
Important Points:
The Main() method is the entry point a C# program from where the execution starts.
Main() method must be static because it is a class level method. To invoked without any
instance of the class it must be static. Non-static Main() method will give a compile-time
error.
Main() Method cannot be overridden because it is the static method. Also, the static
method cannot be virtual or abstract.
Overloading of Main() method is allowed. But in that case, only one Main() method is
considered as one entry point to start the execution of the program.
Variables allocated on the stack are stored directly to the memory and access to this memory is very
fast, and it's allocation is dealt with when the program is compiled. When a function or a method calls
another function which in turns calls another function etc., the execution of all those functions remains
suspended until the very last function returns its value. The stack is always reserved in a LIFO order, the
most recently reserved block is always the next block to be freed. This makes it really simple to keep
track of the stack, freeing a block from the stack is nothing more than adjusting one pointer.
Variables allocated on the heap have their memory allocated at run time and accessing this memory is a
bit slower, but the heap size is only limited by the size of virtual memory . Element of the heap have no
dependencies with each other and can always be accessed randomly at any time. You can allocate a
block at any time and free it at any time. This makes it much more complex to keep track of which parts
of the heap are allocated or free at any given time.
You can use the stack if you know exactly how much data you need to allocate before compile time and
it is not too big. You can use heap if you don't know exactly how much data you will need at runtime or
if you need to allocate a lot of data.
In a multi-threaded situation each thread will have its own completely independent stack but they will
share the heap. Stack is thread specific and Heap is application specific. The stack is important to
consider in exception handling and thread executions.
Value Type
Value type variables can be assigned a value directly. They are derived from the class System.ValueType.
The value types directly contain data. When you declare an int type, the system allocates memory to
store the value.
Value Type variables are stored in the stack.
Examples are int, char, and float, which stores numbers, alphabets, and floating point numbers,
respectively. bool
Reference Type
It refers to a memory location. Using multiple variables, the reference types can refer to a memory
location. If the data in the memory location is changed by one of the variables, the other variable
automatically reflects this change in value.
Reference Type variables are stored in the heap.
Example of built-in reference types are −
object
dynamic
string
Type Casting
Type conversion happens when we assign the value of one data type to another. If the data types
are compatible, then C# does Automatic Type Conversion. If not comparable, then they need to
be converted explicitly which is known as Explicit Type conversion. For example, assigning an
int value to a long variable.
It happens when:
For Example, in C#, the numeric data types are compatible with each other but no automatic
conversion is supported from numeric type to char or boolean. Also, char and boolean are not
compatible with each other. Before converting, the compiler first checks the compatibility
according to the following figure and then it decides whether it is alright or there some error.
float double
Example :
using System;
namespace Casting{
class GFG {
// Main Method
int i = 57;
// automatic type conversion
long l = i;
float f = l;
// Display Result
}} }
Output:
Int value 57
Long value 57
Float value 57
There may be compilation error when types not compatible with each other. For example,
assigning double value to int data type:
using System;
namespace Casting{
class GFG {
// Main Method
double d = 765.12;
int i = d;
// Display Result
} } }
Error :
prog.cs(14,21): error CS0266: Cannot implicitly convert type `double' to
`int'.
An explicit conversion exists (are you missing a cast?)
So, if we want to assign a value of larger data type to a smaller data type we perform explicit
type casting.
This is useful for incompatible data types where automatic conversion cannot be done.
Here, target-type specifies the desired type to convert the specified value to.
Sometimes, it may result into the lossy conversion.
Example :
using System;
namespace Casting{
class GFG {
// Main Method
double d = 765.12;
int i = (int)d;
// Display Result
} } }
Output:
Value of i is 765
Explanation :
Here due to lossy conversion, the value of i becomes 765 and there is a loss of 0.12 value.
Method Description
Example :
using System;
namespace Casting{
class GFG {
// Main Method
int i = 12;
double d = 765.12;
float f = 56.123F;
Console.WriteLine(Convert.ToString(f));
Console.WriteLine(Convert.ToInt32(d));
Console.WriteLine(Convert.ToUInt32(f));
Console.WriteLine(Convert.ToDouble(i));
Console.WriteLine("GeeksforGeeks");
} } }
Output:
56.123
765
56
12
ma
Passing By Reference
When the parameters are passed by reference to a method, new memory variables are not created for
these parameters. Rather, the reference parameters point to the original parameters so that the
changes done in the reference variables reflect back to the original values.
The reference parameters can be declared using the ref keyword in C#. A program that demonstrates
this is as follows:
using System;
namespace PassByRefDemo
{
class Example {
static void Swap(ref int m, ref int n)
{
int temp;
temp = m;
m = n;
n = temp;
}
static void Main(string[] args)
{
int a = 5;
int b = 10;
Console.WriteLine("Passing By Reference");
Console.WriteLine("Before Swap method is called");
Console.WriteLine("a = {0}", a);
Console.WriteLine("b = {0}", b);
Swap(ref a, ref b);
Console.WriteLine("After Swap method is called");
Console.WriteLine("a = {0}", a);
Console.WriteLine("b = {0}", b);
}}}
Passing By Value
Before Swap method is called
a=5
b = 10
After Swap method is called
a = 10
b=5
In the above output, you can see the values get swapped successfully.
Output Parameters
The output parameters are useful in transferring data out of the method. They can be used to return
multiple values while the return statement can only return one value at a time. The out keyword is used
to declare an output parameter.
using System;
namespace OutputDemo
{
class Example {
static void OutValue(out int val )
{
val = 7;
}
static void Main(string[] args)
{
int num = 4;
Console.WriteLine("Value of num before calling OutValue: {0}", num);
OutValue(out num);
Console.WriteLine("Value of num after calling OutValue: {0}", num);
} }}