Chapter One:
Visual Programming
concept
A First Program Using C#
PREPARED BY HABIMANA 1
PATRICK
Objectives
• Learn about programming tasks
• Learn object-oriented programming concepts
• Learn about the C# programming language
• Learn how to write a C# program that
produces output
• Learn how to select identifiers to use within
your programs
PREPARED BY HABIMANA 2
PATRICK
Objective
• Learn how to compile and execute a C# program
from the command line
• Learn how to add comments to a C# program
• Learn how to compile and execute a program
using Visual Studio IDE
• Learn how to eliminate the reference to Out by
using the System namespace
PREPARED BY HABIMANA 3
PATRICK
Briefly in this chapter we will see the following:
-basic programming terminology
-we will write our first C# program
-We will familiarize ourselves with programming
-we will review the different stages of software development.
-We will introduce the C# language, the .NET platform and the
different Microsoft technologies used in software development.
-We will examine what tools we need to program in C#.
-We will use the C# language to write our first computer program,
compile and run it from the command line as well as from
Microsoft Visual Studio integrated development environment.
PREPARED BY HABIMANA 4
PATRICK
Programming
• A computer program is a set of instructions that you
write to tell a computer what to do
• A computer program is the software that makes
computers valuable to the end-user, allowing for many
different types of services that change our lives.
• Programmers do not use machine language when
creating computer programs. Instead, programmers tend
to use high-level programming languages
• Each high-level language has its own syntax and limited
set of vocabulary that is translated into machine code by
a compiler
PREPARED BY HABIMANA 5
PATRICK
• In addition to understanding syntax, a programmer must also
understand programming logic.
• To “program” means writing sequences of instructions in order
to organize the work of the computer to perform something.
These sequences of instructions are called “computer
programs” or “scripts”.
• Programmers are the people who create these instructions,
which control computers. These instructions are called
programs.
• Numerous programs exist, and they are created using different
kinds of programming languages. Only high level languages
used to create application programs. Such languages include
C#, Java, C++, PHP, Visual Basic, Python, Ruby, Perl,
JavaScript and others.
PREPARED BY HABIMANA 6
PATRICK
In this book we will take a look at the C# programming language
– a modern high level language.
Stages in Software Development
Writing software can be a very complex and time-
consuming task, involving a whole team of
software engineers and other specialists.
As a result, many methods and practices, which
make the life of programmers easier, have
emerged.
PREPARED BY HABIMANA 7
PATRICK
All they have in common is that the development of each software
product goes through several different stages:
- Gathering the requirements for the product and creating a task;
-Planning and preparing the architecture and design;
-Implementation (includes the writing of program code);
-Product trials (testing);
-Deployment and exploitation;
-Support.
PREPARED BY HABIMANA 8
PATRICK
Object-Oriented Programming
• Variables are named computer memory locations used
to hold values that may vary
• Operations are usually called or invoked to manipulate
variables
• A procedural program defines the variable memory
locations, then calls a series of procedures to input,
manipulate, and output the value stored in those
locations
• A single procedural program often contains hundreds of
variables and thousands of procedure calls
PREPARED BY HABIMANA 9
PATRICK
Object-Oriented Programming
• Object-oriented programming is an extension of
procedural programming, which in addition to variables
and procedures contains: objects, classes,
encapsulation, interfaces, polymorphism, and inheritance
• Objects are object-oriented components(real thing)
• Attributes of an object represent its characteristics
• A class is a category of objects or a type of object.
a class is an extensible program-code-template for
creating objects, providing initial values for state
(member variables) and implementations of behavior
(member functions or methods).
• An instance refers to an object based on a class
PREPARED BY HABIMANA 10
PATRICK
Object-Oriented Programming
• For example:
– An Automobile is a class whose objects have the following
attributes: year, make, model, color, and current running status
– Your 1997 red Chevrolet is an instance of the class that is made
up of all Automobiles
• Methods of classes are used to change attributes and
discover values of attributes
– The Automobile class may have the following methods:
getGas(), accelerate(), applyBreaks()
PREPARED BY HABIMANA 11
PATRICK
The C# Programming Language
• C# was developed as an object-oriented and
component-oriented language
• It exists as part of the Visual Studio .NET package
• C# (like Java) is modeled after the C++ programming
language
• Pointers are not used in C#
• C# does NOT require the use of object destructors,
forward declarations, or #include files
• It has the ability to pass by reference
• Multiple inheritance is not allowed in C#
PREPARED BY HABIMANA 12
PATRICK
Creating a console application Program
A console application, in the context of C#, is an application that
takes input and displays output at a command line
A C# program consists of the following parts:
Namespace declaration
A class
Class methods
Class attributes
A Main method
Statements and Expressions
Comments
PREPARED BY HABIMANA 13
PATRICK
Steps of Compiling and Executing the console application Program
If you are using Visual Studio.Net for compiling and executing C#
programs, take the following steps:
Start Visual Studio.
On the menu bar, choose File -> New -> Project.
Choose Visual C# from templates, and then choose Windows.
Choose Console Application.
Specify a name for your project and click OK button. This creates
a new project in Solution Explorer.
Write code in the Code Editor.
Click the Run button or press F5 key to execute the project.
PREPARED BY HABIMANA 14
PATRICK
A Command Prompt window appears that contains the line Hello
World.
Let us look at a simple code that prints the words "Hello World":
PREPARED BY HABIMANA 15
PATRICK
using System;
namespace HelloWorldApplication
{
class HelloWorld
{
static void Main(string[] args)
{
/* my first program in C# */
PREPARED BY HABIMANA 16
PATRICK
/* my first program in C# */
Console.WriteLine("Hello World");
Console.ReadKey();
}
}
}
When this code is compiled or run and executed, it produces the
following result:
Hello World.
Let us look at the various parts of the given program:
1. The first line of the program using System; - the using
keyword is used to include the System namespace in the
program. A program generally has multiple using statements.
PREPARED BY HABIMANA 17
PATRICK
2.The next line has the namespace declaration. what is
namespace?
A namespace is a collection of classes. The HelloWorld
Application namespace contains the class HelloWorld.
3.The next line has a class declaration, the class HelloWorld
contains the data and method definitions that your program uses.
Classes generally contain multiple methods.
Methods define the behavior of the class. However, the
HelloWorld class has only one method Main.
4.The next line defines the Main method, which is the entry point
for all C# programs. The Main method states what the class does
when executed.
5.The next line /*...*/ is ignored by the compiler and it is put to add
comments in the program.
PREPARED BY HABIMANA 18
PATRICK
6.The next line /*...*/ is ignored by the compiler and it is
put to add comments in the program.
7.The Main method specifies its behavior with the
statement Console.WriteLine("Hello World");
8. WriteLine is a method of the Console class defined in
the System namespace. This statement causes the
message "Hello, World!" to be displayed on the screen.
9.The last line Console.ReadKey(); is for the VS.NET
Users. This makes the program wait for a key press and
it prevents the screen from running and closing quickly
when the program is launched from Visual Studio .NET.
PREPARED BY HABIMANA 19
PATRICK
It is worth to note the following points:
1.C# is case sensitive.
2.All statements and expression must end with a semicolon (;).
3.The program execution starts at the Main method.
C# Distinguishes between Uppercase and
Lowercase!
The C# language distinguishes between uppercase and
lowercase letters so we should use the correct casing when we
write C# code.
Be careful when writing! The same thing, written in
uppercase, lower-case or a mix of both, means different
things in C#. Writing Class is different from class and
System.Console is different from SYSTEM.CONSOLE.
PREPARED BY HABIMANA 20
PATRICK
Writing a C# Program that Produces Output
• “This is my first C# program” is a literal string of
characters
• The string appears in parenthesis because it is a
parameter or an argument
• The WriteLine() method prints a line of output on the
screen
PREPARED BY HABIMANA 21
PATRICK
Writing a C# Program that Produces Output
• Out is an object that represents the screen
• The Out object was created and endowed with the
method WriteLine()
• Not all objects have the WriteLine() method
PREPARED BY HABIMANA 22
PATRICK
Writing a C# Program that Produces Output
• Console is a class
• Console defines the attributes of a collection of similar
“Console” objects
PREPARED BY HABIMANA 23
PATRICK
Writing a C# Program that Produces Output
• System is a namespace, which is a scheme that
provides a way to group similar classes
• Namespaces are used to organize classes
PREPARED BY HABIMANA 24
PATRICK
Writing a C# Program that Produces Output
• The difference between the above code and the previous
code is the amount of whitespace
• Both versions of code share the same method header
(including access modifiers and other keywords)
PREPARED BY HABIMANA 25
PATRICK
C# Variable Declaration(variable definition)
A variable is nothing but a name given to a storage area that
our programs can manipulate.
Each variable in C# has a specific type, which determines the
size and layout of the variable's memory the range of values
that can be stored within that memory and the set of
operations that can be applied to the variable.
The basic value types provided in C# can be categorized
as below:
PREPARED BY HABIMANA 26
PATRICK
The basic value types provided in C# can be categorized as:
Type Example
Integral types sbyte, byte, short, ushort, int, uint, long,
ulong, and char
Floating point float and double
types
Decimal decimal
types
Boolean true or false values, as assigned
types
Nullable Nullable data types
types
PREPARED BY HABIMANA 27
PATRICK
Defining(declare) Variables
syntax for variable definition in C# is:
<data_type> <variable_list>;
Here, data_type must be a valid C# data type including char, int,
float, double, or any user-defined data type, and variable_list may
consist of one or more identifier names separated by commas.
Some valid variable definitions are shown here −
int i, j, k;
char c, ch;
float f, salary;
double d;
PREPARED BY HABIMANA 28
PATRICK
you can initialize a variable at the time of definition as :
int i = 100;
Initializing Variables:
Variables are initialized (assigned a value) with an equal
sign followed by a constant expression. The general
form of initialization is :
variable_name = value;
Variables can be initialized in their declaration. The
initializer consists of an equal sign followed by a
constant expression as −
<data_type> <variable_name> = value;
PREPARED BY HABIMANA 29
PATRICK
Some examples are :
int d = 3, f = 5; /* initializing d and f. */
byte z = 22; /* initializes z. */
double pi = 3.14159; /* declares an approximation of pi. */
char x = 'x'; /* the variable x has the value 'x'. */
It is a good programming practice to initialize variables properly,
otherwise sometimes program may produce unexpected result.
The following example uses various types of variables:
PREPARED BY HABIMANA 30
PATRICK
using System;
namespace VariableDefinition {
class Program {
static void Main(string[] args) {
short a;
int b ;
double c;
/* actual initialization */
a = 10;
b = 20;
c = a + b;
Console.WriteLine("a = {0}, b = {1}, c = {2}", a, b, c);
Console.ReadLine();
}
}
}
PREPARED BY HABIMANA 31
PATRICK
When the above code is compiled and executed, it produces the
following result :
a = 10, b = 20, c = 30
Accepting Values from User
The Console class in the System namespace provides a function
ReadLine() for accepting input from the user and store it into a
variable.
For example,
int num;
num = Convert.ToInt32(Console.ReadLine());
The function Convert.ToInt32() converts the data entered by the
user to int data type, because Console.ReadLine() accepts the
data in string format.Let’s see the Example below:
PREPARED BY HABIMANA 32
PATRICK
Example1: Calculate the total of two numbers entered by user
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace calculateTotal{
class calculateSum
{
public static int Sum(int num1,int num2)
{
int total;
total = num1 + num2;
return total;
} 33
PREPARED BY HABIMANA PATRICK
static void Main() {
Console.Write("\n\n Function to calculate the sum of two
numbers: \n");
Console.Write("-------------------------------------------------\n");
Console.Write("Enter first number: ");
int n1 = Convert.ToInt32(Console.ReadLine());
Console.Write("Enter second number: ");
int n2 = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("\nThe sum of two numbers is: {0} \
n", Sum(n1, n2));
Console.ReadKey();
}
} 34
PREPARED BY HABIMANA PATRICK
Example2:a program
that displays names
entered from user
Let’s look below example:
PREPARED BY HABIMANA 35
PATRICK
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace concatenatestring
{ class combineStrings
{ public static string cocantenatename(string name1,string
name2)
{
string name;
name= name1 + name2;
return name;
} PREPARED BY HABIMANA
PATRICK
36
static void Main() {
Console.Write("\n\n Function TO CANCATENATE(COMBINE)
STRINGS: \n");
Console.Write("-------------------------------------------------\n");
Console.Write("Enter first name: ");
string n1 = Console.ReadLine();
Console.Write("\nEnter last name: ");
string n2 = Console.ReadLine();
Console.Write("\nMy name is: {0} \n", cocantenatename(n1," "
+n2));
Console.Write("\n\nPRESS ANY KEY TO EXIT \n\n\n");
Console.ReadKey();
}
}
} PREPARED BY HABIMANA 37
PATRICK
Selecting Identifiers
• Every method used in C# must be part of a class
• A C# class name or identifier must meet the basic
following requirements:
– An identifier must begin with an underscore or a letter
– An identifier can contain only letters or digits, not special
characters such as #,$, or &
– An identifier cannot be a C# reserved keyword
PREPARED BY HABIMANA 38
PATRICK
Selecting Identifiers
• The reserved public keyword is an access modifier
that defines the circumstance under which a class can
be accessed
PREPARED BY HABIMANA 39
PATRICK
Compiling and Executing a Program from
the Command Line
• A syntax error occurs when you introduce typing errors
into your program
• The C# compiler issues warnings as wells as errors
• If a syntax error occurs, you must reopen the source
code and make the necessary corrections.
PREPARED BY HABIMANA 40
PATRICK
Compiling and Executing a Program from
the Command Line
• Output of Hello Program
PREPARED BY HABIMANA 41
PATRICK
Adding Comments to a Program
• In large programs it becomes difficult to remember why
certain steps were included and the role of certain
variables and methods
• Program comments are nonexecuting statements that
you add to document a program
• You can also comment out various statements in a
program to debug and observe the effects of the
program with the statement or statements commented
out
PREPARED BY HABIMANA 42
PATRICK
Adding Comments to a Program
• There are three types of comments in C#:
– Line comments
– Block comments
– XML-documentation format
PREPARED BY HABIMANA 43
PATRICK
Compiling and Executing a Program Using
the Visual Studio IDE
• C# programs can also be written using the Visual Studio
IDE (instead of a text editor). This approach offers many
advantages including:
– Some of the code you need is already created for you
– The code is displayed in color, so you can more easily identify
parts of your program
– If error messages appear when you compile your program, you
can double-click on an error message and the cursor will move
to the line of code that contains the error
– Other debugging tools are available
PREPARED BY HABIMANA 44
PATRICK
Compiling and Executing a Program Using
the Visual Studio IDE
• Navigating to Visual Studio .NET
PREPARED BY HABIMANA 45
PATRICK
Compiling and Executing a Program Using
the Visual Studio IDE
• Creating a project
PREPARED BY HABIMANA 46
PATRICK
Compiling and Executing a Program Using
the Visual Studio IDE
• Selecting project options
PREPARED BY HABIMANA 47
PATRICK
Compiling and Executing a Program Using
the Visual Studio IDE
• The console application template
PREPARED BY HABIMANA 48
PATRICK
Compiling and Executing a Program Using
the Visual Studio IDE
• Output screen after compiling the Hello program
PREPARED BY HABIMANA 49
PATRICK
Compiling and Executing a Program Using
the Visual Studio IDE
• Output of the Hello program as run from the Visual
Studio IDE
PREPARED BY HABIMANA 50
PATRICK
Compiling and Executing a Program Using
the Visual Studio IDE
• List of Hello Program Files
PREPARED BY HABIMANA 51
PATRICK
Eliminating the Reference to Out by Using
the System Namespace
• A program may contain an unlimited number of
statements, as long as they are each terminated by a
semicolon
PREPARED BY HABIMANA 52
PATRICK
Eliminating the Reference to Out by Using
the System Namespace
• The Output of ThreeLines program
PREPARED BY HABIMANA 53
PATRICK
Eliminating the Reference to Out by Using
the System Namespace
• When you need to repeatedly use a class from the same
namespace, you can shorten statements by using the
“using” keyword
• Output is identical as the previous version of ThreeLines
PREPARED BY HABIMANA 54
PATRICK
Eliminating the Reference to Out by Using
the System Namespace
• An alias is an alternative name for a class
• An alias can be used to shorten a long class name (as in
the above example)
PREPARED BY HABIMANA 55
PATRICK
Chapter Summary
• A computer program is a set of instructions that you write
to tell a computer what to do
• Procedural Programming involves creating computer
memory locations, called variables, and a set of
operations, called procedures. In object-oriented
programming, you envision program components as
objects that are similar to concrete objects in the real
world
• The C# language was developed as an object-oriented
and component-oriented language
PREPARED BY HABIMANA 56
PATRICK
Chapter Summary
• To write a C# program that produces a line of console
output, you must pass a literal string as a parameter to
the System.Console.Out.WriteLine() method
• You can define a C# class or variable by using any name
or identifier that begins with an underscore or a letter,
that contains only letters or digits, and that is not a C#
reserved keyword
• To create a C# program, you can use the Microsoft
Visual Studio environment or any text editor
PREPARED BY HABIMANA 57
PATRICK
Chapter Summary
• After you write and save a program, you must compile
the source code
• Program comments are nonexecuting statements that
add to document a program or to disable statements
• As an alternative to using the command line, you can
compile and write your program within the Visual Studio
IDE
• When you need to repeatedly use a class from the same
namespace, you can shorten the statements you type by
using a clause that indicates a namespace where the
class can be found
PREPARED BY HABIMANA 58
PATRICK