This program is accepting only 5 inputs while i am giving n=8, kindly help me out to find the error
The int n;
(in the function main()) declares a variable with automatic storage class and it has garbage value (unless you initialize it int n = 100;
). So, it's undefined what value variable n
will hold and since, you are using it to declare an array of int with size n
, the array may have random size. So, running such a program may give you some undefined behavior that may vary from machine to machine or may be you get different behavior if you run the same program in the same machine multiple times.
The compiler is free to do anything from crashing to summoning demons through your nasal passages.
The right way to do this is:
#define MAX_ARRAY_SIZE 100
int n = 0;
int arr[MAX_ARRAY_SIZE];
or
int n = 0;
std::cin >> n;
int arr[n];
or using std::vector
#include <iostream>
#include <vector>
#include <algorithm>
int main(void)
{
int n;
std::vector<int> arr;
std::cin >> n;
for(int i = 0; i < n; i++)
{
int e;
std::cin >> e;
arr.push_back(e);
}
int sum1 = std::count_if(std::begin(arr), std::end(arr), [] (int num) { return num < 0; });
int sum2 = std::count_if(std::begin(arr), std::end(arr), [] (int num) { return num > 0; });
int sum3 = n - (sum1 + sum2);
std::cout << (float(sum2) / n) << std::endl;
std::cout << (float(sum1) / n) << std::endl;
std::cout << (float(sum3) / n) << std::endl;
return 0;
}