There is an array a[9] . Made such an implementation of filling the array with only odd numbers starting from 1. It seems a bit clumsy, have ideas how you can implement a more rational way?

 #include <iostream> using namespace std; int main() { const int SIZE = 9; int a[SIZE]; int i = 0; int j = 0; while (j < SIZE) { if (i % 2 != 0) { a[j] = i; j++; } i++; } for (int i = 0; i < SIZE; i++) { cout << a[i] << " "; } system("pause"); } 
  • Do not write constants in upper case, this is an anti - pattern - Slava
  • one
    Most rationally: int a[] = {1, 3, 5, 7, 9, 11, 13, 15, 17}; :) - αλεχολυτ
  • @alexolut is fraught with errors when changing the size of the array - Slava
  • @Slava it is clear that for the larger sizes it is necessary to generate, but for small n , I think, it is quite suitable. - αλεχολυτ

4 answers 4

 const int SIZE = 9; int a[SIZE]; for(int i = 0; i < SIZE; ++i) a[i] = 2*i+1; 
     #include <iostream> using namespace std; int main(){ int arr[9] = { 1 }; for (int i = 1; i < 9; i++){ arr[i] = arr[i - 1] + 2; } // вывод for (int i = 0; i < 9; i++){ cout << arr[i] << endl; } return 0; } 

    result:

    result

       const size_t sz = 9; int arr[sz]; for(int i{0}, j{1}; i < sz; i++, j += 2){ arr[i] = j; std::cout << arr[i] << '\t'; } 
         int n = 1; std::generate( std::begin( a ), std::end( a ), [&n] { auto t = n; n+= 2; return t; } );