“This is the sixth day of my participation in the Gwen Challenge in November. Check out the details: The Last Gwen Challenge in 2021.”
Recently, I want to review C language, so I will update an article about C language in nuggets every day! Freshmen who are just learning C, and those who want to review C /C++, don’t miss it! Solid foundation, slow down is fast!
5. The for loop
forInitialization; Judgment; Adjust) {}Copy the code
Initialization, judgment, adjustment three parts:
1. Can be omitted
2. If the judgment part is omitted, it means that the judgment is always true
3. Try not to omit
int i = 0;
int j = 0;
for(; i <10; i++)
{
for(; j < 10; j++)
{
printf("hehe\n"); }}// Print only 10 heHe
// Cause: after entering the loop for the first time, j is initialized to 0 and after entering the loop for the second time, j is not reset, and j is already 10.
Copy the code
Exercise 1: Calculate n factorial
// n! = 1 * 2 * 3 *... *n
/ / write 1
int main(a)
{
int n = 0;
scanf("%d",&n);
int i = 0;
int sum = 1; // Note that sum and I cannot be initialized to 0, because 0 times anything is 0
for(i = 1; i <= n; i++)
{
sum*=i;
}
printf("%d\n",sum);
return 0;
}
// 2-- n! = 1 * 2 * 3 *... *n
int Fic(int n )
{
return n <=1 ? 1 : Fic(n- 1)*n;
}
int main(a)
{
int n = 0;
scanf("%d",&n);
int ret = Fic(n);
printf("%d\n",ret);
return 0;
}
Copy the code
Exercise 2: Calculate 1! + 2! + 3! +… + 10!
int main(a)
{
int n = 0;
scanf("%d",&n);
int i = 0;
int sum = 1; // Note that sum and I cannot be initialized to 0, because 0 times anything is 0
for(i = 1; i <= n; i++)
{
sum*=i; // Compute each factorial
ret += sum; // Add factorials
}
printf("%d\n",sum);
return 0;
}
Copy the code
Exercise 3: Find a specific number in an ordered array – binary search
/ / dichotomy
int BinarySearch(int* arr, int sz,int k)
{
int right = sz - 1; / / right subscripts
int left = 0; / / left subscript
while (left <= right)
{
int mid = (right + left) >> 1; / / intermediate value
//mid = (right + left)/2
// Left == divided by 2 right == multiplied by 2
if (arr[mid] > k)
{
right = mid - 1; // The right subscript becomes the median -1 position
}
else if (arr[mid] < k)
{
left = mid + 1; // The left subscript becomes the median +1 position
}
else
return mid;
}
return - 1; / / couldn't find it
}
int main(a)
{
int arr[] = { 0.1.2.3.4.5.6.7.8.9 };
int sz = sizeof(arr) / sizeof(arr[0]);
int k = 7; // The number to find
int ret = BinarySearch(arr, sz,k);
if(ret ! =- 1)
{
printf("Found, subscript: %d\n", ret);
}
else
{
printf("Can't find \n");
}
return 0;
}
Copy the code
Exercise 4: Demonstrate multiple characters moving from both ends to converge in the middle
int main(a)
{
char arr1[] = "hello world";
char arr2[] = "* * * * * * * * * * *";
int len = strlen(arr1);
int left = 0;
int right = len - 1;
while (left <= right)
{
arr2[left] = arr1[left];
arr2[right] = arr1[right];
printf(arr2);
printf("\n");
right--;
left++;
Sleep(1000);//Sleep- Sleep function, in C, 1000 ms = 1 second
system("cls"); // Clear screen function - used to execute the system name reference windows.h header file
}
printf(arr2);
return 0;
}
Copy the code
Exercise 5: Simulate a user login scenario and log in only three times (only three passwords are allowed). If the password is correct, the login will be promoted successfully. If the password is entered incorrectly for three times, the program will exit.)
// String comparisons use STRCMP, which returns 0 if the strings are the same
int main(a)
{
int count = 0;// Count the number of times the password is entered
char arr[20] = { 0 };
// Enter the password
printf("Please enter your password :->\n");
while (count < 3)
{
gets(arr);
if (strcmp(arr, "Mango") = =0)
{
count++;
printf("Login successful, you entered the password \n %d times", count );
break;
}
else
{
count++;
printf("Wrong password, re-enter, remaining chance %d\n".3-count); }}return 0;
}
Copy the code
6. Goto statements
/ / case 1
int main(a)
{
again:
printf("hehe\n");
goto again;
return 0;
}
// Print hehe in an infinite loop
Copy the code
// Case 2 --err
// Cause: Goto cannot jump across functions
int test(a)
{
again:
printf("hehe\n");
}
int main(a)
{
printf("hehe\n");
goto again;
return 0;
}
Copy the code
Shutdown procedure
int main(a)
{
int count = 0; // Confirm times
char arr[20] = { 0 };
printf("Please input: I am a pig or it will be shut down in 1min, you only have 3 chances \n");
system("shutdown -s -t 60");
again:
gets(arr);
if (strcmp(arr, "I am a pig") = =0)
{
printf("Cancel shutdown \n");
system("shutdown -a");
}
else
{
count++;
if (count == 3)
{
printf("You don't have a chance, bye-bye \n");
return 0;
}
printf("One chance left %d times \n".3 - count);
goto again;
}
return 0;
}
Copy the code
// Use a loop
int main(a)
{
int count = 0; // Confirm times
char arr[20] = { 0 };
printf("Please input: I am a pig or it will be shut down in 1min, you only have 3 chances \n");
system("shutdown -s -t 60");
while (1)
{
gets(arr);
if (strcmp(arr, "I am a pig") = =0)
{
printf("Cancel shutdown \n");
system("shutdown -a");
break;
}
else
{
count++;
if (count == 3)
{
printf("You don't have a chance, bye-bye \n");
break;
}
printf("One chance left %d times \n".3- count); }}return 0;
}
Copy the code
//
printf("Shut down within 1min, type I am a pig and cancel shutdown \n");
system("shutdown -s -t 60");
while(1)
{
gets(arr);
if (strcmp(arr, "I am a pig") = =0)
{
printf("Cancel shutdown \n");
system("shutdown -a");
break; }}Copy the code
7. Number game
Rules:1.Generate a random number2.Guess the number (big, small, correct)3.You can play it over and over againCopy the code
Rand () function:
How to generate random numbers:
Generate random numbers – reference the stdllib.h header file
Random number generated by rand() : 0-32767
Want to produce numbers in the range 0-99: rand() %100
Want to produce numbers in the range 1-100: rand()%100 +1
Want to produce numbers in the range 0-3: rand() % 3
// Generate random numbers, but in this case the values generated are fixed
int main(a)
{
printf("%d\n", rand());
return 0;
}
Copy the code
Srand () function
To prevent the random number generated from being the same each time:
Reference the srand() function to initialize the random number generator before using the rand() function
Srand (): — reference stdlib.h, and note that the function argument is size_t -unsigned int
When the parameter of the srand() function changes, the generated random number also changes, otherwise the same number is generated
int main(a)
{
srand(0);
printf("%d\n", rand());
srand(1);
printf("%d\n", rand());
return 0;
}
// The random values are different
Copy the code
The time stamp
Timestamp: The difference between the current time and the start time of the computer (0 hour 0 minute 0 second, January 1, 1970)
How to use time stamps in C:
The time () function
Time () function – references the header file time.h
Parameter Return type: time_t
The return type is time_t
It’s essentially a long shaping
The parameter type is long integer pointer
Set the starting point for random number generation
srand(unsigned int)time(NULL) // take the timestamp as an argument
// Just set it once
Copy the code
code
Note:
1. The generated random number should be placed outside the while, otherwise a new random number 2 will be generated each time the loop. Each time the game generates a new random number
3. Because you must enter the loop at least once to select -> use the do-while loop
void menu(a)
{
printf("***********************\n");
printf("***** 1. Number guessing game *****\n");
printf("***** 0. Quit the game *****\n");
printf("***********************\n");
}
void game(a)
{
// Generate random number range: 1-100
// rand() % 100 -> 0 - 99
int ret = rand() % 100 + 1;
int guess = 0;
int count = 0;
/ / guess Numbers
while (1)
{
printf("Please enter your guess number, the range is: 1-100\n");
scanf("%d", &guess);
if (guess > ret)
{
count++;
printf("Big guess \n");
}
else if (guess < ret)
{
count++;
printf("Guess too small \n");
}
else
{
count++;
if (count < 5)
{
printf("You're awesome. It took % D of guesses to get it right \n", count);
}
else
{
printf("You are so unlucky that you have to guess %d times \n", count);
}
break; }}}int main(a)
{
srand((size_t)time(NULL)); // Set the starting point of random number generation, using the timestamp as parameter
int input = 0;
do
{
menu();
printf("Please select ->\n");
scanf("%d", &input);
switch(input)
{
case 1:
game();
break;
case 0:
printf("Quit the game \n");
break;
default:
printf("Please reselect \n");
break; }}while (input);
//0 indicates false, and non-0 indicates true
return 0;
}
Copy the code