Getting Started with Basic Statements

A statement is a programming construct that is used to instruct the computer to perform specific actions.

C# like most programming languages gives you the ability to write statements. The most basic statement looks like this

A statement like this serves very little purpose. However, all statements that instruct/compute should end with a semi-colon as shown here.

Consider the following problem -

For a given number of seconds in a day, we want to convert this to hours, minutes, and seconds and then print the values out.

We can break down the solution into the following steps

  1. Specify the number of seconds

  2. Calculate the number of seconds that are not divisible by 60; call this “seconds left” - this is the remainder seconds if they were to convert the seconds to minutes

  3. Remove the “seconds left” from the initial number of seconds, this will give us a whole number, divide this number by 3600 (this is the number of seconds in an hour), this will convert the seconds into hours

  4. Remove the “seconds left” from the initial number of seconds, this will give us a whole number, take the modulo division 60 x the number hours, this will result in the remaining number of minutes

fig 2.

Before continuing read the section on variables

Breakdown of the code

int seconds;

This is a declaration statement. This declares a variable called seconds of type int without an initial value. If you do not specify an initial value, C# will create the variable with an initial default value. In this case, it will be 0.

 

seconds = 7197;

This is an assignment statement. It comprises three parts; the left hand, an equal operator, and a right hand. The variable seconds is assigned the value 7197.

 

int secondsLeft = seconds % 60;

This is a declaration with initialisation. The variable secondsLeft is created with an initial value from the result of the expression seconds * 60.

 

 

The remaining declarations create two new variables hours and minutes with the values from the hand expressions.

Notice the use of several operators in the above piece of code (%, /, *, -, and +). There are many operators available, see below. These operators will work comfortably with the C# built-in types.

 

Console.WriteLine(…) is an API function to print to the console.