C language-Program Analysis of counting votes-example in the book and example in the ballot paper
# Include <stdio. h> // common header files
Struct candidate // create a struct, followed by the name
{
Char name [20]; // defines the variable name and sets the length to 20.
Int count; // defines the variable count.
} List [] = {"invalid", 0 },{ "Zhang", 0 },{ "Wang", 0 },{ "Li", 0 }, {"Zhao", 0 },{ "Liu", 0 }};
// Important !! If you add a struct directly, the data in the struct corresponds to the defined variables in the struct!
// That is, Zhang corresponds to name, and 0 corresponds to count. In addition, list is an array with a lot of data in the array, and the data format is the same.
Int main () // main Function Definition
{
Int I, n; // defines the variables I and n
Printf ("Enter vote \ n"); // output enter vote, which means entering the voting stage
Scanf ("% d", & n); // enter a number to intercept a number.
While (n! =-1) // n as long as it is not equal to-1, the loop will not be stopped
{
If (n> = 1 & n <= 5) // if n is greater than or equal to 1 and less than or equal to 5, that is, n is between 1 and 5
List [n]. count ++; // adds 1 to the count data in group n of the list array.
Else // otherwise
{
Printf ("invalid \ n"); // The output is invalid,
List [0]. count ++; // then add 1 to the count data in the 0th group of the list Array
}
Scanf ("% d", & n); // enter a number and capture a number
}
For (I = 1; I <= 5; I ++) // for Loop determination, first 1. If I is less than or equal to 5, first loop, and then add 1, until I is changed to 6, it does not meet the criteria for loop determination, that is, from 1 to 5, the cycle is 5 times.
Printf ("% s: % d \ n", list [I]. name, list [I]. count); // % s is a string, % d is data, and % s and % d correspond to list [I]. name, list [I]. count,
Printf ("% s: % d \ n", list [0]. name, list [0]. count); // This is the same,
}