Programming basics: what are strings ?

0

Welcome reader,

When we first talk about, it was mentioned that the String data type were to be discussed in a later post. So what exactly are String ? If you remember, we have the char data type, which is used to store a single character inside a char variable. Sometimes, we need to manipulate more than just one character. What previous programmers did to get around this issue was to use Arrays.

Arrays can really simply your work when you have to store a lot of information into your program. You have to look at arrays like entities in which you can store multiple variables of the same data type in a single structure.

In programming,  an array type is use to describe a collection of elements of the same data type like it was said before.  Each element in the array can be access with identifying keys (indices). Usually, when we have a ten values that we want to store, we start counting from value 1 to value 10. In computer science, we start counting starting from 0.  A quick trick to know the last identifying key of your array would be to take its length and reduce it by one. The length of an array is defined as how many elements it can possibly store.

This is how arrays works :

Array in Java Comparision

Something must be kept in mind while we’re using arrays : they are static. STATIC. Usually, when we use variables, the value that is stored in the variable can be modified at any time. When we initialize an array, we either directly store the values it will hold or we give the maximal length of the array. If ever we were simply initialize the array with its maximal length, every value in the array will either be undefined (null) or 0. Null values will be aborted in a later post. We’ll see below how to do such things.

arrays


//this is how to initialize an array of int

//With a maximal length of 10

int[] anIntArray = new int[10];

//the new operator can be omitted if an initializer is provided

int[] arrayOfNumber = {1,3,5,7,9,11,13,15,17,19};

//once we initialize an array, its maximal length can't be CHANGE !

//but the values that are stored can be modified.

//Storing values in an array can be achieved with the help of their indices

anIntArray[0]=1;

anIntArray[1]=2;

//so on and so on until we reach the last indice

//Storing values can be achieved with the help of loop

//Example with a for loop and using the size (maximal length) of the array

for(int i=0; i<anIntArray.size();i++)

{

anIntArray[i]=(i*2)+3;

//Accessing the indices of the array to store a value, one at a time

}

Arrays have a lot of potential when we are developing a software application. In fact, as it was mentioned before, the programmers of the old had to use char array to store what have become String value. We’ll see an example how to create a char array and showing the values of the array for the user.

4

char chABC[26]= {'a','b','c','d','e','f','g','h',i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'};

for(int i=0;chABC.size();i++){

Console.Write(chABC[i]);

}

Now, we can directly manipulate the String class ( more on classes and null later).  Doing so, we can directly store input from the end-user like a name  or an address. We can also have information which will never change to present to the end-user such as “warning, you are entering a dangerous zone, please make sure you know what you’re doing or get out of here.”

What’s particular with the string data type is the following : it is immutable. That’s kind of big word for beginners and it is somehow kind of hard to understand at first. Like arrays, strings cannot be modified. But not in the same way as arrays. When a string data type is initialized, it holds a certain value. If along the way, a programmer was to modify the same string variable, it would not cause any problems. But, it would be as if the programmer created a new string. A string only points to certain memory at a time, if the value is modify, it will never be the same string even though it is the same variable.  After a while, what is called extension methods are used to modify data type that are immutable such as string. This is a more advanced topic and will be discussed at length in a later post. We’ll see below an example how of to initialize a string variable


string ourFirstString="This is a string variable. We'll be able to show text with it to end-users of our software application";

Console.WriteLine(ourFirstString);

Kevin

Advertisements

Programming basics : Using loops

0

Welcome reader,

This blog post will cover the use of loops. Loops are used to repeat the same operation(s) at least once. Usually, most programs you can think of will need this kind of functionnality. We can use loops to go through data or let a program start from the start, they can even be use when we need to compute data. In order to execute a loop, a condition must be validate, which was why we had to know how to manage the program flow of a software application.

The first loop we’re going to see is the while loop. In order to know what is happening in a loop, we must first know how to write a loop. When using a while loop, we’re telling the computer the following statement: while the following condition is true, please perform all the stuff that is inside the loop. It is thanks to this condition that the loop will know when it has to stop the looping operation. While this must sound like an easy task to do, this is a well known issue for beginners: infinite loops. For example, like we saw earlier with the comparison operators, if we were to tell while the value of 1,  the while loop will never know when to stop because the value, in the condition, does not change. We’ll see below how to write a while loop with an example :


char selectedAnswerFromUser='Y';

while(selectedAnswerFromUser== 'Y') //We are evaluating the condition the the    equality operator and not the assign operator !

{

Console.WriteLine("Would you like to stop this loop? Please press y for yes or n for no");

selectedAnswerFromUser =Console.ReadLine();

if(selectedAnswerFromUser== 'n')

{

Console.WriteLine("GoodBye ! ");

}

if(selectedAnswerFromUser !='y' || selectedAnswerFromUser != 'n')
{
   Console.WriteLine("Please, you can either press the y or the n letter!");

}

To continue, there is a similar loop to the while loop; it is called the do while loop. The single difference is that the do while will be performed at least once even if the condition is not true. That is the difference between the while and do while loop. We’ll see below an example of the do while loop :


int a=2;

int b=5;

do{ //We start the loop without giving a condition, it will be given below

a++; //The ++ operator tells the computer to increment the value of the a variable by one

Console.WriteLine(a); //This will print the value of a while we are performing the loop

}while(a<b); //in the do while loop, after giving your condition, finish your statement with the ';'

While we are using loops, you can also use variables to count the number of times the loop will perform. We saw the ++ operator earlier, which is meant to increment the value of a variable by one after the line has been read. We have an equal operator in case we want to decrease the value of a variable; the — operator. Here where it gets tricky: depending on which side you put the operators, the have different effects :

  1. variable++ :  The value we use is the value before the incrementation (Postfix incrementation)
  2. ++variable:The value of the variable we’re using is the value after the incrementation (Prefix incrementation)
  3. variable–: The value we use is the value before the variable decreases by 1(Postfix decrementation)
  4. –variable: The value we use is the value after the variable decreases by 1 (Prefix decrementation)

Thanks to those, we’ll now see how to create a condition in a while loop.


int a=5;

while(a<20) { ++a; Console.WriteLine("This the value of the a variable : {0}",a); //This the modulo operator. //It divide the variable a by 2 and looks for remainders //if there are none ->the value will be 0

// else -> We'll see the remainder

if( a%2 == 0 )

{

Console.WriteLine("The value of a will be diminish by 2. This is the value of a now: {0},a);

a=a-2;

}else{

int remainderFromModulo=a%2;

Console.WriteLine("This is the remainder of the modulo : {0}",remainderFromModulo);

}

a=a+3;

}

The last loop we’re going to see in this post is called the for loop. This loop is different from the previous ones that we first saw. This kind of a loop is used when we know exactly the number of times we are going to repeat the block of code until the condition becomes false. The structure is a bit different as we can see below :


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

{

//do stuff

//when the i variable has the value of 5, then the for loop will stop its iteration

}

In the for loop, we first have to initialize which variable is used to iterate, but it does not have to hold the value of 0. Then, after the semi-colon, we have to give a condition to the loop, which, like we know, use to know how long we have to iterate. And finally, we have to specify if the value of this variable is going to increase or to decrease. Also, we don’t have to increase/decrease by the value of 1. It was used to serve as an example.

Kevin

Programming basics : manage program flow final part

0

Welcome reader,

This will be the final part in the programming basics mini series in how to manage the program flow of your software application. We’re going to see how to manage the flow of your program when we’re using a switch. It is a structure that is mostly use when we have predefined conditions.When this happen, knowing exactly those condition, we’ll have the correct operation to perform if it is met. For example, when someone is doing an exam, we could have three states

  1. He didn’t know what to do, so he had a 0
  2. The knowledge on the topic was not mastered he managed to get 11 out of 25
  3. The student mastered the topic and had 25 out of 25

If conditions like these we found in our application, it would be better to use a switch instead of the if-else if – else structure because we’ll have less to write. We’ll see below the structure of a switch statement :


/*

Everything in this code will not work

it is used to demonstrate how a switch statement is written

*/

switch (aVariable)
{
 case /*ValueOfAVariable*/:
        /*Operation*/;
 break; //tells the computer to stop the operation in this case
 default: //Represent what to do if no condition is met
        /*Operation*/;
}

In a swich statement, a case represents the value of the variable we’re evaluating in the switch. If a case is met, then all the operations for this case will be perform until the machine find the line with a break statement. Moreover, the cases can be link altogether. Like it was said before, until the computer find the statement “break;”, the switch will continue to operate. Below, we’ll see an example of such a switch:

switch(value)
{
   case 1:
   case 2:
   case 3:
   case 4:
     //do some stuff
     break;
  case 5:
  case 6:
    //do other stuff
    break;
  default:
      //do some default stuff
      break;
}

Also, we have the ternary operator, which embeds the way the if-else structure work. We’ll be able to find the structure of the ternary operator below for when you want to assign a value to a variable:

  • dataType variable = ( aCondition) ? (firstValue) : (secondValue) ;

The ternary operator evaluates the given condition. If it is true, firstValue will be assign to variable. If the condition was to be false in our program, then secondValue would be assigned to variable. We’ll try out a code sample to see how it could be useful:


int minValue=15;

int midValue=30;

int maxValue=45;

int aMaxValue=(midValue&gt;maxValue) ? midValue : maxValue;

All of this covers how to manage the program flow in your software application. If for the moment this does not look useful, in the next posts,  it will get more clear as we get deeper into programming as our knowledge of the basics gets better.

Kevin

Programming basics: manage program flow part two

0

Welcome reader,

We’ll pick up where we left with how to manage the program flow of a software application. We saw how to use the if-else if-else structure. To evaluate a condition, we need comparaison operators. Those are use evaluate a boolean expression, which will either result a true or false. Below, you’ll be able to find them.

Operator

Description

==

Equality

!=

Inequality

>

Greater than

<

Less than

>=

Greater or equal

<=

Less or equal

&&

Called Logical AND operator. If both the operands are true, then condition becomes true.

||

Called the logical OR operator. If any the operands is true, then the condition become true.

!

Called the logical NOT operator. It uses the reverse logical state of a an operand. Which means that if an operand was initially at true, the NOT operator makes it false during the evaluation

Thanks to these operators,  there is a lot that can be achieved to evaluation an expression. We’ll use them in samples to try to understand how they work. You can use more than just one to evaluate a given condition in your program flow.

Here, we can see how to evaluate operand(values on each side of the operator) with the greater than and less than.
float bankAccount=2500;
if(bankAccount&gt;3000){
  Console.WriteLine("You have quite a big account");
}else if(bankAccount<1000 && bankAccount>2000){
Console.WriteLine("You have more than 1000 $ and less than 2000 $ in your account");
}else{
    Console.WriteLine("We can't evaluate the value in your account, here's how much you have now : {0} $",bankAccount);
}
This sample will show how to use the NOT opeator.
bool aBoolValue=true;
if(!aBoolValue){
    Console.WriteLine("That's not right ! Is it ?"); //You should see this as false
}
if(aBoolValue){
  Console.WriteLine("That is true! If you have guess that the ouput, good job!");
}
Finally, we’re going to see how to use the equality operator. Beware, because this is a general known issue for beginners; the “=” is use to assign values and the “==” is used to evaluate is two values are equals. Because if you use the “=” operator, it will be a true expression. Why? Because you are assigning a value to a variable; doing so you’re asking the computer, for example, is it true that this variable as the value of 8?
int ageOfPerson=18;
if(ageOfPerson == 18)&lt;/div&gt;
{
   Console.WriteLine(&quot;You are consider as an adult in Canada&quot;);
}
//next example is a bad example. Please be sure not to reproduce code likethis one
if(ageOfPerson=21)
{
    Console.WriteLine("You can vote in any country that you want, or I think ?");
}
We will learn how to use switches and the ternary operator in the last part of how to manage the program flow.
Kevin

Programming basics: manage program flow part one

0

Welcome reader,

Our journey into programming began with the use of variables, how to name and how to store data in them. Programming goes a bit further than this. When you tell your machine to perform a given operation, sometimes, you want to check a state or a condition before your console application performs the work that needs to be done. In your daily life, these events surely happens often such as “if I get 80 or more on this test, I’ll go to X party” or else if “I get a bonus in the end of year, I’m going to go to the Bahamas”. I think you can see a pattern? Basically, we do the same thing in a software application such as if this events does happen, perform this task. In short, we evaluate conditions and, depending of what happened and what we are looking for, we’ll either perform a task or we coule just do nothing.  In programming, we use if-else if-else, the ternary operator or switches(more on them in a later post). We’ll code below an example in which will create a variable storing an integer value. We’ll evaluate conditions and then print the value of the variable if one of these conditions are met.


public static void Main(){

int ageOfClient=30;

//the operators which were use to create the condition will be explained in the next post

//using the if- else if - else structure

if(ageOfClient<18){

Console.WriteLine("The client is a child");

}

else{

Console.WriteLine("Your client is an adult");

}
}

// the ternary operator will be mention when we'll talk about strings.

Kevin

Programming basics: My first console application

0

Welcome reader,

We haven’t create an application since the start of the programming basics. It is sort of a ritual that the first program that a programmer writes will print of the screen the following : “Hello World!”. So, we are actually going to write this as our first console application.

Open your IDE and select Console application. Copy paste the follow code below and hit the run button in your IDE :

public static void Main()
   {
      System.Console.WriteLine(&quot;Hello, World!&quot;);
   }

There, you have the most basic application you can create. You are actually using a method called “WriteLine” and putting information inside the parenthesis. This information that was passed as a parameter (they will be discussed at length during the method post) was then written on your screen.

There you go ! It wasn’t so bad, you can now call yourself a “developer” or a “programmer”. As we’ll progress, you’ll see that programming isn’t so hard as long as you put your time in it and really want to learn. Being passionate about what you’re trying to achieve will help you to master a lot of subjects. Don’t beat yourself down if there was ever a subject that eluded you even if it was the 100th that you tried to do it. Take some time off and come back, make sure you understand the core fundamentals before moving foward !

Kevin

Programming basics: naming convention, indent and white spaces

0

Welcome reader,

We’ll follow where we left off when we’ve talked about variables. When you are behind you screen, there is a lot more going on then just writing lines in the IDE to make you computer do something.  There are a set of rules that you should always stick to make your code clearer. Before, we talked about commenting your code.  Comments are meant to explain the purposes of your program. As an example,  when you’re creating variables, placing comments can help explain what you’re trying to do with those variables. When you’re programming, your instructions will be read by the IDE. Comments will be ignore by the IDE.

There are different ways to comment code. You can place comment on one line. You can also you what I call paragraph commenting. These will come handy when we’ll describe the behavior of methods. You’ll find some commenting examples.


//This is a single line comment

/*

This a paragraph comment. While I'm inside the /**/

all that will be written will be ignored by the IDE

*/

int myIntVariable; //Explain the usefulness of your variable with this comment 

More than just comments, there are other ways to make sure that other programmers who might read your code will appreciate reading it. As you could have seen, when I’m writting my variables, I follow a set of rules which I strongly suggest that you should also follow. This is called the “camelCase” convention. When you’re creating something like a variable or a method (more on methods later), these are the rules that you’ll have to follow.

  • The name of your variable cannot start with a number such as “123MyVariable”
  • The name of the variable should always start with a lower case letter such as “myVariable”
  • When you’re trying to write a composed name, you can either do this : “thisIsTheNameOfTheVariable” or use the underscore to separate either word of the variable’s name like this :  “this_Is_The_Name_Of_The_Variable”
  • Never forget to give a meaningful name to your variable

Finally, even following those set of rules is not quite enough. A good programmer should always indent his code a have a moderate use of white spaces. Well, I’ve just blurred some words that won’t really mean something to you so I’ll explain what I’m trying to tell you. Indenting code is a convention where you place tabs in the blocks of code. As for white spaces, there just meant to make code easier to read. It could all be close together, but that wouldn’t do any good if one must spend some time, trying to decrypt what you’ve wrote.

You’ll find below an example :

/*
The following block of code won't work
It will serve as an example to make sure
that you understand indentation
*/
//indentation
int variable_1=10;
{
   int variable_2=13; //See? There was a tab after the curly brace
}

//white spaces(none)
int variable_3=15;
double variable_4=20.0;
decimal variable_5=0.05m;
short variable_6=56;

//white spaces
/*
Putting white before and after operators(more on them later)
is helpful. Your code does not have to be too cramped
More than just that, separate your variables makes it also easier to read

What I suggest is if you have a set of variables that have a relation
altogether, let them be in a group but after create an empty line and then
resume your coding activity
*/
int variable_7 = 123;

double variable_8 = 234.98;

decimal variable_9 = 0.45m;

Programming basics : variables

0

Welcome reader,

This is the first part of a mini-serie to introduce the basics of programming with C#. Don’t forget to look at my GitHub account. I haven’t decide yet, but surely I will create a project which will resume every topic that I’ve talked about during the Programming basics serie.

So, we’re finally there, will start talking about the programming at last! In this serie, I assume that you’ll have already downloaded your IDE( if you don’t know what’s an IDE, please go read my blog post about IDEs) on your machine. Like I have mentionned before, I’ll be using the Visual Studio Community Edition IDE in this blog.

The introduction to programming start with a fundemental topic : variables. When you are programming, you are telling your machine exactly what you want it to achieve. In order to do so, you have to manipulate data directly on your machine, and when you’ll be running your software application(more of running later), the code that you’ve given will look like this:

0101010 0101 010101 01010

For the untrained eyes, it’s only 0s and 1s. But that is called binary code. This is what your machine use to achieve an operation that you have order it to do.  Even when you are on your user interface of you operating system, you are telling your computer what to achieve for you such as

Opening a folder

Save a file

With the IDEs,  our life is easier, we don’t need to actually manipulate data on the computer with binary code, we use variables. What this means is this: variables points to different parts of the computer memory. In short, variables have a name and a value.They hold different kind of data which can be manipulate and consume by a programmer in order to achieve his goal. Below, you’ll be able to see all the variables that are accessible in most programming languages:

  • byte – 8 bits
  • short – 16 bits
  • int – 32 bits
  • long -64 bits
  • float – single precision 32 bit floating numbers
  • double – double precision 64 bits floating numbers
  • decimal – 16 bits
  • bool – boolean value (true/false)
  • char – holds a character
  • String (it will be discussed in a later post)

From byte to long, these represent integer values such as 0, 100, 200. We have access to different kind of integer values, and when you are programming, you have to choose carefully the exact type you need because each type has its own weight in bit. The more you use, the bigger the software application will be. To understand the difference between the type of integer you can choose, you will find below the range of values each one has:

  • byte [0,255]
  • short [-32768,32767]
  • int [-2147483648,2147483647]
  • long [-9223372036854775808,9223372036854775807]

For example, if you create a software application which will only hold employees ages, using long variables because of their weight. Rapidly, in an application with around a million employees, the software would be heavy to process because you’re using the wrong type of data. In this case, knowing that the human’s span life is around 80 years, using the byte type would be much better. While using variables, you should always use your judgement in order to be memory efficient. Lower, you’ll be able to find an example of a byte variable containing the age of an employee:


byte employeeAge=30;

As you can see, when using a variable, the variable’s name is on the left and the value,which will be assigned, is on the right.  To continue, the float,double and decimal types should be use only when you to consume data which contained the full value of number like 1.25.


int firstValue=1.25; //firstValue will only be 1 because it is an integer
float secondValue=1.25; //secondValue will be 1.25

Console.WriteLine(firstValue);//Will display the value of 1
Console.WriteLine(secondValue); //Will display the value of 1.25

Upward, you can see some code sample showing the use of two variables and C# function(more on functions later) in order to display data to the screen. There’s quite a lot going on in this sample, the part with the double slash is called comments. Comment will be discussed in the next part of this serie. Moreover, as you can see, the names of the variable don’t really represent anything. When using variables, the names you use should always be meaningful. By always doing so, you’ll be able to understand the code you’ve written a while back faster without, or almost, need of comments.

To finish, the char type can only hold a character as a value. A character can be anything such as a alpha or numerical character. The char data is assigned with single quotes. You can see an example below.


byte charVariable='1';

To wrap up, variables have a meaningful name and a value. When using variables in your software application, you should make sure to always use the right type in order to be memory efficient.

Kevin