C++ Code Issues: Partial Execution and Unexpected Results

49 views Asked by At

I have a problem, I have this code and when I run it, the code starts and tells me to enter numbers, but when I enter them, nothing happens the code is supposed to show me the elements that divided by 2 give 0 from the vector, but it doesn't do anything(nu sunt elemente pare means there are no elements that divided by 2 give 0.....and numere pare means elements that divided by 2 give 0enter image description hereenter image description here

I expected the two to give me the elements in the vector that are exactly divisible by 2, but the code doesn't give them to me this is the code:

#include <iostream>
using namespace std; int n,i,a[100],t;
int main()
{
cout << "n="; cin>>n;
i=1;
do{
cin>>a[i];
if(a[i]%2==0)t++;
}while(i<n||i==n);
i++;
if(t==0){
cout<<"Nu sunt elemente pare.";
}else cout<<t<<" numere pare";
return 0;
}
1

There are 1 answers

0
Pepijn Kramer On

Just to show you current C++ usually is written differently than what you are learning now.

#include <iostream>
#include <vector>
#include <algorithm>

// using namespace std; No don't do this.
// learn to make functions for substeps
std::vector<int> ask_for_values()
{
    int count;
    std::cout << "Enter number of values : ";
    std::cin >> count;

    // create a (dynamic) array with count elements
    // and set all of them to 0
    std::vector<int> values(count,0);

    // range based for loop
    // reading each value from std::cin
    for(auto& value : values)
    {
        std::cout << "Enter a value : ";
        std::cin >> value;
    }

    return values;
}

// declare a predicate for odd
// again an extra function helps you describe your intent in code
bool is_odd(int value)
{
    return (value % 2) == 1;
}

int main()
{
    //std::vector values = ask_for_values();
    std::vector values{1,2,5,4,3,9}; // test values

    //don't be afraid to use long variable names ;)
    //std::count_if counts the number of elements for which the predicate holds.
    auto number_of_odd_numbers = std::count_if(values.begin(), values.end(), is_odd );
    std::cout << "Number of odd numbers =  " << number_of_odd_numbers<< "\n";

    return 0;
}