SG2-IPT-101
SG2-IPT-101
Module No.2
MODULE TITLE
BASICS OF C# PROGRAMMING LANGUAGE
MODULE OVERVIEW
This module discussed the basic syntax and structure of a C# program. It also provides a discussion on using
variables, displaying output, and accepting input from a console and control structures. At the end of the
module, the student should be able to write and execute a dynamic console program using C#.
LEARNING OBJECTIVES
LEARNING CONTENTS
• A typical program uses various values that change during its execution.
• A variable stores a value that can change as the program executes.
• Before you can use a variable, you must declare its data type and name and then initialize it by
assigning a value to it.
Primitive C# Types
Syntax Example
Syntax Example
D. Naming conventions
- Start the names of variables with lowercase letter and capitalize the first letter of each word
after the first word. This is called ‘camel notation’
- Capitalize the first letter of each word of a constant name. This is known as ‘Pascal notation’
- A name must begin with a letter that could be followed by a sequence of letters, digits (0 - 9) or
underscore. The first character in an identifier cannot be a digit.
- It must not contain any embedded space or symbol such as ? - +! @ # % ^ & * ( ) [ ] { } . ; : " ' /
and \. However, an underscore ( _ ) can be used.
- It should not be a C# keyword.
C# Keywords
-Keywords are reserved words predefined to the C# compiler. These keywords cannot be used
as identifiers. However, if you want to use these keywords as identifiers, you may prefix the
keyword with the @ character.
- In C#, some identifiers have special meaning in context of code, such as get and set
are called contextual keywords.
- The following table lists the reserved keywords and contextual keywords in C#:
Reserved Keywords
abstract as base bool break byte case
catch char checked class const continue decimal
default delegate do double else enum event
explicit extern false finally fixed float for
in (generic
foreach goto if implicit In int
modifier)
interface internal is lock long namespace new
out
null object operator out (generic override params
modifier)
private protected public readonly ref return sbyte
sealed short sizeof stackalloc static string struct
switch this throw true try typeof uint
ulong unchecked unsafe ushort using virtual void
volatile while
Contextual Keywords
add alias ascending descending dynamic from get
partial
global group into join let orderby
(type)
partial
remove select set
(method)
// Print String
Console.WriteLine("Hello World");
// Print int
Console.WriteLine(5);
// Print double
Console.WriteLine(3.14159265358979);
Hello World
5
3.14159265358979
- The difference between Write(…) and WriteLine(…) is that the Write(…) method prints on the
console what it is provided between the parentheses but does nothing in addition while the
method WriteLine(…) means directly “write line”. This method does what the Write(…) one does
but in addition goes to a new line.
- Additional Readings: Outputs can be formatted using WriteLine. You can read the
discussion on output formatting in Svetlin Nakov & Co. (2013). Fundamentals of
Computer Programming with C#. Svetlin Nakov & Co. page 174 – 183
UsingReadLine.cs
class UsingReadLine{
static void Main(){
Console.Write("Please enter your first name: ");
string firstName = Console.ReadLine();
Console.Write("Please enter your last name: ");
string lastName = Console.ReadLine();
Console.WriteLine("Hello, {0} {1}!", firstName, lastName);
}
}
D. Reading Numbers
- Reading numbers from the console in C# is not done directly.
- To read a number we should have previously read the input as a string (using ReadLine()) and
then convert this string to a number.
- The operation of converting a string into another type is called parsing.
- All primitive types have methods for parsing.
- We will give a simple example for reading and parsing of numbers:
ReadingNumbers.cs
class ReadingNumbers{
static void Main(){
Console.Write("a = ");
int a = int.Parse(Console.ReadLine());
Console.Write("b = ");
int b = int.Parse(Console.ReadLine());
Console.WriteLine("{0} + {1} = {2}", a, b, a + b);
Console.WriteLine("{0} * {1} = {2}", a, b, a * b);
Console.Write("f = ");
double f = double.Parse(Console.ReadLine());
Console.WriteLine("{0} * {1} / {2} = {3}",a, b, f, a * b / f);
}
}
The result of program execution might be as follows (if we enter 5, 6 and
7.5 as input):
a = 5
b = 6
5 + 6 = 11
5 * 6 = 30
f = 7.5
5 * 6 / 7.5 = 4
A. Arithmetic Operators
Following table shows all the arithmetic operators supported by C#. Assume variable A holds 10
and variable B holds 20 then:
Example:
using System;
namespace OperatorsAppl{
class Program{
static void Main(string[] args){
int a = 21;
int b = 10;
int c;
c = a + b;
Console.WriteLine("Line 1 - Value of c is {0}", c);
c = a - b;
Console.WriteLine("Line 2 - Value of c is {0}", c);
c = a * b;
Console.WriteLine("Line 3 - Value of c is {0}", c);
c = a / b;
Console.WriteLine("Line 4 - Value of c is {0}", c);
c = a % b;
Console.WriteLine("Line 5 - Value of c is {0}", c);
c = a++;
Console.WriteLine("Line 6 - Value of c is {0}", c);
c = a--;
Console.WriteLine("Line 7 - Value of c is {0}", c);
Console.ReadLine();
}
}
}
B. Relational Operators
Following table shows all the relational operators supported by C#. Assume variable A holds 10 and
variable B holds 20, then:
Operator Description Example
Checks if the values of two operands are equal or not, if yes then
== (A == B) is not true.
condition becomes true.
Checks if the values of two operands are equal or not, if values
!= (A != B) is true.
are not equal then condition becomes true.
Checks if the value of left operand is greater than the value of right
> (A > B) is not true.
operand, if yes then condition becomes true.
Checks if the value of left operand is less than the value of right
< (A < B) is true.
operand, if yes then condition becomes true.
Checks if the value of left operand is greater than or equal to the
>= (A >= B) is not true.
value of right operand, if yes then condition becomes true.
Checks if the value of left operand is less than or equal to the
<= (A <= B) is true.
value of right operand, if yes then condition becomes true.
C. Logical Operators
Following table shows all the logical operators supported by C#. Assume variable A holds Boolean value
true and variable B holds Boolean value false, then:
D. Miscellaneous Operators
There are few other important operators including sizeof, typeof and ? : supported by C#.
Example. Execute the code below to see how these operators work.
using System;
namespace OperatorsAppl{
class Program{
static void Main(string[] args) {
int a, b;
a = 10;
b = (a == 1) ? 20 : 30;
b = (a == 10) ? 20 : 30;
Console.ReadLine();
}
}
if (Boolean expression)
{
Body of the conditional statement;
}
- If the Boolean expression is calculated to false, the else-body is executed, the main body of the
conditional statement is omitted and the operators in it are not executed.
- Example implementation
if(boolean_expression 1) {
/* Executes when the boolean expression 1 is true */
} else if( boolean_expression 2){
/* Executes when the boolean expression 2 is true */
}else if( boolean_expression 3){
/* Executes when the boolean expression 3 is true */
}else{
/* executes when the none of the above condition is true */
}
if (num == 1)
{
Console.WriteLine("One");
}
else if (num == 2)
{
Console.WriteLine("Two");
}
else if (num == 3)
{
Console.WriteLine("Three");
}
else
{
Console.WriteLine("Other number");
}
D. Switch Statement
- A switch statement allows a variable to be tested for equality against a list of values.
- Each value is called a case, and the variable being switched on is checked for each switch
case.
switch(expression){
case constant-expression:
statement(s);
break; /* optional */
case constant-expression:
statement(s);
break; /* optional */
/* you can have any number of case statements */
default: /* Optional */
statement(s);
}
- Here is a sample implementation of switch statement
Well done
Your grade is B
A. While Loop
- A while loop statement in C# repeatedly executes a target statement if a given condition is true.
Syntax
The syntax of a while loop in C# is:
while(condition)
{
statement(s);
}
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 15
value of a: 16
value of a: 17
value of a: 18
value of a: 19
B. For Loop
- A for loop is a repetition control structure that allows you to efficiently write a loop that needs to
execute a specific number of times.
Syntax
The syntax of a for loop in C# is:
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 15
value of a: 16
value of a: 17
value of a: 18
value of a: 19
Syntax
The syntax of a do..while loop in C# is:
do
{
statement(s);
}while(condition);
- The statement(s) in the loop execute once before the condition is tested.
- If the condition is true, the flow of control jumps back up to do, and the statement(s) in the loop
execute again. This process repeats until the given condition becomes false.
- Here is an example implementation of the do-while loop:
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 15
value of a: 16
value of a: 17
value of a: 18
value of a: 19
• Additional Readings: Nested conditional statements and loops can be found in the following
references:
- Svetlin Nakov & Co. (2013). Fundamentals of Computer Programming with C#. Svetlin Nakov &
Co. page 204 – 205 and page 226 – 227.
- Tutorialspoint. (2014). C# Programming: Object Oriented Programming.
www.tutorialspoint.com. Page 58 – 63 and page 75 - 77
LEARNING POINTS
• A typical program uses various values that change during its execution.
• Before you can use a variable, you must declare its data type and name and then initialize it by
assigning a value to it.
• Keywords are reserved words predefined to the C# compiler.
• Write and WriteLine displays output to the screen while ReadLine will allow user to enter for an
input.
• Data entered using ReadLine are treated string and needs to be converted to another type.
• Parsing is a process of converting data from one type to another
• There are 4 groups of operators that can be used in writing expressions.
LEARNING ACTIVITIES
1. Write an if-statement that takes two integer variables and exchanges their values if the first one is
greater than the second one.
2. Write a program that applies bonus points to given scores in the range [1…9] by the following rules:
- If the score is between 1 and 3, the program multiplies it by 10.
- If the score is between 4 and 6, the program multiplies it by 100.
- If the score is between 7 and 9, the program multiplies it by 1000.
- If the score is 0 or more than 9, the program prints an error message.
3. Write a program that prints on the console the numbers from 1 to N, which are not divisible by 3 and
7 simultaneously. The number N should be read from the standard input.
4. Write a program that converts a given number from decimal to hexadecimal notation.
5. Write a program that given two numbers finds their greatest common divisor (GCD) and their least
common multiple (LCM). You may use the formula LCM(a, b) = |a*b| / GCD(a, b).
REFERENCES
A. Broehm, A., & Murach, J. (2016). Murach’s C# 2015. Mike Murach & Associates, Inc.
B. Svetlin Nakov & Co. (2013). Fundamentals of Computer Programming with C#. Svetlin Nakov & Co.
C. Troelsen, A., & Japikse, P. (2017). Pro C# 7 With .NET and .NET Core, 8e. Minneapolis,
Minnesota, USA: Apress.
D. Tutorialspoint. (2014). C# Programming: Object Oriented Programming. www.tutorialspoint.com.
E. Ateneo De Manila University Lecture Slide 6 (Decision) and Slide 7 (Loops)