C# Lesson 1
Learn how to declare and use variables in the very first lesson from our series on learning C# for beginners.
Author
Lesson 12 in a our series about learning C# teaches you about working with methods.
In this lesson we are going to learn about Methods.
Afterwards you can continue to the next lesson!
Or go back and review the previous lesson.
We also have the source code on GitHub.
using System;
namespace Lesson12
{
class Methods
{
// A method needs to be delared inside a class
static void Main()
{
RunProgram();
}
static void RunProgram()
{
string name = PromptTheUser("What is your name?");
// Make a method to ask the user for their age
// int age = PromptTheUserForInt("What is your age?");
int age = PromptTheUserForInt("What is your age?");
Console.WriteLine($"Your name is {name} and you are {age} years old");
}
static int PromptTheUserForInt(string prompt)
{
Console.WriteLine(prompt);
int userInput = Convert.ToInt32(Console.ReadLine());
return userInput;
}
static string PromptTheUser(string prompt)
{
Console.WriteLine(prompt);
string userInput = Console.ReadLine();
return userInput;
}
}
}
/*
* TASK
*
* You are creating a password creation tool.
* A password has to meet 4 requirements...
* -Contain at least 1 upper case letter.
* -Contain at least 1 lower case letter.
* -Contain one of these special characters !#$%&
* -Be more than 8 characters long.
*
* Create 4 methods to check if the password is 'Valid' or 'Invalid'.
* One method for each of the requirements.
*
* I have started the program by prompting the user and checking the first requirement.
*
*/
using System;
namespace Lesson12Task
{
class MethodsTask
{
static void Main(string[] args)
{
Console.WriteLine("A password must be...");
Console.WriteLine("Contain at least 1 upper case letter.");
Console.WriteLine("Contain at least 1 lower case letter.");
Console.WriteLine("Contain one of these special characters !#$%&");
Console.WriteLine("Be more than 8 characters long.");
Console.WriteLine();
Console.Write("Enter a password: ");
string password = Console.ReadLine();
bool containsUpperCase = CheckUpperCase(password);
if (containsUpperCase)
{
Console.WriteLine("Valid");
}
else
{
Console.WriteLine("Rejected");
}
}
static bool CheckUpperCase(string password)
{
for (int i = 0; i < password.Length; i++)
{
if (password[i] >= 65 && password[i] <= 'Z')
{
return true;
}
}
return false;
}
}
}
We have similar articles. Keep reading!
Learn how to declare and use variables in the very first lesson from our series on learning C# for beginners.
Author
Learn how to read input from the user in the second lesson from our series on learning C# for beginners.
Author
Learn how to do some basic math with C# in the 3rd lesson from our series for beginners learning C#.
Author