Easy Tutorial
❮ C Exercise Example22 C Examples Octal Decimal Convert ❯

C Exercise Example 69

C Language Classic 100 Examples

Title: There are n people standing in a circle, numbered in order. Starting from the first person, they count (from 1 to 3). Anyone who counts to 3 exits the circle. The question is, who is the last person remaining, originally numbered as?

Program Analysis: None.

Example

//  Created by www.tutorialpro.org on 15/11/9.
//  Copyright © 2015年 tutorialpro.org. All rights reserved.
//

#include <stdio.h>
void main()
{
    int num[50],n,*p,j,loop,i,m,k;
    printf("Please enter the number of people in the circle:\n");
    scanf("%d",&n);
    p=num;
    // Start numbering these people
    for (j=0;j&lt;n;j++)
    {
        *(p+j)=j+1;
    }
    i=0;// i is used for counting, i.e., moving the pointer forward
    m=0;// m records the number of people who have exited the circle
    k=0;// k counts 1, 2, 3
    while(m&lt;n-1)// When the number of people exiting is less than the total number, i.e., at least one person remains
        // This cannot be written as m&lt;n, because if there are 8 people, when 6 have exited, the process continues with m++,
        // At this point, 7&lt;8, and the last person counts 1, 2, 3 by themselves and exits, resulting in no output
    {
        if (*(p+i)!=0)// If this person's number is not 0, start counting up, here the method is to reset the number of the person who counts to 3 to 0
        {
            k++;
        }
        if (k==3)
        {    k=0;    // Reset the count, i.e., the next person starts counting from 1
            *(p+i)=0;// Reset the number of the person who counts to 3 to 0
            m++;    // Increment the number of people who have exited
        }
        i++;      // Move the pointer forward
        if (i==n)// This is crucial, if it reaches the end of the line, the pointer needs to be reset to the beginning
            // And it can only be placed after i++, because only after i++ can i==n occur
        {
            i=0;
        }


    }
    printf("The person remaining is:");
    for (loop=0;loop&lt;n;loop++)
    {
        if (num[loop]!=0)
        {
            printf("%2d号\n",num[loop]);
        }
    }

}

The above program execution output is:

Please enter the number of people in the circle:
8
The person remaining is: 7号

C Language Classic 100 Examples

❮ C Exercise Example22 C Examples Octal Decimal Convert ❯