当前位置:网站首页>Basic examples that must be mastered by beginners of C #
Basic examples that must be mastered by beginners of C #
2022-07-28 09:55:00 【South wind fahaxiki】
Catalog
1. Rectangular form of 99 multiplication table
2. The multiplication table in the lower triangular form
4. Sum of positive and negative input numbers
5. Leap year 、 Judgment of month
9. Input and output of array elements
1. Rectangular form of 99 multiplication table
By observing the external circulation plus 1, Internal circulation from 1, Gradually add 1 To 9; So it will be used twice for loop , The procedure is as follows :
for (int i = 1; i <= 9; i++) // External circulation , from 1 Start to 9
{
for (int j = 1; j <= 9; j++) // External circulation plus 1(i++), Internal circulation from 1 To 9
{
Console.Write("{0}*{1}={2}\t", i, j, i * j); // \t It's the escape character , It's equivalent to executing once Tab Key empty four lattice
}
Console.WriteLine(); // Internal circulation 9 Time , Do it once Console.WriteLine(); Line feed
} among Console.Write(); And Console.WriteLine(); The difference is that the former outputs continuously , The latter is line feed output .
After entering the code , stay Visual Studio Click generate... In the menu bar of --> Build solution , perhaps F6 Shortcut key compilation code , stay Visual Studio Click debug... In the menu bar of --> Start debugging , perhaps F5 Execute code .
2. The multiplication table in the lower triangular form

The output form of 99 multiplication table is divided into rectangular form and lower triangular form , Through observation, it is found that when the number of internal cycles is different from that of external cycles , Execute continuous space output , When the number of internal cycles is the same as the number of external cycles , Execute newline output , So we need if The judgment statement judges whether the number of internal loops is equal to the number of external loops , The procedure is as follows :
for (int i = 1; i <= 9; i++) // External loop from 1 To 9
{
for (int j = 1; j <= i; j++) // Internal circulation from 1 To i, To equal i
{
if (i == j) // Judge when the values of the internal loop and the external loop are equal , Code to execute
{
Console.WriteLine("{0}*{1}={2}", i, j, i * j); //Console.WriteLine(); Line feed output ,{0},{1},{2} by C# Placeholder in . amount to C In language %d,%c,%f etc. .
}
else // if If the statement does not hold, that is : When the values of the internal loop and the external loop are different
{
Console.Write("{0}*{1}={2}\t", i, j, i * j); //Console.Write(); Don't wrap output
}
}
}After entering the code , stay Visual Studio Click generate... In the menu bar of --> Build solution , perhaps F6 Shortcut key compilation code , stay Visual Studio Click debug... In the menu bar of --> Start debugging , perhaps F5 Execute code .
3. Narcissistic number
Narcissus number refers to 100 To 999 Between a certain number : The cube of a bit + The cube of ten + A hundred cube = Some number ( Interval is [100,999] )
seek [100,999] The previous procedure for the number of daffodils is as follows :
int a = 1;
int b = 0;
int c = 0;
for (int i = 100; i <=999; i++)
{
a = i%10; // Take out [100,999] Between the bits of a number
b = i/ 100; // Take out [100,999] The hundredth of a certain number
c = (i - a - b * 100)/10; // Take out [100,999] Ten digits of a certain number
if (a*a*a + b * b * b + c*c*c == i) // Judge whether it meets the characteristics of narcissus number , When it comes to true Is to perform if Judge the statements within the condition
{
Console.WriteLine("{0} It's Narcissus ", i);
}
}
4. Sum of positive and negative input numbers
Console.WriteLine(" Please enter a positive integer "); // Print content on the console ,Console For a class , call WriteLine Method
try // Prevent users from entering content that is not prompted
{
int number = Convert.ToInt32(Console.ReadLine());
int a = number;
for (int i = 0; i <= a; i++)
{
Console.WriteLine("{0}+{1}={2}", i, number--, number + 1 + i);
}
}
catch // When try When there is an error in the code execution in , Execute the code
{
Console.WriteLine(" Please enter a positive integer ");
}When prompted to enter : Please enter a number , The value entered here is 6

5. Leap year 、 Judgment of month
Ask the user to enter a year and month : Judge whether the entered year is a leap year and how many days there are in this month of the year
int year = 0;
int month = 0;
int day = 28;
try
{
Console.WriteLine(" Please enter the year ");
year = Convert.ToInt32(Console.ReadLine()); //C# The type of user received by default is string type
try
{
Console.WriteLine(" Please enter the month ");
month = Convert.ToInt32(Console.ReadLine()); // Receive user input and convert the input string type to integer
if (year % 400 == 0 || year % 4 == 0 && year % 100 != 0) // Determine if it's a leap year
{
Console.WriteLine("{0} Year is a leap year ", year);
if (month == 2) // Leap year's 2 Month is a special month , Yes 29 God
{
day = 29;
}
}
switch (month) // Judge the number of days in the month
{
// stay switch--case In structure , When case With the same code , Only in the last one case The write , The rest can be omitted
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:
Console.WriteLine("{0} In the first {1} There are... Months 31 God ", year, month);
break;
case 4:
case 6:
case 9:
case 11:
Console.WriteLine("{0} In the first {1} Monthly 30 God ", year, month);
break;
default: // If none of the above conditions is true
if (month <= 12 && month >= 1)
{
Console.WriteLine("{0} In the second month of the year {1}", year, day);
}
else // // Prevent the user from entering a month that is not [1,12] Between
{
Console.WriteLine(" Please enter the correct month ! Program exit !!!");
}
break; //default Ending
}
}
catch // Execute when the entered month format is incorrect ; 2a, 8_ Etc. are incorrect month format
{
Console.WriteLine(" Please enter the correct month ! Program exit !!!");
}
}
catch // Execute when the input year format is incorrect ; 2022a,1998_ Etc. are incorrect year format
{
Console.WriteLine(" Please enter the year correctly ! Program exit !!!");
}
Console.ReadKey(); // The effect of pause , The program stops here and pauses When the year entered is 2000, Month is 6 when , The result of program execution is shown in Fig 5 Shown :

When the year entered is 2022, Month is 2 when , The result of program execution is shown in Fig 6 Shown :

6. Compare the size
Compare the size of the three numbers and output from large to small
Console.WriteLine(" Please enter the first number "); // Prompt user for a number
int a = Convert.ToInt32(Console.ReadLine()); // Receive user input and convert the input string type to integer
Console.WriteLine(" Please enter the second number ");
int b = Convert.ToInt32(Console.ReadLine());
Console.WriteLine(" Please enter the third number ");
int c = Convert.ToInt32(Console.ReadLine()); // Define three integer variables to receive three integers entered by the user
if (a > b) //a>b
{
if (b > c) //b>c
{
Console.WriteLine("{0},{1},{2}", a, b, c);
}
else if (c > a) //b<c
{
Console.WriteLine("{0},{1},{2}", c, a, b);
}
}
else if (c > b) //b>a
{
Console.WriteLine("{0},{1},{2}", c, b, a);
}
else if (c > a) //b>c>a
{
Console.WriteLine("{0},{1},{2}", b, c, a);
}
else //a>c And b>a
{
Console.WriteLine("{0},{1},{2}", b, c, a);
}When prompted for user input : The values entered are 5 , 1, 8 when , The execution result of the program is shown in the figure :

7. Bubble sort
for Nesting of loops , Arrange the input array in ascending order .
int[] nums = { 0, 9, 8, 5, 6, 5, 4, 3, 2, 1, 0 };
for (int i = 0; i < nums.Length; i++) //nums.Length call Length Method , Compute arrays nums[] The length of
{
for (int j = i + 1; j < nums.Length; j++) //nums.Length call Length Method , Compute arrays nums[] The length of
{
if (nums[i] > nums[j])
{
nums[i] = nums[i] - nums[j]; // Don't use third-party variables , Exchange the values of two numbers
nums[j] = nums[j] +nums[i];
nums[i] = nums[j] - nums[i];
}
}
}
for (int i = 0; i < nums.Length; i++) // Output the array after sorting
{
Console.Write("{0} ",nums[i]);
}
Console.ReadKey(); // Suspend program , Press any key to end the pause Execution procedure , The result of the program is shown in the figure :

8. Exchange of array elements
Swap the beginning and end of the elements in the array
string t=" "; // Define a string and assign an initial value
string[] str = { "a", "b", "c","d","e","f" };
for (int i = 0; i < str.Length/2; i++) //str.Length call Length Method , Compute arrays str[] The length of
{
t = str[i]; // Use a third-party variable to exchange the values of two numbers
str[i]=str[str.Length-1-i];
str[str.Length-1-i] = t;
}
for (int i = 0; i < str.Length; i++)
{
Console.Write(str[i]);
}
Console.ReadKey();Execution procedure , The result of the program is shown in the figure :

9. Input and output of array elements
Output the sum of the elements in the array , Maximum , minimum value .
int[] a = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, }; // Define an integer array and assign values
int max = a[0]; // Assign values to elements in the array , Prevent the output result from not being an element in the array
int min = a[0];
int sum=0;
for (int i = 0; i < a.Length; i++)
{
if (a[i] > max) // Take the maximum value in the array
{
max = a[i];
}
if (a[i] < min) // Get the minimum value in the array
{
min = a[i];
}
sum +=a[i]; // Sum the elements in the array
}
Console.WriteLine("{0},{1},{2}",sum,max,min);Execution procedure , The result of the program is shown in the figure :
![]()
10. object-oriented
namespace _01_ object-oriented
{
public class Person // Class does not occupy memory , Objects occupy memory , So when loading the project , Class is not loaded to run
{
public string? _names; // Field
public int _age;
public string? _gender;
public void CHLSS() // Define a method
{ //this Represents the object of the current class
Console.WriteLine(" My name is {0}, I this year {1} Year old , I am a {2} raw ", this._names, this._age, this._gender);
}
public void CHLSSOne() // Define a method , A class can contain multiple methods
{ //this Represents the object of the current class
Console.WriteLine(" My name is {0}, I this year {1} Year old , I am a {2} raw ", this._names, this._age, this._gender);
}
}
}Call to class
using _01_ object-oriented ; // Use the classes under this namespace
// Class instantiation
Person ZhangSan = new Person(); // Declare a before using Person Class object , Object calls things in the class ( attribute , Field , Method )
// To declare an object, you must first declare a class , Objects contain various properties , Field , Method
ZhangSan._names = " Zhang San "; // Assign values to fields in the class
ZhangSan._age = 24; // Assign values to fields in the class
ZhangSan._gender = " male "; // Assign values to fields in the class
ZhangSan.CHLSS(); // Calls a method in the class object . Method name
Console.ReadKey();
Person LiSi = new Person();
// Instantiate an object Li Si Later operations are only for object operations
LiSi._names = " Li Si ";
LiSi._age = 18;
LiSi._gender = " Woman ";
LiSi.CHLSS();
Console.ReadKey();
Person WangWu = new Person();
// Instantiate an object king five ,WangWu It is equivalent to a variable occupying memory ,Person amount to int Do not occupy memory
WangWu._names = " Wang Wu "; // In fact, the initial value is assigned to the field , Set a breakpoint here to observe WangWud Value
WangWu._age = 19;
WangWu._gender = "AB";
WangWu.CHLSSOne(); // Call another method , A class can contain multiple methods
Console.ReadKey();Execution procedure , The result of the program is shown in the figure :

From the output, we can see that Wang Wu's gender output is wrong , The reason is that the assignment and value of fields are not limited in the class . Class can contain three parts of fields 、 attribute 、 Method . Among them, attributes are used to limit the assignment and value of fields , Want to use get(); set(); Method .get(); Method is used to limit the value of the field ,set(); Method is used to define what value can be assigned to a field . In addition, let's talk about the similarities and differences between classes and structures .
struct Both structures and classes can contain fields 、 attribute 、 Method three parts . But structure is a process oriented approach , Classes are object-oriented methods , Structure does not contain the three basic characteristics of a class : encapsulation 、 Inherit 、 polymorphic .
Please correct the deficiencies in the article !!!
And that's all for today , Remember to praise the collection , Share and forward , Pay attention to the little brother ! Last , If you want to learn or are learning C/C++ Programming , You can join Xiaobian Programming learning C/C++ Penguin circle
https://jq.qq.com/?_wv=1027&k=vLNylJeG
边栏推荐
- SQL server, MySQL master-slave construction, EF core read-write separation code implementation
- 3 minutes to tell you how to become a hacker | zero foundation to hacker getting started guide, you only need to master these five abilities
- fastjson中@jsonType注解的功能简介说明
- Linux操作系统(Centos7)安装MySQL
- Window source code analysis (IV): window deletion mechanism
- OSS直连上传-Rails服务实践
- In php7?? And?: Differences between
- 能够遍历一个文件夹下的所有文件和子文件夹
- PHP连接mysql原生代码
- Domain events and integration events are not so big
猜你喜欢

Net 3 lines of code to realize the function of text to speech

Learn a hammer.Net zero foundation reverse tutorial lesson 3 (shell and homework)

居家健康诊断时代下,Senzo打造增强侧向流测试产品

时序分析41 - 时序预测 TBATS模型

Opencv4.60 installation and configuration

Leetcode - hashtable topic

My vivado practice - single cycle CPU instruction analysis

高温持续,公交企业开展安全专项培训

The high temperature continues, and public transport enterprises carry out special safety training
![ASP.NET Core 6框架揭秘实例演示[29]:搭建文件服务器](/img/90/40869d7c03f09010beb989af07e2f0.png)
ASP.NET Core 6框架揭秘实例演示[29]:搭建文件服务器
随机推荐
3分钟告诉你如何成为一名黑客|零基础到黑客入门指南,你只需要掌握这五点能力
This wechat plug-in is very easy to use
IDC script file running
总线相关概念集合
pkg打包node工程
JS提升:实现flat平铺的底层原理
Go language slice vs array panic runtime error index out of range problem solving
NTU Lin Xuantian's "machine learning cornerstone" problem solving and code implementation | [you deserve it]
Array method of J S, loop
软件测试与质量学习笔记2----黑盒测试
哪些字符串会被FastJson解析为null呢?
MATLAB启动慢解决措施
路由器固件解密思路
【MySQL】查询多个ID返回字符串拼接
Judge whether the string is palindrome
Window source code analysis (II): the adding mechanism of window
高温天气筑牢安全生产防线,广州海珠区开展加油站应急演练
NET 3行代码实现文字转语音功能
Word segmentation results of ES query index fields
Seektiger eco pass STI new progress, log in to ZB on April 14
