hello guys this is my first attempt in C++ and i am getting an error :(
the programs is made to read 20 numbers and find how many of them are even (like 2,4,6,20,40)

#include <iostream>

using namespace std;
int c[20];
int s = 0;
int i = 1;
int main()
{

  cout << "Enter the numbers followed by the ENTER key\n";

       loop:
            cin >> c[i];
            if(c[i]%2=0) //line with error
            {s++;}
            i++;
            if (i<=20) goto loop;

  cout << "done!\n Number of values: ";
  cout << s;
  system("PAUSE");
return 0;
}

and the error:

In function `int main()'
line 14: error: non-lvalue in assignment

Dani AI

Generated

— the compile error you hit is exactly what pointed out: using assignment where a comparison belongs. After fixing that, there are a few other issues worth addressing so the program is safe and portable.

First, the array indexing is off-by-one: a built-in array of size 20 has valid indices 0..19, so starting at 1 and looping through 20 writes past the end and causes undefined behavior. Prefer a container that expresses size explicitly (for example, std::vector or std::array) or make the loop 0-based. Keep counters and the index local to main rather than as globals. Also, check input extraction (std::cin) so the program stops cleanly if the user types non-numeric data. Finally, avoid goto and system("PAUSE") — the former obscures flow, the latter is non-portable.

A simple, safer pattern: read up to 20 integers into a container, validate input as you go, then count evens with an algorithm. The following is a compact, modern example that implements those ideas:

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

int main() {
    std::vector<int> nums;
    nums.reserve(20);
    int x;
    while (nums.size() < 20 && (std::cin >> x)) nums.push_back(x);

    auto evens = std::count_if(nums.begin(), nums.end(),
                               [](int n){ return (n & 1) == 0; });

    std::cout << "Even count: " << evens << '\n';
    return 0;
}

For background on safe containers and portability, see the std::vector reference and notes on std::system and arithmetic operators:

Recommended Answers

All 2 Replies

One equal sign assigns a value. Two equal signs compare values.
Change

if(c[i]%2=0)

to

if(c[i]%2==0)

and it should get rid of that error.

But you probably shouldn't use goto.
You can use a for loop or a while loop or even a instead.

how could i miss that?
thank you so much !

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.