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

Computer Programming 1 Module Final 2024-2025 -First Year

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
18 views

Computer Programming 1 Module Final 2024-2025 -First Year

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 129

Excellence | Service | Leadership and Good Governance | Innovation | Social Responsibility | Integrity | Professionalism | Spirituality

IT103 & 103L- Computer Programming 1


Course Module
First Semester AY: 2024-2025

Rosemarie Y. Saligue, MSIT


Subject Instructor

1
Course Overview
Course Code IT103 & 103L

Descriptive Title Computer Programming 1

Credit Units 2 units Lecture and 1 unit Laboratory

School Year/ Term AY 2024-2025/ 1st Semester

Mode of Delivery Online/ Offline Learning

Name of Instructor Rosemarie Y. Saligue, MSIT

This course allows the students to learn and apply the art and style of
procedural programming to solve computational problems adhering to the
Course Description standards and guidelines of documentation. It includes discussion on I/O
statements, loop and branching instruction, and creating functions and
procedures using Visual C#.net.

At the end of the module, you must have:

1. Analyze simple problems and propose solutions that satisfy specified


requirements using C# programming language
Course Outcomes 2. Adopt an appropriate coding standard with proper documentation in
order to come up with a logically correct program.
3. Implement, test and debug a computer program that integrates
appropriate programming solution that meets the specified needs and
requirements.

By 2040, Southern Leyte State University is a leading higher education


institution that advances knowledge and will be known for innovation
SLSU Vision
and compassion for humanity, creating an inclusive society and a suitable
world

We commit to be smart and green University that advances education,


technological and professional instruction, research and innovation,
community engagement services and progressive leadership in arts, sciences
SLSU Mission
and technology that are relevant to the needs of the glocal communities. We
produce graduates and life-long learners equipped with knowledge that
enhance lives and invigorates economic development.

2
Module Guide

This module was prepared for you to work on diligently and independently. Remember, the key to
successfully finish this module lies in your hands. To get the most from this module, you need to do the
following:

1. Understand the objective. Begin by thoroughly reading and comprehending the Course Outcomes
and the Learning Outcomes for each unit. These will provide you with a clear understanding of what
knowledge and skills you should acquire by the end of this module.
2. Time management. Develop effective strategies to manage your time and balance the activities of
this module with your other courses. Create a schedule and allocate sufficient time to read and
understand each part of the module. Repeat the readings until you grasp the main points. Avoid
asking questions that are already addressed in the provided guide.
3. Be resourceful. If you encounter difficulties in understanding the readings or completing other tasks,
make use of available resources. Revisit the readings and concentrate on comprehension. If
necessary, seek assistance from family members. If further assistance is still required, please reach
out to me via text message so that I can offer support over a call or through further messaging.
Note: Remember that you are the primary learner, and it is your responsibility to engage with the
module. While your family members and friends at home can offer support, the activities must be
completed by you.
4. Strive for excellence. Aim for the highest standards when undertaking both formative and summative
assessment tasks. Do not settle for subpar results; always strive for the highest quality in completing
your assigned tasks.
5. Avoid skipping. Ensure that you do not miss any activities, whether they are formative or summative
assessments. Complete all the required learning activities as directed.
6. Provide precise answers. Whenever possible, respond to tasks with accuracy. Therefore, carefully
read the instructions to ensure that you follow them correctly. Similarly, attentively read the
questions to make informed decisions and select the correct answers.
Note: Write your responses neatly and legibly on the module. Ensure that your answers are complete,
concise, and composed of grammatically correct sentences. Avoid using abbreviations and acronyms
unless they have been introduced in the readings. Refrain from using text-speak. Avoid writing in all
capital letters. For essay-type answers, please refer to the attached rubric for evaluation.
7. Submit on time. Avoid procrastination, as it hampers proper work completion. Allocate ample time
to complete the tasks assigned by this subject, ensuring timely submission. Once I receive your
materials, I will promptly notify you.
8. Exercise patience. I will provide feedback on your work to ensure that you are on the right track.
While waiting for the feedback on your completed modules, continue progressing through the tasks
in the subsequent units of the module, as scheduled
for the finals.

By following the guidelines above, surely you will be able to accomplish all the required tasks in this
module.

3
TABLE OF CONTENTS

Page
Title Page 1
Course Overview 2
Module Guide 3
Table of Contents 4
Module 1- Basic Structure of C# Programming 7
Unit 1- Basic Structure of C# Programming 8
C# Console Environment 8
Basic Concept of C# 9
Output Statement 11
Write() and WriteLine() 12
Escape Sequence Character 13
Self-Assessment 14
Programming Exercises 16
Unit 2- Data Types and Variables 17
C# Data Types 17
Defining Variables 18
Variable Declaration 19
Variable Initialization 19
C# Identifiers 21
C# Keywords 21
Naming Convention 21
Data Types Conversion 22
Self-Assessment 24
Programming Exercises 26
Unit 3- Input Statement 27
ReadLine() 27
Self-Assessment 30
Programming Exercises 31
Module 2- Fundamentals of Designing Console Displays 32
Unit 1- Set Cursor Positioning 33
Self-Assessment 36
Programming Exercise 37
Unit 2- Set Window Size 38
Self-Assessment 40
Programming Exercise 41
Unit 3- Set Background and Foreground Color 42
Self-Assessment 44
Programming Exercises 45
Module 3- Working with Strings 46
Unit 1- String Concatenation 47

4
Self-Assessment 49
Programming Exercises 50
Unit 2- String Interpolation 51
Self-Assessment 52
Programming Exercises 53
Unit 3- String Formatting 54
Self-Assessment 56
Programming Exercises 56
Module 4- Working with Numbers 57
Unit 1- Assignment Operator & Arithmetic Operator 58
Self-Assessment 62
Programming Exercise 63
Unit 2- Common Compound Assignment Operator & Operator Precedence 64
Self-Assessment 67
Programming Exercise 68
Unit 3-Relational Operator & Logical Operator 69
Self-Assessment 72
Unit 4- Unary Operator & Ternary Operator 73
Self-Assessment 76
Programming Exercise 77
Module 5- Decision Making Statements 78
Unit 1- Algorithm and Flowchart 79
Self-Assessment 81
Unit 2- if Statements 82
Self-Assessment 93
Programming Exercises 96
Unit 3- Switch Statement 98
Self-Assessment 103
Programming Exercise 104
Module 6- Looping Statements 105
Unit 1- For loop Statement 106
Self-Assessment 112
Programming Exercise 112
Unit 2- While loop Statement 113
Self-Assessment 115
Programming Exercise 115
Unit 3- do…while loop 116
Self-Assessment 119
Programming Exercise 119
Unit 4- Goto Statement 120
Self-Assessment 122
Programming Exercise 122
Module 7- Array 123

5
Unit 1. Single Dimensional Array 124
Self-Assessment 127
Programming Exercise 128
References 129

6
MODULE 1
Basic Structure of C# Programming

This module consists of three Units. Unit 1 introduces the basic structure of C# Programming. Unit 2
explores the data types and variables, while Unit 3 delves into the input statements.

It's crucial to remember that most modules conclude with an evaluation, or a series of assessments,
as you progress through the module. Before proceeding to the next section of the course, make sure you
give them enough time to be finished.

And lastly, remember to have fun during the whole educational process. Enjoy yourselves!

You are now embarking on a journey filled with valuable experiences and
enriching learning opportunities. Engage in the exercises and respond to the
suggested worksheets to immerse yourself in a lifelong journey of practical
learning that awaits you upon completing this module.

ENJOY YOUR JOURNEY!

7
Unit 1 BASIC STRUCTURE OF C# PROGRAMMING

At the end of this module, the students should be able to:


a. Become familiar with the features and capabilities of the .Net Framework and
its integrated development environment (IDE).
b. Identify the basics of the C# programming language, including its syntax,
keywords, and structure.
c. Utilize the basic tools and development environment for writing and running
C# programs.

Basic Structure of C# Programming

C Sharp, often articulated as "C#," is a programming language that adheres to the object-oriented
model. This programming language can be employed to design any applications either web
application, desktop applications, mobile apps, games, or etc. Anders Hejlsberg and his team
developed it while working on the Microsoft .Net Framework. The .Net framework offers an
empowering environment for crafting diverse types of web and windows-based applications. It has
been architected to facilitate access for multiple programming languages, such as C#, C++, and Visual
Basic, allowing for seamless communication between these languages and the framework.

C# Console Environment

In this instance, the 2022 version of Visual Studio is utilized, but earlier versions are also suitable. To
initiate a Visual Studio C# (2022) Console application, simply click the Visual Studio Application twice
and generate a fresh project. Choose the .Net Framework Console App and click on the "Next" button
to proceed.

Figure 1. C# console create a new project layout

8
Enter a name for the project and specify or browse the location where you want to save the file.
Finally, click the "Create" button.

Figure 2. Creating a new project

Once you have clicked the "Create" button, you are now set and prepared to start coding. This means
that you can now proceed to write and run code in your C# console application.

Basic Concept of C#

As a beginner in C# programming, it is important to understand the basic concepts that make up a C#


program, such as namespaces, classes, methods/functions, data members, keywords, statements,
and expressions. Familiarizing yourself with these concepts will lay a foundation for creating high-
quality programs in the future.

Figure 3. C# console programming coding area

A C# program consists of using directive, namespace declaration, a class declaration, class methods,
a main method, comments and statement, and expression.

9
The code below is the basic structure of C#.

1. Using
2. Namespace
Directive
Declaration
3. Class Declaration
4.
4. Main Method
5. Comment

6. Statements and Expressions

1. Using Directive
To refer to the C# library or namespace, the 'using' keyword is utilized, which guides the
compiler to incorporate the object code from the library required for the program. For
instance, in the program, 'ReadKey' and 'WriteLine' functions interpret their significance from
the System namespace, which is one of the numerous built-in code libraries in C#. Apart from
System, C# has several other code libraries, such as mathematical and graphics libraries, for
which you can include additional using directives.
2. Namespace Declaration
To organize code and group related classes and types, namespaces are employed. By using
namespaces, programmers can classify their code effectively and prevent naming conflicts
with other code that may be present in the same project or larger codebase. For instance, in
your provided example, the programmer has utilized the "ProgrammingApplication"
namespace and included the "WelcomeProgramming" class within it. This approach enables
the programmer to access the "WelcomeProgramming" class in a structured and systematic
manner, while also ensuring that the class name does not conflict with any other class names
used in the program.
3. Class Declaration
Every console application must have a start-up class, which is a class that contains a "Main()"
method. In this application, the start-up class is called "WelcomeProgramming". It
encompasses the data and method definitions that the program uses. Generally, classes
consist of multiple methods or functions that specify the behavior of the class by performing
a particular task. However, in the case of the "WelcomeProgramming" class, it comprises only
one method, which is Main.
4. Main Method
The "main" method serves as the program's starting point. It is the initial code that runs
when the program is executed. Typically, the main method contains the program's logic and
invokes other methods as required. It's worth noting that a program can have only one Main
method.

10
5. Comments
Comments in the code offer human-readable explanations and annotations. Comments have
no impact on the program;s performance and ignored by the compiler. The "//" symbol is
use for a single line comment, and "/*…*/" is use in a multi-line comment.
6. Statements and Expressions
The behavior of the Main method is defined by the use of the Console.WriteLine("Welcome
Programming!"); and Console.ReadKey(); statements. The Console class, which is part of the
System namespace, has a WriteLine() method that is utilized to output text, in this case
displaying "Welcome Programming!".
Additionally, the ReadKey() method from the Console class is utilized to prevent the screen
from closing immediately after the program is launched, as it requires a key press before
ending. In the event that the "using System" line is left out, the compiler won't be able to
identify the Console class or its methods, namely, WriteLine() and ReadKey().
C# is a case-sensitive language, implying that "myclass" and "MyClass" are distinct.
Therefore, it's crucial to be aware of the letter case while coding in C#.
Semicolons are necessary at the end of statements and expressions, with the exception of
comments, namespace declarations, class headers, and function headers.
Curly braces, indicated by {} are utilized to specify the beginning and end of a code block.

Output Statement
In C#, WriteLine() is the most frequently used technique for displaying output, but Write() can also
be used. The key difference is that WriteLine() outputs the text on a new line each time, whereas
Write() outputs the text on the same line.
Sample Code for WriteLine():
using System;
namespace ProgrammingApplication
{
class OutputStatement
{
static void Main(string[] args)
{
Console.WriteLine("Hello Philippines!");
Console.WriteLine("Hello San Juan!");
Console.ReadKey();
}
}
}
Output:

Hello Philippines!
Hello San Juan!
_

11
The code shows that the subsequent statement in WriteLine() will produce output that appears on a
new line. The output demonstrates that "Hello San Juan!" and "Hello Philippines!" are displayed on
separate lines, and the cursor is also on a new line, due to the usage of Console.WriteLine().

Sample Code for Write():


using System;
namespace ProgrammingApplication
{
class OutputStatement
{
static void Main(string[] args)
{
Console.Write("Hello Philippines!");
Console.Write("Hello San Juan!");
Console.ReadKey();
}
}
}

Output:

Hello Philippines!Hello San Juan!_

The code demonstrates that the following statement in Write() will result in output that is
displayed on the same line. The output shows that "Hello San Juan!", "Hello Philippines!", and its
cursor are all displayed on the same line because Console.Write() was used.
To gain a deeper understanding of this topic, let's examine the two statements, Write() and
WriteLine().

Sample Code combination of Write() and WriteLine():


using System;
namespace ProgrammingApplication
{
class OutputStatement
{
static void Main(string[] args)
{
Console.Write("Hello Philippines!");
Console.WriteLine("Hello San Juan!");
Console.ReadKey();
}
}
}

Output:

Hello Philippines!Hello San Juan!


_

12
As demonstrated by the code, "Hello Philippines!" uses the Write() output statement, which means
that the next statement will be printed on the same line as "Hello Philippines". On the other hand,
"Hello San Juan!" uses the WriteLine() output statement, causing the cursor to be positioned on a
new line.

ESCAPE SEQUENCE CHARACTER

Escape
sequence Description
character
\n Cursor advances to the next line; like pressing the enter key
\t Cursor advances to the next horizontal tab stop
\” Double quote is printed
\’ Single quote is printed
\\ Backslash is printed
\a Alert signal (short beep) is sounded

The table shown above illustrate the use of string literals in the WriteLine() or Write() method. The
value that you want to display is placed inside the parenthesis. If you want to display a string literal,
enclose the text with double quotes and for single character enclose it with single or double quotes.
An exception occurs when an escape character is included. The backslash (‘\’) is called the escape
character. The escape character is combined with one or more characters to create a special escape
sequence, such as ‘\n’ to represent advance to next line, and ‘\t’ for a tab indention.
Sample Code for string literals:
using System;
namespace ProgrammingApplication
{
class EscapeSequence
{
static void Main(string[] args)
{
Console.Write("\"Hello Philippines!\"");
Console.Write("\nHello\t\t San \nJuan!");
Console.ReadKey();
}
}
}

Output:

"Hello Philippines!"
Hello San
Juan!
Exercises

13
Name: ____________________________________ Date: __________________
Self-Assessment No.1 Score: _________________
Direction: Encircle the letter of the correct answer.
1. Who created the C# object-oriented programming language?
a. Anders Hejlberg b. Anders Hejlberg and his team
c. James Gosling d. James Gosling and his team

2. What is the purpose of the .NET Framework?


a. To provide a platform for building web applications
b. To provide a platform for building Windows desktop applications
c. To provide a platform for building mobile applications
d. To provide a platform for building cross-platform applications

3. What is the purpose of the using directive in C#?


a. To import namespaces b. To declare variables
c. To define classes d. To specify access modifiers

4. Which of the following statements is true about the using directive?


a. The using directive can only be used at the top of a C# file.
b. The using directive can be used anywhere in a C# file.
c. The using directive is not necessary in C# because namespaces are automatically
imported.
d. The using directive is used to define classes in C#.

5. Which of the following is a valid syntax for the using directive?


a. using System;
b. using System::Windows::Forms;
c. using System, Windows.Forms;
d. using System - Windows.Forms;
6. What is a namespace in C#?
a. A container for classes and other types
b. A keyword used to declare variables
c. A collection of related keywords
d. A modifier used to control access to members

7. What is the syntax for declaring a namespace in C#?


a. namespace MyNamespace { }
b. using MyNamespace;
c. namespace MyNamespace;
d. import MyNamespace;

8. What is a class in C#?


a. A type that defines data and behavior
b. A keyword used to declare variables
c. A collection of related keywords
d. A modifier used to control access to members
14
9. What is the syntax for declaring a class in C#?
a. class MyClass { }
b. using MyClass;
c. namespace MyClass;
d. import MyClass;

10. What is the Main method in C#?


a. The entry point of a C# program
b. A method that executes when an object is created
c. A method that defines properties and behavior
d. A method used for error handling

11. Can you have multiple Main methods in a C# program?


a. Yes b. No

12. What is the purpose of comments in C#?


a. To provide a way to execute code
b. To document code for future developers
c. To debug code
d. To declare variables
13. Which of the following is a valid single-line comment in C#?
a. / This is a comment / b. # This is a comment #
c. // This is a comment d. /* This is a comment */
14. Which of the following is a valid multi-line comment in C#?
a. / This is a comment / b. # This is a comment #
c. // This is a comment d. /* This is a comment */
15. What is the difference between Write() and WriteLine() methods in C#?
a. Write() adds a new line after the output, while WriteLine() does not.
b. WriteLine() adds a new line after the output, while Write() does not.
c. Write() and WriteLine() are the same thing in C#.
d. Write() and WriteLine() cannot be used interchangeably in C#.

15
Name: ____________________________________ Date: __________________
Programming Exercises Score: _________________
Direction: Read and analyze the task carefully before writing your code.
Exercise 1: Using only one statement, the WriteLine(), create a system that will display your Name,
Course, Year & Section, and your Address. Use the escape sequence, to separate their indentions and
lines. Sample output is shown below:

Name: Rosemarie Y. Saligue


Course, Year & Section: BSIT, 1A
Address: Hilongos, Leyte

Exercise 2: Create a system that will display your Name, Course, Year & Section, and your Address
inside a box. You can choose any symbol you prefer to use to create a box. Sample output is shown
below:

$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$
$ $
$ Name: Rosemarie Y. Saligue $
$ Course, Year & Section: BSIT, 1A $
$ Address: Hilongos, Leyte $
$ $
$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$

16
Unit 2 DATA TYPES AND VARIABLES

At the end of this module, the students should be able to:


a. identify the four basic data types (integer, float, string, and boolean)
b. declare and initialize variables of various data types in C# programming
language
c. perform explicit and implicit type conversions between different data types
d. perform common string operations

Introduction to Data Types and Variables in C#

When programming, we command computers to process diverse kinds of data, including numeric
values used in arithmetic operations and textual data to be presented on the screen. However, how
does a computer distinguish between a numeric value and a character? And why is it vital to have
this differentiation in programming?
Data types are used in programming languages like C# to inform the computer about the type of
information being used in a program, and how it should be treated. This concept of data types is vital
in ensuring that the computer processes the information correctly.
Without the use of data types, computers may attempt operations that are not possible, such as
trying to square a piece of text or capitalize a numerical value. This is a common cause of bugs in
programming.
C# is strongly and statically typed, which means that it mandates the declaration of data types used
in a program and checks for correct type usage before the program runs. These language
characteristics are vital in helping to write scalable code with fewer errors.
The use of data types is a crucial aspect of learning C#, and it will be encountered in multiple
instances. Initially, we will delve into the impact of data types on variable declaration and the
utilization of various data types within a program."

C# Data Types
Programming relies heavily on data types because they inform us of the nature and properties of the
data we are dealing with. They assist us in defining and classifying data in a way that the computer
can comprehend and successfully process. The three main things that data types tell us about a piece
of data are:
1. How it can be stored?
2. What operations we can perform with it?
3. What are the different methods it can be used with?

17
Data types are a fundamental aspect of programming, as they provide valuable information about
the data we are working with, enabling the computer to process it effectively and efficiently.
C# offers several built-in data types, and while it is not necessary to memorize all of them, it is
important to focus on the frequently used ones that will be utilized in our lessons:
The most common data types are:

Data Type Description


int Stores whole numbers from -2,147,483,648 to 2,147,483,647
Example: 346, -200, 34
long Stores whole numbers from -9,223,372,036,854,775,808 to
9,223,372,036,854,775,807.
float Stores fractional numbers. Sufficient for storing 6 to 7 decimal digits.
Example: 7.9, 200.0, 0.00012
double Stores fractional numbers. Sufficient for storing 15 decimal digits
bool The bool data type is used to store values that represent either true or
false. This data type is particularly useful in situations where you need
to make decisions based on a binary condition, such as testing if a
certain condition is met or not.
Example: True, False
char The char data type is used to store a single character or letter. A
character value is enclosed in single quotes (') to distinguish it from a
string value, which is enclosed in double quotes (").
Example: ‘R’, ‘*’
string the string data type is used to store sequences of characters, also
known as strings. Strings are typically used to store text-based data,
such as names, addresses, and messages. To declare a string variable in
C#, you surround the string value with double quotes (").
Example: “Hilongos, Leyte”, “063-12345”

Retrieved from https://www.w3schools.com/cs/cs_data_types.php

Defining Variables
Declaring variables in C# involves specifying a valid data type, such as char, int, float, double, or a
user-defined type, followed by one or more identifiers of that same type.
Syntax for variable definition:
<data_type> <variable_name>;
or
<data_type> <variable_list>;

18
Variable Declaration
When working with data in C# programs, it's a best practice to store it in variables. A variable serves
as a container in the computer's memory where values used in the code can be stored. When
declaring a variable, it is necessary to specify its data type.

Example 1: Example 2:
string name; string name, address,course;
string address; char gender, status;
string course; float prog1Grade,introProgGrade,mathGrade, finalGrade;
char gender;
char status;
float prog1Grade;
float introProgGrade;
float mathGrade;
float finalGrade;

In contrast to Example 2, which specifies all variables that have the same data type, Example 1
establishes a variable with a specific data type. In example 2, each variable in this example has the
same data type and is declared on a single line, with commas between each declaration.

Variable Initialization

There are two methods for assigning values to variables. The first method involves declaring and
assigning the variable on separate lines:

//Declare an integer variable


int myAge;
myAge = 32;

Alternatively, we can also declare and assign the variable in a single line for shortness of code.

//Declare an integer variable


int myAge = 32;

Both methods involve declaring the data type, followed by the variable name and using the equals
sign (=) to assign a value to the variable.

19
Sample Code with Variable Declaration
using System;
namespace ProgrammingApplication
{
class VariableDeclaration
{
static void Main(string[] args)
{
//Variable Declarion
string name, address, course;
char gender, status;
float prog1Grade,introProgGrade,mathGrade, finalGrade;

//Variable initialization
name = "Rosemarie Y. Saligue";
address = "Brgy. Osao, San Juan, Southern Leyte";
course = "BS Information Technology";
gender = 'F';
status = 'M';

/* The letter f following a decimal number is used to


specify that the number is a single-precision floating-
point literal,rather than a double-precision floating-point
literal.*/

prog1Grade = 1.4f;
introProgGrade = 1.2f;
mathGrade = 1.8f;

/*finalGrade initialization comes from the average of the 3


subjects*/
finalGrade=(prog1Grade+introProgGrade+mathGrade)/3;

//Printing the assign value of variables


Console.Write("Name:");
Console.WriteLine(name);
Console.Write("Address:");
Console.WriteLine(address);
Console.Write("Course:");
Console.WriteLine(course);
Console.Write("Gender:");
Console.WriteLine(gender);
Console.Write("status:");
Console.WriteLine(status);
Console.Write("Final Grade:");
Console.WriteLine(finalGrade);

/*this method is use to prevent the screen


from closing immediately after the program is launched*/
Console.ReadKey();

}
}
}

Output:

Name: Rosemarie Y. Saligue


Address: Brgy. Osao, San Juan, Southern Leyte
Course: BS Information Technology
C#Gender: F
Identifiers
Status: M
Final Grade: 1.466667

20
In C#, an identifier is a name given to a class, variable, function, or other user-defined item. The
purpose of using identifiers is to provide a way to refer to these items in the code, and they must be
unique within the scope in which they are used.

The basic rules for naming identifiers in C# are as follows:

1. Identifiers can contain letters and digits (0-9).


2. Identifiers must start with a letter or an underscore (_).
3. Identifiers should not contain any spaces or symbols such as ?, -, +, !, @, #, %, ^, &, *, (, ), [, ],
{, }, ., ;, :, ", ', /, and \. However, an underscore (_) can be used.
4. Identifiers are case sensitive (myAge and myage are considered different variables).
5. Identifiers can be short (such as x and y) or more descriptive (such as age, name, or
finalGrade). It is recommended to use descriptive names to make the code more
understandable and maintainable.
6. Reserved words, such as int or double in C#, cannot be used as names.

In addition to these basic rules, C# also follows naming conventions, which are a set of guidelines for
naming identifiers in a consistent and readable way. Some common naming conventions in C# include
using PascalCase for class names and camelCase for variable names.

It is important to follow the rules and conventions for naming identifiers in C#, as this can greatly
improve the readability and maintainability of the code (w3 Schools, 2023).

C# Keywords
In C#, keywords are a collection of reserved identifiers that have particular significance for the
compiler. Because they are predefined and cannot be used as identifiers, keywords cannot be used
to name variables, functions, or classes. As they are used to create language structures like
statements, data types, and control structures, keywords play a crucial role in the C# language.
You can prefix the keyword with the @ character if you want to utilize them as identifiers. You can
use keywords as identifiers by using the @ sign, however this is typically not advised. It is best to
avoid using keywords as identifiers and to use descriptive, meaningful names for your variables,
functions, and classes instead.
Naming Convention
The expression "coding style" refers to the accepted practices for writing source code. These
conventions extend beyond the language's regulations and provide recommendations that should
be followed to maintain consistency among individuals working towards a shared objective. In the
C# programming language, there are a set of guidelines that must be observed when naming
identifiers like variables, methods, classes, and namespaces. These guidelines are referred to as
naming conventions. Its goal is to provide code a dependable and understandable structure, making
it simpler for developers to comprehend and maintain the code. In C#, some typical naming practices
are as follows:
1. When naming identifiers, choose words that are descriptive and have significance.
2. Only use abbreviations for identifiers if they are widely recognized.
3. Avoid using single-letter identifiers for anything other than variables used as loop iterators.

21
4. The naming convention known as Pascal Casing involves capitalizing the first letter of each
word in a name, with all other characters being in lowercase. This convention is used for
Class names, Method names, Namespace identifiers, and Property names.
5. The name of a file should match the name of the class it contains.
6. A class should be named using a noun or noun phrase.
7. Camel Casing involves capitalizing the first letter of each word, except for the first word, and
using lowercase for all other characters. This convention is applied to local variables, object
identifiers, private data members, and parameters.
8. Constants are named using all uppercase characters.

Data Types Conversion


Type conversion, also known as type casting, refers to the process of converting data from one type
to another. In the C# programming language, type casting can take place in several ways, including:
• Implicit casting: C# performs these conversions in a type-safe manner, meaning that it
ensures the data remains intact and free from errors. This type of conversion is automatically
performed when passing a smaller data type to a larger one.
char -> int -> long -> float -> double
Example
int myInt = 35;
double myDouble = myInt; // Automatic casting: int to double
Console.WriteLine(myInt); // Outputs 35
Console.WriteLine(myDouble); // Outputs 35

• Explicit casting: This occurs when you manually specify that a type cast should take place.
For example, converting a decimal to an integer requires an explicit cast.
double -> float -> long -> int -> char
Example
double myDouble = 99.9;
int myInt = (int)myDouble; // Manual casting: double to int
Console.WriteLine(myDouble); // Outputs 99.9
Console.WriteLine(myInt); // Outputs 99

• Using conversion methods: C# includes several built-in methods that can be used to perform
type conversions. The conversion of one data type into another can be achieved by utilizing
methods from the Convert class or by utilizing a Parse method that is available for numerical
data types.
C# provides built-in methods for Type-Conversions as follows:
METHOD DESCRIPTION
ToBoolean converts a type to Boolean value
ToChar converts a type to a character value
ToByte converts a value to Byte Value
ToDecimal converts a value to Decimal point value
ToDouble converts a type to double data type
ToInt16 converts a type to 16-bit integer

22
ToInt32 converts a type to 32 bit integer
ToInt64 converts a type to 64 bit integer
ToString converts a given type to string
ToUInt16 converts a type to unsigned 16 bit integer
ToUInt32 converts a type to unsigned 32 bit integer
ToUInt64 converts a type to unsigned 64 bit integer

Example
int myInt = 12;
double myDouble = 95.6;
float myFloat = 56.123F;

// Using Built- In Type Conversion


// Methods & Displaying Result
Console.WriteLine(Convert.ToString(myFloat)); //Outputs 56.123
Console.WriteLine(Convert.ToInt32(myDouble)); //Outputs 96
Console.WriteLine(Convert.ToUInt32(myFloat)); //Outputs 56
Console.WriteLine(Convert.ToDouble(myInt)); //Outputs 12

The Parse method is particularly useful when converting a string into a numerical value and
is both simple and efficient to use. In this case, the conversion of a string into a numerical
data type is performed using the Parse method.

Example

int myInt;
double myDouble;
float myFloat;
string myStringInt = "144";
string myString = "12.345";

myInt = int.Parse(myStringInt);
myFloat = float.Parse(myString);
myDouble = double.Parse(myString);

Console.WriteLine(myInt); //Outputs 144


Console.WriteLine(myDouble); //Outputs 12.345
Console.WriteLine(myFloat); //Outputs 12.345

23
Name: ____________________________________ Date: __________________
Self-Assessment No. 2 Score: _________________
Direction: Encircle the letter of the correct answer.
1. Which data type is used to represent a single Unicode character in C#?
a. char b. string c. int d. byte

2. Which data type is used to represent a true or false value in C#?


a. int b. double c. boolean d. string

3. 3. Which of the following is a valid identifier in C#?


a. 123abc b. _myVar c. #myVar d. my-Var

4. Which of the following is not a valid identifier in C#?


a. myVar b. MyVar c. my_var d. 123_myVar

5. What is the maximum length of an identifier in C#?


a. 16 characters b. 32 characters
c. 64 characters d. there is no maximum length

6. Which of the following is a valid way to declare a variable with an identifier of "myVar" in C#?
a. int myVar = 10; b. string MyVar = "hello";
c. float my-var = 2.5f; d. bool my var = true;

7. Which of the following is not a valid way to declare a variable in C#?


a. int myNum = 10; b. var myAddress = "Hilongos, Leyte";
c. bool myDecision; d) float myNum = 2.5f;

8. Which of the following is a valid way to declare an integer variable named "myInt" with an
initial value of 5 in C#?
a. int myInt = 5; b. var myInt = 5;
c. myInt = 5; d. int myInt;

9. Which of the following is a valid way to declare a string variable named "myString" without
an initial value in C#?
a. string myString; b. myString = "";
c. myString = null; d) string my String= "Hello";

10. Which of the following is a valid way to declare a double variable named "myDouble" with an
initial value of 3.14 in C#?
a. double myDouble = 3.14; b. var myDouble = 3.14;
c. myDouble = 3.14; d. double myDouble;
11. What is the recommended naming convention for classes in C#?
a. CamelCase b. PascalCase
c. snake_case d. kebab-case

12. What is the recommended naming convention for variables in C#?


a. CamelCase b. PascalCase
c. snake_case d. kebab-case

24
13. What is the recommended naming convention for fields in C#?
a. CamelCase b. PascalCase
c. snake_case d. kebab-case

14. What is the recommended naming convention for methods in C#?


a. CamelCase b. PascalCase
c. snake_case d. kebab-case

15. What is the recommended naming convention for namespaces in C#?


a. CamelCase b. PascalCase
c. snake_case d. kebab-case

16. Which of the following is an example of implicit type conversion in C#? a. int myInt = 10; float
myFloat = myInt;
b. float myFloat = 3.14f; int myInt = (int)myFloat;
c. string myString = "10"; int myInt = Convert.ToInt32(myString);
d. double myDouble = 2.5; bool myBool = (myDouble != 0);

17. Which of the following is an example of explicit type conversion in C#?


a. int myInt = 10; float myFloat = myInt;
b. float myFloat = 3.14f; int myInt = (int)myFloat;
c. string myString = "10"; int myInt = Convert.ToInt32(myString);
d. double myDouble = 2.5; bool myBool = (myDouble != 0);

18. Which of the following is not a valid way to convert a string to an integer in C#?
a. int myInt = int.Parse("10"); b. int myInt = Convert.ToInt32("10");
c. int myInt = (int)"10"; d) int.TryParse("10", out int myInt);

19. Which of the following is not a valid way to convert an integer to a string in C#?
a. string myString = myInt.ToString();
b. string myString = Convert.ToString(myInt);
c. string myString = (string)myInt;
d. string myString = $"{myInt}";

20. What is the correct syntax to declare a char variable in C#?


a. char x; b. ch x; c. x = char; d. var x = char;

25
Name: ____________________________________ Date: __________________
Programming Exercises Score: _________________
Direction: Read and analyze the task carefully before writing your code.

Exercise 1: Create a program that assigns the relevant data to a variable and computes the
solution. The task is to determine the total number of chocolate bars in a big box that holds
20 small boxes, each containing 25 chocolate bars.

Exercise 2: Develop a program that assigns the data to a variable and performs the
calculation. The problem to solve is determining the total number of TV sets produced by a
factory in three years. The factory produced 4200 sets in the first year, 5100 sets in the
second year, and in the third year, the production increased by 600 sets compared to the
second year.

Exercise 3: Create a program that assigns the required data to a variable and computes the
solution. The task is to determine the total amount spent by Emann for his purchases. Emann
purchased three folders at Php7.50 each, a box of pencils at Php35.75, and 2 boxes of pens at
Php60.00.

26
Unit 3 INPUT STATEMENT

At the end of this module, the students should be able to:


a. write C# programs that correctly use Console.ReadLine() to capture user input
b. convert user input from string to appropriate data types

Input Statement
The user types a line of text into the console, and the Console.ReadLine() method reads that line and
stores it in the specified variable.
In the representation shown in our outputs below, we have utilized an underline to distinguish
between input statements and output statements, however, there is no such underline in the actual
output.
Sample code for ReadLine():
Example 1:
using System;
namespace ProgrammingApplication
{
class InputStatement
{
static void Main(string[] args)
{
//Variable Declarion
string name, motto;

Console.Write("Name:");
/*no need to convert the user input into a string
as Console.ReadLine() returns a string by default */
name = Console.ReadLine();
Console.Write("Motto:");
motto = Console.ReadLine();

/*this method is use to prevent the screen


from closing immediately after the program is launched */
Console.ReadKey();
}
}
}
Output:

Name:Rosemarie Y. Saligue
Motto:Nothing is impossible

The default data type for Console.ReadLine() is string, and since the variables 'name' and 'motto'
have been declared as strings, there is no need to perform a conversion to string.

27
Example 2:
using System;
namespace ProgrammingApplication
{
class InputStatement
{
static void Main(string[] args)
{
//Variable Declarion
string name, address, course;
char gender, status;
float prog1Grade,introProgGrade,mathGrade, finalGrade;

//Variable initialization
prog1Grade = 0f;
introProgGrade = 0f;
mathGrade = 0f;

Console.Write("Name:");
/*no need to convert the user input into a string
as Console.ReadLine() returns a string by default */
name = Console.ReadLine();
Console.Write("Address:");
address=Console.ReadLine();
Console.Write("Course:");
course= Console.ReadLine();

Console.Write("Gender[F/M]:");
//convert the user input into char datatype
gender = char.Parse(Console.ReadLine());
Console.Write("status[S/M/W/U]:");
status = char.Parse(Console.ReadLine());

Console.WriteLine("------ My Grades------");
Console.Write("Programming 1:");
//convert the user input into float datatype
prog1Grade = float.Parse(Console.ReadLine());
Console.Write("Introduction to Computing:");
introProgGrade = float.Parse(Console.ReadLine());
Console.Write("Mathematics in Modern World:");
mathGrade = float.Parse(Console.ReadLine());

/*finalGrade initialization comes from the average of the 3


subjects*/
finalGrade = (prog1Grade + introProgGrade + mathGrade) / 3;

Console.Write("Final Grade:");
Console.WriteLine(finalGrade); //display the finalGrade result

/*this method is use to prevent the screen


from closing immediately after the program is launched */
Console.ReadKey();
}
}
}

28
Output:

Name:Rosemarie Y. Saligue
Address:Brgy. Osao, San Juan, Southern Leyte
Course:BS Information Technology
Gender[F/M]:F
status[S/M/W/U]:M
------ My Grades------
Programming 1:1.8
Introduction to Computing:1.4
Mathematics in Modern World:2.3
Final Grade:1.833333

As per the code above, the system prompts the user to enter their name, address, course, gender,
status, grades in Programming 1, Introduction to Computing, and Mathematics in the Modern World.
Upon completion of the inputs, the final grade will be displayed.
Because the variables "name," "address," and "course" have been declared as strings, it is not
necessary to change Console.ReadLine() to another data type, as shown in example 2. However, data
type conversion is necessary for character data types like "gender" and "status," as demonstrated in
the following code:

To Data type: char

gender = char.Parse(Console.ReadLine());
From Data type: string

It is imperative to change the data type of the input for the variables 'prog1Grade', 'introProgGrade',
and 'mathGrade' into float. This is because the data entered for these variables is expected to be
numerical values that may contain decimal points. The float data type is specifically designed to
store numerical values with decimal points, and converting the input data into this data type will
ensure that the values are stored and processed correctly. An example of code for converting to float
is displayed below:

To Data type: float

prog1Grade = float.Parse(Console.ReadLine());
From Data type: string

29
Name: ____________________________________ Date: __________________
Self-Assessment No. 3 Score: _________________

Direction: Encircle the letter of the correct answer.

1. Which keyword is used in C# to read input from the user?


a. console b. input c. read d. scan

2. Which namespace is required to use the Console class in C#?


a. System b. IO c. Console d. Input

3. What is the default data type for input in C#?


a. string b. int c. float d. double

4. How can you convert a string input to an integer in C#?


a. int.Parse() b. int.Convert()
b. int.ToInteger() d. int.ToString()

5. Which of the following methods can be used to read a line of text input in C#?
a. Console.Read() b. Console.ReadLine()
c. Console.ReadChar() d. Console.ReadText()

6. Which of the following is the correct syntax to read a line of text input and store it in a
decimal variable in C#?
a. decimal input = Console.ReadLine();
b. decimal input = Console.Readline();
c. decimal input = decimal.Parse(Console.ReadLine());
d. decimal input = decimal.Parse(Console.Readline());

7. Which of the following statements is used to display output to the console in C#?
a. Console.Print() b. Console.WriteLine()
c. Console.Output() d. Console.Display()

8. Which of the following methods can be used to read a boolean input in C#?
a. bool.Parse() b. int.Parse()
c. float.Parse() d. double.Parse()

9. Which method can be used to read a single keystroke input in C#?


a. Console.ReadKey() b. Console.ReadLine()
c. Console.Read() d. Console.ReadChar()

10. Which of the following is the correct syntax to read a line of text input and store it in a
string variable in C#?
a. string input = Console.Read();
b. string input = Console.ReadChar();
c. string input = Console.ReadLine();
d. string input = Console.ReadText();

30
Name: ____________________________________ Date: __________________
Programming Exercises Score: _________________

Direction: Read and analyze the task carefully before writing your code.

Exercise 1: Write a C# application that will ask the user to enter their personal information such as
name, address, zip code, age, birthday, status, citizenship, mother’s name, and father’s name. Use a
dash line to separate the text. Sample output shown below:

----------------------------------------------------------------------------------
Name: Rosemarie Y. Saligue
----------------------------------------------------------------------------------
Address: Hilongos, Leyte
----------------------------------------------------------------------------------
Zip Code: 6524
----------------------------------------------------------------------------------
Birthday: 03-02-1991
----------------------------------------------------------------------------------
Age: 32
----------------------------------------------------------------------------------
Status: Married
----------------------------------------------------------------------------------
Citizenship: Filipino
----------------------------------------------------------------------------------
Mother's Name: Jocelyn Yangyang
----------------------------------------------------------------------------------
Father's Name: Romeo Yangyang
----------------------------------------------------------------------------------

Exercise 2: Write a C# application that prompts the user to input their name and the radius of a circle
and computes the area of the circle. The example result is displayed as follows:

Name:Rosemarie Y. Saligue
Radius of a circle:5
Area of a circle:78.54

31
MODULE 2
Fundamentals of Designing Console Displays

This module consists of three Units. Unit 1 is about the Set Cursor Positioning. Unit 2 is about the
Window Size setting. And unit 3 talks about the setting of background and foreground color.

It's crucial to remember that most modules conclude with an evaluation, or a series of assessments,
as you progress through the module. Before proceeding to the next section of the course, make sure you
give them enough time to be finished.

And lastly, remember to have fun during the whole educational process. Enjoy yourselves!

You are now embarking on a journey filled with valuable experiences and
enriching learning opportunities. Engage in the exercises and respond to the
suggested worksheets to immerse yourself in a lifelong journey of practical
learning that awaits you upon completing this module.

ENJOY YOUR JOURNEY!

32
Unit 1 SET CURSOR POSITIONING

At the end of this module, the students should be able to:


a. explain the concept and purpose of cursor positioning in console applications.
b. demonstrate the ability to use the Console.SetCursorPosition(int left, int top)
method in C#

Set Cursor Positioning

The console window's cursor can be moved using the Console.SetCursorPosition(Int32, Int32)
function. The next write operation's beginning point is established using this procedure. The origin
of the window will be changed to display the cursor if the specified cursor point is not currently
visible in the console window. It will starts at zero both the left and top positions.
Syntax
Console.SetCursorPosition(left, Top);
Example
using System;
namespace ProgrammingApplication
{
class SetCursorPosition
{
static void Main(string[] args)
{
Console.WriteLine("######################################");
Console.WriteLine("# #");
Console.WriteLine("# #");
Console.WriteLine("# #");
Console.WriteLine("# #");
Console.WriteLine("# #");
Console.WriteLine("# #");
Console.WriteLine("# #");
Console.WriteLine("######################################");

Console.SetCursorPosition(18, 1);
Console.Write("*");
Console.SetCursorPosition(17,2);
Console.Write("***");
Console.SetCursorPosition(15, 3);
Console.Write("*******");
Console.SetCursorPosition(13, 4);
Console.Write("***********");
Console.SetCursorPosition(11, 5);
Console.Write("***************");
Console.SetCursorPosition(9, 6);
Console.Write("*******************");
Console.SetCursorPosition(7, 7);
Console.Write("***********************");
Console.ReadKey();
}
}
}

33
Output:

######################################
# * #
# *** #
# ******* #
# *********** #
# *************** #
# ******************* #
# *********************** #
######################################

Let's examine the left and top positions as demonstrated in the sample output.

10 12 14 16 18 20 22 24 26 28 30 32 34 36
0123456789 11 13 15 17 19 21 23 25 27 29 31 33 35 37

0
1
2
3
4
5
6
7
8

Examine the code to understand how it reflects the output shown above.

Console.SetCursorPosition(18, 1);
Console.Write("*");
Console.SetCursorPosition(17, 2);
Console.Write("***");
Console.SetCursorPosition(15, 3);
Console.Write("*******");
Console.SetCursorPosition(13, 4);
Console.Write("***********");
Console.SetCursorPosition(11, 5);
Console.Write("***************");
Console.SetCursorPosition(9, 6);
Console.Write("*******************");
Console.SetCursorPosition(7, 7);
Console.Write("***********************");

34
Example 2

Output:

##########################################################
# Name: Rosemarie Y. Saligue #
# #
# Address: Brgy. Osao, San Juan, Southern Leyte #
# #
# Course: BS Information Technology #
# #
##########################################################

Using the SetCursorPosition method, the user will input their name, address, and course within the
designated box as indicated by the running system.

35
Name: ____________________________________ Date: __________________
Self-Assessment No. 4 Score: _________________
Direction: Encircle the letter of the correct answer.

1. What method is used to set the cursor position in a C# console application?


a. Console.SetCursor() b. Console.SetPosition()
c. Console.SetCursorPosition() d. Console.CursorPosition()

2. Which parameters are required by the Console.SetCursorPosition() method?


a. x, y b. top, left
c. width, height d. left, top

3. What is the coordinate of the top-left corner of the console window?


a. (0, 0) b. (1, 1) c. (0, 1) d. (1, 0)

4. How can you move the cursor to the beginning of the next line in the console?
a. Console.SetCursorPosition(0, currentLine + 1)
b. Console.SetCursorPosition(1, currentLine)
c. Console.SetCursorPosition(0, currentLine - 1)
d. Console.SetCursorPosition(1, currentLine + 1)

5. Which method can be used to get the current cursor position?


a. Console.GetCursorPosition()
b. Console.GetPosition()
c. Console.CursorPosition()
d. Console.GetCursorLeft() and Console.GetCursorTop()

6. Which of the following commands clears the console window?


a. Console.ClearScreen() b. Console.Erase()
c. Console.Clear() d. Console.Reset()

7. To move the cursor to the right by one position, which method call would you use if the current
position is (5, 5)?
a. Console.SetCursorPosition(5, 6) b. Console.SetCursorPosition(6, 5)
c. Console.SetCursorPosition(5, 4) d. Console.SetCursorPosition(4, 5)

8. If you want to position the cursor at the bottom right corner of the console window, which of the
following methods would you use?
a. Console.SetCursorPosition(Console.WindowWidth - 1, Console.WindowHeight - 1)
b. Console.SetCursorPosition(Console.BufferWidth, Console.BufferHeight)
c. Console.SetCursorPosition(Console.BufferWidth - 1, Console.BufferHeight - 1)
d. Console.SetCursorPosition(Console.WindowWidth, Console.WindowHeight)
9. Which method resets the cursor position to the top-left corner of the console?
a. Console.ResetCursor() b. Console.SetCursorPosition(0, 0)
c. Console.SetCursorHome() d. Console.HomeCursor()

10. Which of the following statements correctly positions the cursor at column 10, row 15?
a. Console.SetCursorPosition(10, 15) b. Console.SetCursorPosition(15, 10)
c. Console.SetCursorPosition("10, 15") d. Console.SetCursorPosition("15, 10")

36
Name: ____________________________________ Date: __________________
Programming Exercise Score: _________________
Direction: Read and analyze the task carefully before writing your code.

Exercise: Write a C# program that will ask the user to enter their name, age, address inside a box.
Sample output shown below:

37
Unit 2 SET WINDOW SIZE

At the end of this module, the students should be able to:


a. Explore demonstrate the ability to set the console window size using the
Console.SetWindowSize() method in C#.
b. retrieve and display the current console window size using Console.WindowWidth
and Console.WindowHeight properties

Set Window Size


The Console.SetWindowSize(Int32, Int32) method is utilized to adjust the height and width of the
console window to the specified dimensions.

Syntax
Console.SetWindowSize(width, height)

Example
using System;
namespace ProgrammingApplication
{
class SetWindowSize
{
static void Main(string[] args)
{
/* The function "SetWindowSize()" is utilized to change the
size of the console window.*/

Console.SetWindowSize(40, 10);
Console.WriteLine("######################################");
Console.WriteLine("# #");
Console.WriteLine("# #");
Console.WriteLine("# #");
Console.WriteLine("# #");
Console.WriteLine("# #");
Console.WriteLine("# #");
Console.WriteLine("# #");
Console.WriteLine("######################################");
Console.SetCursorPosition(18, 1);
Console.Write("*");
Console.SetCursorPosition(17, 2);
Console.Write("***");
Console.SetCursorPosition(15, 3);
Console.Write("*******");
Console.SetCursorPosition(13, 4);
Console.Write("***********");
Console.SetCursorPosition(11, 5);
Console.Write("***************");
Console.SetCursorPosition(9, 6);
Console.Write("*******************");
Console.SetCursorPosition(7, 7);
Console.Write("***********************");
Console.ReadKey();

}
}
}

38
Output

Common Error

In order to prevent errors of this type and to eliminate unnecessary modifications, it is advisable to
verify the maximum width and height of your console window prior to adjusting it, so that you can
adjust it properly.

Sample Code:

using System;
namespace ProgrammingApplication
{
class SetWindowSize
{
static void Main(string[] args)
{
//Display Label of the Largest window width
Console.Write("Largest Window Width:");
//Displaying the Largest window width
Console.WriteLine(Console.LargestWindowWidth);
//Display Label of the Largest window height
Console.Write("Largest Window Height:");
//Displaying the Largest window height
Console.WriteLine(Console.LargestWindowHeight);

/*this method is use to prevent the screen


from closing immediately after the program is launched */
Console.ReadKey();

}
}
}
Output:

Largest Window Width:170


Largest Window Height:44

39
Name: ____________________________________ Date: __________________
Self-Assessment No. 5 Score: _________________

Direction: Encircle the letter of the correct answer.

1. Which method is used to set the console window size in C#?


a. Console.SetWindowDimensions() b. Console.SetWindowSize()
c. Console.SetSize() d. Console.ResizeWindow()

2. Which parameters are required by the Console.SetWindowSize() method?


a. width, height b. rows, columns
c. top, left d. x, y

3. What is the default maximum width of a console window in C#?


a. 90 b. 170
c. 120 d. It depends on the screen resolution.

4. How can you retrieve the current width of the console window?
a. Console.WindowWidth b. Console.BufferWidth
c. Console.GetWindowWidth() d. Console.GetWidth()

5. Which property would you use to get the current height of the console window?
a. Console.WindowHeight b. Console.BufferHeight
c. Console.GetWindowHeight() d. Console.GetHeight()

6. To set the console window size to 80 columns and 25 rows, which method call would you
use?
a. Console.SetWindowSize(25, 80) b. Console.SetWindowSize(80, 25)
c. Console.SetWindowSize(80, 24) d. Console.SetWindowSize(25, 79)

7. What method can be used to clear the console window?


a. Console.ClearScreen() b. Console.Erase()
c. Console.Clear() d. Console.Reset()
8. Which property retrieves the maximum allowable height of the console window?
a. Console.MaxHeight b. Console.WindowMaxHeight
c. Console.LargestWindowHeight d. Console.BufferMaxHeight

9. Which property retrieves the maximum allowable width of the console window?
a. Console.MaxWidth b. Console.WindowMaxWidth
c. Console.LargestWindowWidth d. Console.BufferMaxWidth

10. Which of the following statements correctly sets the console window size to 100 columns
and 40 rows?
a. Console.SetWindowSize(100, 40)
b. Console.SetWindowSize("100, 40")
c. Console.SetWindowSize(40, 100)
d. Console.SetWindowSize("40, 100")

40
Name: ____________________________________ Date: __________________
Programming Exercise Score: _________________

Direction: Read and analyze the task carefully before writing your code.

Exercise 1: Write a C# program that will ask the user’s name, age, address inside a box. Set the width
to 53 and height to 8. Sample output shown below:

41
Unit 3 SET BACKGROUND AND FOREGROUND COLOR

At the end of this module, the students should be able to:


a. create console applications that use a combination of background and
foreground colors to enhance readability
b. design and implement simple user interfaces in the console that utilize various
background and foreground colors

Setting Background color and Text Color


Altering the foreground and background colors can enhance the appearance of your console
windows, making them more visually appealing and user-friendly.

Syntax
Console.ForegroundColor = ConsoleColor.Blue;
Console. BackgroundColor = ConsoleColor.Blue;

Sample Code:
using System;
namespace ProgrammingApplication
{
class ConsoleAppColors
{
static void Main(string[] args)
{
/* The function "SetWindowSize()" is utilized to change the
size of the console window.*/
Console.SetWindowSize(40, 10);

/* ForegroundColor is use to change the text color */


Console.ForegroundColor = ConsoleColor.DarkMagenta;

/* BackgroundColor is use to change the background color */


Console.BackgroundColor = ConsoleColor.White;

/* Console.Clear is use to erase any previous data and fill the


console with the updated background color */
Console.Clear();

Console.WriteLine("######################################");
Console.WriteLine("# #");
Console.WriteLine("# #");
Console.WriteLine("# #");
Console.WriteLine("# #");
Console.WriteLine("# #");
Console.WriteLine("# #");
Console.WriteLine("# #");
Console.WriteLine("######################################");

42
/* ResetColor() is use to reset the color to its default state*/
Console.ResetColor();

Console.SetCursorPosition(18, 1);
Console.Write("*");
Console.SetCursorPosition(17, 2);
Console.Write("***");
Console.SetCursorPosition(15, 3);
Console.Write("*******");
Console.SetCursorPosition(13, 4);
Console.Write("***********");
Console.SetCursorPosition(11, 5);
Console.Write("***************");
Console.SetCursorPosition(9, 6);
Console.Write("*******************");
Console.SetCursorPosition(7, 7);
Console.Write("***********************");

/*this method is use to prevent the screen


from closing immediately after the program is launched */
Console.ReadKey();

}
}
}

Output

In the example code, the "Console.Clear()" function serves the purpose of wiping the contents of the
console window and filling it with the background color that has been set using
"Console.BackgroundColor". Therefore, after adjusting the background color using
"Console.BackgroundColor", you can use "Console.Clear()" to erase any previous data and fill the
console with the updated background color.
The "Console.BackgroundColor" property is assigned the value of "ConsoleColor.White", resulting in
a change of the background color to white. The subsequent execution of the "Console.Clear()"
method clears any previous content in the console window and fills it with the white background
color. While the ForegroundColor is set to ‘Dark Magenta’. After the foreground and background
colors of the box have been set, the subsequent code is the "Reset Color" section, which applies the
default color scheme to the triangular layout.

43
Name: ____________________________________ Date: __________________
Self-Assessment No. 6 Score: _________________
Direction: Encircle the letter of the correct answer.
1. Which property is used to set the foreground color of the console text in C#?
a. Console.TextColor b. Console.ForegroundColor
c.Console.Color d. Console.TextForeground
2. Which property is used to set the background color of the console text in C#?
a. Console.BackgroundColor b. Console.BackColor
c. Console.TextBackground d. Console.Color
3. How do you reset the console colors to their default values?
a. Console.ResetColors() b. Console.DefaultColors()
c. Console.ResetColor() d. Console.DefaultColor()
4. Which statement correctly sets the console's foreground color to yellow?
a. Console.ForegroundColor = Color.Yellow; b. Console.ForegroundColor = ConsoleColor.Yellow;
c. Console.ForegroundColor = ConsoleColors.Yellow; d. Console.ForegroundColor = Yellow;
5. Which statement correctly sets the console's background color to blue?
a. Console.BackgroundColor = Blue; b. Console.BackgroundColor = ConsoleColors.Blue;
c. Console.BackgroundColor = Color.Blue; d. Console.BackgroundColor = ConsoleColor.Blue;
6. What is the default foreground color of the console text?
a. Black b. White c. Gray d. Yellow
7. What is the default background color of the console text?
a. Black b. White c. Gray d. Blue
8. To change the foreground color to green and the background color to black, which of the
following is correct?
a. Console.ForegroundColor = ConsoleColor.Green; Console.BackgroundColor =
ConsoleColor.Black;
b. Console.BackgroundColor = ConsoleColor.Black; Console.ForegroundColor =
ConsoleColor.Green;
c. Console.ForegroundColor = ConsoleColor.Green, Console.BackgroundColor =
ConsoleColor.Black;
d. Both a) and b) are correct.
9. What method call is needed to ensure the entire console screen reflects a new background color
after setting Console.BackgroundColor?
a. Console.UpdateBackground() b. Console.Refresh()
c. Console.Clear() d. Console.ApplyBackgroundColor()
10. Which statement correctly demonstrates how to set the foreground color to red and the
background color to yellow, write a message, and then reset colors?
a. Console.ForegroundColor = ConsoleColor.Red; Console.BackgroundColor =
ConsoleColor.Yellow; Console.WriteLine("Hello"); Console.ResetColor();
b. Console.SetColor(ConsoleColor.Red, ConsoleColor.Yellow); Console.WriteLine("Hello");
Console.ResetColor();
c. Console.ForegroundColor = ConsoleColor.Yellow; Console.BackgroundColor =
ConsoleColor.Red; Console.WriteLine("Hello"); Console.ResetColor();
d. Console.ForegroundColor = ConsoleColor.Red; Console.BackgroundColor =
ConsoleColor.Yellow; Console.Write("Hello"); Console.DefaultColor();

44
Name: ____________________________________ Date: __________________
Programming Exercise Score: _________________

Direction: Read and analyze the task carefully before writing your code.
Exercise : Write a C# application that shows a star within a box using a yellow foreground color and
a black background color. Upon pressing a key, the program will modify the star to a triangle inside
a box with a magenta foreground color and a white background color. The provided example
illustrates the expected output.
Layout 1:

Layout 2

45
MODULE 3
Working with Strings

This module consists of three Units. Unit 1 talks about the string concatenation. Unit 2 discusses the
string interpolation and unit 3 elaborates on the string formatting technique.

It's crucial to remember that most modules conclude with an evaluation, or a series of assessments,
as you progress through the module. Before proceeding to the next section of the course, make sure you
give them enough time to be finished.

And lastly, remember to have fun during the whole educational process. Enjoy yourselves!

You are now embarking on a journey filled with valuable experiences and
enriching learning opportunities. Engage in the exercises and respond to the
suggested worksheets to immerse yourself in a lifelong journey of practical
learning that awaits you upon completing this module.

ENJOY YOUR JOURNEY!

46
Unit 1 STRING CONCATENATION

At the end of this module, the students should be able to:


a. demonstrate basic concatenation using the + operator

A string is a sequence of characters contained within quotation marks, such as "hello Philippines" or
"Hello San Juan." There are methods for handling strings, including concatenation, formatting, and
interpolation.
Example:
string myStr1="Moon and";
string myStr2=" Star";

String Concatenation

string result = myStr1 + myStr2;

String Interpolation

string result =$"{myStr1}{myStr2}";

Output

Moon and Star

The combined text or string variables can be assigned to a string variable in two different ways. String
interpolation or string concatenation can both be used, as was demonstrated above. It is only
possible to utilize string formatting in Write() and WriteLine(). The three methods will be detailed on
the following page to help you understand it better.

String Concatenation
This method is commonly used in handling strings. By using ‘+’ symbol you can now combine strings.

47
Sample code:

Output
Screen 1.

###########################################################
# #
# Name: Rosemarie Y. Saligue #
# #
# Address: San Juan, Southern Leyte #
# #
###########################################################
Screen 2.

###########################################################
# #
# Hi,Rosemarie Y. Saligue #
# #
# Your place San Juan, Southern Leyte is nice! #
# #
48
###########################################################
Name: ____________________________________ Date: __________________
Self-Assessment No. 7 Score: _________________

Direction: Encircle the letter of the correct answer.

1. Which operator is commonly used for string concatenation in many programming


languages?
a. + b. & c. * d. /

2. What is the result of the following concatenation operation: "Hello" + "World"?


a. HelloWorld b. Hello World c. Hello+World d. Error

3. What is the correct syntax for string interpolation in C#?


a. $"Hello {name}" b. "$Hello {name}"
c. "{Hello} $name" d. "Hello $name"

4. What is the result of the following string concatenation: "10" + "20" + 30?
a. "30" b. "1020" c. "10 20 30" d. Error

5. What is the result of the following string concatenation: "Hello" + 5 + "World"?


a. "Hello5World" b. "Hello World" c. "Hello5 World" d. Error

49
Name: ____________________________________ Date: __________________
Programming Exercise Score: _________________

Direction: Read and analyze the task carefully before writing your code.
Exercise. Make a system where the user is required to enter their name, the amount they wish to
invest, and the annual interest inside a box. Afterwards, the system will show the user’s name and
the total amount earned at the end of 2 years in another box. Sample output is shown below.
Screen 1
$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$
$ $
$ Name:Karev $
$ Amount to invest: 1000 $
$ Annual Interest: 6 $
$ $
$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$

Screen 2

$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$
$ $
$ Hello, Karev $
$ Your possible total interest earned in 2 years is 120. $
$ $
$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$

50
Unit 2 STRING INTERPOLATION

At the end of this module, the students should be able to:


a. demonstrate basic concatenation using the $ operator

String Interpolation
To concatenate strings with the $ symbol, this approach requires the use of braces {} to include
variables. It's important to avoid any space between the starting quotation mark and the $. This
technique is exclusive to features found in C# 6.0 and newer versions of the language.

Sample code:

51
Output
Screen 1.

###########################################################
# #
# Name: Rosemarie Y. Saligue #
# #
# Address: San Juan, Southern Leyte #
# #
###########################################################

Screen 2.

###########################################################
# #
# Hi,Rosemarie Y. Saligue #
# #
# Your place San Juan, Southern Leyte is nice! #
# #
###########################################################

Name: ____________________________________ Date: __________________


Self-Assessment No.8 Score: _________________
Direction: Encircle the letter of the correct answer.
1. What will be the code if I want to display the variable total?
a. $"Total: {total}" b. "$ Total: { total }"
c. "{ Total: } $total " d. " Total: $ total"

2. What will be the syntax if I will display the variables firstNum, secondNum and total?
a. ${firstNum}+{secondNum}=" {total}" b. "${firstNum}+{secondNum}={ total }"
c. $"{firstNum}+{secondNum}= {total}" d. "$firstNum+secondNum= total "

3. What is the correct syntax for string interpolation in C#?


a. $"Hello {name}" b. "$Hello {name}" c. "{Hello} $name" d. "Hello $name"

4. What advantage does string interpolation offer over traditional string concatenation?
a. String interpolation is faster.
b. String interpolation allows for easier formatting and readability.
c. String interpolation is only available in certain programming languages.
d. String interpolation consumes less memory.

5. Which of the following is a valid syntax for string interpolation in C#?


a. $"The result is {result}"
b. "The result is {result}"
c. The result is ${result}
d. $"The result is {result}"

52
Name: ____________________________________ Date: __________________
Programming Exercise Score: _________________
Direction: Read and analyze the task carefully before writing your code.

Exercise : Write a system with five variables. In naming your variables, make sure it follows the
naming convention. Your First Name will be the first variable, your Middle Name the second, your
Last Name the third, your Highest Grade obtained the fourth, and the fifth variable's value will be
determined by adding the four preceding variables using the string concatenation method. Show the
value of the fifth variable between the lines of dollar sign ($). To complete the task, follow the sample
output shown below.

$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$

I am Emarie Sheen Ocba Sumalinog.


The highest grade I obtained was 98.9.

$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$

53
Unit 3 STRING FORMATTING

At the end of this module, the students should be able to:


a. demonstrate basic concatenation using the string formatting

String Formatting

Another approach is to use a format string that specifies the structure of the resulting
string and the format for the values that will be inserted into it.

54
All the code for string manipulation above has SAME RESULT but with different ways of formatting
the strings either using concatenation, using interpolation, or using format strings.
The user will enter their name and address. Then the system will display a screen shown on screen
2.
Output
Screen 1.

###########################################################
# #
# Name: Rosemarie Y. Saligue #
# #
# Address: San Juan, Southern Leyte #
# #
###########################################################

Screen 2.

###########################################################
# #
# Hi,Rosemarie Y. Saligue #
# #
# Your place San Juan, Southern Leyte is nice! #
# #
###########################################################

55
Name: ____________________________________ Date: __________________
Self-Assessment No.9 Score: _________________

Direction: Encircle the letter of the correct answer.

1. What will be the code if I want to display the variable total?


a. "Total: {0}",total b. "Total: {total},0" c. "Total:{0},total " d. " Total: {total}",0

2. What will be the syntax if I will display the variables firstNum, secondNum and total?
a. "{firstNum}+{secondNum}= {total}",0,1,2
b. "{0}+{1}={ 2 }" firstNum, secondNum, total
c. "{0}+{1}={ 2 }" ,firstNum, secondNum, total
d. "{firstNum}+{secondNum}= {total}, 0,1,2"

3. What is the correct syntax for string formatting in C#?


a. "Hello {name}",0 b. "Hello {0}",name
c. "{Hello} name,0 " d. "Hello {0},name"

4. What is the benefit of using string formatting over concatenation?


a. String formatting is more memory-efficient.
b. String formatting offers better performance.
c. String formatting provides clearer and more concise syntax.
d. There is no difference between string formatting and concatenation.

5. Which of the following is a valid syntax for string formatting in C#?


a. "The result is {result}",0 b. "The result is {0}", result
c. "The result is {result},0" d. "The result is {0}, result "

Name: ____________________________________ Date: __________________


Programming Exercise Score: _________________
Direction: Read and analyze the task carefully before writing your code.
Exercise. Write a system where the user is required to enter their first name, middle name, and last
name. Sample output is shown below.
Screen 1
$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$
$ $
$ First Name:Karev $
$ Middle Name: Yangyang $
$ Last Name: Saligue $
$ $
$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$
Screen 2

$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$
$ $
$ Hello, Karev $
$ Your full name is Karev Yangyang Saligue. $
$ $
$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$
56
MODULE 4
Working with Numbers

In this module of our course, we've organized the content into 4 units, each dedicated to exploring a
specific type of operator. Unit 1 zooms in on the assignment and arithmetic operator, while Unit 2 delves into
the Common compound assignment operator and operator precedence. Unit 3 shines a light on the relational
and logical operator, and finally, Unit 4 delves into the intricacies of the unary and ternary operator.

It's crucial to remember that most modules conclude with an evaluation, or a series of assessments,
as you progress through the module. Before proceeding to the next section of the course, make sure you
give them enough time to be finished.

And lastly, remember to have fun during the whole educational process. Enjoy yourselves!

You are now embarking on a journey filled with valuable experiences and
enriching learning opportunities. Engage in the exercises and respond to the
suggested worksheets to immerse yourself in a lifelong journey of practical
learning that awaits you upon completing this module.

ENJOY YOUR JOURNEY!

57
Unit 1 ASSIGNMENT & ARITHMETIC OPERATOR

At the end of this module, the students should be able to:


a. demonstrate proficiency in using the assignment and arithmetic operator to
assign values to variables in basic C# programs
b. grasp the purpose and syntax of the assignment operator in C#
c. apply the assignment operator to declare and initialize variables in simple C#
programs

C# Operator

In programming, operators are symbols or characters that are used to perform various types of
operations on operands. An operand is a term that refers to the variable or constant value that is
used with an operator to perform the desired operation.

For instance, consider the arithmetic operation of addition. The plus symbol (+) is an operator that
is used to add two operands together.

Example: 9+3=12

In the expression "9 + 3," the operands are the numbers 9 and 3, and the operator is the plus symbol
(+). The result of this operation is the value 12.

In programming, operands can be either variables or constants. A variable is a named storage


location in memory that can hold a value, whereas a constant is a value that remains unchanged
throughout the program.

Assignment Operator

Assignment operator used to assign values to variables using the equal sign (=) symbol. For example,

int wholeNumber = 300;


double doubleNumber = 300.50;
decimal decimalNumber = 300.50m;
float floatNumber = 300.50f;

same with:
int wholeNumber;
double doubleNumber;
decimal decimalNumber;
float floatNumber;

wholeNumber = 300;
doubleNumber = 300.50;
decimalNumber = 300.50m;
floatNumber = 300.50f;

58
In C#, you can declare a variable and assign a value to it at the same time using what is called an
initialization. Alternatively, you can declare a variable first, then assign a value to it later in the code.

Arithmetic Operators
Arithmetic operators are utilized to carry out mathematical operations, including but not limited to
addition, subtraction, multiplication, and division.

C# Arithmetic Operators
Operator Operator Name Example
+ Addition Operator 9 + 2 = 11
- Subtraction Operator 9-2=7
* Multiplication Operator 9 * 9 = 18
/ Division Operator 9/2=4
% Modulo Operator (Remainder) 9%2=1

Example 1:

Output:

Answer 1:280.75
Answer 2:19

59
Is your answer same with the shown output?
If yes, then you understood the order of operations like PMDAS. Which stands for Parentheses,
Multiplication and Division (from left to right), and Addition and Subtraction (from left to right).
If no, let’s delve in.

Priority/ Order of Operations Associativity of


Order operators
1 P Parenthesis ()
2 MD Multiplication *, Division / Left to right
3 AS Addition +, Subtraction - Left to right

Let’s start with answer1:

Output: Answer 1:280.75

The computation starts with the highest priority or order in operation. Based on the equation
(90+85+84+87/4), we use 2 operators the division (/) and addition (+). Following the rule of PMDAS,
the higher priority operator between division and addition is the division, hence, the computation
starts with division (90+85+84+87/4)

Computation:
=90+85+84+87/4
=90+85+84+21.75
=280.75

Reason why the output resulted to 280.75.

For answer2,

we have 3 operators. The addition, multiplication, and subtraction. Based on the PMDAS rule,
multiplication has the higher operator than addition and subtraction. Thus, the computation starts
with multiplication (5 + 6 * 3 – 4)

Computation:
=5 + 6 * 3 – 4 (Since addition and subtraction have the same level of priority, the
=5 + 18 – 4 Associativity of operators will be applied. So, the process will be from left
=23-4 to right. So it will be, 5+18-4)
=19

If you want to make the lower level to have a highest priority, then you just need to enclose the
operation with a parenthesis.

60
Example 2:

Output:

Answer 1:86.5
Answer 2:29

Through enclosing with parenthesis, the result above from example 1 differs from the result in
example 2. Since parenthesis has the highest priority, hence, all the operation enclosed in
parenthesis is computed first. However, within a set of parentheses, the order of operations still
applies, meaning that any multiplication, division, addition, or subtraction within the parentheses
should be performed according to the PMDAS order.

61
Name: ____________________________________ Date: __________________
Self-Assessment No.10 Score: _________________

Direction: Encircle the letter of the correct answer.

1. Which of the following is the assignment operator in C#?


A. = B. == C. != D. <=

2. What is the purpose of the assignment operator in C#?


A. To compare two values for equality.
B. To perform mathematical operations.
C. To assign a value to a variable.
D. To create a loop.

3. Which of the following statements is true about the assignment operator in C#?
A. It can only be used with integer variables.
B. It can be used to assign a value to multiple variables at once.
C. It cannot be used with string variables.
D. It can only be used in a conditional statement.

4. What happens when you use the assignment operator to assign a value to a variable in C#?
A. The value of the variable is increased by the assigned value.
B. The value of the variable is decreased by the assigned value.
C. The value of the variable is replaced with the assigned value.
D. The value of the variable is multiplied by the assigned value.

5. What is the difference between the = operator and the == operator in C#?
A. They are interchangeable.
B. The = operator is used for assignment, while the == operator is used for comparison.
C. The == operator is used for assignment, while the = operator is used for comparison.
D. There is no difference between them.

6. Which of the following is an arithmetic operator in C#?


A. % B. ++ C. && D. ||

7. What is the result of the following expression in C#?


5+3*2
A. 16 B. 11 C. 13 D. 10

8. What is the purpose of the % operator in C#?


A. To perform exponentiation. B. To perform integer division.
C. To perform modulus division. D. To perform bitwise operations.

9. What is the result of the following expression in C#? (7 + 10 / 5 )* 2


A. 18 B. 6.8 C. 13 D. 10

10. What is the result of the following expression in C#? 2 + 3 * 4 - 5


A. 9 B. 11 C. 14 D. 15

62
Name: ____________________________________ Date: __________________
Programming Exercise Score: _________________

Direction: Read and analyze the task carefully before writing your code.

Write a basic cashier system that prompts the user to enter customer’s name and the information of
the item, including the price and quantity purchased. Subsequently, calculate and present the total
payable amount. The system should then request the user's payment input and exhibit the
corresponding change.

$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$

Customer Name: Rosemarie Y. Saligue

Item: Sunsilk Shampoo


Price: 10
Qty: 5
total: 50
Cash:100
Change:50

$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$

63
Common Compound Assignment
Unit 2 Operator & Operator Precedence

At the end of this module, the students should be able to:


a. grasp the concept of compound assignment operators
b. apply compound assignment operators to perform arithmetic operations
c. explore the rules governing operator precedence in C#, including the hierarchy
of operators and how parentheses can be used to override default precedence.

Common Compound Assignment Operator

Compound Assignment Operator


Operator Operator Name Example Expanded to
+= Additional Assignment result+=5 result=result+5
-= Subtraction Assignment result-=5 result=result-5
*= Multiplication Assignment result*=5 result=result*5
/= Division Assignment result/=5 result=result/5
%= Modulo Assignment result%=5 result=result%5

Compound assignment operator is usually used if we want to calculate the new value with the
previous result.
Example:

64
Output:
Total (+): 50
Total (+): 140
Total (+): 190
Total (-): 140
Total (-): 50
Total (-): 0

Let’s delve in.


We have, result=0, firstNum=50, secondNum=90, and thirdNum=50.

0 + 50
result=result+firstNum =result now is 50

50 + 90
result=result+secondNum =result now is 140

140 + 50
result=result+thirdNum =result now is 190

190 - 50
result=result-firstNum =result now is 140

140 - 90
result=result - secondNum =result now is 50

50 - 50
result=result-thirdNum =result now is 0

Operator Precedence
The order in which operators are evaluated in an expression is referred to as operator precedence.
Certain operators in C# are evaluated first because they have higher precedence than other
operators. For instance, multiplication rules take precedence over additive rules.
The associativity of the operators determines the evaluation order when two operators have the
same precedence. Others associate from right to left, while some operators associate from left to
right.
You can use parenthesis to specifically describe the order of evaluation in order to eliminate any
doubt about the order of operations. Regardless of the operator precedence, expressions enclosed
in parenthesis are always evaluated first.

65
C# Operator Precedence and its Associativity of operators
Category Operators Associativity
Postfix Increment and Decrement ++, -- Left to Right
Prefix Increment, Decrement and Unary ++, --, +, -, !, ~ Right to Left
Multiplicative *, /, % Left to Right
Additive +, - Left to Right
Relational <, <=, >, >=,==, != Left to Right
Bitwise AND & Left to Right
Bitwise XOR ^ Left to Right
Bitwise OR | Left to Right
Logical AND && Left to Right
Logical OR || Left to Right
Ternary ?: Right to Left
Assignment =, +=, -=, *=, /=, %=, &=, |=, ^=, <<=, Right to Left
>>=
From: https://www.programiz.com/csharp-programming/operator-precedence-associativity

Example:

Output:

289
True

66
Let’s delve in.
sampleResult = firstNum * secondNum - ++thirdNum + --firstNum;
10 30 19 10

Here, we have 5 operators the multiplication, subtraction, prefix


sampleResult=10*30- ++19 + --10; increment, addition, and prefix decrement. The highest priority will be
prefix increment and decrement, multiplicative and lastly the additive.

Computation
10-1=9
sampleResult=10*30 - ++19 + --10;
19+1=20
sampleResult=10*30 - ++19 + 9;
10*30=300
sampleResult=10*30 - 20 + 9;
300-20=280
sampleResult=300 - 20 + 9;
sampleResult=280 + 9;
sampleResult=289;
decisionResult = secondNum >= thirdNum + firstNum
30 20 9

To get the result of our first relational statement (>=), the system will
decisionResult=30>=20+9; process the additive operator first since it has a higher priority than the
relational operator.

decisionResult=30>=29;
decisionResult=true; Given that 30 is greater than 29, the Boolean value of decisionResult will
evaluate to true.

Name: ____________________________________ Date: __________________


Self-Assessment No.11 Score: _________________
Direction: Encircle the letter of the correct answer.

1.What is the output of the following code snippet? int a = 22; a += 10; Console.WriteLine("{0}", a);
a.22 b. 23 c. 32
2.What is the output of the following code snippet? int a = 28; a -= 5; Console.WriteLine("{0}", a);
a.22 b. 23 c. 32
3.What is the output of the following code snippet? int a = 25; a /= 5; Console.WriteLine("{0}", a);
a.25 b. 5 c. 10
4.What is the output of the following code snippet? int a = 28; a %= 5; Console.WriteLine("{0}", a);
a.5 b. 3 c. 10

5.What is the output of the following code snippet? int a = 10; a *= 5; Console.WriteLine("{0}", a);
a.50 b. 15 c. 5

67
Name: ____________________________________ Date: __________________
Programming Exercise Score: _________________

Direction: Read and analyze the task carefully before writing your code
Develop a basic cashier system that prompts the user to enter customer’s name and the information
for 5 items, including their respective prices and quantities purchased. Subsequently, calculate and
present the total payable amount using the provided data. The system should then request the user's
payment input and exhibit the corresponding change.

$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$

Customer Name: Rosemarie Y. Saligue

Item No.1: Sunsilk Shampoo


Price: 10
Qty: 5
Sub-total: 50

Item No.2: Keratin Conditioner


Price: 10
Qty: 3
Sub-total: 30

Item No.3: Safeguard


Price: 30
Qty: 1
Sub-total: 30

Item No.4: Colgate Toothpaste


Price: 13
Qty: 1
Sub-total: 13

Item No.5: Toothbrush


Price: 50
Qty: 2
Sub-total: 100

Total Payment: 223


Cash: 250
Change: 27

$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$

68
Unit 3 RELATIONAL & LOGICAL OPERATOR

At the end of this module, the students should be able to:


a. apply logical operators to construct complex boolean expressions in conditional
statements
b. apply relational operators to compare values in conditional statements
c. construct chained relational expressions using multiple relational operators to
compare multiple values simultaneously.

Relational Operators
Relational operators compare two operands and return a boolean value of true if the comparison is
valid, and false if it is not. Relational operators are used in decision making and loops.

C# Relational Operators
Operator Operator Name Example
== Equal to 50 == 90 results to false
> Greater than 50 > 90 results to false
< Less than 50 < 90 results to true
>= Greater than or equal to 50 >= 90 results to false
<= Less than or equal to 50 <= 90 results to true
!= Not equal to 50 != 90 results to true

Example:

69
Output:
False
False
True
False
True
True

Logical Operator
Logical operator is used to check the combine 2 or more operands. For example, if the logical
operator used is && (and), all the operands must result with true to have result of true.

Logical Operator Operand 1 Operand 2 Result


&& (And) True True True
False True False
True False False
False False False
|| (Or) True True True
False True True
True False True
False False False

Example:

Logical Operator Operand 1 Operand 2 Result


&& (And) 50==90 50==50
False True False
50>=90 50>=50
False True False
50<=90 50<=50
True True True
|| (Or) 50==90 50==50
False True True
50>=90 50>=50
False True True
50<=90 50<=50
True True True

The AND (&&) and OR (||) logical operators differ in that for an AND operation to result in true, all its
operands must be true, whereas for an OR operation to result in true, only one of its operands needs
to be true.

70
Sample Code:

Output:
False
False
True
True
True
True

71
Name: ____________________________________ Date: __________________
Self-Assessment No. 12 Score: _________________

Direction: Encircle the letter of the correct answer.

1. Which of the following is a relational operator?


a. && b. || c. != d. +

2. What is the output of the following code snippet?


int a = 23; float b = 25.0f; Console.WriteLine("{0}",(a<b));
a. 25 b. true c. false d. 23

3. What is the output of the following code snippet?


string a = "Hello"; string b = "Philippines"; Console.WriteLine("{0}",(a==b));
a. Hello b. true c. false d. Philippines

4. What is the result of the following code snippet?


string a = "Hello"; string b = "Philippines"; Console.WriteLine("{0}",(a<=b));
a. The output will display "True"
b. The result will display "Hello Philippines"
c. The result will display "Error 1 Operator '<=' cannot be applied to
operands of type 'string' and 'string' "
d. The result will display "False"

5. What is the output of the following code snippet?


int a = 55; int b = 33; Console.WriteLine("{0}",(a!=b));
a. 55 b. true c. false d. 33

6. Which of the following is the correct operator to check if at least one of two conditions is true?
a. || b. && c. ! d. =

7. What is the output of the following code snippet?


int a = 12; int b =21; int c=11; Console.WriteLine("{0}",(a<b || a<c));
a. 12 b. true c. false d. 21

8. What is the output of the following code snippet?


int a = 12; int b =21; int c=15; Console.WriteLine("{0}",(a>b && a>c));
a. 12 b. true c. false d. 21

9. What is the output of the following code snippet?


int a = 22; int b =21; int c=22; Console.WriteLine("{0}",(a==b || a==c));
a. 22 b. true c. false d. 21

10. What is the output of the following code snippet?


int a = 22; int b =21; int c=22; Console.WriteLine("{0}",(a==b && a==c));
a. 22 b. true c. false d. 21

72
Unit 4 UNARY & TERNARY OPERATOR

At the end of this module, the students should be able to:


a. apply unary operators to perform arithmetic operations such as negation and
increment/decrement on variables
b. implement inline conditional logic
c. use of nested ternary expressions to handle multiple conditional branches
within a single expression.

Unary Operator

Unary Operators
Operator Operator Name Example
+ Unary Plus (prefix) 10
- Unary Minus (prefix) -10
++ Increment (prefix and postfix) 10+1=11
-- Decrement (prefix and postfix) 10-1=9
! Logical Negation (Not) (prefix) !(false)= true

Example 1:

Output:
10
-10
True

Based on example 1, these three unary operators (+, - and!) are all prefixes.

73
Example 2:

Output:
prefix increment: 11
prefix decrement: 10
result: 10
postfix increment: 10
postfix decrement: 11
result: 10

Observed our example 2 result, in both prefix increment and decrement, the change of value is seen
on the same line while in postfix the change of value is seen on the next line.

Ternary Operator
The ternary operator is a shorthand for if-then-else statement. Below is the syntax of ternary
operator:
variable = Condition? Expression1 : Expression2;

74
Sample Code:
using System;
namespace ProgrammingApplication
{
class TernaryOperator
{
static void Main(string[] args)
{
int firstNum, secondNum,thirdNum;
string displayResult;

firstNum = 50;
secondNum = 90;
thirdNum=50;

displayResult = (firstNum == secondNum) ? "firstNum is equal to secondNum" : "firstNum is not equal to secondNum";
Console.WriteLine(displayResult);

displayResult = ((firstNum >= secondNum) && (firstNum >= thirdNum)) ? "The statement is true" : "The statement is false";
Console.WriteLine(displayResult);

displayResult = ((firstNum <= secondNum) && (firstNum <= thirdNum)) ? "The statement is true" : "The statement is false";
Console.WriteLine(displayResult);

Console.ReadKey();
}
}
}

Output:
firstNum is not equal to secondNum
The statement is false
The statement is true

75
Name: ____________________________________ Date: __________________
Self-Assessment No. 13 Score: _________________

Direction: Encircle the letter of the correct answer.

1. What is the output of the following code snippet?


int a = 23; Console.WriteLine("{0}", ++a);
a. 23 b. 24 c. 22 d. None of the choices

2. What is the output of the following code snippet?


int a = 25; Console.WriteLine("{0}", a++);
a. 25 b. 26 c. 24 d. None of the choices
3. What is the output of the following code snippet?
int a = 25; Console.WriteLine("{0}", !(a!=25));
a. 25 b. true c. false d. None of the choices
4. What is the output of the following code snippet?
int a = 23; Console.WriteLine("{0}", --a);
a. 23 b. 24 c. 22 d. None of the choices
5. What is the output of the following code snippet?
int a = 25; Console.WriteLine("{0}", a--);
a. 25 b. 26 c. 24 d. None of the choices
6. What is the output of the following code snippet?
int a = 22; int b = 21; Console.WriteLine("{0}", (a < b?a:b));
a. 22 b. true c. false d. 21

7. What is the output of the following code snippet?


int a = 22; int b = 21; int c = 18;
Console.WriteLine("{0}", (a > b && a > c ? "Highest!" : "Not Highest!"));
a. Highest! b. Not Highest! c. None of the choices

8. What is the output of the following code snippet?


int a = 22; int b = 21; int c = 18;
Console.WriteLine("{0}", (b > a ||b > c ? "Highest!" : "Not Highest!"));
a. Highest! b. Not Highest! c. None of the choices

9. What is the output of the following code snippet?


int a = 22; int b = 21; int c = 18;
Console.WriteLine("{0}", (b > a &&b > c ? "Highest!" : "Not Highest!"));
a. Highest! b. Not Highest! c. None of the choices

10. What is the output of the following code snippet?


int a = 22; int b = 21; int c = 18;
Console.WriteLine("{0}", (!(b > a && b > c) ? "Highest!" : "Not Highest!"));
a. Highest! b. Not Highest! c. None of the choices

76
Name: ____________________________________ Date: __________________
Programming Exercise Score: _________________

Direction: Read and analyze the task carefully before writing your code
Based from our previous activity, if the user enters an amount less than the total payment, the
change will yield a negative value. In this context, we will address this issue by employing the ternary
operator. Rather than displaying a negative value, the system should instead show the message
"insufficient amount." But if the amount is exact or higher than the total amount to be paid, then the
change will be displayed. Sample output is shown below:

$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$

Customer Name: Rosemarie Y. Saligue

Item No.1: Sunsilk Shampoo


Price: 10.00
Qty: 5
Sub-total: 50

Item No.2: Keratin Conditioner


Price: 10.00
Qty: 3
Sub-total: 30

Item No.3: Safeguard


Price: 30.00
Qty: 1
Sub-total: 30

Item No.4: Colgate Toothpaste


Price: 13.00
Qty: 1
Sub-total: 13

Item No.5: Toothbrush


Price: 50.00
Qty: 2
Sub-total: 100

Total Payment: 223


Cash: 200
Insufficient Amount

$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$

77
MODULE 5
Decision Making Statements

In this module, there are 3 units. Unit 1 covers the significance and symbols of algorithms and
flowcharts. Following that, Unit 2 delves into the if statements, followed by Unit 3, which discusses the switch
statement.

As you progress through the module, keep in mind that most units conclude with an assessment or a
series of assessments. So, make sure to complete them before moving on to the next part of the course.

Lastly, remember to have fun throughout the entire learning process. Enjoy!

You are now embarking on a journey filled with valuable experiences and
enriching learning opportunities. Engage in the exercises and respond to the
suggested worksheets to immerse yourself in a lifelong journey of practical
learning that awaits you upon completing this module.

ENJOY YOUR JOURNEY!

78
Unit 1 ALGORITHM AND FLOWCHART

At the end of this module, the students should be able to:


a. grasp the fundamental concept of algorithms as step-by-step procedures for
solving problems or accomplishing tasks.
b. create simple algorithms for solving basic problems, demonstrating their
understanding of algorithmic logic and structure.
c. analyze and debug flowcharts to identify errors, inefficiencies, or logical
inconsistencies in algorithmic designs.
d. apply flowcharts as problem-solving tools to analyze, plan, and execute
solutions for various real-world problems or scenarios.

A flowchart is a diagram that shows the logical steps that must be taken to resolve a problem. This
diagram is necessary in creating your system. It shows the path of the logic of the algorithm from
start to finish. The following standard symbols are used to create flowcharts.

Symbol Name Function

This symbol represents a process


Process

A parallelogram represents input


or output.
Input/output

This symbol indicates a decision


Decision (True or False)

Allows the flowchart to be drawn


without intersecting lines or
Page Connector without a reverse flow.

Indicates the starting or ending of


the program, process, or interrupt
Terminator program.

Show direction of flow.

Flow Arrow

Retrieved from: https://www.smartdraw.com/flowchart/flowchart-symbols.htm

79
Algorithm and flowchart are essential tools in program development. Prior to coding, it is
necessary to establish a procedural strategy for solving the current issue must be
established. A series of detailed instructions detailing how to solve a particular problem like
algorithm is commonly used. It is crucial that each stage of the problem-solving process is
clearly and accurately specified to achieve a definitive solution.

Example
Scenario: Write an algorithm and a flowchart that will prompt the user to input grades in
Math from first grade up to fourth grade. The system will calculate the average grade across
the four grading periods and will display either "PASS" if the average is 75 or higher, or "FAIL"
if it is below 75.

Algorithm:
1. Start
2. Input the four grades of the students in Math (firstGrading, secondGrading,
thirdGrading & fourthGrading)
3. Compute the average grade average=( firstGrading+ secondGrading+ thirdGrading +
fourthGrading)/4
4. Determine if the average is greater than or equal to 75, if yes display “PASS”,
otherwise, display “FAIL”
5. End

Flowchart:

80
Name: ____________________________________ Date: __________________
Self-assessment No.14 Score: _________________

Direction: Encircle the letter of the correct answer.

1. What symbol in a flowchart represents a process or action to be taken?


A. Parallelogram B. Diamond C. Rectangle D. Circle

2. Which symbol is used to indicate a decision point in a flowchart?


A. Parallelogram B. Diamond C. Rectangle D. Circle

3. What does the parallelogram symbol represent in a flowchart?


A. Start or End B. Input/Output C. Decision D. Process

4. What is the purpose of a page connector in a flowchart?


A. To indicate the start or end of a process
B. To represent an input or output operation
C. To avoid intersecting lines or reverse flow
D. To show direction of flow

5. Which symbol indicates the starting or ending of the program in a flowchart?


A. Parallelogram B. Diamond C. Rectangle D. Oval

6. In algorithm development, why is it important to clearly define each stage of the


problem-solving process?
A. To ensure ambiguity
B. To make the problem-solving process more complex
C. To achieve a definitive solution
D. To avoid writing code

7. What is the first step in creating an algorithm?


A. Input data B. Start C. Output results D. End

8. Which flowchart symbol should be used to represent the calculation of the average
grade?
A. Parallelogram B. Diamond C. Rectangle D. Oval

9. In a flowchart, how is the flow of the process typically indicated?


A. With arrows B. With circles
B. With rectangles D. With squares

10. What is the primary purpose of using a flowchart in system design?


A. To create complex designs
B. To simplify the logic of a system
C. To replace written code
D. To obscure the logic of a process

81
Unit 2 IF STATEMENTS

At the end of this module, the students should be able to:


a. comprehend and explain how conditional statements (If, If…Else, If…Else If…Else)
are used to control the flow of a program based on different conditions.
b. write and implement simple If statements to perform specific actions when a
particular condition is true.
c. construct and utilize If…Else statements to execute alternative blocks of code
when the specified condition is false.
d. apply nested If and Else If statements to handle multiple conditions in a
structured and efficient manner.
e. identify and correct logical errors in the use of If, If…Else, and If…Else If…Else
statements to ensure accurate program execution.

C# IF Statements
There are various types of if statements in c#, these are the following:
➢ If statement
➢ If…else statement
➢ If…else if…else statement
➢ Nested if statement
C# IF Statement
The syntax of if statement in C# is:
if (boolean-expression)
{
// statements executed if boolean-expression is true
}

IF Statement Flowchart

START

FALSE
Boolean-expression

TRUE

execute code
(INSIDE IF STATEMENT)

END

82
In C# if statement, once the condition or Boolean expression is true, the block of code inside
the if statement will be executed. And if false, the statements inside the if statement will be
ignored.

Example 1
Scenario: Write a C# program that will check if the entered value is less than 20, if yes,
display text “The number is less than 20”.

Flowchart:

START

input number

FALSE
number<20

TRUE

Print “The number is less than 20”

END

Sample Code
using System;
namespace ProgrammingApplication
{
class IfStatement
{
public static void Main(string[] args)
{
int number;
Console.Write("Enter a number:");
number = int.Parse(Console.ReadLine());
if (number < 20)
{
Console.WriteLine("The number is less than 20");
}
Console.ReadKey();
}
}
}

83
Let’s delve in.
If Boolean-Expression is true

If Boolean-Expression is false

Output 1: (if Boolean-expression is true)

Enter a number: 15
The number is less than 20

Output 2: (if Boolean-expression is true)

Enter a number: 21

The outputs 1 and 2 show that the entered numbers are not the same. Also, the if statement
will only run if the entered number is less than 20 in accordance with the stated condition.
Given that the entered value is less than 20, the Boolean expression in Output 1 is true. Thus,
the statements included within the if statement will be carried out. As the Boolean
expression in the if statement for output 2 returned false, code execution immediately shifts
to the next line of code after the closing curly bracket.

84
C# if...else (if-then-else) Statement
The syntax of if...else statement in C# is:
if (boolean-expression)
{
// statements executed if boolean-expression is true
}
else
{
// statements executed if boolean-expression is false
}

If…else… Statement Flowchart

START

FALSE
Boolean-expression

TRUE
execute code
execute code (INSIDE ELSE STATEMENT)
(INSIDE IF STATEMENT)

END

The if statement in C# may have an optional else statement. The block of code inside the else
statement will only be executed if the Boolean-expression is false. But if the Boolean-
expression is true, the code inside if statement will be executed and the code inside else
statement will be ignored.
An optional else statement may be included in a C# if statement. The code inside the if block
will be performed while the code inside the otherwise block is disregarded if the Boolean
expression in the if statement is true. If the Boolean statement is false, the else block's code
will be run in its place.

Example

Scenario: Write a C# program that will check if the entered number is less than 20, if yes,
display text “The number is less than 20”, otherwise display “The number is equal or greater
than 20”

85
Flowchart:

START

input number

FALSE
number<20

Print “The number is equal or


greater than 20”
TRUE

Print “The number is less


than 20”

END

Sample Code:

Let’s delve in.


If Boolean-Expression is true

86
If Boolean-Expression is false

Output 1: (if Boolean-expression is true)

Enter a number: 15
The number is less than 20

Output 2: (if Boolean-expression

Enter a number: 21
The number is equal or greater than 20

Else statement will handle the false Boolean-expression of if statement.

C# if...else if (if-then-else if) Statement


The syntax for if...else if statement is:
if (boolean-expression-1)
{
// statements executed if boolean-expression-1 is true
}
else if (boolean-expression-2)
{
// statements executed if boolean-expression-2 is true
}
else if (boolean-expression-3)
{
// statements executed if boolean-expression-3 is true
}
.
.
.
else
{
// statements executed if all above expressions are false
}

87
Flowchart
This statement will test multiple conditions. The if statements are
executed from the top down. As soon as one of the conditions is true,
the statement associated with that if is executed, and the rest of the
else-if ladder is bypassed. If none of the conditions are true, then the
START final else statement will be executed.

TRUE execute code


Boolean-expression 1 (INSIDE ELSE IF STATEMENT 1)

FALSE

TRUE execute code


Boolean-expression 2
(INSIDE ELSE IF STATEMENT 2)

FALSE

TRUE execute code


Boolean-expression 3
(INSIDE ELSE IF STATEMENT 3)

FALSE

execute code
(INSIDE ELSE STATEMENT)

END

Example
Scenario: Write a system that will ask the user to input the final grade. And based on the
entered grade, the system will display its interim grade letter and its description.

Final Mark Interim grade letter Description


90-100 HD High Distinction
80-89 D Distinction
75-79 P Pass
0-74 F Fail

88
Flowchart:

START

Input finalGrade

Print “Interim grade letter: HD”


finalGrade>=90 TRUE Print “Description: High
&& finalGrade<=100 Distinction

FALSE

finalGrade>=80 TRUE Print “Interim grade letter: D”


&& finalGrade<=89 Print “Description: Distinction

FALSE

finalGrade>=75 && TRUE Print “Interim grade letter: P”


finalGrade<=79 Print “Description: Pass

FALSE

TRUE
finalGrade>=0 && Print “Interim grade letter: F”
finalGrade<=74 Print “Description: Fail

FALSE

Print “Out of Range”

END

89
Sample Code
using System;
namespace ProgrammingApplication
{
class IfElseIfStatement
{
public static void Main(string[] args)
{
float finalGrade;
Console.Write(“Enter Final Grade:”);
finalGrade = float.Parse(Console.ReadLine());
if (finalGrade >= 90 && finalGrade <= 100)
{
Console.WriteLine("Interim grade letter: HD”);
Console.WriteLine("Description: High Distinction”);
}
else if (finalGrade >= 80 && finalGrade <= 89)
{
Console.WriteLine("Interim grade letter: D”);

Console.WriteLine("Description: Distinction”);
}
else if (finalGrade >= 75 && finalGrade <= 79)
{
Console.WriteLine("Interim grade letter: P”);
Console.WriteLine("Description: Pass”);
}
else if (finalGrade >= 0 && finalGrade <= 74)
{
Console.WriteLine("Interim grade letter: F”);
Console.WriteLine("Description: Fail”);
}
else
{
Console.WriteLine("Out of Range");
}
Console.ReadKey();
}
}
}

Output 1 (if Boolean-expression 1 is true)


Enter Final Grade: 92
Interim grade letter: HD
Description: High Distinction

Output 2 (if Boolean-expression 2 is true)


Enter Final Grade: 83
Interim grade letter: D
Description: Distinction

Output 3 (if Boolean-expression 3 is true)


Enter Final Grade: 76
Interim grade letter: P
Description: Pass

Output 4 (if Boolean-expression 4 is true)


Enter Final Grade: 70
Interim grade letter: F
Description: Fail

90
Output 5 (if Boolean-expression 1-4 is false)
Enter Final Grade: 102
Out of Range

Nested If Statement
When a series of decision is required, nested if-else is used. Nested if statement means an if
statement inside if statement.
The syntax for a nested if-else statement is as follows −
if( boolean_expression 1)
{
/* Executes when the boolean expression 1 is true */
if(boolean_expression 2) {
/* Executes when the boolean expression 2 is true */
}
else
{
// statements executed if all above expression is false
}
}

Flowchart

START

TRUE Nested FALSE


Boolean-expression execute code
Boolean-expression
(INSIDE ELSE STATEMENT)

TRUE
FALSE

execute code
(INSIDE IF STATEMENT)

END

Example
Scenario: Create a system that will ask the user to enter a number. If the number is lesser
than 20 it will display “The number is lesser than 20.” However, if the entered number is
greater than or equal to 20, the system will recognize if it is even or odd.

91
Flowchart:

START

Input number

TRUE TRUE
number>=20 number%2==0 Print “Even Number”

FALSE FALSE

Print “The number is lesser Print “Odd Number”


than 20”

END
Sample Code

Output 1 (if the user entered a number greater than or equal to 20)

Enter a number: 20
Even Number

Output 2 (if the user entered a number lesser than 20)

Enter a number: 15
The Number is lesser than 20 92
Name: ____________________________________ Date: __________________
Self-assessment No.15 Score: _________________
Direction: Encircle the letter of the correct answer.
1. What is the primary function of an "If" statement in programming?
A. To create loops B. To perform arithmetic operations
C. To execute code based on a condition D. To define variables

2. Which of the following is a correct syntax for an "If" statement in most programming
languages?
A. if condition B. if (condition) { } C. if { condition } D. if: condition

3. What will the following code output? if (5 > 3) { console.log("True"); }


A. No output B. "False" C. "True" D. An error

4. Which of the following conditions will make an "If" statement true?


A. if (0) B. if (false) C. if (1) D. if ("")

5. In an "If" statement, what does the condition evaluate to for the block of code to
execute?
A. String B. Boolean C. Integer D. Array

6. What happens if the condition in an "If" statement is false and there is an "Else"
statement?
A. The program stops B. The "Else" block of code is executed
C. The "If" block is executed D. The program skips to the next statement

7. What is the output of the following code? if (5 < 3) { console.log("True"); } else {


console.log("False"); }
A. No output B. "True" C. "False" D. An error

8. In an "If…Else" statement, how many times can the "Else" block be executed?
A. Multiple times B. Once per condition C. Never D. Only once

9. Which of the following is NOT true about "If…Else" statements?


A. They can handle two possible outcomes.
B. They must always have an "Else" block.
C. They can be nested within each other.
D. The "Else" block executes if the "If" condition is false.

10. What does the "Else" keyword represent in an "If…Else" statement?


A. A loop structure B. An alternative block of code
C. A condition D. A function call

11. Which statement is true about "If…Else If…Else" structures?


A. They can only handle one condition.
B. They can handle multiple conditions with different outcomes.
C. They always require an "Else If" block.
D. They are only used in loops.

93
12. In an "If…Else If…Else" structure, which block of code is executed if none of the
conditions are true?
A. The "If" block B. The "Else If" block
C. The "Else" block D. None of the blocks are executed

13. How many "Else If" blocks can you have in an "If…Else If…Else" structure?
A. Only one B. Two C. As many as needed D. None

14. Which of the following conditions will be evaluated first in an "If…Else If…Else"
structure?
A. The "Else" condition B. The first "If" condition
C. The first "Else If" condition D. The last "Else If" condition

15. What will the following code output? if (false) { console.log("False"); } else if (true) {
console.log("True"); } else { console.log("Neither"); }
A. "False" B. "True" C. "Neither" D. No output

16. Which block will execute in the following code? if (3 == 4) { console.log("A"); } else if
(3 > 4) { console.log("B"); } else { console.log("C"); }
A. "A" B. "B" C. "C" D. No block will execute

17. If the "If" condition is true, what happens to the "Else If" and "Else" conditions?
A. They are evaluated as well B. They are skipped
C. They cause an error D. They are ignored but still executed

18. Which statement is true regarding nested "If…Else If…Else" structures?


A. They cannot contain more than two levels.
B. They must have a return statement.
C. They allow complex decision-making.
D. They always require an "Else" block.

19. What is a common mistake when using "If…Else If…Else" structures?


A. Forgetting to close brackets
B. Placing the "Else" block before the "If" block
C. Using too many conditions
D. Not having an "Else If" block

20. In an "If…Else If…Else" structure, how can you ensure the correct condition is being
evaluated?
A. By adding print statements within each block B. By removing the "Else If" block
C. By using an infinite loop D. By avoiding the "Else" block

21. Why is the order of conditions important in an "If…Else If…Else" structure?


A. Because the conditions are evaluated in reverse order
B. Because the first true condition determines the executed block
C. Because the "Else" block always runs first
D. Because conditions are evaluated randomly

94
22. What will the following code output? if (false) { console.log("X"); } else if (false) {
console.log("Y"); } else { console.log("Z"); }
A). "X" B. "Y" C. "Z" D. No output

23. What happens if no condition is true in an "If…Else If…Else" structure, and there is
no "Else" block?
A. The program will crash
B. An error will be thrown
C. The program continues without executing any block
D. The first block will be executed by default

26. Which of the following is a correct way to combine conditions in an "If" statement?
A. if (condition1 and condition2) B. if (condition1 || condition2)
C. if (condition1 & condition2) D. if (condition1 ||| condition2)

27. In an "If…Else If…Else" structure, when should the "Else" block be omitted?
A. When all possible conditions are accounted for
B. When the program needs to loop
C. When the "If" condition is always true
D. When there are no alternative outcomes

28. What is the best practice when writing "If…Else If…Else" structures with multiple
conditions?
A. Always include an "Else" block
B. Use nested "If" statements instead
C. Keep the conditions as simple as possible
D. Avoid using "Else If"

29. What will be the output of the following code? if (false && true) { console.log("1"); }
else if (true || false) { console.log("2"); } else { console.log("3"); }
A. "1" B. "2" C. "3" D. No output

30. Which of the following is an example of a nested "If" statement?


A. if (condition) { if (condition) { } }
B. if (condition) { else { if (condition) { } } }
C. if (condition) { } else if (condition) { }
D. if (condition) else { if (condition) { } }

95
Name: ____________________________________ Date: __________________
Programming Exercises Score: _________________

Direction: Using the C# console application, read and analyze the task carefully before
writing your code.
Exercise 1: Write a system that will ask the user to input their choices based on the options.
If the entered option is none of the choices, the system will display “None of the choices.”
The first options are as follows:

Available Products
A. Shampoo
B. Toothpaste

If the user will choose option A, available shampoo will be displayed.

Product: Shampoo
Available
Items Price
A. Sunsilk Php6.00
B. Vaseline Php5.00

If the user will choose option B, available shampoo will be displayed:

Product: Toothpaste
Available
Items Price
A. Colgate Php36.00
B. Pepsodent Php35.00
Exercise 2: Continuation of Exercise 1. Write a simple cashiering system that will ask the user
to input their choices based on the options. If the entered option is none of the choices, the
system will display “None of the choices.”

The first options are as follows:


Available Products
A. Shampoo
B. Toothpaste

If the user will choose option A, available shampoo will be displayed.

Product: Shampoo
Available
Items Price
A. Sunsilk Php6.00
B. Vaseline Php5.00

96
If the user will choose option B, available shampoo will be displayed:

Product: Toothpaste
Available
Items Price
A. Colgate Php36.00
B. Pepsodent Php35.00
From this point, the user has the ability to enter the desired item for purchase along with the
quantity desired. Additionally, the user retains the option to select another item by inquiring
whether they wish to add another item. If the user affirms, the system will revert to the initial
choices, which encompass the available products. This cycle continues until the user opts for
"no." Upon making the new selections, the cumulative payment required for the chosen items
and quantities becomes visible. The system will then prompt the user for payment and
exhibit the resulting change. Should the payment fall short of the total amount, the system
will indicate insufficiency and request further payment. Conversely, if the payment matches
or exceeds the total, the system will reveal the change amount.

97
Unit 3 SWITCH STATEMENT

At the end of this module, the students should be able to:


a. comprehend the syntax and structure of switch statements.
b. compare and contrast switch statements with if…else statements, recognizing
when it is more appropriate to use one over the other.
c. write and implement switch statements in various programming scenarios to
handle multiple conditions effectively.
d. incorporate and understand the importance of the default case in a switch
statement to ensure that the program can handle unexpected or unlisted values.

C# Switch Statement
Switch statement can be used to replace the if...else if statement in C#. Its advantage is its
codes looks much cleaner and readable than if…else statement.

The syntax of switch statement is:


switch (variable/expression)
{
case value1:
// Statements executed if expression(or variable) = value1
break;
case value2:
// Statements executed if expression(or variable) = value1
break;
... ... ...
... ... ...
default: /*optional*/
// Statements executed if no case matches
}

98
Flowchart

START

VARIABLE/EXPRESSION

MATCHED
CASE 1 EXECUTE CODE BLOCK 1 BREAK

UNMATCHED
MATCHED
CASE 2 EXECUTE CODE BLOCK 2 BREAK

UNMATCHED
MATCHED
CASE n EXECUTE CODE BLOCK 3 BREAK

UNMATCHED

DEFAULT EXECUTE CODE BLOCK N BREAK

END

The image depicts a flowchart representing the logic of a "Switch" statement in programming.
Here's a breakdown of the components and their function:
1. Start: This flowchart starts from the "Start" symbol, which indicates the beginning of
the process for the switch statement.
2. Cases:
o The flowchart has multiple decision points labeled as "CASE 1," "CASE 2," "CASE
n," representing different cases that the switch statement evaluates. Each
"CASE" diamond represents a specific, unique condition or value being
checked against the input variable.
3. Code Blocks:
o For each case, there is an associated code block (e.g., "EXECUTE CODE BLOCK
1," "EXECUTE CODE BLOCK 2") that is executed if the condition matches the
input.The code blocks contain the actions or operations that will be
performed when a particular case is true.
4. Break Statements:
o After each code block, there is a "BREAK" statement, which is used to
terminate the switch statement and prevent further cases from being
evaluated. This ensures that only one case block is executed.

99
5. Default Case:
o The "DEFAULT" case is included at the end, which serves as a fallback option.
If none of the specified cases match the input, the code in the "DEFAULT" block
is executed. Like the other cases, it also has an associated "BREAK" statement.
6. End:
o The flowchart concludes at the "END" symbol, indicating the termination of
the switch statement process.
Write a system that will ask the user to enter first and second number. Then, the system will
ask the user to enter what operator to be used (+, -, *, /).

Flowchart:

100
Sample Code

Output 1 (if the user entered 2 numbers and selected the addition operator)

Enter first number: 23


Enter second number: 10
Enter operator (+, -, *, /): +
23 + 10 = 33

Output 2 (if the user entered 2 numbers and selected the multiplication operator)

Enter first number: 23


Enter second number: 10
Enter operator (+, -, *, /): *
23 * 10 = 230

Output 3 (if the user entered 2 numbers and entered the invalid operator)

Enter first number: 23


Enter second number: 10
Enter operator (+, -, *, /): #
Invalid Operator
101
The Switch statement in C# allows us to add a default statement. If the variable value does
not match with any of the case statements, the code present in the default will execute.
A break case is useful to come out from the switch statement. Otherwise, all the statements
in the condition will execute. Whenever a Break Statement encountered, the execution flow
would directly come out of it.

102
Name: ____________________________________ Date: __________________
Self-Assessment No.16 Score: _________________

Direction: Encircle the letter of the correct answer.


1. What is the primary use of a switch statement in programming?
A. To create loops
B. To execute code based on different conditions
C. To perform arithmetic operations
D. To define variables

2. Which keyword is used to define a switch statement in most programming


languages?
A. case B. switch C. if D. else

3. In a switch statement, what keyword is used to specify different possible values of a


variable?
A. switch B. case C. default D. break

4. What is the purpose of the break statement in a switch block?


A. To exit the switch block and prevent the execution of subsequent cases
B. To continue to the next case
C. To terminate the program
D. To skip the current case

5. What will happen if there is no break statement after a case in a switch statement?
A. The program will stop executing
B. The next case will automatically execute
C. The switch statement will not compile
D. An error will occur

6. What is the purpose of the default case in a switch statement?


A. To execute code if none of the specified cases match
B. To end the switch statement
C. To specify the first case to be executed
D. To continue to the next case
7. Where is the default case typically placed in a switch statement?
A. At the beginning B. In the middle
C. At the end D. Anywhere
8. What happens if the switch statement does not include a default case?
A. The program will crash
B. The program will execute the first case
C. The program will skip the switch statement
D. The program will do nothing if no cases match
9. Which keyword must be used at the end of each case block in a switch statement to
prevent "fall-through"?
A. continue B. stop C. return D. break

103
10. Which of the following is a correct syntax for a switch statement?
A. switch(variable) { case value1: ... } B. switch: { case variable; ... }
C. switch(variable) { case = value1; ... } D. switch(variable) [ case value1: ... ]

11. What happens if two cases in a switch statement have the same value?
A. The switch statement will run both cases
B. The switch statement will run only the first case
C. The switch statement will throw an error
D. The switch statement will not run either case

12. If a switch statement does not match any case and has no default case, what will
happen?
A. The first case will execute
B. The last case will execute
C. The program will crash
D. The switch statement will exit without executing any code

13. In which of the following situations would a switch statement be more appropriate
than an if-else chain?
A. When you have multiple cases to check against a single variable
B. When you need to compare ranges of values
C. When you are working with Boolean values
D. When you only have two possible conditions

14. What is a common error when using switch statements?


A. Forgetting the default case
B. Using multiple cases with the same value
C. Using break statements incorrectly
D. All of the above

15. Can switch statements be nested within each other?


A. Yes, switch statements can be nested
B. No, switch statements cannot be nested
C. Only in certain programming languages
D. It depends on the compiler

Name: ____________________________________ Date: __________________


Programming Exercise Score: _________________
Direction: Using the C# console application, read and analyze the task carefully before
writing your code.
Exercise: Create a program that acts as a simple calculator. The program will prompt the
user to enter two numbers and an operation they want to perform (addition, subtraction,
multiplication, or division). Use a switch statement to determine which operation to perform
based on the user's input.

104
MODULE 6
Looping Statements

This module is divided into four major units, with one control flow statement covered in each. Unit 1
introduces the 'for loop' statement, a structured approach to iteration over some sequence of values. Unit 2
will talk about statements for 'while loops', explaining how some block of code can be repeatedly executed
under some given condition. Unit 3: The general 'do…while loop' statement ensures that a code block is run at
least once before the condition is evaluated. Unit 4: Goto statement: this is a device of flow control that
enables an unconditional jump into some part of the code, although in modern programming, it is normally
used with caution.

As you progress through the module, keep in mind that most units conclude with an assessment or a
series of assessments. So, make sure to complete them before moving on to the next part of the course.

Lastly, remember to have fun throughout the entire learning process. Enjoy!

You are now embarking on a journey filled with valuable experiences and
enriching learning opportunities. Engage in the exercises and respond to the
suggested worksheets to immerse yourself in a lifelong journey of practical
learning that awaits you upon completing this module.

ENJOY YOUR JOURNEY!

105
Unit 1 FOR LOOP STATEMENT

At the end of this module, the students should be able to:


a. explain the components of a for loop, including initialization, condition, and
iteration expressions, and understand how these elements control the loop's
execution.
b. write for loops to solve problems involving iteration, such as iterating over
arrays, lists, or ranges of values in different programming contexts.
c. recognize opportunities to use for loops to simplify code, reduce redundancy,
and enhance the efficiency of algorithms.

C# for Loop
The for keyword is used to create for loop in C#. The ‘for’ loop is also used for iterative
purposes.
The syntax for for loop is:
for (initialization; condition; increment)
{
// body of for loop
}

Flowchart:
START

Initialization Statement

FALSE
Test Expression

TRUE

execute code
(INSIDE FOR LOOP STATEMENT)

Counter Statement

END

106
Example 1
Scenario: Create a C# program that iterates 5 times and displays the iteration number along
with the phrase "Sample Iteration number nth".

Flowchart:

START

i=1

FALSE
i<=5

TRUE

Print
Sample Iteration number i

i++

END

Sample Code
using System;
namespace ProgrammingApplication
{
class ForLoop
{
public static void Main(string[] args)
{
for (int i = 1; i <= 5; i++)
{
Console.WriteLine("Sample Iteration number {0}", i);
}
Console.ReadKey();
}
}
}

Output

Sample Iteration number 1


Sample Iteration number 2
Sample Iteration number 3
Sample Iteration number 4
Sample Iteration number 5 107
How for loop works?

C# for loop has three If the condition is evaluated to true, the


statements: initialization, condition, and statements inside the for loop are executed.
incrementor.

The initialization statement is executed at first and only once.


Here, the variable is usually declared and initialized. In the
example we have i=1.

2 3 4
1

The condition is a boolean expression it returns The iterator (i++) increments the
either true or false. If the condition is evaluated to true: value of i=i+1. For example, from
✓ The statements inside the for loop are executed. i=1, it will become i=2 after
✓ The incrementor statement is executed which usually incremented by 1.
changes the value of the initialized variable.
✓ Again, the condition is evaluated.
✓ The process continues until the condition is evaluated
to false. For example, once the value of i returns to 6
the condition will result to false and the for loop will be
terminated.

Example 2
Scenario: Write a C# program that will display the value of sum and number of loops are
initialized to 0 and 5 respectively. The iteration variable is initialized to 1 and incremented
on each iteration. Inside the for loop, value of sum is incremented by iteration variable i.e.
sum = sum + iteration variable. The for loop continues until iteration variable is less than or
equal to the given number of loops. Then will display the text “Sum:” with the value of
variable sum.

108
Flowchart:

START

n = 5, sum = 0, i=1

FALSE
i<=n

TRUE

sum+=i

Print
Sum: sum value

END

Sample Code:
using System;
namespace ProgrammingApplication
{
class ForLoop
{
public static void Main(string[] args)
{
int n = 5, sum = 0;
for (int i = 1; i <= n; i++)
{
// sum = sum + i;
sum += i;
}
Console.WriteLine("Sum: " + sum);
Console.ReadKey();
}
}
}

Output

Sum: 15

109
Initially, i = 1, sum = 0 and n = 5

Computation Of Sum
sum=sum + i
Value of i i<=5 computation of sum Value of sum
1 True 0+1 1
2 True 1+2 3
3 True 3+3 6
4 True 6+4 10
5 True 10 + 5 15
6 False Loop Terminates

C# nested for loop

A for loop inside another for loop is called nested for loop.

Example:
for (int x=0; x<10; x++)
{
// body of outer for loop
for (int y=0; y<5; y++)
{
// body of inner for loop
}
// body of outer for loop
}

Example
Scenario: Write a C# program that will have an outer loop of 10 and an inner loop of 5. Then,
will display the total counter of inner and outer loop. Outer loop must start with 0 while inner
loop must start with 1.

110
Flowchart:

Sample Code

using System;
namespace ProgrammingApplication
{
class NestedForLoop
{
public static void Main(string[] args)
{
int outerLoop = 0, innerLoop = 0;
for (int x = 0; x < 10; x++)
{
outerLoop++;
for (int y = 1; y <= 5; y++)
{
innerLoop++;
}
}
Console.WriteLine("Outer Loop runs {0} times", outerLoop);
Console.WriteLine("Inner Loop runs {0} times", innerLoop);
Console.ReadKey();
}
}
}

Output
Outer Loop runs 10 times
Inner Loop runs 50 times

111
Name: ____________________________________ Date: __________________
Self-Assessment No.17 Score: _________________

Direction: Encircle the letter of the correct answer.

1. What are the three main components of a for loop?


A) Initialization, Condition, Iteration B) Start, Condition, End
C) Setup, Execution, Termination D) Begin, Middle, End

2. Which of the following is the correct syntax for a for loop in most programming
languages?
A. for (initialization; condition; iteration) { }
B. for (initialization condition iteration) { }
C. for initialization, condition, iteration { }
D. for initialization; condition; iteration; { }

3. In a for loop, when is the iteration expression evaluated?


A. Before the loop starts B. At the end of each iteration
C. Only once at the start D. After the loop ends

4. Which keyword can be used to exit a for loop prematurely?


A. continue B. break C. exit D. return

5. Which of the following can cause an infinite loop?


A. for (int i = 0; i < 10; i++) B. for (int i = 1; i > 0; i++)
C. for (int i = 0; i < 5; i++) D. for (int i = 10; i > 0; i--)

Name: ____________________________________ Date: __________________


Programming Exercise Score: _________________

Direction: Using the C# console application, read and analyze the task carefully before
writing your code.
Exercise: Create a program that calculates the sum of all natural numbers up to a given
number n using a for loop. The user will input the value of n, and the program will output the
sum of all natural numbers from 1 to n.

112
Unit 2 WHILE LOOP STATEMENT

At the end of this module, the students should be able to:


a. write while loops to solve problems where the number of iterations is not known
in advance but depends on a condition that is checked before each iteration.
b. compare and contrast while loops with other loop constructs like for loops

C# while Loop
Same with for loop statement, the while loop is also used for iterative purposes. As long as
the given condition is true, the while loop statement will repeatedly execute.

The syntax of a while loop in C# is:


while(condition)
{
//statement(s);
}

When using the while loop, initialization should be done before the loop starts, and
increment or decrement steps should be inside the loop.

Example
Scenario: Create a C# program that iterates 5 times and displays the iteration number along
with the phrase "Sample Iteration number nth".

Flowchart:

113
Sample code:
using System;
namespace ProgrammingApplication
{
class WhileLoop
{
public static void Main(string[] args)
{
int i = 1;
while (i <= 5)
{
Console.WriteLine("Sample Iteration number {0}", i);
i++;
}
Console.ReadKey();
}
}
}

Output

Sample Iteration number 1


Sample Iteration number 2
Sample Iteration number 3
Sample Iteration number 4
Sample Iteration number 5

114
Name: ____________________________________ Date: __________________
Self-Assessment No.18 Score: _________________

Direction: Encircle the letter of the correct answer.

1. Which of the following is the correct syntax for a while loop in most programming
languages?
A. while (condition) { } B. while { condition }
C. while condition { } D. while: condition

2. When is the condition of a while loop evaluated?


A. After each iteration B. Before each iteration
C. Only once at the beginning D. Only at the end

3. Which keyword can be used to exit a while loop prematurely?


A. continue B. break C. exit D. return

4. What is a common mistake when using while loops?


A. Forgetting to initialize the loop counter
B. Not providing a condition
C. Forgetting to update the loop variable within the loop
D. All of the above

5. In which situation would a while loop be preferred over a for loop?


A. When you need to iterate a fixed number of times
B. When you need to iterate based on a condition that may change during execution
C. When you need to traverse an array
D. When you need to break the loop immediately

Name: ____________________________________ Date: __________________


Programming Exercise Score: _________________
Direction: Using the C# console application, read and analyze the task carefully before
writing your code.
Exercise: Create a program that calculates the sum of all natural numbers up to a given
number n using a for loop. The user will input the value of n, and the program will output the
sum of all natural numbers from 1 to n.

115
Unit 3 DO…WHILE LOOP STATEMENT

At the end of this module, the students should be able to:


a. write and execute do...while loops statement.
b. compare do...while loops with while loops and for loops, recognizing scenarios
where a do...while loop is the most appropriate choice.

C# do...while loop
A do...while loop is similar to a while loop, except that a do...while loop is guaranteed to
execute at least one time.

The syntax of a do...while loop in C# is −

do {
//statement(s);
} while (condition);

Example1
Scenario: Using do…while loop, write a C# program that will start at 10 and will loop until not
lesser than 20. The system will display the text “For example. Loop number” with the value
of variable a. The text will display every time the boolean expression is true.
Flowchart:
START

a = 10

Print
For example. Loop number
value of a

FALSE
a<20

TRUE

a++

116
END
Sample Code:
using System;
namespace ProgrammingApplication
{
class DoWhileLoop
{
static void Main(string[] args)
{
/* local variable definition */
int a = 10;

/* do loop execution */
do
{
Console.WriteLine("For example. Loop number " + a);
a++;
}
while (a < 20);
Console.ReadKey();
}
}
}

Output

For example. Loop number 10


For example. Loop number 11
For example. Loop number 12
For example. Loop number 13
For example. Loop number 14
For example. Loop number 15
For example. Loop number 16
For example. Loop number 17
For example. Loop number 18
For example. Loop number 19

Example 2
Scenario: With the use of a do…while loop, develop a C# program that requests the user's
name and address. Subsequently, the system should inquire if the user wishes to enter more
data. If the user indicates "yes," the program should prompt for their name and address
again. If the user indicates "no," the program will end.

117
Flowchart:

Print Input
START
“Name:” name

Print input Print


“Do you still want to input another address “Address:”
data [Y/N]? : ”

input TRUE
Char.ToUpper
answer (answer)=='Y'

FALSE

END
Sample Code:

using System;
namespace ProgrammingApplication
{
class DoWhileLoop
{
static void Main(string[] args)
{
string name, address;
char answer;
do
{
Console.Write("Name:");
name = Console.ReadLine();
Console.Write("Address:");
address = Console.ReadLine();
Console.Write("Do you still want to input another data [Y/N]?:");
answer = char.Parse(Console.ReadLine());
}
while (Char.ToUpper(answer) == 'Y');
Console.ReadKey();
}
}
}

Output
Name:Rosemarie Y. Saligue
Address:Hilognos, Leyte
Do you still want to input another data [Y/N]?:Y
Name:Chyler Greigh
Address:Brgy. Osao, San Juan, Southern Leyte
Do you still want to input another data [Y/N]?:N

As shown in the output, in case the user responds with "Y," the system will prompt for the
user's name and address again. However, if the user opts for "N," the program will terminate.

118
Name: ____________________________________ Date: __________________
Self-Assessment No.19 Score: _________________

Direction: Encircle the letter of the correct answer.

1. What is the key characteristic of a do...while loop?


A. It executes the loop body only if the condition is true
B. It guarantees the loop body is executed at least once
C. It evaluates the condition before the loop body
D. It cannot handle multiple conditions

2. Which of the following is the correct syntax for a do...while loop in most programming
languages?
A) do { } while (condition); B) while { } do (condition);
C) do (condition) { } D) while (condition) { do; }

3. When is the condition checked in a do...while loop?


A. Before each iteration B. After each iteration
C. Only once at the start D. Only at the end

4. In which scenario is a do...while loop preferred?


A. When the loop should run at least once regardless of the condition
B. When the loop should run only if the condition is true
C. When the number of iterations is known in advance
D. When the loop must terminate before checking the condition

5. What will happen if the condition in a do...while loop is never true?


A. The loop will never run
B. The loop will run indefinitely
C. The loop will run once and then stop
D. The loop will throw an error

Name: ____________________________________ Date: __________________


Programming Exercise Score: _________________
Direction: Using the C# console application, read and analyze the task carefully before
writing your code.
Exercise: Create a program that repeatedly asks the user to enter a positive integer. If the
user enters a negative number or zero, the program should display an error message and
prompt the user to try again. The program will stop asking for input when a valid positive
integer is entered.

119
Unit 4 GOTO STATEMENT

At the end of this module, the students should be able to:


a. recognize scenarios where the use of a goto statement may be appropriate.
b. write and execute programs that correctly implement goto statements, using
labels to direct the flow of control within a program.

C# Goto Statement
The C# goto statement is also known as a jump statement. It jumps unconditionally to the
specified label.
Syntax:
Label:
goto Label;

Example
Scenario: using goto statement, develop a C# program that requests the user's name and
address. Subsequently, the system should inquire if the user wishes to enter more data. If
the user indicates "yes," the program should prompt for their name and address again. If the
user indicates "no," the program will end.
Flowchart:

Print Input
START
“Name:” name

Print input Print


“Do you still want to input another address “Address:”
data [Y/N]? : ”

input TRUE
Char.ToUpper
answer (answer)=='Y'

FALSE

END

120
Sample Code:
using System;
namespace ProgrammingApplication
{
class GotoStatement
{
static void Main(string[] args)
{
string name, address;
char answer;
start:
Console.Write("Name:");
name = Console.ReadLine();
Console.Write("Address:");
address = Console.ReadLine();
Console.Write("Do you still want to input another data [Y/N]?:");
answer = char.Parse(Console.ReadLine());

if (Char.ToUpper(answer) == 'Y')
{
goto start;
}
Console.ReadKey();
}
}
}

121
Name: ____________________________________ Date: __________________
Self-Assessment No. 20 Score: _________________
Direction: Encircle the letter of the correct answer.

1. What does the goto statement do in programming?


A. It creates a loop
B. It defines a function
C. It transfers control to a labeled statement in the program
D. It terminates a program

2. Which of the following is a correct syntax for a goto statement?


A. goto label; B. go to label; C. goto: label; D. label: goto;

3. Which of the following is a possible consequence of overusing goto statements in a


program?
A. Increased execution speed B. More structured and clear code
C. Complex and hard-to-debug code D. Reduced memory usage

4. Which of the following alternatives can often be used instead of a goto statement?
A. A loop or function B. A variable C. A comment D. A pointer

5. What is a key reason why many modern programming languages discourage or avoid the
use of goto statements?
A. It increases memory usage
B. It can lead to inefficient code execution
C. It can lead to code that is difficult to understand, maintain, and debug
D. It limits the use of other control structures

Name: ____________________________________ Date: __________________


Programming Exercise Score: _________________

Direction: Using the C# console application, read and analyze the task carefully before
writing your code.
Exercise: Create a program that asks the user to enter a positive integer. If the user enters a
negative number or zero, the program should display an error message and use a goto
statement to prompt the user to enter a valid input again. The program will exit when the
user provides a valid positive integer.

122
MODULE 7
Single- Dimension Arrays

This module contains one unit that discusses single-dimension arrays. It is termed a single-
dimensional or one-dimensional array because the elements are stored together in one block of memory, and
all the elements are of the same data type. This forms the basic or simplest form of an array and is commonly
used for storing lists of data.

As you progress through the module, keep in mind that most units conclude with an assessment or a
series of assessments. So, make sure to complete them before moving on to the next part of the course.

Lastly, remember to have fun throughout the entire learning process. Enjoy!

You are now embarking on a journey filled with valuable experiences and
enriching learning opportunities. Engage in the exercises and respond to the
suggested worksheets to immerse yourself in a lifelong journey of practical
learning that awaits you upon completing this module.

ENJOY YOUR JOURNEY!

123
Unit 1 SINGLE DIMENSIONAL ARRAY

At the end of this module, the students should be able to:


a. explain the concept of a single-dimension array, including how elements are
stored in contiguous memory locations and how they are accessed using indices.
b. access, modify, and manipulate elements within a single-dimension array using
array indexing and loops, performing common operations such as traversing,
updating, and retrieving values.
c. apply single-dimension arrays to implement basic algorithms, such as searching
for an element, sorting the array, or calculating the sum or average of the
elements.

Arrays serve as a mechanism for storing data collections, but it can be more practical to
envision an array as a grouping of variables of identical type that are located in continuous
memory locations.
Instead of declaring from:
int number1, number2, number3, number4, number5, number6, number7;
We can have an array variable by only declaring:
int[] number = new int[7];
We can access a particular element in the array by providing the index.

Array Declaration and allocation of memory in an array:

int[] age = new int[5];


string[] name = new string[5];

C# Array Example: Declaration and Initialization at same time


There are 3 ways to initialize array at the time of declaration.

int[] age = new int[5]{32,2,1,31,8};


string[] name = new string[5]{"Rose","Chyler","Karev","Emann","Emarie"};

We can omit the size of array.

int[] age = new int[]{ 32, 2, 1, 31, 8 };


string[] name = new string[]{"Rose", "Chyler", "Karev", "Emann", "Emarie"};

124
We can omit the new operator also.

int[] age = { 32, 2, 1, 31, 8 };


string[] name = { "Rose", "Chyler", "Karev", "Emann", "Emarie" };

We can also declare the array and then initialize.

int[] age = new int[5];


string[] name = new string[5];

age[0] = 32;
age[1] = 2;
age[2] = 1;
age[3] = 31;
age[4] = 8;

name[0] = "Rose";
name[1] = "Chyler";
name[2] = "Karev";
name[3] = "Emann";
name[4] = "Emarie";

Array Representation

32 2 1 31 8

VariableName[Index#] Elements/Data
age[0] 32
age[1] 2
age[2] 1
age[3] 31
age[4] 8

125
Example 1

using System;
namespace ProgrammingApplication
{
class SingleArray
{
static void Main (string[] args)
{

int[] age = new int[5] {32, 2, 1, 31, 8 };


string[] name = new string[5] {"Rose", "Chyler", "Karev", "Emann", "Emarie”};

Console.WriteLine("Length of array age: " + age. Length);


for (int i = 0; i < age. Length; i++)
{
Console.WriteLine(age[i]);
}
Console.WriteLine("\nLength of array name: " + name.Length);
for (int i = 0; i < name.Length; i++)
{
Console.WriteLine(name[i]);
}
Console.ReadKey();
}
}
}

Output

Length of array age: 5


32
2
1
31
8

Length of array name: 5


Rose
Chyler
Karev
Emann
Emarie

126
Name: ____________________________________ Date: __________________
Self-Assessment No. 21 Score: _________________

Direction: Encircle the letter of the correct answer.

1. What is a single-dimension array?


A. A collection of elements of different data types
B. A collection of elements stored in a sequence in memory
C. A collection of elements stored in rows and columns
D. A collection of elements stored randomly in memory

2. How are elements in a single-dimension array accessed?


A. By using a row and column index
B. By using a single index starting from 1
C. By using a single index starting from 0
D. By using pointers only

3. What does the index of an array represent?


A. The total number of elements in the array
B. The position of an element in the array
C. The memory address of the array
D. The data type of the array

4. What will happen if you try to access an element at an index that is out of bounds in an
array?
A. The program will return a random value
B. The program will access the next available element
C. The program will throw an error or crash
D. The program will ignore the request

5. What is the length of the following array?


Int[] sample = {10, 20, 30, 40};
A) 3 B) 4 C) 5 D) Length cannot be determined

6. How do you declare a single-dimension array in C#?


A. int[] arr = new int[5]; B. int arr[] = new int[5];
C. int arr[5]; D. int[] arr = int[5];

7. What is the index of the first element in a single-dimension array in C#?


A. 1 B. 0 C. -1 D. It depends on the array size

8. How do you find the length of an array in C#?


A. arr.size B. arr.length C. arr.Length D. arr.count

9. What happens if you try to access an index that is out of bounds in a C# array?
A. The program will return a default value
B. The program will return null
C. The program will throw an IndexOutOfRangeException
D. The program will ignore the statement

127
10. What is the correct way to update the third element of an array in C#?
A. arr[2] = 50; B. arr[3] = 50; C. arr(2) = 50; D. arr = 50;

11. What is the correct way to sort a single-dimension array in ascending order in C#?
A. arr.Sort(); B. Array.Sort(arr);
C. Sort.Array(arr); D. arr.sortArray();

12. How do you find the index of a specific element in an array in C#?
A. arr.IndexOf(5); B. Array.IndexOf(arr, 5);
C. arr.FindIndex(5); D. arr.SearchIndex(5);

13. What will the following C# code output?


int[] arr = new int[4];
Console.WriteLine(arr[3]);
A. 0 B. 3 C. Uninitialized value D. An error will be thrown

14. What is the output of the following C# code?


int[] arr = {1, 2, 3, 4, 5};
int sum = 0;
foreach(int num in arr)
{
sum += num;
}
Console.WriteLine(sum);

A. 10 B.15 C. 20 D. 25

15. What does the following C# code do?


int[] arr = new int[5];
for(int i = 0; i < arr.Length; i++)
{
arr[i] = i * 2;
}

A. Initializes the array with values 1, 2, 3, 4, 5


B. Initializes the array with values 0, 2, 4, 6, 8
C. Initializes the array with values 2, 4, 6, 8, 10
D. Leaves the array elements uninitialized

Name: ____________________________________ Date: __________________


Programming Exercise Score: _________________
Direction: Using the C# console application, read and analyze the task carefully before
writing your code.
Exercise: Create a C# console application that declares a single-dimension array of integers.
The program will allow the user to input the values for the array, calculate the sum and
average of the elements, and then display the results. Declare 5 elements.

128
References

https://www.geeksforgeeks.org/c-sharp-type-casting/
https://www.w3schools.com/cs/cs_data_types.php
https://www.programiz.com/csharp-programming/operator-precedence-associativity
https://www.smartdraw.com/flowchart/flowchart-symbols.htm

129

You might also like