0% found this document useful (0 votes)
4 views

SG2-IPT-101

Module 2 of IPT 101 covers the basics of the C# programming language, focusing on syntax, variables, input/output operations, and control structures. Students will learn to write and execute interactive console programs, understand variable declaration and initialization, and utilize various operators and conditional statements. The module aims to equip students with foundational programming skills necessary for developing C# applications.

Uploaded by

manahancj16
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

SG2-IPT-101

Module 2 of IPT 101 covers the basics of the C# programming language, focusing on syntax, variables, input/output operations, and control structures. Students will learn to write and execute interactive console programs, understand variable declaration and initialization, and utilize various operators and conditional statements. The module aims to equip students with foundational programming skills necessary for developing C# applications.

Uploaded by

manahancj16
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 11

Study Guide in IPT 101 (Integrative Programming and Technologies) Module 2 – Basics of C# Programming Language

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

At the end of the module, the student is expected to:


1. Understand the basic structure and components of the C# Programming language
2. Write and execute an interactive C# program
3. Design and develop a program applying these constructs

LEARNING CONTENTS

Primitive Types and Variable

• 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

A. Declaring and Initializing a variable in two statements


Syntax Example

type variableName; int counter;


variableName = value; counter = 1;

PANGASINAN STATE UNIVERSITY 1


Study Guide in IPT 101 (Integrative Programming and Technologies) Module 2 – Basics of C# Programming Language

B. Declaring and Initializing in one statement

Syntax Example

type variableName = value; int counter = 1;


float interestRate = 8.125f
//f or F indicates a float value
bool valid = false;

C. Declaring and initializing a constant


- A constant stores values that cannot be changed.

Syntax Example

const type ConstantName = value; const double pi = 3.1416


const double tax = .075

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)

PANGASINAN STATE UNIVERSITY 2


Study Guide in IPT 101 (Integrative Programming and Technologies) Module 2 – Basics of C# Programming Language

partial
remove select set
(method)

Standard Input and Output


A. Console
- The Console is a window of the operating system through which users can interact with system
programs of the operating system or with other console applications.
- The interaction consists of text input from the standard input (usually keyboard) or text display
on the standard output (usually on the computer screen).
- These actions are also known as input-output operations.

B. Using Console.Write(…) and Console.WriteLine(…)


- Work with these methods is easy because they can print all the basic types
(string, numeric and primitive types).
- Here are some examples of printing various types of data:

// Print String
Console.WriteLine("Hello World");
// Print int
Console.WriteLine(5);
// Print double
Console.WriteLine(3.14159265358979);

The result of this code execution


looks like this:

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

C. Reading through Console.ReadLine()


- The method Console.ReadLine() provides great convenience for reading from console.
- The method Console.ReadLine() returns as result the string entered by the user.
- The following example demonstrates the operation of Console.ReadLine():

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);
}
}

PANGASINAN STATE UNIVERSITY 3


Study Guide in IPT 101 (Integrative Programming and Technologies) Module 2 – Basics of C# Programming Language

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

Operators and Expressions


- An operator is a symbol that tells the compiler to perform specific mathematical or logical
manipulations. C# has rich set of built-in operators and provides the following type of operators:
a. Arithmetic Operators
b. Relational Operators
c. Logical Operators
d. Miscellaneous Operators

A. Arithmetic Operators

Following table shows all the arithmetic operators supported by C#. Assume variable A holds 10
and variable B holds 20 then:

Operator Description Example


+ Adds two operands A + B = 30
- Subtracts second operand from the first A - B = -10
* Multiplies both operands A * B = 200
/ Divides numerator by de-numerator B/A=2
Modulus Operator and remainder of after an integer
% B%A=0
division
++ Increment operator increases integer value by one A++ = 11
-- Decrement operator decreases integer value by one A-- = 9

Example:

PANGASINAN STATE UNIVERSITY 4


Study Guide in IPT 101 (Integrative Programming and Technologies) Module 2 – Basics of C# Programming Language

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:

Operator Description Example


Called Logical AND operator. If both the operands are non-zero,
&& (A && B) is false.
then condition becomes true.
Called Logical OR Operator. If any of the two operands are non-
|| (A || B) is true.
zero, then condition becomes true.
Called Logical NOT Operator. Use to reverses the logical state of
! its operand. If a condition is true, then Logical NOT operator will !(A && B) is true.
make false.

D. Miscellaneous Operators

PANGASINAN STATE UNIVERSITY 5


Study Guide in IPT 101 (Integrative Programming and Technologies) Module 2 – Basics of C# Programming Language

There are few other important operators including sizeof, typeof and ? : supported by C#.

Operator Description Example


sizeof() Returns the size of a data type. sizeof(int), returns 4.
typeof() Returns the type of a class. typeof(StreamReader);
&a; returns actual address of
& Returns the address of a variable.
the variable.
*a; creates pointer named ‘a’
* Pointer to a variable.
to a variable.
If Condition is true ? Then
?: Conditional Expression
value X : Otherwise value Y
If( Ford is Car) // checks if
Determines whether an object is of a
is Ford is an object of the Car
certain type.
class.
Object obj = new
Cast without raising an exception if the StringReader("Hello");
as
cast fails. StringReader r = obj as
StringReader;

Example. Execute the code below to see how these operators work.

using System;
namespace OperatorsAppl{
class Program{
static void Main(string[] args) {

/* example of sizeof operator */


Console.WriteLine("The size of int is {0}", sizeof(int));
Console.WriteLine("The size of short is {0}", sizeof(short));
Console.WriteLine("The size of double is {0}", sizeof(double));
/* example of ternary operator */

int a, b;
a = 10;

b = (a == 1) ? 20 : 30;

Console.WriteLine("Value of b is {0}", b);

b = (a == 10) ? 20 : 30;

Console.WriteLine("Value of b is {0}", b);

Console.ReadLine();

}
}

Control Structures I – Conditional Statements

- Conditional statements if and if-else are conditional control statements


A. Conditional Statement "if"
- The main format of the conditional statements if is as follows:

PANGASINAN STATE UNIVERSITY 6


Study Guide in IPT 101 (Integrative Programming and Technologies) Module 2 – Basics of C# Programming Language

if (Boolean expression)
{
Body of the conditional statement;
}

- It includes: if-clause, Boolean expression, and body of the conditional statement.


- The Boolean expression can be a Boolean variable or Boolean logical expression. Boolean
expressions cannot be integer (unlike other programming languages like C and C++).
- The body of the statement is the part locked between the curly brackets: {}. It may consist of
one or more operations (statements).

if (amount <= balance){


balance = balance - amount;
}
Console.WriteLine("End of Transaction");
// print statement executed unconditionally

B. Conditional Statement "if-else"


if (Boolean expression {
Body of the conditional statement;
}else{
Body of the else 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(amount <= balance){


balance = balance - amount;
}else{
balance = balance – penalty;
}
Console.WriteLine("End of Transaction");
// print statement executed unconditionally

C. The if...else if...else Statement


- An if statement can be followed by an optional else if...else statement, which is very useful to
test various conditions using single if...else if statement.
- When using if, else if and else statements there are few points to keep in mind.
a. An if can have zero or one else's and it must come after any else if's.
b. An if can have zero to many else if's and they must come before the else.
c. Once an else if succeeds, none of the remaining else if's or else's will be tested.
d. The syntax of an if...else if...else statement in C# is:

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 */
}

- Here is an example implementation:

PANGASINAN STATE UNIVERSITY 7


Study Guide in IPT 101 (Integrative Programming and Technologies) Module 2 – Basics of C# Programming Language

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

/* local variable definition */


char grade = 'B';
switch (grade){
case 'A':
Console.WriteLine("Excellent!");
break;
case 'B':
case 'C':
Console.WriteLine("Well done");
break;
case 'D':
Console.WriteLine("You passed");
break;
case 'F':
Console.WriteLine("Better try again");
break;
default:
Console.WriteLine("Invalid grade");
break;
}
Console.WriteLine("Your grade is {0}", grade);
Console.ReadLine();
When the above code is compiled and executed, it

PANGASINAN STATE UNIVERSITY 8


Study Guide in IPT 101 (Integrative Programming and Technologies) Module 2 – Basics of C# Programming Language

produces the following result:

Well done
Your grade is B

Control Structures II – Loops


- A loop statement allows us to execute a statement or a group of statements multiple times.
- C# provides following types of loop to handle looping requirements.

Loop Type Description


It repeats a statement or a group of
statements while a given
while loop condition is true. It tests the
condition before executing the loop
body.
It executes a sequence of
statements multiple times and
for loop
abbreviates the code that manages
the loop variable.
It is like a while statement, except
do...while loop that it tests the
condition at the end of the loop body

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);
}

- Here, statement(s) may be a single statement or a block of statements.


- The condition may be any expression, and true is any non-zero value. The loop iterates while
the condition is true.
- When the condition becomes false, program control passes to the line immediately following the
loop
- Here is an implementation of ‘while’ loop:

/* local variable definition */


int a = 10;

/* while loop execution */


while (a < 20)
{
Console.WriteLine("value of a: {0}", a);
a++;
}
Console.ReadLine();
When the above code is compiled and executed, it
produces the following result:

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

PANGASINAN STATE UNIVERSITY 9


Study Guide in IPT 101 (Integrative Programming and Technologies) Module 2 – Basics of C# Programming Language

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:

for (init; condition; increment)


{
statement(s);
}

- Here is the sample implementation of the ‘for’ loop:


/* for loop execution */
for (int a = 10; a < 20; a = a + 1)72
{
Console.WriteLine("value of a: {0}", a);
}
Console.ReadLine();
When the above code is compiled and executed, it
produces the following result:

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

C. Do…. While loop


- Unlike for and while loops, which test the loop condition at the start of the loop, the do...while
loop checks its condition at the end of the loop.
- A do...while loop is like a while loop, except that a do...while loop is guaranteed to execute at
least one time.

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:

/* local variable definition */


int a = 10;
/* do loop execution */
do
{
Console.WriteLine("value of a: {0}", a);
a = a + 1;

PANGASINAN STATE UNIVERSITY 10


Study Guide in IPT 101 (Integrative Programming and Technologies) Module 2 – Basics of C# Programming Language

} while (a < 20);


Console.ReadLine();
When the above code is compiled and executed, it
produces the following result:

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)

PANGASINAN STATE UNIVERSITY 11

You might also like