0

I am practicing c++. I need to convert these 2 codes to c++. I am having trouble with the for loop conversion like in the next example:


    # Cuenta todos los números enteros que estén en una lista
import random

def cuenta_pares(numeros):
    cuenta = 0
    for numero in numeros:
        if numero % 2 == 0:
            cuenta += 1

    return cuenta

def cuenta_impares(numeros):
    cuenta = 0
    for idx in range(len(numeros)):
        if numeros[idx] % 2 != 0:
            cuenta += 1

    return cuenta

def main():

    terminos = int(input("Cuántos numeros quieres que tenga la lista: "))
    numeros = []
    for id in range(terminos):
        numeros.append(random.randint(1, 20))

    pares = cuenta_pares(numeros)
    impares = cuenta_impares(numeros)

    print("Tu lista es: ", numeros)
    print(f"Tu lista tiene {pares} numeros pares")
    print(f"Tu lista tiene {impares} numeros impares")

main()

Also the next example has the for loops. I already managed to declare the variables but haven't been able to manage the for loops. and

    def cuadrado(width, height):

    if width % 2 == 0:
        width += 1
    if height % 2 ==  0:
        height +=1

    for row in range(height):
        for col in range(width):
            if 0 < row < height - 1 and 0 < col < width - 1:
                print(" ", end = "")
            elif col % 2 == 0:
                print("+", end = "")
            else:
                print("-", end = "")
        print()

def main():
    alto = int(input("Dame el alto del cuadrado: "))
    ancho = int(input("Dame el ancho del cuadrado: "))

    cuadrado(ancho, alto)

main()
Fred Larson
  • 60,987
  • 18
  • 112
  • 174
  • Your question is all but specific. Please start with the [tour] and read [ask]. Then, you should be able to ask specific problems. Just for your info, it currently looks more or less like homework. – Ulrich Eckhardt Nov 14 '19 at 18:34
  • Note: If you get into the habit of naming your variables and functions in English you'll make your code *much* easier to comprehend by a *much* larger group of people. I know it may be tempting to use your native language, but 1) since the language keywords are English anyway you end up with a confusing language mix. 2) It's just easier to accept up front that the "global" language of programmers is English and adapt to that and be understood more widely. – Jesper Juhl Nov 14 '19 at 18:35
  • Possible duplicate of [Convert Python program to C/C++ code?](https://stackoverflow.com/q/4650243/608639) – jww Nov 21 '19 at 13:30

4 Answers4

4

The C++ equivalent of the Python

for x in range(n):

will be

for (int x = 0; x < n; ++x)

C++ (since C++11) also provides a range-base for loop to iterate over containers, including native arrays, std::array, std::vector, etc.

for (const auto& element : container)
Fred Larson
  • 60,987
  • 18
  • 112
  • 174
1

For loops in c++ look like this:

for(int i = 0; i < max_iter; i++) {
    // do something
}

You can also iterate over an array like this:

int array[] = {7, 8, 1, 5, 7, 10, 6};

for(int number : array) {
    // do something with number as a part of array
}

I'll leave the rest on you. Good luck :)

Maxxik CZ
  • 314
  • 2
  • 9
1

With a little helper class

class range {
    class iterator {
    public:
        iterator(int i) : i_(i) {}

        int operator*() const { return i_; }
        void operator++() { ++i_; }
        bool operator!=(iterator other) const { return i_ != other.i_; }

    private:
        int i_;
    };

public:
    range(int first, int last) : first_(first), last_(last) {}
    range(int last) : range(0, last) {}

    iterator begin() const { return iterator(first_); }
    iterator end() const { return iterator(last_); }

private:
    const int first_;
    const int last_;
};

you can write:

for (auto i : range(4))
    std::cout << i << ' ';        // prints 0 1 2 3

for (auto i : range(0, 5))
    std::cout << i << ' ';        // prints 0 1 2 3 4
Evg
  • 25,259
  • 5
  • 41
  • 83
  • 1
    I think Boost has `irange` if you don't want to roll your own. – Fred Larson Nov 14 '19 at 18:55
  • @FredLarson, and in C++20 we'll have ranges in the standard library: `for (int i : std::ranges::views::iota(0, 5))` (I'm not sure about the exact syntax). – Evg Nov 14 '19 at 19:05
0

Isaac

The structure in C++ for the loops is:

for(declaration of the counter variable;condition to loop; increment of the variable){
    do in the loop
    }

In your examples you can use your lists as vector in c++. So if you want to loop over a vector you can do like this:

int cuenta_pares(vector <int> numeros):
    int cuenta{0};
    for(numero{0};numero<numeros.size();numero++){
        if(numero % 2 == 0){
            cuenta += 1
        }
    }
    return cuenta

for using vector in c++ you must include #include

Here I let a website for reference

enter link description here