Topic 03 - Basic Concepts
Topic 03 - Basic Concepts
In C#, variables are used to store data, and data types define the kind of data a variable can
hold.
Common Data Types:
var number = 10; // The compiler infers that "number" is of type int
var name = "John"; // The compiler infers that "name" is of type string
var isActive = true; // The compiler infers that "isActive" is of type bool
In these examples:
Example:
int age = 25;
double price = 19.99;
char grade = 'A';
bool isStudent = true;
string name = "Alice";
Avoiding conflicts
To use an identifier that clashes with a reserved keyword, we can
do so by qualifying it with the @ prefix. For instance:
class class {...} // Illegal
class @class {...} // Legal
Control Flow (Conditional Statements)
Control flow allows the program to make decisions and execute different code paths based on
conditions.
Common Statements:
Example:
int score = 85;
if (score >= 90)
{
Console.WriteLine("Grade: A");
}else if (score >= 80)
{
Console.WriteLine("Grade: B");
}else
{
Console.WriteLine("Grade: C");
}
switch (score)
{
case 90:
Console.WriteLine("Excellent!");
break;
case 80:
Console.WriteLine("Good job!");
break;
default:
Console.WriteLine("Keep trying!");
break;
}
Loops
Loops in C# are used to repeat a block of code multiple times.
Common Loop Types:
Example:
class Program
{
static void Main()
{
int[] numbers = { 1, 2, 3, 4, 5 };
Exercise:
1. Write a C# program that prompts the user to enter a student's score (an integer
between 0 and 100). Based on the score, the program should determine and display
the corresponding letter grade according to the following criteria:
A: 90 - 100
B: 80 - 89
C: 70 - 79
D: 60 - 69
F: Below 60
2. Write a C# program that prompts the user to enter an integer. The program should
determine whether the number is even or odd and display the appropriate message.
3. Write a C# program that prompts the user to enter their age. The program should
classify the user into one of the following age groups and display the appropriate
message:
Child: 0 - 12 years
Teenager: 13 - 19 years
Adult: 20 - 64 years
Senior: 65 years and above
4. Write a C# program that prompts the user to enter a positive integer N. The
program should find and display all prime numbers less than or equal to N.
5. Write a C# program that prompts the user to enter a positive integer N. The
program should calculate and display the factorial of N.
6. Palindrome number, Neon number, Duck number, Armstrong number, Perfect
Number, Spy Number.