1. An overview of the

  • Believe that friends should know, there are many classic algorithms in C language, and these algorithms is many people’s wisdom crystallization, is also commonly used in programming algorithm, which contains many algorithm thought, mastering these algorithms, to study more advanced, more difficult algorithm will be of great help, today let’s take a look at some of the commonly used algorithm.

2.Algorithm analysis

  • Title: Calculate n + (n-1) + (n-2) +… Plus 3 plus 2 plus 1.
  • Analysis: calculate n + (n-1) + (n-2) +… + 3 + 2 + 1, where the value of n is input by the user. The user first receives the input number and checks whether it is a positive number. To calculate the sum, we first declare a variable sum and initialize the value of sum to zero. We complete the sum through the loop, changing the value of the number (starting at n) in the body of the loop so that the number decreases by 1. As long as the number is greater than 0, the loop continues, and the final sum is stored in the variable sum. This is finally shown by the printf() function. If the user enters a number not greater than zero, an error message is displayed. The specific code is as follows:
#include <stdio.h> int main() { int sum = 0; int number; Printf ("\n Please enter an integer: "); scanf("%d",&number); if(number > 0) { while( number > 0) { sum += number; number--; } printf("\n and = %d\n",sum); } else {printf("\n invalid input value :%d\n",number); } return 0; }Copy the code

The output of the program is shown as follows:

3.thinking

  • Sum += number; Sum *= number; sum *= number; The reader can think a little bit more about this simple statement, which is at the heart of this simple code. The above is a simple C language algorithm implementation, the follow-up will be more in-depth, but also hope that we can communicate more, common progress.