MenuHeader

Wednesday 28 February 2024

Variable and Control structure in C# || C# Full course || ABFirstTech

 Variable and Control structure in C#


Variables in C#:

A variable is a named storage location in a computer's memory where data can be stored and retrieved during the execution of a program. In C#, variables must be declared before they are used. The declaration specifies the data type of the variable and the name by which it can be referred to in the program.

Here is an example of declaring variables in C#:

// Variable declaration
int age; // Declaring an integer variable named 'age'
// Variable initialization
age = 25; // Assigning a value to the 'age' variable

In this example, int is the data type, and age is the variable name. The variable is then assigned a value of 25. C# supports various data types, including int, float, double, char, string, bool, etc.

Control Structures in C#:

Control structures in C# are used to control the flow of a program's execution. They include decision-making structures (if, else, switch) and loop structures (for, while, do-while). These structures help in making decisions based on conditions and repeating certain tasks.

1. Decision-Making Structures:

a. If statement:

int number = 10;
if (number > 0) {
Console.WriteLine("Number is positive");
}
b. If-else statement:
int number = -5;
if (number > 0) {
Console.WriteLine("Number is positive");
} else {
Console.WriteLine("Number is non-positive");
}
c. Switch statement:

int dayOfWeek = 3;
switch (dayOfWeek) {
case 1:
Console.WriteLine("Monday");
break;
case 2:
Console.WriteLine("Tuesday");
break;
// ... (other cases)
default:
Console.WriteLine("Invalid day");
break;
}

2. Loop Structures:

a. For loop:


for (int i = 0; i < 5; i++) {
Console.WriteLine(i); }

b. While loop:

int i = 0;
while (i < 5) {
Console.WriteLine(i);
i++;
}

c. Do-while loop:


int i = 0;
do {
Console.WriteLine(i);
i++;
} while (i < 5);

No comments:

Post a Comment

Angular Interview Questions and Answers 2024 (Real interview) | Angular 18

real time angular interview questions and answers realtime angular interview questions and answers, Top Angular Interview Questions, angular...