Как найти количество нулевых элементов массива

nazsal

2 / 2 / 0

Регистрация: 27.11.2011

Сообщений: 60

1

Как найти количество нулевых елементов в массиве?

27.11.2011, 21:40. Показов 6052. Ответов 7

Метки нет (Все метки)


Студворк — интернет-сервис помощи студентам

Помогите пожалуйста. Нужно найти количество нулевых елементов в одмомерном массиве. Вот тот что есть:

C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include<stdio.h>
#include<conio.h>
main()
{
clrscr();
int a[5],i,sum,k;
sum=0;i=0;k=0;
while(i<=5)
{printf("Введите елементы массива:");
scanf("%d",&a[i]);
if(a[i]==0) k=k+1;}
printf("Количество нулевых елементов=%d",k);
getch();
}



0



2554 / 1319 / 178

Регистрация: 09.05.2011

Сообщений: 3,086

Записей в блоге: 1

27.11.2011, 21:44

2

Цикл неверен. Во-первых, i не увеличиватся, во-вторых, даже если бы увеличивалась, то выходила бы за пределы массива.



0



go

Эксперт С++

3646 / 1378 / 243

Регистрация: 16.04.2009

Сообщений: 4,526

27.11.2011, 21:47

3

C++
1
2
3
4
int count = 0;
for (i=0; i< size_of_arr; i++)
            if (!arr[i])
              count++;



0



2 / 2 / 0

Регистрация: 27.11.2011

Сообщений: 60

27.11.2011, 21:53

 [ТС]

4

Программа написана на Borland C++ 3.1



0



BumerangSP

4299 / 1421 / 463

Регистрация: 16.12.2010

Сообщений: 2,939

Записей в блоге: 3

27.11.2011, 22:11

5

Самый простой:

C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include<stdio.h>
#include<stdlib.h>
#include<conio.h>
int main()
{
 clrscr();
 const int n=10;
 int  m[n],i,j=0;
 randomize();
 for (i=1; i<n; i++)
  {
    m[i]=random(2)-0;
    printf("%d ",m[i]);
  }
 printf("n");
 for (i=1; i<n; i++)
  if (m[i]==0)
   j++;
  printf("n%d",j);
 return 0;
}



0



nazsal

2 / 2 / 0

Регистрация: 27.11.2011

Сообщений: 60

02.12.2011, 16:16

 [ТС]

6

Сам разобрался.

C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include<stdio.h>
#include<conio.h>
main()
{
clrscr();
int a[5];
int sum,i,k;
printf("Введите елементы массива:");
i=0,k=0;
while(i<5)
{
scanf("%d",&a[i]);
if (a[i]==0) k=k+1;
i=i+1;
}
printf("Количество нулевых елементов:%d",k);
getch();
}



0



Петррр

6261 / 3562 / 898

Регистрация: 28.10.2010

Сообщений: 5,926

02.12.2011, 17:14

7

C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <iostream>
#include <algorithm>
#include <iterator>
 
int main()
{
    const int n = 15;
    int array[n] = {
        1, 2, 3, 4, 0, 
        1, 2, 3, 4, 0,
        1, 2, 3, 4, 0
    };
    std::copy(array, array + n, 
        std::ostream_iterator<int> (std::cout, " "));
    std::cout << std::endl;
    std::cout << "Count of zero in array: " <<
        std::count(array, array + n, 0) << std::endl;
    system("pause");
    return 0;
}



0



easybudda

Модератор

Эксперт PythonЭксперт JavaЭксперт CЭксперт С++

11885 / 7258 / 1720

Регистрация: 25.07.2009

Сообщений: 13,276

02.12.2011, 17:17

8

C
1
int zero_count(const int * arr, size_t size) { return ( size ) ? ( ! *arr ) + zero_count(arr+1, size-1) : 0; }



1



Improve Article

Save Article

Like Article

  • Read
  • Discuss(50+)
  • Improve Article

    Save Article

    Like Article

    Given an array of 1s and 0s which has all 1s first followed by all 0s. Find the number of 0s. Count the number of zeroes in the given array.
    Examples : 

    Input: arr[] = {1, 1, 1, 1, 0, 0}
    Output: 2
    
    Input: arr[] = {1, 0, 0, 0, 0}
    Output: 4
    
    Input: arr[] = {0, 0, 0}
    Output: 3
    
    Input: arr[] = {1, 1, 1, 1}
    Output: 0

    Approach 1: A simple solution is to traverse the input array. As soon as we find a 0, we return n – index of first 0. Here n is number of elements in input array. Time complexity of this solution would be O(n).

    Implementation of above approach is below:

    C++

    #include <bits/stdc++.h>

    using namespace std;

    int firstzeroindex(int arr[], int n)

    {

        for (int i = 0; i < n; i++) {

            if (arr[i] == 0) {

                return i;

            }

        }

        return -1;

    }

    int main()

    {

        int arr[] = { 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0 };

        int n = sizeof(arr) / sizeof(arr[0]);

        int x = firstzeroindex(arr, n);

        if (x == -1) {

            cout << "Count of zero is 0" << endl;

        }

        else {

            cout << "count of zero is " << n - x << endl;

        }

        return 0;

    }

    Java

    import java.io.*;

    class GFG {

        static int firstzeroindex(int arr[], int n)

        {

            for (int i = 0; i < n; i++) {

                if (arr[i] == 0) {

                    return i;

                }

            }

            return -1;

        }

        public static void main(String[] args)

        {

            int arr[] = { 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0 };

            int n = arr.length;

            int x = firstzeroindex(arr, n);

            if (x == -1) {

                System.out.println("Count of zero is 0");

            }

            else {

                System.out.print("count of zero is ");

                  System.out.println(n-x);

            }

        }

    }

    Python3

    class GFG :

        @staticmethod

        def  firstzeroindex( arr,  n) :

            i = 0

            while (i < n) :

                if (arr[i] == 0) :

                    return i

                i += 1

            return -1

        @staticmethod

        def main( args) :

            arr = [1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0]

            n = len(arr)

            x = GFG.firstzeroindex(arr, n)

            if (x == -1) :

                print("Count of zero is 0")

            else :

                print("count of zero is ", end ="")

                print(n - x)

    if __name__=="__main__":

        GFG.main([])

    C#

    using System;

    public class GFG{

              static int firstzeroindex(int[] arr, int n)

        {

            for (int i = 0; i < n; i++) {

                if (arr[i] == 0) {

                    return i;

                }

            }

            return -1;

        }

        public static void Main()

        {

            int[] arr = { 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0 };

            int n = arr.Length;

            int x = firstzeroindex(arr, n);

            if (x == -1) {

                  Console.WriteLine("Count of zero is 0");

            }

            else {

                Console.Write("count of zero is ");

                  Console.WriteLine(n-x);

            }

        }

    }

    Javascript

    <script>

    function firstzeroindex(arr, n)

        {

            for (let i = 0; i < n; i++) {

                if (arr[i] == 0) {

                    return i;

                }

            }

            return -1;

        }

            let arr = [ 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0 ];

            let n = arr.length;

            let x = firstzeroindex(arr, n);

            if (x == -1) {

                document.write("Count of zero is 0");

            }

            else {

                document.write("count of zero is " + (n-x));

            }

    </script>

    Time complexity: O(n) where n is size of arr.

    Space Complexity: O(1) as we are not using any extra space.

    Approach 2: Since the input array is sorted, we can use Binary Search to find the first occurrence of 0. Once we have index of first element, we can return count as n – index of first zero.

    Implementation:

    C

    #include <stdio.h>

    int firstZero(int arr[], int low, int high)

    {

        if (high >= low)

        {

            int mid = low + (high - low)/2;

            if (( mid == 0 || arr[mid-1] == 1) && arr[mid] == 0)

                return mid;

            if (arr[mid] == 1)

                return firstZero(arr, (mid + 1), high);

            else

                return firstZero(arr, low, (mid -1));

        }

        return -1;

    }

    int countZeroes(int arr[], int n)

    {

        int first = firstZero(arr, 0, n-1);

        if (first == -1)

            return 0;

        return (n - first);

    }

    int main()

    {

        int arr[] = {1, 1, 1, 0, 0, 0, 0, 0};

        int n = sizeof(arr)/sizeof(arr[0]);

        printf("Count of zeroes is %d", countZeroes(arr, n));

        return 0;

    }

    C++

    #include <bits/stdc++.h>

    using namespace std;

    int firstZero(int arr[], int low, int high)

    {

        if (high >= low)

        {

            int mid = low + (high - low) / 2;

            if ((mid == 0 || arr[mid - 1] == 1) &&

                             arr[mid] == 0)

                return mid;

            if (arr[mid] == 1)

                return firstZero(arr, (mid + 1), high);

            else

                return firstZero(arr, low, (mid -1));

        }

        return -1;

    }

    int countZeroes(int arr[], int n)

    {

        int first = firstZero(arr, 0, n - 1);

        if (first == -1)

            return 0;

        return (n - first);

    }

    int main()

    {

        int arr[] = {1, 1, 1, 0, 0, 0, 0, 0};

        int n = sizeof(arr) / sizeof(arr[0]);

        cout << "Count of zeroes is "

             << countZeroes(arr, n);

        return 0;

    }

    Java

    class CountZeros

    {

        int firstZero(int arr[], int low, int high)

        {

            if (high >= low)

            {

                int mid = low + (high - low) / 2;

                if ((mid == 0 || arr[mid - 1] == 1) && arr[mid] == 0)

                    return mid;

                if (arr[mid] == 1)

                    return firstZero(arr, (mid + 1), high);

                else

                    return firstZero(arr, low, (mid - 1));

            }

            return -1;

        }

        int countZeroes(int arr[], int n)

        {

            int first = firstZero(arr, 0, n - 1);

            if (first == -1)

                return 0;

            return (n - first);

        }

        public static void main(String[] args)

        {

            CountZeros count = new CountZeros();

            int arr[] = {1, 1, 1, 0, 0, 0, 0, 0};

            int n = arr.length;

            System.out.println("Count of zeroes is " + count.countZeroes(arr, n));

        }

    }

    Python3

    def firstZero(arr, low, high):

        if (high >= low):

            mid = low + int((high - low) / 2)

            if (( mid == 0 or arr[mid-1] == 1)

                          and arr[mid] == 0):

                return mid

            if (arr[mid] == 1):

                return firstZero(arr, (mid + 1), high)

            else:

                return firstZero(arr, low, (mid - 1))

        return -1

    def countZeroes(arr, n):

        first = firstZero(arr, 0, n - 1)

        if (first == -1):

            return 0

        return (n - first)

    arr = [1, 1, 1, 0, 0, 0, 0, 0]

    n = len(arr)

    print("Count of zeroes is",

            countZeroes(arr, n))

    C#

    using System;

    class CountZeros

    {

        int firstZero(int []arr, int low, int high)

        {

            if (high >= low)

            {

                int mid = low + (high - low) / 2;

                if ((mid == 0 || arr[mid - 1] == 1) &&

                                     arr[mid] == 0)

                    return mid;

                if (arr[mid] == 1)

                    return firstZero(arr, (mid + 1), high);

                else

                    return firstZero(arr, low, (mid - 1));

            }

            return -1;

        }

        int countZeroes(int []arr, int n)

        {

            int first = firstZero(arr, 0, n - 1);

            if (first == -1)

                return 0;

            return (n - first);

        }

        public static void Main()

        {

            CountZeros count = new CountZeros();

            int []arr = {1, 1, 1, 0, 0, 0, 0, 0};

            int n = arr.Length;

            Console.Write("Count of zeroes is " +

                           count.countZeroes(arr, n));

        }

    }

    PHP

    <?php

    function firstZero($arr, $low, $high)

    {

        if ($high >= $low)

        {

            $mid = $low + floor(($high - $low)/2);

            if (( $mid == 0 || $arr[$mid-1] == 1) &&

                                     $arr[$mid] == 0)

                return $mid;

            if ($arr[$mid] == 1)

                return firstZero($arr, ($mid + 1), $high);

            else

                return firstZero($arr, $low,

                                ($mid - 1));

        }

        return -1;

    }

    function countZeroes($arr, $n)

    {

        $first = firstZero($arr, 0, $n - 1);

        if ($first == -1)

            return 0;

        return ($n - $first);

    }

        $arr = array(1, 1, 1, 0, 0, 0, 0, 0);

        $n = sizeof($arr);

        echo("Count of zeroes is ");

        echo(countZeroes($arr, $n));

    ?>

    Javascript

    <script>

        function firstZero(arr , low , high) {

            if (high >= low) {

                var mid = low + parseInt((high - low) / 2);

                if ((mid == 0 || arr[mid - 1] == 1) && arr[mid] == 0)

                    return mid;

                if (arr[mid] == 1)

                    return firstZero(arr, (mid + 1), high);

                else

                    return firstZero(arr, low, (mid - 1));

            }

            return -1;

        }

        function countZeroes(arr , n)

        {

            var first = firstZero(arr, 0, n - 1);

            if (first == -1)

                return 0;

            return (n - first);

        }

            var arr = [ 1, 1, 1, 0, 0, 0, 0, 0 ];

            var n = arr.length;

            document.write("Count of zeroes is " + countZeroes(arr, n));

    </script>

    Output

    Count of zeroes is 5

    Time Complexity: O(Logn) where n is number of elements in arr[].

    Auxiliary Space: O(logn)

    Last Updated :
    20 Feb, 2023

    Like Article

    Save Article

    Дано файл действительных чисел a.txt Найти количество нулевых элементов и сумму
    элементов меньших 1 и больших 0.

    #include <iostream>
    #include <windows.h>
    #include <fstream>
    
    using namespace std;
    
    int main()
    {
        SetConsoleCP(1251);
        SetConsoleOutputCP(1251);
    
        ifstream file("a.txt");
    
        int num = 0;
    
        while(file)
        {
            string str;
            getline(file, str);
    
            for(int i = 0; i < str.length(); i++)
            {
                if(str[i] != '')
                {
                    if(str[i] == '0') num++;
                }
            }
        }
    
        cout << "Количество '0' в строке = " << num << "." << endl;
    
        file.close();
    
        return 0;
    }
    

    Всё что смог написать, а дальше не получается сделать поиск элементов меньших 1 и больших 0.
    P.S. Пользователь сам вводит числа в файл «a.txt».

    uses crt;
    
    var
      i, m, k, num, numm, nn: integer;
      x: array [1 .. 10000] of integer;
      y: array [1 .. 10000] of integer;
    
    begin;
      clrscr;
      writeln('Введите размер массива x(m)');
      readln(m);
      writeln('Введите размер массива y(k)');
      readln(k);
      writeln('Введите элементы массива x(m)');
      FOR i := 1 TO m do
      begin
        readln(x[i]);
      end;
      writeln('Введите элементы массива y(k)');
      FOR i := 1 TO k do
      begin
        readln(y[i]);
      end;
      FOR i := 1 TO m do
      begin
        IF x[i] = 0 THEN
          num := num + 1;
      end;
      FOR i := 1 TO k do
      begin
        IF y[i] = 0 THEN
          numm := numm + 1;
      end;
      if num > numm then
        nn := numm
      else
        nn := num;
      writeln('Общее количество нулевых элементов в двух массиваx ', nn);
    
    end.
    

    const
      n=100; { размер массива }
    var
      a:array[1..n] of integer;
      i,k:integer;
    begin
      { заполняем массив случайными значениями }
      Randomize;
      k:=0;
      Writeln(‘Элементы массива’);
      for i:=1 to n do
        begin
        a[i]:=Random(41)-20;
        Write(a[i],’ ‘);
        if a[i]=0 then Inc(k)
        end;
      Writeln;  
      Writeln(‘Нулевых элементов: ‘,k)
    end.

    Понравилась статья? Поделить с друзьями:

    Не пропустите также:

  • Портфолио как составить таблицы
  • Как найти компас в игре клондайк
  • Как в одноклассниках найти ролик
  • Как найти зарядку от компьютера
  • Как найти судебное решение в архиве

  • 0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии