Computer >> 컴퓨터 >  >> 프로그램 작성 >> C++

배열에서 짝수를 줄이는 C++ 코드

<시간/>

양의 정수를 포함하는 크기 n의 배열 'arr'이 있다고 가정합니다. 짝수를 찾아 1만큼 줄여야 합니다. 이 과정을 거쳐 배열을 출력합니다.

따라서 입력이 n =7, arr ={10, 9, 7, 6, 4, 8, 3}과 같으면 출력은 9 9 7 5 3 7 3이 됩니다.

단계

이 문제를 해결하기 위해 다음 단계를 따릅니다. −

for initialize i := 0, when i < n, update (increase i by 1), do:
   if arr[i] mod 2 is same as 0, then:
      (decrease arr[i] by 1)
   print(arr[i])
print a new line

예시

이해를 돕기 위해 다음 구현을 살펴보겠습니다. −

#include <bits/stdc++.h>
using namespace std;
#define N 100
void solve(int n, int arr[]) {
   for (int i = 0; i < n; i++){
      if (arr[i] % 2 == 0)
         arr[i]--;
      cout<< arr[i] << " ";
   }
   cout<< endl;
}
int main() {
   int n = 7, arr[] = {10, 9, 7, 6, 4, 8, 3};
   solve(n, arr);
   return 0;
}

입력

7, {10, 9, 7, 6, 4, 8, 3}

출력

9 9 7 5 3 7 3