0% found this document useful (0 votes)
12 views14 pages

C# Programming Basics and Examples

The document provides a comprehensive overview of C# programming concepts, including syntax elements like semicolons, access modifiers, and class definitions. It includes various programming exercises demonstrating loops, file handling, and conditional logic, along with sample code snippets for tasks such as displaying numbers, calculating sums, and managing user input. Additionally, it covers the structure of a program for a banking system, detailing functionalities for account management and transactions.

Uploaded by

Larry Thebenala
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)
12 views14 pages

C# Programming Basics and Examples

The document provides a comprehensive overview of C# programming concepts, including syntax elements like semicolons, access modifiers, and class definitions. It includes various programming exercises demonstrating loops, file handling, and conditional logic, along with sample code snippets for tasks such as displaying numbers, calculating sums, and managing user input. Additionally, it covers the structure of a program for a banking system, detailing functionalities for account management and transactions.

Uploaded by

Larry Thebenala
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

Sharp-Tutorials Questions

C#

“; “= semicolon its is used to tell the complier where one


statement ends and the next one begins.

When we add its called: incrementing = i++

Example 1: Example 2:

input: int a = 10; for (int i = 0; i < 10; i++)

output: [Link](a); {

[Link](i);

public: Access modifier allowing access from any other code.

private: Access modifier restricting access to within the same


class.

class: Defines a new reference type, acting as a blueprint for


objects, containing fields, methods, properties, etc.

Examples of how we use the curly brackets: “ {“ or “ } “


if (condition) reason for comments; 1. readability
{ 2. Documentation
// Code to execute if the condition is true 3. purpose of the
code
} 4. Clarify Logic
for (int i = 0; i < 10; i++)
{
// Code to execute in each iteration of the loop
}

while (condition)
{
// Code to execute while the condition is true
}
1. a) Write a program to display Numbers 1 - 100 using a for
loop

Using System;

Class Program
{
Static Void Main()
{
// program to display Numbers 1 - 100 using a for loop
for ( int number = 1; number <=100; number++)
{
[Link](number);
}
}
}
b) Write a program to display Numbers 1 - 100 using a while
loop
Using System;
class Program
{
Static void Main()
{
//program to display Numbers 1 - 100 using a while loop
Int number = 1;
while (number <= 100)
{
[Link](number)
number++
}
}
}

2. a) Write a program to display Numbers 100 – 1 using a while


loop
Using System;
Class Program
{
Static void Main()
{
//program to display numbers 100 – 1 using while loop
Int number= 100;
While(number >= 1)
{
[Link](number);
number--;
}
}
}
b) Write a program to display Numbers 100 – 1 using a for loop
Using System;
Class Program
{
Static void Main()
{
//program to display numbers from 100 – 1 using for loop
for (int number = 100; number =>1;number--)
{
[Link](number);
}
}
}
3. Write a program to add the numbers 100, 200, 300, 400,
500, ….. 1000
Into an array of integers called arrvalues,
- Calculate and display the sum of the values in the array
- Calculate and display the average of values the array
Using System;
class Program
{
Static void Main()
{
int[] arrValues = new int[10]
int index = 0
for (int i = 1; i < = 10; i++)
{
arrValues[index] = i * 100;
index++;
}
//calculate the sum
Int sum = 0;
for (int i = 0; I < [Link]; i++)
{
sum+= arrValues[ i ];

//Calculate the average of value to hold decimal point

double average = (double)sum/length;

[Link](“Sum of values:” + sum)

[Link](“Average of values:” + average)

}
4. Write a program to write the following data into a TextFile
called [Link]
ABC23-001 | Alice | Johnson | Female | 50 | 85 | 75

using System;
[Link];
Class Program
{
Static void Main()
{
string data = “ABC23-001 | Alice | Johnson | Female | 50 | 85 | 75”;
string path = “[Link]”;
try
{
[Link](path, data);
[Link](“Data has been written to [Link] successfully”);
}
Catch (Exception ex)
{
[Link](“ An error has occurred: + [Link]);
}
}
}
5. Write a program to produce the following pattern:

1 = 1

1 2 = 3

1 2 3 = 6

1 2 3 4 = 10

1 2 3 4 5 = 15

1 2 3 4 5 6 = 21

Using System;

Class Program
{

Static void Main()

int sum;

for (int i = 1; i <=6; i++)

sum = 0;

for (int j = 1; j <= i; j++)

[Link](j + “ “);

sum+= j;

[Link](“=” + sum);

[Link]();

Question 2
a) The following information has been mistakenly captured into wrong
variables.
String country = "enquiries@[Link]";

String cellno = "Botswana";

String email = "74740404";

Write C# program statements to swap the values into their respective


correct variables.

Using System;
Class Program
{
Static void Main()
{
// initial incorrect variable
String country = "enquiries@[Link]";
String cellno = "Botswana";
String email = "74740404";
//temp correct variables
string tempCountry = “Botswana”;
string tempCellno = "74740404";
string tempEmail = "enquiries@[Link]";
//assign correct values
country = tempCountry;
cellno = tempCellno;
email = tempEmail;
// Output correct values
[Link](“Country: ” + country);
[Link](“Cell Number: + cellno);
[Link](“Email: + email);
}
}

[5
Marks]

b) Write down the value stored in the variable result in each of the
following;
i. bool result; no value [1 Marks]
ii. var result = (100 == ([Link]((3+7),2))); TRUE [1
Marks]
iii. var result = ((3 + 9 / 3) > 7) && ((45 / 9) < 6);
= FALSE (0) && TRUE (1)
= FALSE [1
Marks]
iv. bool result = Convert.ToInt32("1" + "1") == 11;
= TRUE
[1 Marks]
v. bool result = "A" == "a";
= false [1
Marks]

c) You have been hired by Hillside High School to develop a program to


calculate the student grade in a given Subject. The grade is based
on the average mark of a student obtained from the three in-class
tests i.e. Test1, Test2 and Test3.

RangeFr
om RangeTo Grade
0 49 FAIL
50 59 PASS
60 69 CREDIT
70 79 MERIT
80 100 DISTINCTION

The following form is proposed for the program, and the control
names are shown on the right.
i. Write C# code for the Calculate Button to accept user input
and calculate student grade, button click event handler is
not necessary. [10 Marks]
using System;
class Program;
{
Static void Main()
{

ii. Given that a student called Melinda Jones whose marks for
Chemistry are; Test1 = 83, Test2 = 75, Test3 = 79. Write
down the output from your program for this student.
[5 Marks]
Question 3
a) The iteration control structure is implemented through looping in
programs. There are two main types of looping constructs, those that
tests the condition at the beginning and those that tests the condition
at the end.
i. Define the term Loop as used in programming.
A loop is a control structure used for repetitive execution of block
code when specific condition is met.

[2 Marks]
ii. Identify any one (1) looping construct that tests the condition at the
beginning.
While loop [1Mark]
iii. State when the looping construct in ii above is suitable to be used.

The while loop is suitable for when you want to test a repetitive of a
block code condition that runs for an unknow number of times.

[2 Marks]
iv. Write a program code to implement the looping construct in ii above
to display numbers from 1 to 100.
[5 Marks]
v. Name any one (1) looping construct that tests the condition at the
end. [1 Mark]
Do while loop
vi. State when the looping construct in v above is suitable to be used.
when you need to execute the block of code at least once regardless
of whether the condition is true or false at the beginning.
[2 Marks]
vii. Write a program code to implement the looping construct in ii above
to display numbers from 1 to 100.
[5 Marks]
viii. What name is given to a loop embedded in another loop?
Nested loop [2 Marks]
Dry run the program below and determine the values of; a, b, c, d,
and e. [5 Marks]
private void button1_Click(object sender, EventArgs e) {
int sum = 0, n = 0;
double avg = 0;
for (int k = 10; k >= 1; k--) {
if(k % 3 == 0) {
sum += k; SUM = K VS SUM
+= K
n += 1;
avg = sum / n;
[Link](k);
}
}
[Link]("Sum is : {0}", sum);
//displaySum
[Link]("Average is : {0}", avg);
//display avg
}

k n sum Avg
10 0 0 0
9 A=1 9 9
8 1 9 9
7 1 9 9
6 2 15 7.5
5 2 15 7.5
4 2 15 7.5
3 3 18 6
2 3 18 6
1 C =3 D=18 E=6
Question 4
a) You have been hired by Molapo Pizza to develop a program to
calculate ticket prices for their shows. The ticket prices vary based
on age and there is a discount given for customers who purchase
tickets online.
AgeFro
Online
m AgeTo AgeGroup TicketPrice Discount

0 5 Infant 0 0

6 12 Child 50 10%

13 19 Teenage 100 15%

20 35 Youth 200 20%

36 45 Adults 300 25%

46 65 Elders 350 30%

66 100+ Senior Citizens 0 0

ix.
x.
Use the information given in the table above to write down the program
which should display the customer's name, age group, ticket price,
discount, and actual price. [10 Marks]
using System;

class Program
{
static void Main()
{
CalculateTicketPrice("John Doe", 25, true);
}

CalculateTicketPrice(string name, int age, bool onlinePurchase)


{
// Define the ticket pricing and discount structure
double pricing = new (int AgeFrom, int AgeTo, string AgeGroup, double
TicketPrice, double Discount);
{
(0, 5, "Infant", 0, 0),
(6, 12, "Child", 50, 0.10),
(13, 19, "Teenage", 100, 0.15),
(20, 35, "Youth", 200, 0.20),
(36, 45, "Adults", 300, 0.25),
(46, 65, "Elders", 350, 0.30),
(66, 100, "Senior Citizens", 0, 0)
};

// Determine the age group and corresponding ticket price and


discount
for ( AgeFrom, AgeTo, AgeGroup, TicketPrice, Discount)
{
if (age >= AgeFrom && age <= AgeTo)
{
double discountAmount = onlinePurchase ? TicketPrice *
Discount : 0;
double actualPrice = TicketPrice - discountAmount;

// Display the customer's details


[Link]("Customer Name:” + name);
[Link]("Age Group: “ + AgeGroup);
[Link]("Ticket Price: “ + TicketPrice);
[Link]("Discount:” + discountAmount);
[Link]("Actual Price:” + actualPrice);
}
}
}
}
xi. Given that a customer called Agness Thomas whose age is 37
years purchased the ticket online. Write down the output from
your program for this customer.
[5 Marks]

Question 5

Create a Windows project called BankingSystem, with the


following functionality:

- A main menu that can link to all the other functionalities


o Form for creating a customer account with the
following fields
 AccountNo, Firstname, Surname, Gender, DOB,
Address, Email, Nationality, DateRegistered,
Status
 All data should be saved in a textfile called
[Link]
o Add a form for making deposits into the customer
account
 The data should be saved into the
[Link] text file
o Add a form for making withdrawals from the
customer account:
 The data should be saved into the
[Link] text file
o Add a form for making a transfer between accounts
 The data should be stored in the
[Link] text file
o Add a form to display all customers and their
accounts:
 hint: use the datagridview / listview / listbox
control to display the tabular data
o Add a report to display the transactions data in your
[Link] file
 Hint: use the Report and ReportViewer controls
to display the data

Common questions

Powered by AI

In C#, a while loop evaluates its condition before executing the block of code, making it suitable for when you need to ensure that the block is executed only if the condition holds right from the start. In contrast, a do-while loop evaluates the condition after the block executes, guaranteeing at least one execution of the loop's code block. This makes the do-while suitable for scenarios where the block must run at least once regardless of the condition, such as prompting a user until correct input is received .

Arrays in C# are beneficial because they allow for the storage and management of multiple values of the same type under a single variable name, thereby reducing the complexity associated with declaring multiple individual variables. This pooled storage simplifies data processing, allows efficient indexed access, and is ideal for iterative operations that require manipulation or aggregation of many items, such as computing the sum or average of a large dataset .

In C#, 'public' is an access modifier that allows code from any other part of the program to access the member it is applied to, making it suitable for members that need to be accessible across different classes and assemblies. 'Private' restricts access to the member it is applied to only within the class it is declared in, ideal for data hiding and encapsulation to prevent direct access from outside the class .

In C#, a nested loop occurs when one loop is located inside another loop. This structure is useful when you need to perform a set of operations multiple times within each iteration of another set of operations. For instance, generating a 2-dimensional array of numbers or creating multiplication tables where for each outer loop iteration (e.g., for each row), all inner loop iterations (e.g., for each column) are executed. This allows complex iterative processes to be encapsulated within simpler, repeatable code segments .

To calculate the average mark in C#, you would sum the three test scores, divide by three, and then use conditional statements to determine the grade based on ranges. The logic follows: ```csharp int test1 = 83, test2 = 75, test3 = 79; double average = (test1 + test2 + test3) / 3; string grade; if (average >= 80) grade = "DISTINCTION"; else if (average >= 70) grade = "MERIT"; else if (average >= 60) grade = "CREDIT"; else if (average >= 50) grade = "PASS"; else grade = "FAIL"; Console.WriteLine("Grade: " + grade); ``` This logic uses if-else chains to check which range the average falls into and assigns the corresponding grade .

Writing data to a text file in C# involves opening a file stream and using write methods to send data to it. The process typically includes specifying the file path, using classes like StreamWriter or File.WriteAllText for direct content writing, and handling exceptions to ensure successful operations. The benefits include persistent data storage, easy data sharing between applications, and the ability to perform data logging or analysis. Text files are also human-readable, making debugging and verification straightforward .

In C#, a semicolon (';') is used to indicate the end of one statement and the beginning of another. This is crucial for the compiler to understand where one instruction finishes and the next one starts, allowing for correct execution sequencing within the program .

The while loop in C# is particularly advantageous for scenarios where the number of iterations is not predetermined or when you are processing until a certain condition is met. Unlike a for loop, which is typically best when the number of iterations is known beforehand, a while loop allows for more flexibility as it continues to iterate based on a logical condition, making it ideal for scenarios like reading from a file until the end is reached or polling for sensor data until a signal is received .

To swap values of string variables in C#, you can use temporary storage variables. Here's a brief approach: First, declare temporary variables to store the correct values that each variable should have. Then, assign these temporary values to the respective original variables. For example: ```csharp string tempCountry = "Botswana"; string tempCellno = "74740404"; string tempEmail = "enquiries@bac.ac.bw"; country = tempCountry; cellno = tempCellno; email = tempEmail; ``` This method ensures each variable ends up with the correct values without direct incorrect swaps .

Comments in C# play a crucial role in improving code readability and maintainability. They provide explanations for complex code sections, document the purpose and functionality of classes and methods, and clarify logic to other developers or to a future self revisiting the code. Best practices for using comments include writing clear, concise statements that explain why decisions were made rather than what standard code is doing, keeping comments up-to-date with code changes, and avoiding over-commenting which can clutter the code space .

You might also like