
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
C++ code to decrease even numbers in an array
An array is a group of similar elements stored together in a single variable which take contiguous memory locations. Arrays help us to store and manage multiple values of the same type, like a list of numbers or names.
In this article, we will solve a beginner level problem in C++ that involves decreasing all the even numbers in an array by 1.
- Program to Decrease Even Numbers in an Array
- How to Check a if Number is Even in C++?
- C++ Program to Decrease Even Numbers in an Array
Decrease Even Numbers in an Array
You are given an array of integers as input, and your task is to iterate through the array and decrease each even number by 1. If the number is odd, it should remain unchanged. The program should then output the modified array. To understand this better, let's look at some example inputs and outputs:
Scenario 1
Input: [4, 5, 6, 7, 8] Output: [3, 5, 5, 7, 7]
Explanation: In the given input array, the even numbers are 4, 6, and 8. After decreasing each of them by 1, we get 3, 5, and 7 respectively. The odd numbers remain unchanged.
Scenario 2
Input: [1, 2, 3, 4, 5] Output: [1, 1, 3, 3, 5]
Explanation: Here, the even numbers are 2 and 4, we will decrease them to 1 and 3. The odd numbers ( 1, 3, and 5) remain same.
How to Check a if Number is Even in C++?
In C++, you can check if a number is even by using the modulus operator (%). The modulus operator will return the remainder of the division of two numbers. For an even number, the remainder when divided by 2 will be 0. To check if a number is even, you can use the following condition:
4 % 2 = 0 // This means 4 is even 5 % 2 = 1 // This means 5 is odd // Condition to check if a number is even if (number % 2 == 0) { // The number is even }
C++ Program to Decrease Even Numbers in an Array
Here is the C++ code that decreases even numbers in an array by 1.
#include <iostream> int main() { int arr[] = {4, 5, 6, 7, 8}; int size = sizeof(arr) / sizeof(arr[0]); // Iterate through the array for (int i = 0; i < size; i++) { // Check if the number is even if (arr[i] % 2 == 0) { arr[i]--; } } // Output the modified array std::cout << "Modified array: "; for (int i = 0; i < size; i++) { std::cout << arr[i] << " "; } std::cout << std::endl; return 0; }
The output of this program will be:
Modified array: 3 5 5 7 7
Conclusion
In this article, we have learned how to decrease even numbers in an array by 1 using C++. To check if a number is even, we used the modulus operator, which returns the remainder of the division. We also provided example inputs and outputs to illustrate how the program works.