Answer the question
In order to leave comments, you need to log in
What happens inside the FOR loop?
Hello. The code is not mine, I'm trying to understand what's going on in the loop.
The program is designed to fulfill the condition
Given a natural number n and integers (m1...mn) . After each even member of the sequence with an odd number preceding the first member with the value max(m1...mn) , insert the value max(m1...mn).
#include <iostream>
#include <cstdlib>
using namespace std;
#define n 30
int main(){
int mas[n];
int max = -9999;
int pos = 0;
cout<<"In: ";
for(int i = 0; i < n; i++){
mas[i] = rand()%105 - 5;
cout<<mas[i]<<" ";
if(max < mas[i]){
max = mas[i];
pos = i;
}
}
cout<<endl<<"Max = "<<max<<endl<<"Out ";
for(int i = 0; i < n; i++){
cout<<mas[i]<<" ";
if(i < pos){
if((i % 2 != 0) && (mas[i] % 2 == 0))
cout<<max<<" ";
}
}
return 0;
}
for(int i = 0; i < n; i++)
Answer the question
In order to leave comments, you need to log in
1) int max = -9999
- initial initialization of the variable (with the hope that this is the maximum minimum value)
2) mas[i] = rand()%105 - 5;
- assigning a random value to the cell with index i in the mas array
3) cout<<mas[i]<<" ";
- displaying the value of cell i from the mas array to the console
4)
if(max < mas[i]){
max = mas[i];
pos = i;
}
cout<<mas[i]<<" ";
- displaying the i value of the mas array cell. if(i < pos){}
- if i is less than the position index of the maximum element if((i % 2 != 0) && (mas[i] % 2 == 0))
cout<<max<<" ";
}
- if the current index i is odd ( i % 2 != 0
) AND ( &&
) the element of the array mas with index i has an even value ( mas[i] % 2 == 0
) , then output the maximum value to the console ( cout<<max<<" ";
)
mas[i] = rand()%105 - 5; // записываем в ячейку массива случайное число диапазоне от 0 до 99
cout<<mas[i]<<" "; // выводим это число на консоль
if(max < mas[i]){ // ищем максимальное значение (max) и его индекс (pos)
max = mas[i];
pos = i;
}
cout<<mas[i]<<" "; // выводим значение текущей ячейки
if(i < pos){ // для всех элементов, предшествующих максимальному
if((i % 2 != 0) && (mas[i] % 2 == 0)) // если номер нечетный и значение чётное
cout<<max<<" "; // выводим значение максимального элемента
}
why int max = -9999So that before passing through the loop, the value of the current maximum (with which the numbers are compared) is guaranteed to be less than any number. Also govnokod, in such cases it is better to use INT_MIN.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question