"Do some exercises with loops" --- C language

Table of contents

Foreword:

1. Practice topics

1.1 Print odd numbers between 1-100

1.2 Calculate the factorial of n

1.3 Calculate the sum of the first m factorials reaching n factorial

1.4 Demonstrate the effect of dynamic string changes

2. goto statement


❤ Blogger CSDN: Ah Su wants to learn

  ▶Column classification: C language

  The learning of C language is to lay a solid foundation for us to learn other languages ​​in the future, and C produces everything!

  Let's start our journey of C language!

Foreword:

  After learning the knowledge, we need to type the code with our hands to ensure that we have really mastered it, instead of the brain knowing it and the hands still staying in place .


1. Practice topics

1.1 Print odd numbers between 1-100

the first method:

#include <stdio.h>
int main()
{
    int i = 0;
    for(i = 1; i <= 100; i+=2)
    {
        printf("%d ", i);
    }
    return 0;
}

  Actively avoid even numbers when printing, and the printed ones are all odd numbers .

The second method:

#include <stdio.h>
int main()
{
    int i = 0;
    for(i = 1; i <= 100; i++)
    {
        if(i%2 != 0)
        {
            printf("%d ", i);
        }
    }
    return 0;
}

  By judging whether it is divisible by 2, if it is not divisible by 2, it is odd, enter the if statement and print it out .

1.2 Calculate the factorial of n

#include <stdio.h>
int main()
{
    int n = 0;
    int i = 0;
    int ret = 1;
    scanf("%d", &n);
    for(i = 1; i <= n; i++)
    {
        ret *= i;
    }
    return 0;
}

 Using n to denote the factorial we want to calculate, i is a loop variable that grows from the number 1 to the number n. Multiply all i to the ret variable, *= has a cumulative effect, ret is initialized to 1, which does not affect the process of multiplication .

1.3 Calculate the sum of the first m factorials reaching n factorial

  What does that mean? For example: add the first 4 factorials to 5!, that is, find the sum of 1!+2!+3!+4 !.

The first:

#include <stdio.h>
int main()
{
    int i = 0;
    int n = 0;
    int j = 0;
    int ret = 1;
    int sum = 0;
    scanf("%d", &n);
    for(i = 1; i < n; i++)
    {
        ret = 1;
        for(j = 1; j <= i; j++)
        {
            ret *= j;
        }
        sum += ret;
    }
    return 0; 
}

 Use n to determine the factorial of arrival, i < n means how many numbers there are before reaching n . The j loop inside the i loop calculates the factorial based on the value of i . For example: when i is equal to 1, the cycle of j finds the factorial of 1, and then adds it to the sum; then i becomes 2, and the cycle of j finds the factorial of 2, and adds it to the sum; and so on Going down, there are a total of n-1 cycles, that is, the factorials from 1 to n-1 are all added to the sum .

  Note: Every time i meets the conditions, reassign ret to 1, because if it is not reassigned to 0, ret represents the factorial of the previous number, and if it is not reassigned to 1, it will affect the cumulative multiplication .

  For example, once i entered the loop with 3, then the last time was to add the factorial of 2 to the sum, ret *= j; with j from 1, then 2, multiplied to ret, ret finally It becomes 2, which is the factorial of 2 . If the factorial of 3 is to be found next time, the 2 in ret will affect it. That's it: 2 * 1 * 2 * 3 . So it needs to be assigned as 1, which is 1 * 1 * 2 * 3 .

The second type:

#include <stdio.h>
int main()
{
    int i = 0;
    int n = 0;
    int ret = 1;
    int sum = 0;
    scanf("%d", &n);
    for (i = 1; i < n; i++)
    {
        ret *= i;
        sum += ret;
    }
    printf("%d", sum);
    return 0;
}

  We can clearly feel that the previous method has repeated parts when calculating the factorial . For example, to find the factorial of 2, ret is like this: 1 * 1 * 2; to find the factorial of 3, ret is like this: 1 * 1 * 2 * 3; we use our witty minds, ding~

  We can also find the factorial of 3 in this way, that is, multiply the factorial of the previous number by the number requiring factorial; it is 3! = 2! * 3; Is the hut suddenly opened .

  Of course, the last thing to remind is that the calculated factorial cannot be too large, because when it exceeds the storage range of the integer type, it will be truncated, and the calculated value will be wrong .

1.4 Demonstrate the effect of dynamic string changes

#include <stdio.h>
#include <string.h>
#include <Windons.h>
int main()
{
    char arr1[] = "hello, welcom to C"
    char arr2[] = "******************"
    int left = 0;
    int right = strlen(arr1) - 1;
    
    while(left <= right)
    {
        arr2[left] = arr1[left];
        arr2[right] = arr1[right];
        printf("%s", arr2);
        Sleep(1000);
        system("cls");
        left++;
        right--;
    }
    printf("%s\n", arr2);
    return 0;
}

  Let's slowly analyze this question. First, create two arrays of the same length. left means the left subscript of the number, and right means the right subscript. strlen is looking for the length of the string, and the right subscript is the length of the string minus one, because the array starts from subscript 0 . Then loop, assign the character on the left of arr2 to the character on the left of arr1, assign the character on the right of arr2 to the character on the right of arr1, left++, let the subscript go to the right, and come to the position of the character e, which is h at first . The same is true for the reduction and reduction of right, and the blogger will not repeat it~

  The Sleep function and the system function appear here, and their header files are <Windons.h>. Sleep means to stop the program to rest, and the number behind it is the number of milliseconds to stop . system is to execute the system command, cls is the command to clear the screen, remember to use "" double quotes .

2. goto statement

  Haha, I didn't expect it, here is a little knowledge point, the use of goto statement. The C language provides a statement that can be abused at will, because there is no limit to using the goto statement, which allows the execution flow of the program to jump at will within the same function . Of course, we only expect to use it when we need to use it. If we use it casually, the logic will be messed up .

  goto label; 

  Label:     

  This is how to use the goto statement. We can see that it can change the execution flow of the program. The goto statement can generally be replaced by a loop . Take this for example, we can use while(1) instead of goto to achieve an infinite loop (doge). Of course, it is not to let readers write infinite loop bugs~

  So let's talk about the real application scenario of goto, look at the following code:

  In deep loop nesting, if you want to jump out of multiple layers of loops, you need to use multiple breaks, which is not only error-prone, but also dazzling. At this time, using the goto statement can avoid this situation very well, which is the advantage of goto .

  Well, this article is over. It mainly talked about a few exercises, and supplemented the knowledge of the goto statement . In the next article, we will use the knowledge we have learned to complete a small code for guessing the number game.


Conclusion: I hope readers will gain something after reading it! On the way to learn C, wish us more and more C!✔

  Readers who do not understand this article, or find that there are errors in the content of the article, please leave a message in the comment area below to tell the blogger ~, and you can also give some suggestions for article improvement to the blogger, thank you very much! last of the last!

  ❤Please like, please pay attention, your likes are the driving force for my update, let's work hard to make progress together.

Guess you like

Origin blog.csdn.net/muwithxi/article/details/130310390