-5

im trying to write this code but i couldn't the q is : by using for loop, write a program to receive input for any 5 numbers and display the total of even an odd numbers. the output should be as shown below

---------------------------------
Enter any 5 numbers: 0 1 3 2 11
0 is not even number.
total exists even = 1
total exist odd = 3
--------------------------------

and this is what i did:

    #include<iostream>
using namespace std;
int main()
{
    int i,j=0,c=0;

    for(i=0;i<5;i++)
    {
        cout<<"enter 5 numbers "<<i ;
        cin>>i;
    }
        if(i==0)
        {
        cout<< "0 is not even number"<<endl;
        }
        else if(i%2==0)
        {j++;}
        else if(i%2 !=0)
        {c++;}


    cout<<"total exists even : "<<j<<endl;
    cout<<"total exists ODD : "<<c<<endl;   
return 0;
}
Sebastian Simon
  • 18,263
  • 7
  • 55
  • 75
PRO
  • 1
  • 1
  • 1

5 Answers5

1

Going through your code step by step (notice the changed formatting!):

#include<iostream>
using namespace std; // usually considered bad practice
int main()
{
    int i, j=0, c=0;

    for(i = 0; i < 5; i++)
    {
        cout << "enter 5 numbers " << i;
        cin >> i; // you are overwriting your loop variable!!!
                  // how do you think your program will go on if you enter
                  // e. g. 7 right in the first loop run?
                  // additionally, you did not check the stream state afterwards
                  // if user entered something invalid (e. g. S), cin sets the
                  // fail flag and stops further reading - attemps doing so yield
                  // 0 (since C++11) or don't modify the variable (before C++11)
    }

    // this section is outside the loop already!
    // so you are only checking the number you read in your loop in the very last run
    if(i == 0)
    {
        cout << "0 is not even number" << endl;
    }
    else if(i % 2 == 0)
    {
        j++;
    }
    // this check is redundant: it is the complement to your previous
    // check, so if the first went wrong, the second cannot be false any more
    // (compare: you did not check for i != 0 either before doing the modulo check)
    else /* if(i % 2 != 0) */
    {
        c++;
    }

    cout << "total exists even: " << j << endl;
    cout << "total exists odd:  " << c << endl;   
    return 0;
}

Changed code:

#include<iostream>

int main()
{
    // several serious coding guide lines mandate: only one variable per line:
    unsigned int odd = 0;
    unsigned int even = 0;
    // I used unsigned int here, negative counts are just meaningless...
    // I'm consequent in these matters, but range of (signed) int suffices anyway,
    // so you can use either one...

    // C++ is not C (prior to C99) - keep scope of variables as local as possible
    // (loop counter declared within for header, local variable within body)
    for(unsigned int i = 0; i < 5u; i++) // (unsigned? see above)
    {
        std::cout << "enter 5 numbers (" << i << "): ";
        int n; // separate variable!
        if(!(std::cin >> n))
        {
            // some appropriate error handling!!! e. g.:
            std::cout << "invalid value entered";
            return -1;
        }

        // this now resides INSIDE the for loop
        if(n == 0)
        {
            cout << "0 is not even number" << endl;
        }
        else
        {
            // this is an ALTERNATIVE calculation

            n %= 2;    // gets either 0 or 1...
            odd += n;
            even += 1 - n;

            // (I personally prefer avoiding conditional branches but you *can*,
            //  of course, stay with the if/else you had before, too...
            //  - just don't check the complement as shown above)
        }
    }

    cout << "total exists even: " << even << endl;
    cout << "total exists odd:  " << odd  << endl;   
    return 0;
}

About the unsigned: Sometimes these are of advantage:

void f(int n)          { /* need to check for both 0 <= n && n <= max! */ }
void f(unsigned int n) { /* n <= max suffices */ }

but sometimes one has to handle them with care:

for(unsigned int n = 7; n >= 0; --n) { /* ... */ } // endless loop!!!
for(unsigned int n = 7; n-- >= 0;)   { /* ... */ } // correct variant

(the first one would have worked with signed int, but it is not the fault of the unsigned type, but the programmer's fault who did not chose the right type for what he or she intended...).

Just for completeness: Assuming we could drop the mathically incorrect statement that zero wasn't even, we could have it even much simpler:

unsigned int constexpr LoopRuns = 5u;

int main()
{
    unsigned int odd = 0; // just one single variable...

    for(unsigned int i = 0; i < LoopRuns; i++)
    {
        std::cout << "enter 5 numbers (" << i << "): ";
        int n;
        if(!(std::cin >> n))
        { /* ... */ }

        odd += n %= 2;
    }

    // one single difference instead of five additions...
    cout << "total exists even: " << LoopRuns - odd  << endl;
    cout << "total exists odd:  " << odd             << endl;   
    return 0;
}
Aconcagua
  • 24,880
  • 4
  • 34
  • 59
0

This program will help you out.

#include <iostream>
int main () {
    int num[5], even = 0, odd = 0;
    bool hasZero = false;
    std::cout << "Enter 5 numbers:"
    for (int i = 0; i < 5; i++) {
        std::cin >>  num[i];
    }

    for (int i = 0; i < 5; i++) {
        if (num[i] == 0) { // Checking if the current number is zero
            hasZero = true;
        } else if (num[i] % 2 == 0 ) { // Checking if the current number is even
            ++even;
        } else { // If the number is not even, then it must be odd
            ++odd;
        }
    }

    if (hasZero) { // If the input has zero then print following statement
        std::cout << "0 is not an even number" << std::endl;
    }

    std::cout << "Total even count: " << even << std::endl;
    std::cout << "Total odd count: " << odd << std::endl;

    return 0;
}

If you are unable to understand any line, then you're most welcome in the comments section below ;)


The problem with your code:

  • In the for statement, you're using the same variable for both counter and input , i.e., i. This will allow neither for loop to execute properly nor the input to be captured properly.

  • You're overwriting the i variable everytime you take any input, then only the last input (out of 5 inputs) will be stored in memory.

  • You're just checking the last input, by using if statement, because the loop is already ended before.


If you want your code to run properly, then these modifications will make that work:

#include<iostream>
using namespace std;
int main()
{
    int num,j=0,c=0;  // Change the name to num here, because i will be used later as a counter variable.

    for(int i=0;i<5;i++)
    {
        cout<<"enter 5 numbers "<<i ;
        cin>>num;

        // Don't end for loop here, this will not allow every input to be checked.

        if(num==0)
        {
            cout<< "0 is not even number"<<endl;
        }
        else if(num%2==0)
        {
            j++;
        }
        else if(num%2 !=0)  // Or just add a *else* here instead of *else if*, they will work exactly the same here.
        {
            c++;
        }

    } // End of for loop

    cout<<"total exists even : "<<j<<endl;
    cout<<"total exists ODD : "<<c<<endl;   
    return 0;
}
letsintegreat
  • 3,328
  • 4
  • 18
  • 39
0

Firstly, 0 is an even number, and your code needs to be properly indented, just so you can see that you are indeed reading the input into a single integer, which also controls the loop, and your if statement is outside the for loop (despite the misleading indentation. Here's a simple example implementation, but you can (and should) fix the bugs I pointed out in your own code:

#include <iostream>
int main() {
  std::cout << "Enter 5 numbers\n";
  int cnt(5);
  int n, odd(0), even(0);
  while(cnt-- && (std::cin >> n))
    n % 2 ? ++odd : ++even;

  std::cout << odd << " odd, "
  << even << " even numbers" << std::endl;
  return 0;
}

Note the post decrement and the fact the && short-circuits.

Aykhan Hagverdili
  • 28,141
  • 6
  • 41
  • 93
0

This should be your code: you take an array of integer where you store the input value. Head over to https://www.tutorialspoint.com/cprogramming/c_arrays.htm to learn more abour arrays..

#include<iostream>
using namespace std;
int main(){
int i,j=0,c=0;
int numbers[5];
for(i=0;i<5;i++){
    cout<<"enter 5 numbers "<<i ;
    cin>>numbers[i];
}
for(i=0;i<5;++i){
    if(numbers[i]==0)
    {
    cout<< "0 is not even number"<<endl;
    }
    else if(numbers[i]%2==0)
    {j++;}
    else if(numbers[i]%2 !=0)
    {c++;}
}

cout<<"total exists even : "<<j<<endl;
cout<<"total exists ODD : "<<c<<endl;   
return 0;
}
  • Why the array? One can handle all that is needed with one single temporary variable in one single loop. This variant is inefficient in terms of memory usage and runtime... – Aconcagua Dec 31 '18 at 07:47
-1
using namespace std;

int main()
{
    int * Array = new int[5];
    int even(0), odd(0);    
    for(int i = 0; i < 5; i++)
    {
        cout<<"enter "<< i+1 << "-th number: " << flush;
        cin>>Array[i];
        if(!Array[i]) 
        {
        cout<< "0 is not even number... input again"<<endl;
        i = i-1;
        }
        else
        {
            if(Array[i]&1) odd++;
            else even++;
        }
    }
    cout<<"total exists even : "<<even<<endl;
    cout<<"total exists ODD : "<<odd<<endl;   
    cin.get(); cin.get();
    delete[] Array;
    return 0;
}
  • what? no working? i was not tested... but seems to be OK – Gleb Igorevich Dec 31 '18 at 05:59
  • first method reading the '\n', and second makes the console a wait input... so that the console does not close automatically... – Gleb Igorevich Dec 31 '18 at 06:11
  • If you don't use them, the program will still work in most of the places, excluding the one that you use. – letsintegreat Dec 31 '18 at 06:13
  • @GlebIgorevich You shouldn't do this. It's not the application's task to keep a shell window open. Even worse: it prevents your application being usable in a shell script. – Aconcagua Dec 31 '18 at 06:13
  • Of course, you can simply configure ide, but by default almost everywhere except for some ide the window will close instantly. Of course, you can resort to _getch (), but i don’t want add library – Gleb Igorevich Dec 31 '18 at 06:22
  • @GlebIgorevich You can do so in your own IDE, but you shouldn't present bad practice to others, especially not to beginners. Original question did not contain that either. Apart from, the IDE I am working with all come with their on integrated console window that does not close either. – Aconcagua Dec 31 '18 at 06:26
  • 1
    Array of only five elements on the heap??? Prefer `int array[5];` instead (and you don't have to `delete[]` either). If on heap, modern C++ would rather use a smart pointer. Instead of raw array, 'std::array' usually is the better choice (although this example is too simple to really profit from). – Aconcagua Dec 31 '18 at 06:28
  • @Aconcagua yes for a heap inappropriate. but I do almost everything on the heap. more convenient and practical, especially in the frontend. – Gleb Igorevich Dec 31 '18 at 06:35
  • @Aconcagua i do not know... we, among programmers, cin.get for a pause in the order of things .... – Gleb Igorevich Dec 31 '18 at 06:38
  • @GlebIgorevich There's stuff appropriate for the heap, other isn't. And for the latter, it certainly is *not* more convenient, e. g. you cannot profit from [RAII](https://en.cppreference.com/w/cpp/language/raii). Consider e. g. [`std::lock_guard`](https://en.cppreference.com/w/cpp/thread/lock_guard) - and now construct it on the heap... – Aconcagua Dec 31 '18 at 06:40
  • @Aconcagua I want to add the fact that on the heap objects are declared and stored in the memory of the parent object and life, respectively, is not limited to the area of ​​syntactic visibility ... with static it does not happen ... – Gleb Igorevich Dec 31 '18 at 06:43
  • You're right. i'm using the clever pointer, but only in real (serious) projects... i do not know. how are you undestending me))) or all not so bad? in terms of english? – Gleb Igorevich Dec 31 '18 at 06:49
  • Where's the "parent object" in your little piece of code? There's no other object at all, if we don't count the ints. Taken word by word, this comment was non-sense, although I think I get what you wanted to express. However, in C++, we tend to keep scope of variables as limited as possible. Passing around pointers to heap-allocated `std::vector`s or `std::strings`??? There'd virtually nobody agree with you. Why do you think there has been put so much effort on move semantics since C++11? We want to have directly heap allocated objects the least possible. Where we have, best wrapped by ... – Aconcagua Dec 31 '18 at 07:01
  • ... containers such as `std::vector` (and a smart pointer would count as such), so we don't have to care for memory management. Ideally, not having to use `new` at all any more (objects that *need* to reside on heap would be crated by `std::make_unique` then)... – Aconcagua Dec 31 '18 at 07:01
  • Having *all* on the heap is a bit of Java or C# style - but these two languages have automatic garbage collection (but that comes at some price as well), which C++ does not have (or, well, only in reduced form provided by the smart pointers). – Aconcagua Dec 31 '18 at 07:02
  • a smart pointer cannot remove itself in time, especially if access to an object is impossible, and we are in another class when such situations occur constantly when an object of another class from the current one is called. so there is no point in this code and I said that there is nothing terrible about it. – Gleb Igorevich Dec 31 '18 at 07:46
  • You mean you cannot force a smart pointer to free its object earlier? Well, you can, just reset it with a `nullptr`. Not sure what you want to tell with the second scenario - object A shall provoke object B to delete its inner resource? Then see previous statement again. It is not 'terrible' (and the *good* thing about is that you did not forget to delete!), but it violates what got common sense among C++ programmers. And there's at least one person agreeing with me, the downvote wasn't mine... – Aconcagua Dec 31 '18 at 08:04