KEMBAR78
CMT 307 Notes | PDF | Control Flow | Method (Computer Programming)
0% found this document useful (0 votes)
9 views20 pages

CMT 307 Notes

The document covers fundamental concepts in C# programming, including variables, data types, operators, control structures, arrays, and exception handling. It provides syntax examples, exercises, and explanations for each topic, such as variable declaration, data type categories, and control flow mechanisms like loops and conditional statements. Additionally, it discusses error types and exception handling using try-catch blocks to manage runtime errors.

Uploaded by

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

CMT 307 Notes

The document covers fundamental concepts in C# programming, including variables, data types, operators, control structures, arrays, and exception handling. It provides syntax examples, exercises, and explanations for each topic, such as variable declaration, data type categories, and control flow mechanisms like loops and conditional statements. Additionally, it discusses error types and exception handling using try-catch blocks to manage runtime errors.

Uploaded by

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

CHAPTER 2 Variables

Variable; a named space in the computer's memory that can store different
values at different times.
The act of creating a variable is variable declaration whose syntax in c# is;
datatype variable name;
example
string myname;
int mymarks;

The datatype specifies the type/kind of data that a variable will hold plus
the operations allowed on that variable

variable initialization
string myname="no name";
int mymarks=1;

Identifier naming rules


1). An identifier cannot start with an integer number. alphabet, underscore,@
2). Identifiers are case sensitive
3). An identifier cannot have whitespace
4). You cannot use a reserved word/keyword as the name of an identifier
e.t.c

Conventions
myName

CONSTANTS
const double pi = 3.14159;

CHAPTER 3 DATATYPES
C# Datatype categories −
1). Value types
2). Reference types
3). Pointer types

1). VALUE TYPES: bool,byte,char, decimal, double, float, int, long, sbyte,
short, uint, ulong, ushort

sizeof() => size of a datatype

Console.WriteLine("Size of int: {0}", sizeof(int));

2). REFERENCE TYPES: object, dynamic, and string.

3). POINTER TYPES: pointers

Write a C# console program that prompts the user to key in two floating-point
(decimal) numbers. The program should then calculate and display the product
of the 2 numbers.

double num1=1.0, num2=1.0, prod = 1.0;


Console.Write("Key in the first number:");
num1 = Convert.ToDouble(Console.ReadLine());
Console.Write("Key in the second number:");
num2 = Convert.ToDouble(Console.ReadLine());

prod = num1 * num2;

Console.WriteLine($"{num1} X {num2} = {prod}");

CHAPTER 4 OPERATERS
OPERATORS: An operator is a symbol that is used to perform computations in
programming.
Operator(s) work on operand(s)

No. of operands => Unary operators, binary operators, ternary operators

CATEGORIES OF OPERATORS
1). Arithmetic Operators: +, -, *, /, %, ++, --
2). Relational Operators: ==,!=,<,<=,>,>=
3). Logical Operators: &&, ||, !
4). Bitwise Operators: &, |, ^, ~, <<, >>
5). Assignment Operators: =, +=, *=, /=, -=, <<=, >>=, &=, ^=, |=
6). Misc Operators:sizeof(), typeof(), &, *, ?:, is, as

C# Operators Exercise:
Write a C# program that prompts a user to key in any two integer numbers. The
program should then calculate and display:
a). The division
b). The Moduli and
c). The Exponentiation of the 2 numbers i.e. the first number raised to the
power of the second number

CHAPTER 5 CONTROL STRACTURES


CONTROL STRUCTURES
Control structures are statements that determine the flow of execution of your
code.
By default, each line of code executes once, from top to bottom.

CATEGORIES OF CONTROL STRUCTURES


1). SEQUENCE/SEQUENTIAL CS => The default mode of code execution
2). BRANCHING/DECISION-MAKING/SELECTION => This is where one statement(s) is
executed and another is skipped or vice-versa based on the truth value of some
logical expression/condition.
The if, if-else, if-elseif and switch statements are used to implement
branching in C#.
Nested if statements.
3). LOOPING/ITERATION/REPETITION => Where a statement(s) is executed more than
once. The number of execution times is determined by an integer counter
variable.
The while loop, do-while loop, for loop and foreach loop are used to implement
looping in C#.
Nested loops

IF STATEMENT SYNTAX
if(logical expression)
{
//code here
}

IF-ELSE STATEMENT SYNTAX


if(logical expression)
{
//code here
}
else
{
//code here
}

IF-ELSEIF STATEMENT SYNTAX


if(logical expression-1)
{
//code here
}
else if(logical expression-2)
{
//code here
}
else if(logical expression-3)
{
//code here
}
else if(logical expression-n)
{
//code here
}
else
{
//code here
}

SWITCH SYNTAX
switch(expression)
{
case 1:
//code for case 1
break;

case 2:
//code for case 2
break;

case 3:
//code for case 3
break;

case n:
//code for case n
break;

default:
//code for default
break;
}

EXERCISE 1
Using the if statement, write a C# console program that prompts a user to key
in their age. The program should then display a message "You are a child" if
the age is less than 18.

int myage=1;
Console.Write("Input your age: ");
myage = Convert.ToInt32(Console.ReadLine());

if (myage < 18)


{
Console.WriteLine("You are a child");
}
else
{
Console.WriteLine("You are an adult");
}

IF-ELSEIF-ELSE
byte myage=1;
Console.Write("Input your age: ");
myage = Convert.ToByte(Console.ReadLine());

if (myage <= 18 && myage >= 1)


{
Console.WriteLine("You are a child");
}
else if(myage <= 35 && myage >= 19)
{
Console.WriteLine("You are a Youth");
}
else if(myage <= 55 && myage >= 36)
{
Console.WriteLine("You are an Adult");
}
else if(myage <= 70 && myage >= 56)
{
Console.WriteLine("You are Old");
}
else if(myage <= 120 && myage >= 71)
{
Console.WriteLine("You are a Senior Citizen");
}
else
{
Console.WriteLine("Invalid. Key in a number in the range 1 to 120");
}

EXERCISE 2
XYZ Ltd. uses the below PAYE percentage tax rates for all its employees salary
categories
BASIC SALARY(K.Shs) PAYE RATE (%)
50,000 and above 14
40,000 - 49,999 12
35,000 - 39,999 11
25,000 - 34,999 8
16,000 - 24,999 5
9,500 - 15,999 3
Below 9,500 0

The following standard deductions apply to all employees:


NSSF = K.Shs 800, SHIF = K.Shs 1250, Housing levy = K.Shs 675

The overtime rate is K.Shs 300 per hour for the first 50 hours. Any extra
overtime hour is paid at the rate of K.Shs 350.

Required: Write a C# console program that calculates an employee's net pay


using the formula below:
Net pay = Gross salary-[PAYE + NSSF + SHIF + Housing levy]

Note: Allow the user to input the basic salary and overtime hours worked
Gross salary = basic salary + overtime

SWITCH
byte myyear=1;
Console.Write("Input your year of study: ");
myyear = Convert.ToByte(Console.ReadLine());

switch(myyear)
{
case 1:
Console.WriteLine("Fresher wewe");
break;
case 2:
Console.WriteLine("Sophomore wewe");
break;
case 3:
Console.WriteLine("Continuing wewe");
break;
case 4:
Console.WriteLine("Finalist wewe");
break;
default:
Console.WriteLine("Invalid. Key in a number between 1 and 4");
break;
}

SWITCH WITH RANGE OF VALUES


int myyear=1;
Console.Write("Input your year of study: ");
myyear = Convert.ToByte(Console.ReadLine());
switch (myyear)
{
case 1:
Console.WriteLine("Fresher wewe");
break;
case 2:
Console.WriteLine("Sophomore wewe");
break;
case 3:
Console.WriteLine("Continuing wewe");
break;
case 4:
Console.WriteLine("Finalist wewe");
break;
case int i when (i>=5 && i<=7):
Console.WriteLine("Fifth, sixth or Seventh year");
break;
default:
Console.WriteLine("Invalid. Key in a number between 1 and 7");
break;
}

Ternary operator => ?:

EXERCISE 3
Using the if statement, write a C# console program that prompts a user to key
in their score in the CMT307 unit. The program should then display a message
"You have failed" if the score is less than 40.

Exe3 IF
byte mymark=1;
Console.Write("Key in your expected score in CMT307");
mymark = Convert.ToByte(Console.ReadLine());

if(mymark<40)
{
Console.WriteLine("You have failed");
}

Exe3 IF-ELSE
byte mymark = 1;
Console.Write("Key in your expected score in CMT307: ");
mymark = Convert.ToByte(Console.ReadLine());

if (mymark < 40)


{
Console.WriteLine("You have failed");
}
else
{
Console.WriteLine("You have passed");
}

Exe3 IF-ELSEIF
byte mymark = 1,myage=1;
Console.Write("Key in your expected score in CMT307: ");
mymark = Convert.ToByte(Console.ReadLine());
Console.Write("Key in your Age: ");
myage = Convert.ToByte(Console.ReadLine());
if (mymark<= 39 && mymark>=1)
{
if(myage<18)
{
Console.WriteLine("You have failed, Child");
}
else
{
Console.WriteLine("You have failed, Child");
}
}
else if(mymark<= 49 && mymark>=40)
{
Console.WriteLine("You have passed, Grade D");
}
else if(mymark<= 59 && mymark>=50)
{
Console.WriteLine("You have passed, Grade C");
}
else if(mymark<= 69 && mymark>=60)
{
Console.WriteLine("You have passed, Grade B");
}
else if(mymark<= 100 && mymark>=70)
{
Console.WriteLine("You have passed, Grade A");
}
else
{
Console.WriteLine("Invalid, input a number between 1 and 100");
}

LOOPS
Avoid:
1). Infinite loops
2). Off-by-one-error (OBOE)

WHILE LOOP
Syntax
while(boolean expression)
{
//code here
}

PRINT OUT 1 TO 20 USING A WHILE LOOP


int counter = 1;
while(counter<=20)
{
Console.WriteLine(counter);
counter++;
}

SUM OF 1 TO 20 USING A WHILE LOOP


int counter = 1,sum=0;
while (counter <= 20)
{
Console.WriteLine(counter);
sum = sum + counter;
counter++;
}
Console.WriteLine("\n");
Console.WriteLine($"sum of 1 t0 20: {sum}");

PRINT OUT 1 TO 20 USING THE DO-WHILE LOOP


int counter = 1;
do
{
Console.WriteLine(counter);
counter++;
} while (counter <= 20);

SUM OF 1 TO 20 USING THE DO-WHILE LOOP


int counter = 1,sum=0;
do
{
Console.WriteLine(counter);
sum = sum + counter;
counter++;
}
while (counter <= 20);
Console.WriteLine($"\nSum is: {sum}");

PRINT OUT 1 TO 20 USING THE FOR LOOP


int counter = 20;
for (counter = 20; counter >= 1; counter=counter-3)
{
Console.WriteLine(counter);
}

LOOP TERMINATING STATEMENTS


BREAK, CONTINUE, GOTO

BREAK
for (int i = 1; i <=7; ++i)
{
if (i == 3)
{
break;
}
Console.WriteLine(i);
}

CONTINUE
for (int i = 1; i <= 7; ++i)
{
if (i == 3)
{
continue;
}
Console.WriteLine(i);
}

GOTO
repeat:
Console.Write("Enter a number less than 10: ");
int num = Convert.ToInt32(Console.ReadLine());

if(num >= 10) {


// transfers control to repeat
goto repeat;
}

Console.WriteLine(num + " is less than 10");

MORE LOOPS EXERCISES


1). Write a C# program that prompts the user to key in two integer numbers x
and y, representing the lower and upper limits respectively.
The program should then:
a). Calculate and print out the summation of all the numbers between x and y
(exclusive of x and y).
b). Print out all the even numbers between x and y.

2). An infinite loop is an undesirable situation in programming and should be


totally avoided.
Write a C# code that has an infinite loop

CHAPTER 6 ARRAYS
C# Arrays
An array is a collection of similar types of data. Example:
Suppose we need to record the age of 5 students. Instead of creating 5
separate variables, we can simply create an array:

C# Array Declaration
Syntax:
datatype[] arrayName;

Where:
DataType - data type like int, string, char, etc
arrayName - it is an identifier

Example
int[] age;

// declare an array
int[] age;
// allocate memory for array
age = new int[5];
OR
int[] age = new int[5];

int[] age = new int[5];


age[0] = 20;
age[1] = 25;
age[2] = 18;
age[3] = 19;
age[4] = 39;

Console.WriteLine(age[0]);
Console.WriteLine(age[1]);
Console.WriteLine(age[2]);
Console.WriteLine(age[3]);
Console.WriteLine(age[4]);

Improved Version
int counter = 0;
int[] age = new int[5];
age[0] = 14;
age[1] = 5;
age[2] = 418;
age[3] = 197;
age[4] = 389;

for (counter = 0; counter <= 4; counter++)


{
Console.WriteLine(age[counter]);
}

DYNAMIC VERSION
int counter = 0;
int[] age = new int[5];
for(counter = 0; counter <=4;counter++)
{
Console.Write($"Key in value {counter+1}: ");
age[counter] = Convert.ToInt32(Console.ReadLine());
}

for (counter = 0; counter <= 4; counter++)


{
Console.WriteLine(age[counter]);
}

CHAPTER 7 EXEMPTION HANDLING


TYPES OF ERRORS
1). Syntax errors / Design-time errors
2). Runtime errors => wrong input, accessing a non-existent resource
3). Logical errors => Wrong logic

C# EXCEPTIONS
An exception is an unexpected event that occurs during program execution and
makes the program NOT execute to completion i.e. the program crashes.

When an Exception happens in a program, we say that the program has thrown an
exception.
A programmer should foresee Exceptions that might be thrown by their program
and provide corrective measures (codes) to ensure that the exceptions do not
crash their program (Catch the Exception / Exception handling)

The try-catch-finally statement is used to catch/handle exceptions in the C#


language.

int divideByZero = 7 / 0;

The above code causes an exception as it is not possible to divide a number by


0.

EXAMPLE1: CODE THAT THROWS EXCEPTION (NO TRY-CATCH)


string[] colors = { "Red", "Green", "Pink" };
// print the array element present at 3rd index position
Console.WriteLine(colors[3]);

EXAMPLE2: CODE THAT THROWS EXCEPTION (HAS TRY-CATCH)


string[] colors = { "Red", "Green", "Pink" };
// print the array element present at 3rd index position
try
{
Console.WriteLine(colors[3]);
}
catch(IndexOutOfRangeException exc)
{
Console.WriteLine("Error. Check your indexes/indices!");
}
Console.WriteLine("Line after printing");

EXAMPLE3: CODE THAT THROWS EXCEPTION (HAS TRY-CATCH)


try
{
int num = 0;
// code that may raise an exception
int divideByZero = 7 / num;
Console.WriteLine(divideByZero);
}
catch (DivideByZeroException e)
{
Console.WriteLine("Error:"+e.Message);
}
Console.WriteLine("Line after try-catch");

EXAMPLE4: CODE THAT THROWS EXCEPTION (HAS TRY-CATCH)


string[] colors = { "Red", "Blue", "Green" };

try
{
// code that may raise an exception
Console.WriteLine(colors[5]);
}
catch (IndexOutOfRangeException e)
{
Console.WriteLine("Error: " + e.Message);
}
Console.WriteLine("Line after exception");

EXAMPLE5: CODE THAT THROWS EXCEPTION (HAS FINALLY BLOCK)


// take first int input from user
Console.WriteLine("Enter first number:");
int firstNumber = int.Parse(Console.ReadLine());

// take second int input from user


Console.WriteLine("Enter second number:");
int secondNumber = int.Parse(Console.ReadLine());

try
{
// code that may raise raise an exception
int divisionResult = firstNumber / secondNumber;
Console.WriteLine("Division of two numbers is: " +
divisionResult);
}

// this catch block gets executed only when an exception is raised


catch (Exception e)
{
Console.WriteLine("An exception occurred: " + e.Message);
}

finally
{
// this code is always executed whether of exception occurred or
not
Console.WriteLine("Sum of two numbers is: " + (firstNumber +
secondNumber));
}

EXAMPLE6: NESTED TRY-CATCH


int divisor = 0;
try
{
// nested try block
try
{
int divideByZero = 6 / divisor;
}

// inner catch block


catch (IndexOutOfRangeException e)
{
Console.WriteLine("Inner catch is executed. " + e.Message);
}
}
// outer catch block
catch (DivideByZeroException e)
{
Console.WriteLine("Outer catch block is executed. " + e.Message);
}

EXAMPLE7: GENERIC CATCH BLOCK


int[] numbers = { 1, 2, 3 };
try
{
// access element present at 5th index position
Console.WriteLine(numbers[5]);
}

// generic catch block


catch
{
Console.WriteLine("Some exception occurred");
}

EXAMPLE8: EXCEPTION HANDLING WITH MORE THAN ONE CATCH BLOCKS


int[] numbers = { 1, 0, 3, 4 };
try
{
// code that may raise an exception
int divide = numbers[2] / numbers[1];
}

// if IndexOutofRangeException occurs, the following block is executed


catch (IndexOutOfRangeException e)
{
Console.WriteLine(e.Message);
}

// if the above catch block doesn't handle the exception,


// this block is executed
catch(Exception e)
{
Console.WriteLine("Some exception occurred");
}
catch(System.ArrayTypeMismatchException exc)
{
Console.WriteLine(exc.Message);
}

EXERCISES
1). Write a C# program that takes an integer as input and throws an exception
if the number is negative.

2). Write a C# program that calculates the factorial of a given number. Handle
the OverflowException that occurs if the result exceeds that Int32 maximum
value.

CHAPTER 8 OOP
OBJECT-ORIENTED PROGRAMMING IN C#
OOP is a programming paradigm that focuses on objects and their interactions.
An object is a real-world entity or thing that is created from a class.
A class is a blueprint/stencil/template that describes what an object of the
class consists of and what operations can be performed on that object.

A class consists of 2 main components =>


actions/operations/methods/functions/routines/procedure and
properties/characteristics/data members/data/variables

Objects are instances of a class. (copy/replica)


The methods and variables that constitute a class are called members of the
class.

ADVANTAGES OF OOP
1). Code reusability
2). Simplicity
3). Extendable code
4). Easier maintenance
5). etc

SYNTAX FOR DEFINING A CLASS


<access specifier> class class_name
{
// member variables
<access specifier> <data type> variable1;

// member methods
<access specifier> <return type> method1(parameter_list)
{
// method body
}
}

EXAMPLE1
class Box
{
private double length; // Length of a box
private double breadth; // Breadth of a box
private double height; // Height of a box

public void setLength( double len )


{
length = len;
}
public void setBreadth( double bre )
{
breadth = bre;
}
public void setHeight( double hei )
{
height = hei;
}
public double getVolume()
{
return length * breadth * height;
}
}
class Boxtester
{
static void Main(string[] args)
{
Box Box1 = new Box(); // Declare Box1 of type Box
double volume;

// box 1 specification
Box1.setLength(6.0);Box1.setBreadth(7.0);Box1.setHeight(5.0);

// volume of box 1
volume = Box1.getVolume();
Console.WriteLine("Volume of Box1 : {0}" ,volume);

}
}

C# Constructors
A class constructor is a special method of a class that is executed
automatically whenever we create new objects of that class.

A constructor has exactly the same name as that of class and it does not have
any return type

EXAMPLE2
class Line {
private double length; // Length of a line
public Line() {
Console.WriteLine("Object is being created");
}
public void setLength( double len ) {
length = len;
}
public double getLength() {
return length;
}
static void Main(string[] args) {
Line line = new Line();

// set line length


line.setLength(6.0);
Console.WriteLine("Length of line : {0}", line.getLength());
}
}

A default constructor does not have any parameter but if you need, a
constructor can have parameters. Such constructors are called parameterized
constructors. This technique helps you to assign initial value to an object at
the time of its creation as shown in the following example −

class Line {
private double length; // Length of a line

public Line(double len) { //Parameterized constructor


Console.WriteLine("Object is being created, length = {0}", len);
length = len;
}
public void setLength( double len ) {
length = len;
}
public double getLength() {
return length;
}
static void Main(string[] args) {
Line line = new Line(10.0);
Console.WriteLine("Length of line : {0}", line.getLength());

// set line length


line.setLength(6.0);
Console.WriteLine("Length of line : {0}", line.getLength());
Console.ReadKey();
}
}

C# Destructors
A destructor is a special member function of a class that is executed whenever
an object of its class goes out of scope. A destructor has exactly the same
name as that of the class with a prefixed tilde (~) and it can neither return
a value nor can it take any parameters.

Destructor can be very useful for releasing memory resources before exiting
the program. Destructors cannot be inherited or overloaded.

Following example explains the concept of destructor −

Live Demo
using System;

namespace LineApplication {
class Line {
private double length; // Length of a line

public Line() { // constructor


Console.WriteLine("Object is being created");
}
~Line() { //destructor
Console.WriteLine("Object is being deleted");
}
public void setLength( double len ) {
length = len;
}
public double getLength() {
return length;
}
static void Main(string[] args) {
Line line = new Line();

// set line length


line.setLength(6.0);
Console.WriteLine("Length of line : {0}", line.getLength());
}
}
}
Static Members of a C# Class
We can define class members as static using the static keyword. When we
declare a member of a class as static, it means no matter how many objects of
the class are created, there is only one copy of the static member.

The keyword static implies that only one instance of the member exists for a
class. Static variables are used for defining constants because their values
can be retrieved by invoking the class without creating an instance of it.
Static variables can be initialized outside the member function or class
definition. You can also initialize static variables inside the class
definition.

The following example demonstrates the use of static variables −

Live Demo
using System;

namespace StaticVarApplication {
class StaticVar
{
public static int num;

public void count() {


num++;
}
public int getNum() {
return num;
}
}
class StaticTester {
static void Main(string[] args) {
StaticVar s1 = new StaticVar();
StaticVar s2 = new StaticVar();

s1.count();
s1.count();
s1.count();

s2.count();
s2.count();
s2.count();

Console.WriteLine("Variable num for s1: {0}", s1.getNum());


Console.WriteLine("Variable num for s2: {0}", s2.getNum());
Console.ReadKey();
}
}
}

You can also declare a member function as static. Such functions can access
only static variables. The static functions exist even before the object is
created. The following example demonstrates the use of static functions −

Live Demo
using System;
namespace StaticVarApplication {
class StaticVar {
public static int num;

public void count() {


num++;
}
public static int getNum() {
return num;
}
}
class StaticTester {
static void Main(string[] args) {
StaticVar s = new StaticVar();

s.count();
s.count();
s.count();

Console.WriteLine("Variable num: {0}", StaticVar.getNum());


Console.ReadKey();
}
}
}

OOP FEATURES (OOPs)


1). ENCAPSULATION: Bundling data members and methods into a single entity
called a class i.e. creating a class.
2). DATA HIDING / INFORMATION HIDING: Accessing the data members should NOT be
direct but via the methods. All data members should have the private
accessibility modifier.
3). INHERITANCE: Using the full colon between the child class and parent class
4). ABSTRACTION: interfaces, abstract classes
5). POLYMORPHISM: Method overloading, operator overloading, method overriding

class Shape
{
public void setWidth(int w)
{
width = w;
}
public void setHeight(int h) {
height = h;
}
protected int width;
protected int height;
}

// Derived class
class Rectangle:Shape {
public int getArea() {
return (width * height);
}
}
QUESTIONS ON THE PORTAL
EXERCISE 2

XYZ Ltd. uses the below PAYE percentage tax rates for all its employees salary
categories:

BASIC SALARY(K.Shs) PAYE RATE (%)

50,000 and above 14

40,000 - 49,999 12

35,000 - 39,999 11

25,000 - 34,999 8

16,000 - 24,999 5

9,500 - 15,999 3

Below 9,500 0

The following standard deductions apply to all employees:

NSSF = K.Shs 800, SHIF = K.Shs 1250, Housing levy = K.Shs 675

The overtime rate is K.Shs 300 per hour for the first 50 hours. Any extra
overtime hour is paid at the rate of K.Shs 350.

Required: Write a C# console program that calculates an employee's net pay


using the formula below:

Net pay = Gross salary-[PAYE + NSSF + SHIF + Housing levy]

Note: Allow the user to input the basic salary and overtime hours worked

Gross salary = basic salary + overtime

You might also like