0% found this document useful (0 votes)
10 views15 pages

C# Conditional Statements Guide

The document provides an overview of conditional statements and loops in C#, explaining their purpose and types, including if, else, else if, switch statements, and various loop structures like for, while, and do-while. It also covers arrays, both single-dimensional and multi-dimensional, and introduces Object-Oriented Programming (OOP) concepts such as classes, objects, abstraction, encapsulation, inheritance, and polymorphism. Examples are provided for each concept to illustrate their application in programming.

Uploaded by

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

C# Conditional Statements Guide

The document provides an overview of conditional statements and loops in C#, explaining their purpose and types, including if, else, else if, switch statements, and various loop structures like for, while, and do-while. It also covers arrays, both single-dimensional and multi-dimensional, and introduces Object-Oriented Programming (OOP) concepts such as classes, objects, abstraction, encapsulation, inheritance, and polymorphism. Examples are provided for each concept to illustrate their application in programming.

Uploaded by

HUNDAOL WORKU
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd

Conditional Statements

Conditional statements in programming are used to perform different actions based on


different conditions. Those statement allow the program to make decisions and
execute certain blocks of code only when a specific conditions are met. In real world
applications, we often need our program to make decisions.
For example:
 Should a user allowed to login?
 Is the entered password correct?
 Should a discount be applied?
Conditional statements help to implement such logic and make our programs dynamic
and interactive.
Types of conditional Statements in C#
1. if statement
2. Else statement
3. Else if statement
4. Switch statement
IF statement
the if statement is the simplest form of conditional logic .it checks whether a given
condition is true, and if it is, it executes the block of code inside it. If the condition is
false, the block is skipped.
Syntax
if (condition) {
//code to execute if condition is true
}
Example ATM system access
Output

In this example we simulate a basic ATM access system. The program checks if the
user has entered a correct pin code. If the input matches with the stored pin, it grants
access to the account.
Else Statement
The else statement is used to specify a block of code that will be executed if the
condition in the if statement is false. It acts as an alternative path when the original
condition isn't met.
Syntax
if (condition) {
//code to execute if condition is true
}
else {
//code to execute if condition is false
}
Example: let’s use the above ATM system example when the condition fails.
Output

Else If Statement
The else if statement allows us to check multiple conditions sequentially. If the first if
condition is false, the program checks the next else if condition, and so on. It helps in
decision-making where there are more than two possible outcomes.
Syntax
if (condition) {
//code to execute if condition 1 is true
}
else if (condition){
//code to execute if condition 2 is true
}
else {
//code to execute if none of the condition is true
}
Example: let’s see student grading system

Output

The program prompts the user to enter a [Link] on the value entered, it checks
the range using if and multiple else if statements. Only one condition will be true, and
the matching grade message is printed. The else block catches all grades below 50,
which is considered a fail.
Switch Statement
The switch statement is used to replace multiple if-else-if statements when we're
comparing the same variable against different values. It provides a cleaner and more
readable way to handle multiple possible values of a variable.
Syntax
switch (expression){
case value1:
// Code for value1
break;
case value2:
// Code for value2
break;
default:
// Code if none of the cases match
}
Example: simple menu selection system using switch statement where a user can select an
option to perform a specific task

Output

The user is shown a menu with three options. Based on the input (1, 2, or 3), the
program executes the appropriate case. The default case handles any input outside of
the expected [Link] is commonly used in console apps.
Loop Statement
A loop statement in programming is a control structure that allows you to execute a
block of code repeatedly as long as a specified condition is met. Loops are essential
for automating repetitive tasks without writing the same code multiple times.
Loops help when we need to:
 Repeat tasks without writing the same code multiple times.
 Traverse collections or arrays.
 Perform operations like counting, iterating, processing user input, etc.

Types of Loops in C#
1. for loop – Repeats code for a known number of times.
2. while loop – Repeats code while a condition is true.
3. do-while loop – Similar to while but executes at least once.
4. foreach loop – Used to iterate through collections/arrays.

1. For loop
Syntax:
for (initialization; condition; increment)
{
// Code to execute
}
Explanation:
initialization – Set starting value (e.g. int i = 0)
condition – Checked before each iteration
increment – Update after each loop (e.g. i++)
Example: Print numbers from 1 to 5
2. While loop
A while loop is a control structure that repeatedly executes a block of code as long as
a given condition remains true. The condition is evaluated before each iteration, and if
it's false from the beginning, the loop body may not execute at all.
Use Cases:
 When the number of repetitions is not known in advance
 Continuously waiting for a condition to be true (e.g., user input, status check)
 Reading input until a specific keyword or value is entered
Syntax:
while (condition)
{
// Code to execute
}
Example: user login system

Output

This example simulates a login system where the user has to enter the correct
password. The loop continues until the correct password is entered.
3. do-while loop
A do-while loop is similar to a while loop, but with one key difference: It executes the
loop body at least once, before checking the [Link] condition is evaluated after
each iteration. This guarantees that the code inside the loop will run at least one time,
even if the condition is false initially.
Use Cases:
 When you need to run the loop at least once, like showing a menu or taking input
 Repeating actions until a user chooses to exit (e.g., game menus, ATM interfaces)
 Validating input where the user must enter a correct value
Syntax:
do
{
// Code to execute
}
while (condition);
Example: let’s check wheather a user want continue or exists a current service

Output

This example simulate a simple program where a user is asked whether they want to
continue or not. The loop repeats until the user enters "no".
Array in C#
An array is a collection of variables (called elements) that are stored in contiguous
memory locations and are accessed using a common name and an index. In C#, arrays
are:
 Fixed in size (you must define the number of elements when creating the array)
 Zero-based (the first element is accessed with index 0)
 Strongly typed (all elements must be of the same data type)
Use Cases: Arrays are used when
 You need to store and manage multiple values of the same type (e.g., scores,
names, items).
 You want to process a collection using loops.
 You are dealing with matrices, lists, or batch operations in real-world applications
 Storing product prices in an e-commerce app
 Managing student grades
 Representing game boards or image pixels (multi-dimensional arrays)
Single-Dimensional Arrays
A single-dimensional array (also called a linear array) stores elements in a single row
(or list-like structure). Each element is accessed using one index.
Syntax:
datatype[] arrayName = new datatype[size];
Or, with initialization:
int[] numbers = { 10, 20, 30, 40 };
Example: Store 5 student scores using Single-Dimensional Arrays and calculate their
average.

Output
Multi-Dimensional Arrays
A multi-dimensional array is an array with more than one dimension often visualized
as a table or matrix with rows and columns.
The most common is the 2D array, like a grid.
Syntax (2D Array):
datatype[,] arrayName = new datatype[rows, columns];
Or, with initialization:
int[,] matrix = { {1, 2}, {3, 4}, {5, 6} };
Example: Store and print marks of 2 students in 3 subjects

Output
Object-Oriented Programming (OOP)
Object-Oriented Programming (OOP) is a programming paradigm based on the
concept of "objects" which are instances of classes. OOP allows us to model real-
world entities by bundling data (fields) and behavior (methods) together into units
called objects.
OOP makes code:
 Easier to understand and maintain
 Modular and reusable
 Scalable and organized

What is Object?
An object is an instance of a class. It represents a real-world entity that has state
(attribute) and behavior (methods).
Attribute: A characteristic of an object like a variable associated with a kind of
object.
Methods: A behaviour of an object like a function associated with a kind of object.

What is Class?
A class is a blueprint or template for creating objects. It defines the attributes (fields)
and behaviors (methods) that the objects will have.
Object-Oriented Principle
oop contains the following fundamentals principle
 Abstraction
Abstraction is the process of hiding complex implementation and showing only the
essential features to the [Link] focuses on what an object does, not how it does it.
Example:

Output

 Encapsulation
Encapsulation means hiding internal details of an object and only exposing what is
necessary through methods (like getters and setters). It helps to protect data and
ensures controlled access.
Example:
Output

 Inheritance
Inheritance allows a child class to acquire the properties and behaviors of a parent
class, promoting code re-usability.
Example:
 Polymorphism
Polymorphism means one function behaving differently depending on the object or
context. It can be achieved via method overloading or method overriding.
Types of Polymorphism in C#
 Compile-time Polymorphism (Static Binding)
 Runtime Polymorphism (Dynamic Binding)

1. Compile-time Polymorphism (Static Binding)


This occurs when the method to be executed is determined at compile time.
It is mainly achieved through:
Method Overloading: Multiple methods with the same name but different parameter
lists.
Operator Overloading: Custom behavior for standard operators.
Example – Method Overloading:

In this example, the Add method is overloaded with different parameter types and
counts, which is resolved at compile-time.
2. Runtime Polymorphism (Dynamic Binding)
This happens when the method that gets executed is determined at runtime.
It is achieved through:
Method Overriding: A derived class provides its specific implementation of a method
already defined in the base class. Requires virtual in the base class and override in the
derived class.
Example: (Method Overriding)

Animal has a generic speak() methods Cat overrides speak() with its own behavior.

You might also like