You are on page 1of 114

1

Computer Fundamentals
Programming
2nd Semester, SY 2018-2019

IRMA T. PLATA, DIT


ISABELA STATE UNIVERSITY- Main Campus
College of Computing Studies, Information and Communications Technology
Echague, Isabela
About the Course
2

I. Course Title: Computer Fundamentals Programming


II. Course Description: This course provides fundamental
concepts in computer programming using C#. This
course also cover the techniques being applied in
programming. Computer hands-on will be conducted to
apply the different concepts learned.
III. Prerequisite: None
IV. Contact Hours: 6 hrs per week
V. Credit: 2 Units
Course Content/Outline
3

• Definition of Programming
• Purpose of Making Programs
• Programming Language
• Types of Programming Language
• Generations of Programming Language
• Examples of Programming Language
• Compiler
• Interpreter
• Choosing a programming Language
• How to make programs
Continuation…
4

• Flowchart
• Algorithm
• The C# programming Language
• What is C#?
• C# Operators
- (Mathematical, Assignment, Relational, Boolean)
• Looping
- (While, Do, For)
• Arrays
- (Single, Multi-dimensional Arrays)
• Textfiles
Course Requirements
5

• Quizzes
• Attendance
• Recitation
• Seatwork
• Written/Laboratory Midterm and Final
Examinations
• Laboratory Exercises
• Create a simple system using C# Programming
Language (Final Project)

Grading System:
Midterm & Final Exam – 50% Grade – 100%
Other components – 50%
6

Module 1: Introduction to
Computer Programming
What is a Program?
7

• An organized list of instructions that, when executed, causes


the computer to behave in a predetermined manner.

• A computer program, or just a program, is a sequence of


instructions, written to perform a specified task on a
computer.

• A program is like a recipe. It contains a list of ingredients


(called variables) and a list of directions (called statements)
that tell the computer what to do with the variables. The
variables can represent numeric data, text, or graphical
images.

• Without programs, computers are useless!


What is a Program?
8

• an app, application, software application or


software program is the most common software on
the computer that performs a special function or
task.
• For example, Microsoft Word is a word processor
program that allows users to create and write
documents and the browser you are using to view
this page is a program.

• Without programs, a computer would still work with


the operating system, but you would not be able to
do anything.
What is Programming?
9

It is an act of making programs


Without programs, computers are useless!

Programmer. A programmer, developer, dev, coder,


or software engineer is a person who creates
computer software. The term computer programmer
can refer to a specialist in one area of computers or
to a generalist who writes code for many kinds of
software.
What is software?
10

• Generic
• General
• does not necessarily always mean "program" or
"application" (e.g. a software "library" or "framework" is
not a "program" or "application", but are used to
facilitate the functional requirements of "programs" or
"applications").
Without programs, computers are useless!
Computer software, or simply
software, is a collection of data
or computer instructions that tell
the computer how to work. This
is in contrast to physical
hardware, from which the system
is built and actually performs the
work. Wikipedia
Why do programmers make computer
programs?
11

• To simplify task

• Provide accurate results

• Aide in facilitating day-to-day activities


a computers are useless!
LLL vs HLL
12

Low Level Language (LLL) – language that can convert


to machine code without a compiler or interpreter, and
the resulting code runs directly on the CPU/Processor.
(also known as the machine language or assembly
language – the zeros and ones (0,1))

High Level Language (HLL) – needs a compiler or


interpreter to convert the instruction into language that
could be understood by CPU/Processor.

a computers are useless!


What is CPU or Processor?
13

• CPU means central processing unit

• “Brain” of the computer

• Executes commands or instructions

Central processing unit


A central processing unit a computers
(CPU) is the are useless!
electronic circuitry within a computer that
carries out the instructions of a computer
program by performing the basic arithmetic,
logic, controlling, and input/output (I/O)
operations specified by the instructions.
Compiler
14

• It is a program that converts high level language to


low level language that could be understood by
the CPU (this process is called “Compiling”)

• Commonly compiles instruction known as the


“Code”
Interpreter
15

• It is a program that interprets (without


undergoing the process of compiling) high level
language to low level language that could be
understood by the CPU.

• Commonly compiles instruction known as the


“Script”
Types of Programming Language
16

• Web languages
• Software languages
• The different generations of languages
• Procedure oriented programming
• Object oriented programming
Types of Programming Language
17

Web Languages
• HTML
• XML
• JAVASCRIPT
• VBSCRIPT
• PHP
• ASP
• JAVA
Types of Programming Language
18

Software Languages
• C
• C++
• Visual Basic
• JAVA
• C#
Types of Programming Language
19

The different generations of languages


• 1st Generation Language (1GL)
• 2nd Generation Language (2GL)
• 3rd Generation Language (3GL)
• 4th Generation Language (4GL)
• 5th generation language (5GL)
The different generations of languages
20

First generation languages (abbreviated as 1GL)

Represent the very early, primitive computer


languages that consisted entirely of 1's and 0's -
the actual language that the computer
understands (machine language).
The different generations of languages
21

Second generation languages (2GL)

• Represent a step up from the first generation


languages. Allow for the use of symbolic
names instead of just numbers.
• Second generation languages are known as
assembly languages.
• Code written in an assembly language is
converted into machine language (1GL).
The different generations of languages
22

Third generation languages (3GL)

• With the languages introduced by the third


generation of computer programming, words
and commands (instead of just symbols and
numbers) were being used.
• These languages therefore, had syntax that
was much easier to understand.
• Third generation languages are known as
"high level languages" and include C, C++,
Java, and Javascript, among others
The different generations of languages
23

Fourth generation languages (4GL)


• The syntax used in 4GL is very close to
human language, an improvement from the
previous generation of languages.

• 4GL languages are typically used to access


databases and include SQL and ColdFusion,
among others.
The different generations of languages
24

Fifth generation languages (5GL)


• Fifth generation languages are currently
being used for Neural Networks.

• A Neural Network is a form of Artificial


Intelligence that attempts to imitate how the
human mind works.
Example Code of Visual Basic
25
Example Code of Python
26
Example Code of C#
27
28

End of Module 1
Note: prepare for a quiz next meeting
29
30

n
31

Computer Fundamentals
Programming
Module 2 - Designing and Creating a
Program

IRMA T. PLATA, DIT


ISABELA STATE UNIVERSITY- Main Campus
College of Computing Studies, Information and Communications Technology
Echague, Isabela
Algorithm
32

• A formula or set of steps for solving a particular problem.


• To be an algorithm, a set of rules must be unambiguous and
have a clear stopping point.
• Algorithms can be expressed in any language, from natural
languages like English

• We use algorithms every day. For example, a recipe for baking


a cake is an algorithm. Most programs, with the exception of
some artificial intelligence applications, consist of algorithms.

• Inventing elegant algorithms -- algorithms that are simple


and require the fewest steps possible -- is one of the principal
challenges in programming.
Examples of algorithm
33

• Cookbook
• Recipe Booklet
• Choreography

• In the same way, algorithms executed by computer can


combine millions of elementary steps, such as
additions, subtractions, multiplications and divisions
into complicated mathematical calculations.

• In the same way, algorithms executed by computer can


combine millions of elementary steps, such as
additions, subtractions, multiplications and divisions
into complicated mathematical calculations.
Examples of algorithm
34

Here is one algorithm for the usual process of saving a document


in a disk.

1. Find a new or unused disk.


2. Insert the disk in drive G.
3. From the word environment, select file menus then select
save as.
4. From the save as dialog box, select the directory where you
save the document.
5. Position the pointer inside the filename textbox then type the
filename of the document.
6. Then click the save button to formally save the document.
Problems (1,2,3,4,5)
35

1. Create an algorithm on how to kill a chicken.

2. Create an algorithm on how to prepare a cup of coffee.

3. Create an algorithm on how to cook pinakbet.

4. Create an algorithm on how to get the sum of two numbers.

5. Create an algorithm on how to get the average of the three


(3) numbers.
Flowchart
36

A flowchart is a graphical or symbolic representation of


a process. Each step in the process is represented by a
different symbol and contains a short description of the
process step.

The flow chart symbols are linked together with arrows


showing the process flow direction.
Basic Symbols
37

• A flowchart is a graphical or symbolic representation


of a process.

• Each step in the process is represented by a


different symbol and contains a short description of
the process step.

• The flow chart symbols are linked together with


arrows showing the process flow direction.
Basic Symbols
38
Basic Symbols
39
Basic Symbols
40
Basic Symbols
41
Basic Symbols
42
Basic Symbols
43
Basic Symbols
44
45

Example
of
Flowchart
Notations Used in Flowchart
46

Notation Meaning
: comparison
& logical and
Y yes
N no
EOF End of File
Relational Test Operators
47

Notation Meaning
> is greater than
< is less than
<= or =< is less than or equal to
>= or => is greater than or equal to
<> or >< is not equal to
= is equal to
Arithmetic Operators
48

Notations Meaning

+ Addition
- Subtraction
* Multiplication
/ Division
() Grouping
** or ^ Exponentiation
Precedence of the Operators
49

The computer follows this order of


priority

1. Grouping ()
2. Exponentiation
3. Multiplication or division
4. Addition or subtraction
When operators are all of equal priority, the
computer evaluate the expression from left
to right.
50
When operators are of different priorities, the
computer performs those operations with higher
priorities first
51
Operations enclosed in parentheses will take place
before other operations. Note (if there are multiple
parentheses, the innermost parenthesis will be
52

evaluated first).
Write clearly the computation desired
53

Example #2.3
2L / 3G
Answer?
( 2 * L ) / (3 * G )
Problem 6 and 7
54

6. Create a flowchart that would ask for a legal age to


access a particular porn site. If age is greater than or
equal to 18 then print “Yehey, you are allowed, happy
Viewing”, otherwise, print “Sorry, you can’t”.

7. Create a flowchart that would determine if


the grade of student is Passed or Failed. If grade
is greater than or equal to 75, print “Passed”,
else “Failed”.
Problem 8
55

Create a flowchart that would get the


average of student’s grade from 5
subjects (Math, Science, Social Sciences,
Biology, P.E) and determine whether the
average is passed or failed. If the average
is greater than 75, display “Passed”,
otherwise display “Failed”.
Loops and Counters
56

• Looping is used when it is desired to


make the same calculation on more than
one set of data. It consists of repeating a
program, or a section of a program, and
substituting new data for each repetition.

• A counter is set up in a program loop to


keep track of the number of times the
program segment is repeated.
Steps in Loop Control
57

1. Initialization – the value of a counter used is initially


set equal to zero (or one). This process is
always done outside the loop.
2. Test for Limit Conditions – before logic flow gets out
of the loop, a loop – terminating condition
must first be satisfied. The process of
testing is usually found either at the
beginning or at the end of a loop.

3. Incrementation – after each loop is executed, 1 is


added to the counter. Thus the counter
reflects the number of times the operation
has been performed. This process is always
done within the loop.
The algorithm for this particular requirement
could be listed as follows:
58

1. Initialize the counter (ctr) and accumulator (sum) to


zero.
2. Read in student’s name and score.
3. Print out the student’s name and score.
4. Accumulate the data value (score) into sum.
5. Test if the desired amount of data (40) has been
reached.
6. If the value of counter (ctr) is less than 40, repeat
steps 2 through 5. However, if the desired amount
of data has been reached (40), compute the average
score by dividing the sum by the value of counter.
7. Print out the average score.
Equivalent flowchart of the problem

59
Problem 9 and 10
60

9. Create a flowchart that would change the


initial value of the variable X which is 10 to
100 when the value of variable Y is 50.

10. Draw a flowchart that would convert the a


particular number to words. Numbers may be from
1 to 5. Example, if the value is 1, then it will display
the word “One”, “Two” for 2 and so on…
Problem 11
61

Find the amount to charge people of varying ages for a food


ticket. When the person is under 16, the charge is Php 7.00,
when the person is 65 or over, the charge is Php 5.00, all others
are charged Php 10.00. The conditions are the following:

Age Charge
<16 7
>=16 and <65 10
>=65 5
Problem 12 and 13
62

12. Calculate the commission rate for a salesperson given the


amount of sales. When the salesperson has sold less than of
equal to 2,000.00 worth of goods, the commission is 2%. When
the sales total is more than 2,000.00 and less than or equal
4,000.00 the commission is 4%. When the sales total is more
than 4,000.00 and less than or equal to 6,000.00, the
commission is 7%. When the salesperson sold more than
6,000.00, the commission is 10%.

13. Create a flowchart that would determine if a


particular number is an Odd number. When the
number is Odd, print “The Number is an Odd”.
Problem 14, 15
63

14. Create a flowchart that would determine if a


particular number is an Even number. When the
number is Even, print “The Number is an Even”.

15. Draw a flowchart that would count and display


all the even and odd numbers from 1 to 10.
64

End of Module 2
Note: prepare for a quiz next meeting; Submit all answer to Problems
provided, use the worksheet template provided.
65

Computer Fundamentals
Programming
Module 3 – The C# Programming
Language

IRMA T. PLATA, DIT


ISABELA STATE UNIVERSITY- Main Campus
College of Computing Studies, Information and Communications Technology
Echague, Isabela
Overview
66

• C# is a modern, general-purpose, object-oriented


programming language developed by Microsoft and
approved by Ecma and ISO.

• C# was developed by Anders Hejlsberg and his team


during the development of .Net Framework.

• C# is designed for Common Language Infrastructure


(CLI), which consists of the executable code and
runtime environment that allows use of various high-
level languages to be used on different computer
platforms and architectures.
Overview
67

The following reasons make C# a widely used professional


language:

• Modern, general-purpose programming language


• Object oriented.
• Component oriented.
• Easy to learn.
• Structured language.
• It produces efficient programs.
• It can be compiled on a variety of computer platforms.
• Part of .Net Framework.
C# Program Structure
68

• Namespace declaration
• A class
• Class methods
• Class attributes
• A Main method
• Statements & Expressions
• Comments
The C# Code
69

using System;

class HelloWorld
{
static void Main(string[]
args)
{
/* my first program in C#
*/
Console.WriteLine("Hello
World");
Console.ReadKey();
}
}
Line #1: using System;
70

The first line of the


program using
System; - the using
keyword is used to
include the System
namespace in the
program. A
program generally
has multiple using
statements.
Line #2: class HelloWorld
71

The next line has a class


declaration, the class
HelloWorld contains the
data and method
definitions that your
program uses. Classes
generally would contain
more than one method.
Methods define the
behavior of the class.
However, the
HelloWorld class has
only one method Main.
Line #4: static void Main(string[] args)

72

The next line


defines the Main
method, which is
the entry point
for all C#
programs. The
Main method
states what the
class will do when
executed
Line #6:/* my first program in C# */
73

The next line /*...*/


will be ignored by
the compiler and it
has been put to add
additional
comments in the
program.
Comments are used for explaining code.
Compilers ignore the comment entries. The
multiline comments in C# programs start
with /* and terminates with the characters
*/ as shown below:

/*
This program demonstrates
The basic syntax of C# programming
Language
*/

}//end of class hello world


Line #7: Console.WriteLine("Hello World");

74

WriteLine is a
method of the
Console class
defined in the
System
namespace. This
statement causes
the message
"Hello, World!" to
be displayed on
the screen.
Line #8: Console.ReadKey();

75

The last line


Console.ReadKey(); is
for the VS.NET Users.
This makes the
program wait for a key
press and it prevents
the screen from
running and closing
quickly when the
program is launched
from Visual Studio
.NET.
Note the following points
76

• C# is case sensitive.

• All statements and expression must end with


a semicolon (;).

• The program execution starts at the Main


method.
Identifiers
77

• Namespace declaration
• A class
• Class methods
• Class attributes
• A Main method
• Statements & Expressions
• Comments
Identifier
78

An identifier is a name used to identify a class, variable, function,


or any other user-defined item.

RULE #1:

A name must begin with


a letter that could be RULE #2:
followed by a sequence
of letters, digits (0 - 9) It must not contain any
or underscore. The first embedded space or
character in an symbol like ? - +! @ # %
identifier cannot be a ^&*()[]{}.;:"'/
digit. and \. However, an RULE #3:
underscore ( _ ) can be
used. It should not be a C#
keyword.
C# Keywords
79

Sometimes called “RESERVED WORDS”


which have a special meaning in a
programming language

NEVER EVER
USE THEM AS IDENTIFIERS!
C# Keywords
abstract as base bool break byte case
80 catch char checked class const continue decimal
default delegate do double else enum event
explicit extern false finally fixed float for
foreach goto if implicit in in (generic) int
interface internal is lock long namespace new
null object operator out out(generic) override params
private protected public randomly ref return sbyte
sealed short sizeof stackalloc static String struct
switch this throw true try typeof uint
ulong unchecked unsafe ushort using virtual void
volatile while

Contextual keywords
add alias ascending descending dynamic from get
global group Into join let order by partial (type)
partial (method) remove select set
Concept of Variables
81

• It is a location inside the computer’s memory that allows


us to store information.

• It is like tiny box inside the computer’s memory.

• Its primary purpose is to store information like text,


numbers, date, time, objects.

- Text (abc, 21programming)


- Numbers (1,2,3,4,5,6,7,8,9,0)
- Date (07/19/1987)
- Time (9:00)
Concept of Variables
82

0 “Ana” ”BSIT” 10:00 19

Computer’s Memory
sAge
num1 fname

deptName mTime

Note: Every location has a


name and characteristic, in
short, a variable has a
name and data type
Rules in Naming Variables
83

• It must start with a letter.

• It must not contain any special characters. (*,#,$,etc).

• It must not be a keyword or reserved word.


(keywords/reserved words – words that have special
meaning in programming language.)

• It must not be long.

Note: ALL VARIABLES HAVE NAMES (identifier)


Valid Variable Names
84

Abc
abc123
bahaykubokahitmunti
student_name
sum
average
Valid or Invalid?
85

Rule #1: It must start with a letter


Rule #2: It must not contain any special
123 Invalid characters. (*,#,$,etc).
Name_123 Valid Rule #3: It must not be a keyword or
$dollar Invalid reserved word. (keywords/reserved words –
words that have special meaning in programming
*asterisk Invalid language.)
Studentname Valid
Rule #4: It must not be long.

Note: ALL VARIABLES HAVE NAMES


(identifier)
C# Datatypes
86

• Determines what the nature of a value a variable can hold


• Nature of values

Number String

Signed Unsigned Empty


Not empty
Or
(-) (+) Zero-length “ISU”
“Joe”
1 “”
-60 “I love IT”
2
-98.2
Both 5.0
-8
Datatypes in C#
87
Type Represents Range Default Value

1. bool Boolean value True or False False


2. byte 8-bit unsigned integer 0 to 255 0
3. char 16-bit Unicode character U +0000 to U +ffff '\0'
4. decimal 128-bit precise decimal values (-7.9 x 1028 to 7.9 x 1028) / 100 to 0.0M
with 28-29 significant digits 28
5. double 64-bit double-precision (+/-)5.0 x 10-324 to (+/-)1.7 x 0.0D
floating point type 10308
6. float 32-bit single-precision floating -3.4 x 1038 to + 3.4 x 1038 0.0F
point type
7. int 32-bit signed integer type -2,147,483,648 to 2,147,483,647 0
8. long 64-bit signed integer type -923,372,036,854,775,808 to 0L
9,223,372,036,854,775,807
9. sbyte 8-bit signed integer type -128 to 127 0
10. short 16-bit signed integer type -32,768 to 32,767 0
11. uint 32-bit unsigned integer type 0 to 4,294,967,295 0
12. ulong 64-bit unsigned integer type 0 to 18,446,744,073,709,551,615 0
13. ushort 16-bit unsigned integer type 0 to 65,535 0
C# Operators
88

An operator is a symbol that tells the compiler to perform


specific mathematical or logical manipulations.

• Arithmetic Operators
• Relational Operators
• Logical Operators
• Assignment Operators
Arithmetic Operators
89

Operator Description Example

+ Adds two operands A + B will give 30


- Subtracts second operand from the first A - B will give -10

* Multiplies both operands A * B will give 200


/ Divides numerator by de-numerator B / A will give 2
% Modulus Operator and remainder of after B % A will give 0
an integer division

++ Increment operator increases integer A++ will give 11


value by one
-- Decrement operator decreases integer A-- will give 9
value by one
Relational Operators
90
Operator Description Example

== Checks if the values of two operands are equal or not, (A == B) is not true.
if yes then condition becomes true.
!= Checks if the values of two operands are equal or not, (A != B) is true.
if values are not equal then condition becomes true.
> Checks if the value of left operand is greater than the (A > B) is not true.
value of right operand, if yes then condition becomes
true.
< Checks if the value of left operand is less than the (A < B) is true.
value of right operand, if yes then condition becomes
true.
>= Checks if the value of left operand is greater than or (A >= B) is not true.
equal to the value of right operand, if yes then
condition becomes true.
<= Checks if the value of left operand is less than or equal (A <= B) is true.
to the value of right operand, if yes then condition
becomes true.
Logical Operators
91
Operator Description Example

&& Called Logical AND operator. If both the (A && B) is false.


operands are non zero then condition
becomes true.
|| Called Logical OR Operator. If any of the (A || B) is true.
two operands is non zero then condition
becomes true.
! Called Logical NOT Operator. Use to !(A && B) is true.
reverses the logical state of its operand.
If a condition is true then Logical NOT
operator will make false.
Let
A = true
B = false
Assignment Operators
Operator Description Example
92
= Simple assignment operator, Assigns values from right C = A + B will assign value of A + B into C
side operands to left side operand
+= Add AND assignment operator, It adds right operand to C += A is equivalent to C = C + A
the left operand and assign the result to left operand
-= Subtract AND assignment operator, It subtracts right C -= A is equivalent to C = C - A
operand from the left operand and assign the result to
left operand
*= Multiply AND assignment operator, It multiplies right C *= A is equivalent to C = C * A
operand with the left operand and assign the result to
left operand
/= Divide AND assignment operator, It divides left C /= A is equivalent to C = C / A
operand with the right operand and assign the result
to left operand
%= Modulus AND assignment operator, It takes modulus C %= A is equivalent to C = C % A
using two operands and assign the result to left
operand
<<= Left shift AND assignment operator C <<= 2 is same as C = C << 2
>>= Right shift AND assignment operator C >>= 2 is same as C = C >> 2
&= Bitwise AND assignment operator C &= 2 is same as C = C & 2
^= bitwise exclusive OR and assignment operator C ^= 2 is same as C = C ^ 2
|= bitwise inclusive OR and assignment operator C |= 2 is same as C = C | 2
Sample Problem #16
Create a C# program that would get and display the sum of two integer numbers
93
given by the user.
using System;
class my_app
{
static void Main(string[] args)
{
string Num1 = "";
string Num2 = "";
int Sum = 0;

Console.WriteLine("Enter the first number: ");


Num1 = Console.ReadLine();

Console.WriteLine("Enter the second number: ");


Num2 = Console.ReadLine();

Sum = int.Parse(Num1) + int.Parse(Num2);

Console.WriteLine("The sum of " + Num1 + " and " + Num2 + " is: " +
Sum);
Console.ReadKey();

}
}
Sample Problem #17
Create a C# program that would get and display the quotient of two numbers given
94
by the user.

using System;
class my_app
{
static void Main(string[] args)
{
string Num1 = "";
string Num2 = "";
double Quotient = 0;

Console.WriteLine("Enter the first number: ");


Num1 = Console.ReadLine();

Console.WriteLine("Enter the second number: ");


Num2 = Console.ReadLine();

Quotient = double.Parse(Num1) / double.Parse(Num2);

Console.WriteLine("The quotient of " + Num1 + " and " + Num2 + " is: " +
Quotient.ToString ("N2"));

Console.ReadKey();

}
}
95

End of Module 3
Note: prepare for a quiz next meeting; Submit all answer to Problems
provided, use the worksheet template provided.
96

Computer Fundamentals
Programming
Module 4 – Conditional Statements

IRMA T. PLATA, DIT


ISABELA STATE UNIVERSITY- Main Campus
College of Computing Studies, Information and Communications Technology
Echague, Isabela
When do we use conditional statements?
97

Decisions Evaluate a value


C# Conditional Statements
98

• if statement
• if…else statement
• else if statement
• switch statement
if statement
99

Syntax:
if(boolean_expression)
{
/* statement(s) will
execute if the boolean
expression is true */
}

Sample Problem #1

Create a C# program that would


display “UNDER-AGE” if the age
entered is below 18.
Solution to Problem #1
100

using System;
class my_app
{
static void Main(string[] args)
{
string Age = "";

Console.WriteLine("Enter your age: ");


Age = Console.ReadLine();

if( int.Parse(Age) < 18 )


{
Console.WriteLine(“UNDER-AGE");
}
Console.ReadKey();
}
}
if…else statement
101

Syntax:
if(boolean_expression)
{
/* statement(s) will
execute if the boolean
expression is true */
}
else
{
/* statement(s) will
execute if the boolean
expression is false */
}

Sample Problem #2
Create a C# program that would display
“UNDER-AGE” if the age entered is below 18,
otherwise “OVER-AGE” if age above 18.
Solution to Problem #2
102
using System;
class my_app
{
static void Main(string[] args)
{
string Age = "";

Console.WriteLine("Enter your age: ");


Age = Console.ReadLine();

if( int.Parse(Age) < 18 )


{
Console.WriteLine(“UNDER-AGE");
}
else
{
Console.WriteLine(“OVER-AGE");
}

Console.ReadKey();
}
}
nested if……
103

It is used to evaluate multiple conditions

Sample Problem #3

Create a C# program that would display “UNDER-AGE” if the age


entered is below 18, if age is equal to 18 display “EXACT-AGE”,
otherwise “OVER-AGE” if age above 18.
Solution to Problem #3
using System;
class my_app
104
{
static void Main(string[] args)
{
string Age = "";

Console.WriteLine("Enter your age: ");


Age = Console.ReadLine();

if( int.Parse(Age) < 18 )


{
Console.WriteLine(“UNDER-AGE");
}
else if( int.Parse(Age) == 18 )
{
Console.WriteLine(“EXACT-AGE");
}
else
{
Console.WriteLine(“OVER-AGE");
}
Console.ReadKey();
}
105

Computer Fundamentals
Programming
Module 5 – C# Loops

IRMA T. PLATA, DIT


ISABELA STATE UNIVERSITY- Main Campus
College of Computing Studies, Information and Communications Technology
Echague, Isabela
C# Loops
106

• There may be a situation, when you need to


execute a block of code several number of
times. In general, the statements are
executed sequentially: The first statement in
a function is executed first, followed by the
second, and so on.
• Programming languages provide various
control structures that allow for more
complicated execution paths.
C# Conditional Statements
107

• A loop statement
allows us to execute a
statement or a group
of statements
multiple times and
following is the
general form of a loop
statement in most of
the programming
languages
Loop Types and Description
108

Loop Types and Description

while Loop It repeats a statement or a group of statements


while a given condition is true. It tests the
condition before executing the loop body.
For loop It executes a sequence of statements multiple
times and abbreviates the code that manages
the loop variable.
Do…while It is similar to a while statement, except that it
loop tests the condition at the end of the loop body
Nested loops You can use one or more loop inside any
another while, for or do..while loop.
C# - While Loop
109

• A while loop statement in C#


repeatedly executes a target
statement as long as a given
condition is true.
• Here, statement(s) may be a
single statement or a block of
statements. The condition may
be any expression, and true is
any non-zero value. The loop
iterates while the condition is
true.
• When the condition becomes
false, program control passes
to the line immediately
following the loop.
C# - For Loop
110

A for loop is a
repetition control
structure that allows
you to efficiently
write a loop that
needs to execute a
specific number of
times.
C# - For Loop
111
• The init step is executed first, and only once. This step allows you
to declare and initialize any loop control variables. You are not
required to put a statement here, as long as a semicolon appears.

• Next, the condition is evaluated. If it is true, the body of the loop


is executed. If it is false, the body of the loop does not execute
and flow of control jumps to the next statement just after the for
loop.

• After the body of the for loop executes, the flow of control jumps
back up to the increment statement. This statement allows you
to update any loop control variables. This statement can be left
blank, as long as a semicolon appears after the condition.

• The condition is now evaluated again. If it is true, the loop


executes and the process repeats itself (body of loop, then
increment step, and then again testing for a condition). After the
condition becomes false, the for loop terminates.
C# - Do..While Loop
112

• Unlike for and while


loops, which test the
loop condition at the
start of the loop, the
do...while loop checks
its condition at the end
of the loop.
• A do...while loop is
similar to a while loop,
except that a do...while
loop is guaranteed to
execute at least one
time.
C# - Do..While Loop
113

• Notice that the conditional expression appears at the


end of the loop, so the statement(s) in the loop
execute once before the condition is tested.

• If the condition is true, the flow of control jumps back


up to do, and the statement(s) in the loop execute
again. This process repeats until the given condition
becomes false.
C# - Nested Loop
114

• C# allows to use one loop inside another loop. Following


section shows few examples to illustrate the concept.

You might also like