给定大小为N的整数的数组arr ,任务是查找数组中正数和负数的计数
例子:
Input: arr[] = {2, -1, 5, 6, 0, -3}
Output:
Positive elements = 3
Negative elements = 2
There are 3 positive, 2 negative, and 1 zero.
Input: arr[] = {4, 0, -2, -9, -7, 1}
Output:
Positive elements = 2
Negative elements = 3
There are 2 positive, 3 negative, and 1 zero.
方法:
- 逐一遍历数组中的元素。
- 对于每个元素,检查元素是否小于0。如果是,则增加负元素的计数。
- 对于每个元素,检查元素是否大于0。如果大于0,则增加正元素的数量。
- 打印负数和正数元素的计数。
下面是上述方法的实现:
// C program to find the count of positive
// and negative integers in an array
#include
// Function to find the count of
// positive integers in an array
int countPositiveNumbers(int* arr, int n)
{
int pos_count = 0;
int i;
for (i = 0; i < n; i++) {
if (arr[i] > 0)
pos_count++;
}
return pos_count;
}
// Function to find the count of
// negative integers in an array
int countNegativeNumbers(int* arr, int n)
{
int neg_count = 0;
int i;
for (i = 0; i < n; i++) {
if (arr[i] < 0)
neg_count++;
}
return neg_count;
}
// Function to print the array
void printArray(int* arr, int n)
{
int i;
printf("Array: ");
for (i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
printf("\n");
}
// Driver program
int main()
{
int arr[] = { 2, -1, 5, 6, 0, -3 };
int n;
n = sizeof(arr) / sizeof(arr[0]);
printArray(arr, n);
printf("Count of Positive elements = %d\n",
countPositiveNumbers(arr, n));
printf("Count of Negative elements = %d\n",
countNegativeNumbers(arr, n));
return 0;
}
输出:
Array: 2 -1 5 6 0 -3
Count of Positive elements = 3
Count of Negative elements = 2
想要从精选的最佳视频中学习和练习问题,请查看《基础知识到高级C的C基础课程》。