สมมติว่าเราได้รับอาร์เรย์ 'arr' ขนาด n ที่มีจำนวนเต็มบวก เราต้องหาจำนวนคู่และลดลง 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