Computer Programming 1 Module Final 2024-2025 -First Year
Computer Programming 1 Module Final 2024-2025 -First Year
1
Course Overview
Course Code IT103 & 103L
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.
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.
7
Unit 1 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.
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.
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#
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
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().
Output:
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().
Output:
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 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
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:
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
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:
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:
Alternatively, we can also declare and assign the variable in a single line for shortness of code.
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';
prog1Grade = 1.4f;
introProgGrade = 1.2f;
mathGrade = 1.8f;
}
}
}
Output:
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.
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.
• 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;
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);
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
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;
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
24
13. What is the recommended naming convention for fields 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);
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}";
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
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();
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());
Console.Write("Final Grade:");
Console.WriteLine(finalGrade); //display the finalGrade result
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:
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:
prog1Grade = float.Parse(Console.ReadLine());
From Data type: string
29
Name: ____________________________________ Date: __________________
Self-Assessment No. 3 Score: _________________
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()
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.
32
Unit 1 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.
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)
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
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);
}
}
}
Output:
39
Name: ____________________________________ Date: __________________
Self-Assessment No. 5 Score: _________________
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)
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
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);
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("***********************");
}
}
}
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.
46
Unit 1 STRING CONCATENATION
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 Interpolation
Output
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: _________________
4. What is the result of the following string concatenation: "10" + "20" + 30?
a. "30" b. "1020" c. "10 20 30" 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
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! #
# #
###########################################################
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 "
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.
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.
$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$
$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$
53
Unit 3 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: _________________
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"
$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$
$ $
$ 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.
57
Unit 1 ASSIGNMENT & ARITHMETIC OPERATOR
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.
Assignment Operator
Assignment operator used to assign values to variables using the equal sign (=) symbol. For example,
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.
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
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: _________________
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.
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.
$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$
$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$
63
Common Compound Assignment
Unit 2 Operator & Operator Precedence
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
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
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.
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.
$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$
$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$
68
Unit 3 RELATIONAL & LOGICAL OPERATOR
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.
Example:
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: _________________
6. Which of the following is the correct operator to check if at least one of two conditions is true?
a. || b. && c. ! d. =
72
Unit 4 UNARY & TERNARY OPERATOR
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: _________________
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:
$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$
$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$
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.
78
Unit 1 ALGORITHM AND FLOWCHART
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.
Flow Arrow
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: _________________
8. Which flowchart symbol should be used to represent the calculation of the average
grade?
A. Parallelogram B. Diamond C. Rectangle D. Oval
81
Unit 2 IF STATEMENTS
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
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
Enter a number: 15
The number is less than 20
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
}
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
END
Sample Code:
86
If Boolean-Expression is false
Enter a number: 15
The number is less than 20
Enter a number: 21
The number is equal or greater than 20
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.
FALSE
FALSE
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.
88
Flowchart:
START
Input finalGrade
FALSE
FALSE
FALSE
TRUE
finalGrade>=0 && Print “Interim grade letter: F”
finalGrade<=74 Print “Description: Fail
FALSE
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();
}
}
}
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
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
END
Sample Code
Output 1 (if the user entered a number greater than or equal to 20)
Enter a number: 20
Even Number
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
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
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
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
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
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
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
Product: Shampoo
Available
Items Price
A. Sunsilk Php6.00
B. Vaseline Php5.00
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.”
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
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.
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
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)
Output 2 (if the user entered 2 numbers and selected the multiplication operator)
Output 3 (if the user entered 2 numbers and entered the invalid operator)
102
Name: ____________________________________ Date: __________________
Self-Assessment No.16 Score: _________________
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
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
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.
105
Unit 1 FOR LOOP STATEMENT
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
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
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: _________________
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; { }
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
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.
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
114
Name: ____________________________________ Date: __________________
Self-Assessment No.18 Score: _________________
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
115
Unit 3 DO…WHILE LOOP STATEMENT
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.
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
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
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: _________________
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; }
119
Unit 4 GOTO STATEMENT
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
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.
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
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.
123
Unit 1 SINGLE DIMENSIONAL ARRAY
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.
124
We can omit the new operator also.
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)
{
Output
126
Name: ____________________________________ Date: __________________
Self-Assessment No. 21 Score: _________________
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
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);
A. 10 B.15 C. 20 D. 25
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