Fundamentals of C# Programming (Part Two): Digging Deeper with Statements and Arrays.

Martins charles
12 min readSep 16, 2023

--

By Charles Martins

Fundamentals of C# programming

So far, I have described what .NETCore is and explained the Concepts That Make Your “Hello World” a Reality.

In my last article, I described datatypes, variables, and operators in C Sharp programming. As a continuation, I will describe other concepts of C Sharp programming, such as Statements and Arrays.

Statements in C sharp programming

Statements in C# programming

It is always a dilemma for people when distinguishing between a statement and an expression. It is important to learn the difference as a programmer who might interact with multiple languages in the future. So, let us start with that.

What is an expression?

An Expression is simply a piece of code that can be assigned to one value using an operator. The point of an expression is to execute to a value.

counter + 1

An expression is usually made up of operands, variables, function calls, and literals. An expression will always yield an output since it is assigned a value. Based on this, there are typically three different types of expressions: arithmetic, logic, and character. The Expression is therefore evaluated to a numeric value, a character value, or a logical value.

5*2

This is an expression with an output of 10 (a numeric value).

What is a statement?

A statement can be a single line of code or a block of several lines of code that instructs the computer to carry out an action.

Actions may include declaring variables, assigning values, calling methods, looping through collections, and branching from one code to another.

Statements end with a semicolon and are always executed in a flow or sequence.

const double pi = 3.14159;

There are different types of statements, some of which have special keywords associated with them.

Declaration Statements:

Declaration statements declare a variable of any type. The purpose of a declaration statement is to introduce a new constant or variable.

You specify the type of variable (or not, in the case of implicitly typed variables) and give it a name.

string greeting;

This is a variable named greeting, which has the type string

Exception-handling Statements:

In programming, when an error occurs, the program throws an exception. Throwing an exception means interrupting the flow of program execution. The runtime looks for an exception handler to handle the exception.

The role of an exception-handler is to discover what kind of error it is and attempt to recover that error if possible, or gently exit from the program.

There are four exception-handling statements that come into play: the try, throw, catch, and finally statements. try, throw, catch, and finally are also keywords in C#.

The block of statements within which an exception might be thrown is identified with the try or throw statement. The catch statement identifies a set of statements to handle a specific exception within a try block of statements. And the finally statement identifies the block of statements that are executed regardless of whether or not an error occurs within the try block.

try {

statement(s)

} catch (exceptiontype name) {

statement(s)

} finally {

statement(s)

}

Iteration Statements:

Iteration statements allow statements or compound statements to be executed in a loop until certain loop-termination criteria are met. For instance, if you wish to loop through a collection of objects or iterate a set of statements.

Do, for, foreach, range-based for, and while statements are called iteration statements. These are important keywords that can be applied to iteration statements: do, for, foreach, range-based for, while, break, and continue.

The do loop iterates the statements or block of statements until the boolean is true or while the boolean is true. There are many ways that the do loop can be executed, but it is mostly used as a do-while loop or do-until loop.

i = 1

do

{

Console.WriteLine (names[i]);

i++;

} while (i < names.Length)

The code above tells the computer to continue to output the names in an array (the array is called names but not visible in this code) while the number of names in the array is greater than 1. You can also see the increment sign (++). This makes sure that after the first name is executed, we increase i by 1, and then output name 2.

The for loop iterates the statements or block of statements as long as the loop statement is satisfied. When you know the exact number of times you want a code to execute, use the for loop.

for (int i = 0; i < 5; i++)

{

Console. WriteLine (i);

}

Here you initialize i at 0 and continue to print the value of i to the console as long as i is less than 5.

There is also the foreach loop, which is used to exclusively loop through elements in an array.

string[] cars = {“Volvo”, “BMW”, “Ford”, “Mazda”};

foreach (string i in cars)

{

Console.WriteLine(i);

}

Selection Statements:

These are sometimes called conditional statements. The conditional statements generate decisions based on certain conditions. These conditions have some specific boolean expressions.

Conditional statements are a bunch of codes that can be executed by “decision statements”. The boolean expression of these statements generates a boolean value that could be either true or false.

Select statements include if, if-else, if-else-if, and switch statements.

The if statement executes a block of code once the condition is met.

if (100 > 53)

{

Console.WriteLine (“100 is greater than 53”)

}

In this code, if 100 > 53, then the statement within the {} is outputted.

If-else statements have an else clause where, if a condition proves to be false, the else statement executes some other code or statements.

int time = 23;

if (time < 16)

{

Console.WriteLine (“Good day.” );

}

else

{

Console.WriteLine (“Good evening.”);

}

Given that the time is not less than 16, then the output is Good evening.

if-else-if statements are used to specify various conditions when a previous condition proves to be false.

int time= 23

if (time < 12) {

greeting = “Good morning”;

} else if (time <=16) {

greeting = “Good day”;

} else {

greeting = “Good evening”;

}

The if-else-if code above checks three conditions. If the time is less than 12, it is morning. If the time is equal to or less than 16, it is still daytime. And if it is anything else, it is evening. Here, you would expect the output to be Good evening.

You can nest an if statement inside another if statement. For instance, once a condition is met (enter your car), you can go on to check for other conditions (start the car) that must be met concurrently with that condition to get an output (drive away).

Nested ifs check for other conditions within an already established condition, once the previous condition is true. There are also nested else and if-else statements.

The code above is written to output a name. The code shows how nested if-else and if statements are implemented.

First, the code checks to see if the name is Charles, if it is, it then checks to see if the surname is Martins. If both conditions are true, the console outputs the name. If only the first condition is true but the second is not, the output is: “You are not the Charles I know.” If the first condition is not true, it does not check the second and exits with the following output: Your name is not registered.

Switch statements are used to select what block of code should be executed when the condition is met.

The core difference between switch statements and if-else statements is how switch statements are used to choose between many options to be executed.

int day = 4;
switch (day)
{

case 4:
Console.WriteLine(“Thursday”);
break;
case 5:
Console.WriteLine(“Friday”);
break;
case 6:
Console.WriteLine(“Today is Saturday.”);
break;
case 7:
Console.WriteLine(“Today is Sunday.”);
break;
default:
Console.WriteLine(“Looking forward to the Weekend.”);
break;

}

As you can see from the code above, there are four cases and a default. The default is outputted if none of the cases are met. In the code above, case:4 is met, and the output is “Thursday”.

Jump Statements:

credit: www.shekali.com

As I mentioned earlier, statements allow you to perform certain actions. Statements are executed in a flow or sequence. You can manipulate the flow of a program using Jump statements.

There are five keywords in Jump statements: break, continue, Goto, return, and throw.

The break statement allows us to terminate a loop once the condition is met.

The continue statement is used to execute parts of the loop while skipping other parts. Unlike break statements, which terminate a loop, the continue statement skips to the next iteration.

The Goto statement specifies the code you want to execute. Much like the continue statement, you jump to the specified line of code while skipping the others.

The return statement is used to terminate a function after a condition has been met.

The throw statement is used to manually create an object of any valid exception class using the new keyword.

Learn more about the five keywords in jump statements and see how they are used here.

Arrays in C# programming

Arrays in C# programming

An Array is a collection of elements or variables of the same data type stored in contiguous and adjacent memory locations. An array is a type of data structure.

Each item in the array is identified by its assigned index number. The lower bound of the array is 0, meaning the first element of the array is assigned the index number 0.

The elements of an array in C# are all of the same type. A rank determines the number of indices associated with each array element. The array rank is also known as the dimension of the array. Arrays with one dimension (rank) are called single-dimensional arrays. Multi-dimensional arrays are arrays with more than one rank. There is also another type of array called the Jagged array, whose elements are arrays.

An array’s number of dimensions is set when an array variable is declared. For example, to declare and initialize an array that holds five integers:

int [] myArray = new int [5]

Data is stored in an array for the following reasons:

  1. Code Optimization: It offers less memory usage, minimizes CPU time, and offers high speed.
  2. Random Access: You do not have to access the elements in a sequence. All you have to do is call the element by its index.
  3. Easy to transverse data: You can access the elements in an array easily at any entry point.
  4. Easy to manipulate: You can delete, modify, and add elements to an array at whatever position you wish.
  5. Easy to sort data: Arrays are easy to sort as you can insert and replace elements easily.

Many sorting algorithms work easily with arrays. We will look at sorting algorithms and data structures in later articles. You can follow me on medium and subscribe to my mailing list so you get the article once it is done!

I will quickly discuss the types of arrays.

One-dimensional arrays:

This is the simplest array. Data is stored linearly in a row, and the elements can be accessed by specifying the index. You declare a single-dimensional array in C# using a single set of square brackets like this: []

//declare an array

int [] age;

// allocate memory for array

age = new int [5];

The keyword new is used to create an instance of the array. We have created a array with five elements in the code above. The index of the elements are: 0, 1, 2, 3, 4.

Let’s say you wish to access the first element of the array and assign it to the variable firstNumber. Here is what the code would look like:

int[] numbers = new int[5] {1, 2, 3, 4, 5};
int firstNumber = numbers[0];

Here the firstNumber is 1 with an index of 0.

One-dimensional array

Multi-dimensional arrays:

You can have arrays with up to 32 dimensions in C#. Multi-dimensional arrays have two or more rows (up to 32) to store data on.

It is also called a rectangular array because it has the same length of each row.

It is declared with two square brackets [] like a one-dimensional array but commas are used to determine what dimension the array will take.

int[,] multiarr = new int[3, 3] {

{1, 2, 3 },

{4, 5, 6 },

{7, 8, 9 },

};

The above code creates a two dimensional array (one comma) with three rows and three columns.

To access the elements in an array, you must specify it’s row and column number. Suppose you wish to locate row 0, column 1 of an array and change it’s number to 4.

int[,] multiarr = new int[3, 3] {

{1, 2, 3 },

{4, 5, 6 },

{7, 8, 9 },

};

multiarr [0, 1] = 4;

Note: Third dimensional arrays are simply two dimensional arrays stored as elements. You can learn more on arrays here.

credit : Scaler topics

Jagged arrays:

This is an array of arrays, where each sub-array can be of a different length. You can use jagged arrays to store a collection of array of different sizes.

It is intialized by two square brackets.

int [][] jagArr = new int [3][];

jagArr [0] = new int [2]{1, 2};

jagArr [1] = new int [3]{3, 4, 5 };

jagArr [2] = new int [4]{6, 7, 8, 9 };

The code above declares and initializes a jagged array called jagArr that contains 3 sub-arrays of integers with varying lengths.

You can access a jagged array using two for loops. Like in the code below:

int[][] jagArray = new int[2][]{
new int[3]{1, 2, 3},

new int[4]{4, 5, 6, 7}
};

for(int i=0; i<jagArray.Length; i++)
{
for(int j=0; j < (jArray[i]).Length; j++)
Console.WriteLine(jArray[i][j]);
}

Properties in arrays.

There are a couple of properties that can used to manipulate arrays.

Given that an array is arrayName. Here are the actions of methods when appended to it.

arrayName.IsFixedSize — gets a boolean value (true or false) indicating whether the array has a fixed size. The default value is true for all arrays.

arrayName.IsReadOnly — displays a boolean value (true or false) indicating if the array is read-only. The default value is false for all arrays.

arrayName.Length — returns the total number of elements in all the dimensions of the array.

arrayName.Rank — tells you the number of dimensions of an array. A rank property of 1 means it is one-dimensional.

arrayName.BinarySearch — searches an already sorted one-dimensional for a value, using a binary search algorithm.

arrayName.ConvertAll — converts an array of one type to an array of another type

arrayName.ForEach — performs a specified action on each element of the targeted array. For instance, squaring each integer in an array.

There is many more properties of an array that you can learn and use as you code. I have only highlighted a few common ones.

That brings to the end of this article. A lengthy one at that. I’ll be discussing more C sharp programming concepts as weeks go by. Follow my medium account and you can learn so much more!

Next up! A most coveted topic is Git and Github! Stay tuned.

--

--

Martins charles

Hi I'm Charles. A life long learner, welcome to my thought box, if you stay long enough I have exciting things to share!