当前位置:网站首页>Count the number of inputs (C language)

Count the number of inputs (C language)

2022-07-05 08:15:00 chen_ bx

subject : Write a program , Input quantity is uncertain [0,9] Range of integers , The number of occurrences of each , Input -1 Indicates the end of the program


Use arrays and loops to solve this problem . Define a size as 10 Array of , Array count[i] Represents each number i. When entering numbers , Corresponding i++, Record the number of times . It is not necessary to record each number and count the number of times of each number .

#include <stdio.h>

int main()
{
    
	const int number = 10; // Size of array 
	int x;
	int count[10]; // Define an array 
	for (int i = 0; i < number; i++) {
     // Initialize array 
		count[i] = 0;
	}
	scanf_s("%d", &x); // Input x
	while(x!=-1){
    		// When the input is not -1 when , Continue to enter values 
		if (x >= 0 && x <= 9) {
    
			count[x]++; // Arrays participate in operations 
		}
		scanf_s("%d", &x); // Input x
	}
	for (int i = 0; i < number; i++) {
     // Traversal array 
		printf("%d Number of occurrences :%d  Time \n", i, count[i]);
	}
}

Program run results

 Insert picture description here

原网站

版权声明
本文为[chen_ bx]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202140545026676.html