C programming rookie exercises 100 questions (21-30)

Time:2021-6-13

[exercise 21] calculate the sum of natural numbers

Title:
Calculating the sum of natural numbers
1. Analysis
Practice using the for loop structure. The for loop allows a loop control structure to execute a specified number of times.
2. Procedure:

#include  
int main()
{
    int i, iNum, iSum;
    
    Printf ("enter a positive integer):";
    scanf("%d",&iNum);
 
    iSum = 0;
    for(i=1; i <= iNum; i++)
    {
        iSum += i;  // iSum = iSum + i;
    }
    printf("Sum = %d",iSum);
 
    return 0;
}

3. Input and output:

Enter a positive integer: 10
Sum = 55


[exercise 22] output 99 multiplication formula table

Title:
Output 99 multiplication formula table
1. Analysis
Practice using nested for loops. For nested loop structure, the execution order is from inside to outside: first execute the inner loop, and then execute the outer loop.
2. Procedure:

#include  
int main()
{  
    int i = 0;  // Outer loop variable, control line
    int j = 0;   // Inner loop variable, control column

    for(i=1;i<=9;i++)
    {  
        for(j=1;j<=i;j++)
        {
            printf("%dx%d=%d\t",j,i,i*j);
            //printf("%dx%d=%-4d",j,i,i*j);  // %- 4D is left aligned, 4 character bits
        }
        printf("\n");  // Wrap each line after output
    }
    
    return 0;
}

3. Input and output:

1×1=1
1×2=2 2×2=4
1×3=3 2×3=6 3×3=9
1×4=4 2×4=8 3×4=12 4×4=16
1×5=5 2×5=10 3×5=15 4×5=20 5×5=25
1×6=6 2×6=12 3×6=18 4×6=24 5×6=30 6×6=36
1×7=7 2×7=14 3×7=21 4×7=28 5×7=35 6×7=42 7×7=49
1×8=8 2×8=16 3×8=24 4×8=32 5×8=40 6×8=48 7×8=56 8×8=64
1×9=9 2×9=18 3×9=27 4×9=36 5×9=45 6×9=54 7×9=63 8×9=72 9×9=81


[exercise 23] factorial

Title:
Factorial
1. Analysis
The factorial of natural number n is n!, n!= one × two × three ×…× n。
Factorial can also be defined recursively: 0= 1,n!=( n-1)! × n。
This exercise uses the recursive method.
2. Procedure:

#include 
long int multiplyNum(int n);  //  Declaration subroutine
 
int main()
{
    int n;
    Printf ("enter an integer):";
    scanf("%d", &n);
    printf("%d! = %ld", n, multiplyNum(n));
    return 0;
}

long int multiplyNum(int n)
{
    if (n >= 1)
        return n * multiplyNum(n-1);  // n!=n*(n-1)!
    else
        return 1;  // 0!=1
}

3. Input and output:

Enter an integer: 10
10! = 3628800


[exercise 24] Fibonacci sequence

Title:
Fibonacci sequence
1. Analysis
Fibonacci sequence is introduced by taking rabbit breeding as an example. Starting from the third term, each term is equal to the sum of the first two terms.
It can be solved by loop method or recursion method.
2. Procedure:
2.1 procedure 1: cycle method

#include  
int main()
{
    int i, iNum, iFibOne, iFibTwo, nextTerm;
 
    Printf ("output several items");
    scanf("%d", &iNum);
 
    Printf ("Fibonacci sequence");
    iFibOne = 1;
    iFibTwo = 1;
    for (i = 1; i <= iNum; i++)
    {
        printf("%d, ", iFibOne);
        nextTerm = iFibOne + iFibTwo;
        iFibOne = iFibTwo;
        iFibTwo = nextTerm;
    }
    return 0;
}

2.2 program 2: recursive method

#include 
int Fibonacci(int n);  //  Declaration subroutine
Int main() // recursive method 
{
    int i, iNum, iFibOne, iFibTwo, nextTerm;
 
    Printf ("output several items");
    scanf("%d", &iNum);
 
    Printf ("Fibonacci sequence");
    for (i = 1; i <= iNum; i++)
	{
	    printf("%d, ", Fibonacci(i));
	}
    return 0;
}

int Fibonacci(int n)
{
    return n < 2 ? n : Fibonacci(n - 1) + Fibonacci(n - 2);
}

3. Input and output:

Output several items: 10
Fibonacci sequence: 1, 1, 2, 3, 5, 8, 13, 21, 34, 55,

AttentionAlthough Fibonacci sequence is often used as the practice of recursive method, the time complexity and space complexity of circular method are o (n) and O (1), which are better than those of recursive method. The general formula method and matrix multiplication can be used to solve Fibonacci sequence, and the performance of the algorithm is better.


Exercise 25 finding the greatest common divisor of two numbers

Title:
Finding the greatest common divisor of two numbers
1. Analysis
There are many ways to find the greatest common divisor of two numbers, whether in solving algorithm or programming method. This routine is the most simple and easy to understand method for beginners.
2. Procedure:

#include  
int main()
{
    int i, iNum1, iNum2, iGcd;

    Printf ("enter two positive integers separated by spaces");
    scanf("%d %d", &iNum1, &iNum2);

    for(i=1; i <= iNum1 && i <= iNum2; i++)
    {
        If (inum1% I = = 0 & & inum2% I = = 0) // judge whether I is the greatest common divisor
            iGcd = i;
    }

    Printf ("% D and% d's greatest common divisor is% d", inum1, inum2, igcd));

    return 0;
}

3. Input and output:

Enter two positive integers separated by spaces: 81 153
The greatest common divisor of 81 and 153 is 9


Find the least common multiple of two numbers

Title:
Finding the least common multiple of two numbers
1. Analysis
This routine exercises the use of while loop and simplified condition judgment.
2. Procedure:

#include 

int main()
{
    int iNum1, iNum2, iMinMultiple;
    Printf ("enter two positive integers separated by spaces");
    scanf("%d %d", &iNum1, &iNum2);
 
    //Judge the larger value of two numbers and assign it to minmultiple
    iMinMultiple = (iNum1>iNum2) ? iNum1 : iNum2;
    
    While (1) // the condition is true
    {
        if( iMinMultiple%iNum1==0 && iMinMultiple%iNum2==0 )
        {
            Printf ("% D and% d's least common multiple is% d", inum1, inum2, iminmultiple) ";
            break;
        }
        iMinMultiple++;
    }
    
    return 0;
}

3. Input and output:

Enter two positive integers: 45 120
The least common multiple of 45 and 120 is 360


[exercise 27] loop out 26 letters

Title:
Loop out 26 letters
1. Analysis
Learn the format of for loop: for; Cycle conditions; Loop variable (increment)
The common type of loop variable is integer or floating point number, but it can also be other types, such as the character variable in this example.
In addition, the character value is stored in the memory unit in the form of ASCII code. C language allows character variables to participate in numerical operation, that is, to use the ASCII code of characters to participate in the operation. However, when ASCII code is used in operation, it is necessary to avoid data overflow and other errors.
2. Procedure:

#include 
int main()
{
    char cInput, cOut;
 
    Printf ("input u to show upper case letters, input L to show lower case letters");
    scanf("%c", &cInput);
 
    if(cInput== 'U' || cInput== 'u')
    {
       for(cOut = 'A'; cOut <= 'Z'; cOut++)
         printf("%c ", cOut);
    }
    else if (cInput== 'L' || cInput== 'l')
    {
        for(cOut = 'a'; cOut <= 'z'; cOut++)
         printf("%c ", cOut);
    }
    else
       printf("Error!  Enter illegal characters. ");
       
    return 0;
}

3. Input and output:

Enter u to show upper case letters, enter l to show lower case letters: L
a b c d e f g h i j k l m n o p q r s t u v w x y z


Exercise 28: how many digits is the number

Title:
How many digits is the number
1. Analysis
Learn the basic format of while loop: while (expression) {statement block}
2. Procedure:

#include 
int main()
{
    long lNum;
    int iCount = 0;
 
    Printf ("enter an integer):";
    scanf("%ld", &lNum);
    Printf ("number% LD is", lnum));
 
    while(lNum != 0)
    {
        lNum /= 10;
        iCount++;
    }

    Printf (% d digits. ", iCount);
    return 0;
}

3. Input and output:

Enter an integer: 1234500
The number is seven digits.

AttentionBecause the value of lnum in the routine is changed, two printf statements are used to output.


Exercise 29 calculate a number to the nth power

Title:
Calculate the nth power of a number
1. Analysis
Learn the basic format of the while loop: while (expression) {statement block}.
2. Procedure:

#include  
int main()
{
    int iBase, iExponent;
    long lResult = 1;
 
    Printf ("please input Radix (integer):");
    scanf("%d", &iBase);
    Printf ("please enter index (integer):");
    scanf("%d", &iExponent);

    printf("power(%d,%d) ", iBase,iExponent);
    while (iExponent != 0)
    {
        lResult *= iBase;
        iExponent--;
    }
    printf(": %ld", lResult);
 
    return 0;
}

3. Input and output:

Please enter the base number (integer): 2
Please enter the exponent (integer): 10
power(2,10) : 1024


[exercise 30] determine the number of palindromes

Title:
Judge palindrome number
1. Analysis
A palindrome number is a natural number that is equal to the original number if its digits are arranged reversely. For example: 1234321 is palindrome number, 1234567 is not palindrome number.
Routine 1 first reverses the original number to get a new number, and then compares whether the new number after reverse order is equal to the original number. This method is simple and easy to understand. Routine 2 does not generate a new number, so it is more concise and efficient to directly compare whether the forward and reverse corresponding position characters of the original number are the same.
2. Procedure:
2.1 procedure 1: compare whether the value of the new number after reverse order is equal to that of the original number

#include 
int main()
{
    int iNum, iOriginal, iReversed, iRemainder;
 
    Printf ("enter an integer):";
    scanf("%d", &iNum);
 
    iOriginal = iNum;
    iReversed = 0;
    //Invert the digits of the input integer inum to get ireversed
    while( iNum!=0 )
    {
        iRemainder = iNum % 10; //  Single digit
        iReversed = iReversed*10 + iRemainder;
        iNum /= 10;
    }
 
    //Judge whether the reverse order is equal to the original number
    if (iOriginal == iReversed)
        Printf ("% d is palindrome.", iOriginal);
    else
        Printf ("% d is not palindrome.", iOriginal);
    
    return 0;
}

2.2 program 2: directly compare whether the forward and reverse corresponding position characters of the original number are the same

#include 
#Include // character array operation
int main()
{
    char cStr[99];  //  Define character array (string)
    int i, iLen, iMark;
 
    Printf ("enter an integer (or string):");
    gets(cStr);  //  You can enter an integer, but it is also saved as a string

    iMark = 1;  //  Judgment mark
    iLen = strlen(cStr);  //  String length
    for(int i=0;i

3. Input and output:

Enter an integer: 1230321
1230321 is the palindrome number


Copyright notice:
The title and routine are from the rookie course. The author rewrites the program, notes and examples, and adds the analysis of difficulties.