VISUAL
PROGRAMMING
Presented By NJOKO SOPBWE
WHAT’S C#?
C# is an object-oriented programming language created by Microsoft that
runs on the .NET Framework.
C# has roots from the C family, and the language is close to other popular
languages like C++ and Java.
The first version was released in year 2002. The latest version, C# 12, was
released in November 2023.
USE OF C#
• Mobile applications
• Desktop applications
• Web applications
• Web services
• Web sites
• Games
• VR
• Database applications
Etc…
WHY USE C#
• It is one of the most popular programming languages in the world
• It is easy to learn and simple to use
• It has huge community support
• C# is an object-oriented language which gives a clear structure to
programs and allows code to be reused, lowering development costs
BASIC LAYOUT OF A C#
PROGRAM
using System;
namespace MainProgram
{
class Main
{
static void Main(string[] args)
{
Console.WriteLine("Hello World!");
}
}
}
SYNTAX EXPLANATION
using System means that we can use classes from the System namespace.
C# ignores white space.
namespace is used to organize your code, and it is a container for classes
and other namespaces.
The curly braces {} marks the beginning and the end of a block of code.
class is a container for data and methods, which brings functionality to
your program. Every line of code that runs in C# must be inside a class. In
our example, we named the class Main.
SYNTAX EXPLANATION
Main method. Any code inside its curly brackets {} will be executed.
Console is a class of the System namespace, which has a WriteLine()
method that is used to print text.
If you omit the using System line, you would have to write
System.Console.WriteLine() to output text.
Every C# statement ends with a semicolon ;.
C# is case-sensitive; "MyClass" and "myclass" have different meaning.
HANDLING OUTPUTS
Console.Write("Hello World! ");
Console.WriteLine("I will print on the same line.");
NB: The only difference is that write does not insert a new line at the end of
the output:
COMMENTS
Single (//)
Multi-Line ( /* */)
C# DATA TYPES
C# VARIABLES
int - stores integers (whole numbers), without decimals, such as 123 or -
123
double - stores floating point numbers, with decimals, such as 19.99 or -
19.99
char - stores single characters, such as 'a' or 'B'. Char values are
surrounded by single quotes
string - stores text, such as "Hello World". String values are surrounded by
double quotes
bool - stores values with two states: true or false
DECLARING VARIABLES
datatype variableName = value;
E.g int number1 = 10;
PRINTING VARIABLES
Console.WriteLine(variableName);
E.g Console.WriteLine(number1);
DECLARING AND
INITIALIZING VARIABLES
int myNum = 5;
double myDoubleNum = 5.99D;
char myLetter = 'D';
bool myBool = true;
string myText = "Hello";
RULES FOR NAMING
VARIABLES
Names can contain letters, digits and the underscore character (_)
Names must begin with a letter or underscore
Names should start with a lowercase letter, and cannot contain whitespace
Names are case-sensitive ("myVar" and "myvar" are different variables)
Reserved words (like C# keywords, such as int or double) cannot be used
as names
CONSTANT VARIABLES
const int myNum = 15;
PRINTING VARIABLES
TOGETHER
String Interpolation
int age = 10;
string name = “Aymric";
double salary = 500.50;
Console.WriteLine($"Name: {name}, Age: {age}, Salary:
{salary}");
PRINTING VARIABLES
TOGETHER
Composite Formatting:
int age = 10;
string name = “Aymric";
double salary = 50.50;
Console.WriteLine("Name: {0}, Age: {1}, Salary:
{2}", name, age, salary);
PRINTING VARIABLES
To combine both text and a variable, use the + character:
You can also use the + character to add a variable to another variable:
For numeric values, the + character works as a mathematical operator
EXERCISE
Calculator Program: Create a simple calculator
program that takes 6 numbers and an operator (+, -,
*, /) and performs the corresponding operation.
TYPE CASTING: IMPLICIT
CASTING
int myInt = 9;
double myDouble = myInt; // Automatic casting:
int to double
Console.WriteLine(myInt); // Outputs 9
Console.WriteLine(myDouble); // Outputs 9
EXPLICIT CASTING
double myDouble = 9.78;
int myInt = (int) myDouble; // Manual casting:
double to int
Console.WriteLine(myDouble); // Outputs 9.78
Console.WriteLine(myInt); // Outputs 9
TYPE CONVERSION
METHODS
It is also possible to convert data types explicitly by
using built-in methods, such as Convert.ToBoolean(),
Convert.ToDouble(), Convert.ToString(),
Convert.ToInt32(variable) and Convert.ToInt64 (long):
USER INPUT
Strings: Console.ReadLine()
Integer:
ConvertToInt32(Console.ReadLine())
C# OPERATORS
ASSIGNMENT OPERATORS
^= operator is a bitwise XOR
|= operator is a bitwise OR
>>= operator is the right shift
assignment operator. It shifts
the bits of the left operand to
the right by a specified number
of positions (the right operand)
and assigns the result back to
the left operand.
COMPARISON OPERATORS
LOGICAL OPERATORS
THE MATH FUNCTION
C# provides a wide range of math functions through the System.Math class
in the .NET Framework. These functions cover various mathematical
operations such as trigonometry, logarithms, exponentiation, rounding, and
more. Here are some commonly used math functions in C#:
MATH: TRIGONOMETRIC
FUNCTIONS:
Math.Sin(double): Returns the sine of the specified angle in radians.
Math.Cos(double): Returns the cosine of the specified angle in radians.
Math.Tan(double): Returns the tangent of the specified angle in radians.
Math.Asin(double): Returns the angle whose sine is the specified number.
Math.Acos(double): Returns the angle whose cosine is the specified number.
Math.Atan(double): Returns the angle whose tangent is the specified number.
Math.Atan2(double, double): Returns the angle whose tangent is the quotient of two
specified numbers.
EXPONENTIAL AND
LOGARITHMIC FUNCTIONS:
Math.Exp(double): Returns e raised to the specified power.
Math.Log(double): Returns the natural logarithm (base e) of a specified
number.
Math.Log10(double): Returns the base 10 logarithm of a specified number.
Math.Pow(double, double): Returns a specified number raised to the
specified power.
ROUNDING FUNCTIONS
Math.Round(double): Rounds a double-precision floating-point value to the
nearest integral value.
Math.Floor(double): Returns the largest integer less than or equal to the
specified double-precision floating-point number.
Math.Ceiling(double): Returns the smallest integer greater than or equal to
the specified double-precision floating-point number.
Math.Truncate(double): Returns the integral part of a specified double-
precision floating-point number.
MORE FUNCTIONS
Math.Abs(double): Returns the absolute value of a specified number.
Math.Min(double, double): Returns the smaller of two double-precision
floating-point numbers.
Math.Max(double, double): Returns the larger of two double-precision
floating-point numbers.
Math.Sqrt(double): Returns the square root of a specified number.
RANDOM NUMBERS
// Create a Random object
Random random = new Random();
randomNumber = random.Next(min, max + 1); // "+1" to include the upper
bound
EXERCISE
Develop a program that calculates the simple interest based
on the principal amount, interest rate, and time period entered
by the user.
NB: Simple interest = principal * rate * time / (100);
STRINGS
String.Length: Gets the number of characters in the string.
string str = "Hello";
int length = str.Length; // length is 5
STRINGS
IndexOf / LastIndexOf: Finds the index of a specified character or
substring within the string.
string str = "Hello";
int index = str.IndexOf('e'); // index is 1
int lastIndex = str.LastIndexOf('l'); // lastIndex is 3
STRINGS
Substring: Retrieves a substring from the original string.
string str = "Hello";
string sub = str.Substring(1, 3); // sub is "ell"
STRINGS
ToUpper / ToLower: Converts the string to uppercase or lowercase.
string str = "Hello";
string upper = str.ToUpper(); // upper is "HELLO"
string lower = str.ToLower(); // lower is "hello"
STRINGS
Trim: Removes leading and trailing white-space characters from the string.
string str = " Hello ";
string trimmed = str.Trim(); // trimmed is "Hello"
STRINGS
Replace: Replaces all occurrences of a specified character or substring
with another character or substring.
string str = "Hello";
string replaced = str.Replace('l', 'L'); // replaced is "HeLLo"
STRINGS
Contains: Determines whether the string contains a specified substring.
string str = "Hello";
bool contains = str.Contains("ell"); // contains is true
STRINGS
Split: Splits the string into an array of substrings based on a specified
delimiter.
string str = "Hello,World";
string[] parts = str.Split(','); // parts is ["Hello", "World"]
STRINGS
Concat: Concatenates two or more strings.
string str1 = "Hello";
string str2 = "World";
string concatenated = string.Concat(str1, " ", str2); // concatenated is
"Hello World"
STRINGS
Format: Replaces placeholders in a string with corresponding values.
string name = "John";
int age = 30;
string formatted = string.Format("My name is {0} and I am {1} years old.",
name, age);
// formatted is "My name is John and I am 30 years old."
STRING INTERPOLATION
string firstName = "John";
string lastName = "Doe";
string name = $"My full name is: {firstName} {lastName}";
Console.WriteLine(name);
SUB-STRIGNS
SPECIAL CHARACTERS
BOOLEANS
A Boolean expression returns a boolean value: True or False, by comparing
values/variables.
IF -STATEMENT
if (condition)
{
// block of code to be executed if the condition is True
}
ELSE - STATEMENT
if (condition)
{
// block of code to be executed if the condition is True
}
else
{
// block of code to be executed if the condition is False
}
ELSE-IF - STATEMENT
if (condition1)
{
// block of code to be executed if condition1 is True
}
else if (condition2)
{
// block of code to be executed if the condition1 is false and condition2 is True
}
else
{
// block of code to be executed if the condition1 is false and condition2 is False
}
TERNARY OPERATOR
variable = (condition) ? expressionTrue :
expressionFalse;
EXERCISES
Number Guessing Game: Implement a simple number guessing game
where the computer generates a random number between 1 and 100, and
the user has to guess it. Provide feedback to the user if their guess is too
high or too low until they guess the correct number.
Even or Odd: Write a program that takes an integer input from the user and
prints whether it's even or odd.
SWITCH CASE
switch(expression)
{
case x:
// code block
break;
case y:
// code block
break;
default:
// code block
break;
}
EXERCISE
Write a program using switch case that will identify the week day by its
number.
E,g Monday is day1, Tuesday day2 etc…
LOOPS
Loops can execute a block of code as long as a specified condition is
reached.
Loops are handy because they save time, reduce errors, and they make
code more readable.
C# WHILE LOOP
while (condition)
{
// code block to be executed
}
DO WHILE LOOP
do
{
// code block to be executed
}
while (condition);
C# FOR LOOP
for (statement 1; statement 2; statement 3)
{
// code block to be executed
}
NESTED LOOPS
// Outer loop
for (int i = 1; i <= 2; ++i)
{
Console.WriteLine("Outer: " + i); // Executes 2 times
// Inner loop
for (int j = 1; j <= 3; j++)
{
Console.WriteLine(" Inner: " + j); // Executes 6 times (2 * 3)
}
}
FOR EACH LOOP
Used exclusively to loop through elements in an array:
foreach (type variableName in arrayName)
{
// code block to be executed
}
BREAK AND CONTINUE
STATEMENTS
The break statement can also be used to jump out of a loop.
The continue statement breaks one iteration (in the loop), if a specified
condition occurs, and continues with the next iteration in the loop.
ARRAYS
datatype[] variable name;
WAYS OF CREATING ARRAYS
// Create an array of four elements, and add values later
string[] cars = new string[4];
// Create an array of four elements and add values right away
string[] cars = new string[4] {"Volvo", "BMW", "Ford", "Mazda"};
// Create an array of four elements without specifying the size
string[] cars = new string[] {"Volvo", "BMW", "Ford", "Mazda"};
// Create an array of four elements, omitting the new keyword, and without
specifying the size
string[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
NOTE
if you declare an array and initialize it later, you have to use the new
keyword:
ACCESS THE ELEMENTS OF
AN ARRAY
string[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
Console.WriteLine(cars[0]);
// Outputs Volvo
LOOPING THROUGH ARRAYS
string[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
foreach (string i in cars)
{
Console.WriteLine(i);
}
LOOPING THROUGH ARRAYS
string[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
string[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
for (int i = 0; i < cars.Length; i++)
{
Console.WriteLine(cars[i]);
}
SORTING ARRAYS
string[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
Array.Sort(cars);
foreach (string i in cars)
{
Console.WriteLine(i);
}
SYSTEM.LINQ
Useful array methods, such as Min, Max, and Sum, can be found in the System.Linq
To use these methods, you have to add the below line of code at the top of your
program
using System.Linq;
An now include a line like the one below in your main function
Console.WriteLine(variableName.Max()); // returns the
largest value
MULTIDIMENSIONAL ARRAYS
Two-Dimensional Arrays
int[,] numbers = { {1, 4, 2}, {3, 6, 8} };
ACCESS ELEMENTS OF A 2D
ARRAY
int[,] numbers = { {1, 4, 2}, {3, 6, 8} };
Console.WriteLine(numbers[0, 2]); // Outputs 2