Check whether the last inserted number is even or odd

Updated

Given an array of size n and a number k. You have to do the following operation: 1)Insert a number in the array which is just greater than current sum of the array. After doing the above operation K times,find whether the last number inserted is even or odd.

Examples :

Input : arr[] = {1, 2, 3}, K = 3
Output : even
arr = {1 2 3}
arr = {1 2 3 7}, k = 1
arr = {1 2 3 7 14}, k = 2
arr = {1 2 3 7 14 28}, k = 3, the last number inserted is even

Input : arr[] = {1 3}, K = 1
Output : odd

Approach :

The idea is to first find the sum of the array.There can be 2 cases 1)If the current sum of array is even, then (sum+1) will be odd, so in this case last number(sum+1) inserted will be odd.And since even+odd=odd, so from now onwards step 2 will always be correct meaning step 1 will be correct only for k=1 2)If the current sum of array is odd, then (sum+1) will be even, so in this case last number(sum+1) inserted will be even.And again current sum will be odd because odd+even=odd, so 3)We can notice that if the current sum of array is even and k = 1, then ans will always “odd” else “even”

Implementation :

#include<bits/stdc++.h>
using namespace std;

//function to check if last number
//inserted is odd or even
void lastNumber(int a[], int N, int k)
{                                         		
		int sum = 0;                                             
		for(int i=0;i<N;i++)                                                    
		 {                                                                 
			sum += a[i];
		 }
		if (sum % 2 == 0 && k == 1) cout << "odd" << endl;
		else cout << "even" << endl;
	
}

// Driver program to test the case
int main()
{
    int arr[] = {1, 2, 4, 5};
    int k = 5;
    int n = sizeof(arr)/sizeof(arr[0]);
    lastNumber(arr, n, k);
    return 0;
}

Output :

even

Time Complexity : O(n)

Comment
Mithlesh Upadhyay Published 23 Nov 2026 · 2 min read

Mithlesh Upadhyay is a Computer Science and AI expert from Madhya Pradesh with strong academic background (BE in CSE and M.Tech in AI) and over six years of experience in technical content development. He has contributed tech articles, led teams, and worked in Full Stack Development and Data Science. He founded the w3colleges.org portal for learning resources.

Related tutorials