Exercise
Password 5 Attempts
Objective
Write a C# program that prompts the user for their username and password. Both should be strings. After 5 incorrect attempts, the user will be rejected.
Write Your C# Exercise
C# Exercise Example
using System; // Import the System namespace to use basic classes like Console
class Program // Define the main class of the program
{
static void Main() // The entry point of the program
{
string username; // Declare a variable to store the username
string password; // Declare a variable to store the password
int attempts = 0; // Variable to count the number of incorrect attempts
// Allow a maximum of 5 attempts
while (attempts < 5)
{
// Ask the user for their username
Console.Write("Enter your username: ");
username = Console.ReadLine(); // Read the username input from the user
// Ask the user for their password
Console.Write("Enter your password: ");
password = Console.ReadLine(); // Read the password input from the user
// Check if the username and password are correct
if (username == "username" && password == "password") // If both are correct
{
Console.WriteLine("Welcome! You have successfully logged in."); // Display a welcome message
return; // Exit the program successfully
}
else // If the username or password is incorrect
{
attempts++; // Increment the number of attempts
Console.WriteLine("Invalid username or password. Attempts left: " + (5 - attempts)); // Display error message and remaining attempts
}
}
// If the user reaches 5 incorrect attempts, display a rejection message
Console.WriteLine("You have been rejected after 5 incorrect attempts.");
}
}
More C# Programming Exercises of Basic Data Types
Explore our set of C# programming exercises! Specifically designed for beginners, these exercises will help you develop a solid understanding of the basics of C#. From variables and data types to control structures and simple functions, each exercise is crafted to challenge you incrementally as you build confidence in coding in C#.
This C# programming exercise requires creating a program that asks the user for two numbers and an operation to perform on them. The supported operations are ...
In this C# programming exercise, you need to create a program that asks the user for two numbers and a mathematical operation to perform between them. Supporte...
In this C# programming exercise, you need to create a program that calculates the perimeter, area, and diagonal of a rectangle, given its widt...
In this C# programming exercise, you need to create a program that calculates and displays certain values of the function y = x² - 2x + 1, using integer numbers for ...
In this C# programming exercise, you must create a program to "draw" the graph of the function y = (x - 4)² for integer values of x ranging from -1 to 8. The result will be visuall...
In this C# exercise, you are asked to write a program that prompts the user for two important pieces of information: the distance in meters and the time taken,...