Программа на C для подсчета положительных и отрицательных чисел в массиве
Опубликовано: 22 Января, 2022
Для массива arr целых чисел размера N задача состоит в том, чтобы найти количество положительных и отрицательных чисел в массиве
Примеры:
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. Если это так, увеличьте количество положительных элементов.
- Выведите количество отрицательных и положительных элементов.
Below is the implementation of the above approach:
// C program to find the count of positive // and negative integers in an array #include <stdio.h> // 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 ( "
" ); } // 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
" , countPositiveNumbers(arr, n)); printf ( "Count of Negative elements = %d
" , countNegativeNumbers(arr, n)); return 0; } |
Output:
Array: 2 -1 5 6 0 -3 Count of Positive elements = 3 Count of Negative elements = 2
Хотите узнать о лучших видео и практических задачах, ознакомьтесь с Базовым курсом C для базового и продвинутого C.