Given an integer N and a set of N integers. Find the number of the first maximal odd number from the given set. If there are no odd numbers in the set, then output 0.

Program:

#include <vcl.h> #include <iostream.h> #include <conio.h> #include <stdlib.h> char *Rus(const char *text); void main() { int a[10]; int i, n, max; cout << Rus(" Введите n: "); cin >> n; randomize(); for (i = 1; i < n; i++) { a[i] = rand() % 50; cout << a[i] << " "; } max = a[0]; for (i = 1; i <= n - 1; i++) { if ((a[i] > max) && (a[i] % 2 != 0)) max = a[i]; } { if ((max == a[0]) && (a[0] % 2 != 0) || (max != a[0])) cout << " " << Rus("искомый элемент= ") << max; else cout << " " << Rus(" таких элементов нет "); } getch(); } char bufRus[256]; char *Rus(const char *text) { CharToOem(text, bufRus); return bufRus; } 

The program incorrectly counts. How to write the conditions correctly?

  • 2
    @IvAn, so many of the same type of tasks in such time ... for classmates you hand over labs? :) - margosh

2 answers 2

 #include <vcl.h> #include <iostream.h> #include <conio.h> #include <stdlib.h> char *Rus(const char *text); void main() { int a[10]; int i, n, max; cout << Rus("Введите n: "); cin >> n; randomize(); for (i = 0; i < n; i++) { a[i] = rand() % 50; cout << a[i] << " "; } max = 0; for (i = 1; i < n; i++) { if ((a[i] > a[max]) && (a[i] % 2 == 1)) max = i; } if(a[max]%2==1) cout << " " << Rus("Результат: ") << max+1; else cout << " " << Rus("Результат: ") << 0; getch(); } char bufRus[256]; char *Rus(const char *text) { CharToOem(text, bufRus); return bufRus; } 
  • Thank you very much, this option is more like - IvAn
  • and the condition that if there is no odd cisel, then output 0? - IvAn
  • And now I understood everything, I figured it out myself, thanks - IvAn

The algorithm is simple: we consistently look for an odd value that exceeds the last saved one.

 int a[] = {1, 3, 3, 5, 2, 5, 3, 6, 4, 9}; int n = 0, v = INT_MIN; for (int i = 0; i < sizeof(a)/sizeof(a[0]); i++) if (a[i] % 2 == 1 && a[i] > v) { n = i + 1; v = a[i]; } // Нумеруем с единицы printf("Max = %d", n);