C++ program to add 2 in each digit of the integer value

by | Jan 30, 2023 | C++, C++ Programs

Home » C++ » C++ Programs » C++ program to add 2 in each digit of the integer value


In this program, you will learn to add 2 in all the digits of the integer value entered by the user in the C++ language.

For example, if the number is 98542, then this code will add 2 in all the digits of 98542.

This happens as follows

9+2=11; 8+2=10; 5+2=7; 4+2=6; 2+2=4 and display the output as 10764.

In the case of ‘9+2’ and ‘8+2’ we get 11 and 10 respectively, so in that case just print the unit place of the value obtained.

To understand the program, learn the following basic concepts of C++ programming

1. Operators

2. while and do-while loop

3. if-else statement


#include <iostream>
using namespace std;
int main()
int n; // 'n' stores the original value
cout<<"Enter an integer value:"<<endl;

int rem1=0;
int new_num=0;
rem1= n%10;
else if(rem1==9){

new_num=new_num*10+rem1; //this number is reversed of desired output
int rem2=0;
int result=0;

// now reverse the new_num to get answer;
result= result*10+rem2;
cout<<"The number obtained after adding 2 in each digit:\n"<<result;
return 0;




‘n’ stores the value of the integer entered by the user to add 2 in each digit of the value.

int rem1=0;

int new_num=0;

‘rem1’ and ‘new_num’ are the variables declared and initialized with 0 to store the remainder value and the final result, respectively.


The while loop executes until ‘n’ becomes equal to 0.

rem1= n%10;

In each iteration, the last digit of the ‘n’ is stored in ‘rem1’.

n=n/10; after that value of ‘n’ is updated by eliminating the last digit from ‘n’.

According to the value of ‘rem1’ obtained in each iteration, the if-else statements will work.


In the end, the final value gets stored in ‘new_num’ but that will be the reversed value of the desired output.

The value of ‘n’ entered by the user is 659805, thus the value of ‘new_num’ obtained is 720178.

Now we have to do the reverse of 720178 to get the actual value.

That is done using the while loop again by following the same process of accessing the last digits and then creating a new number from them.

Thus, the final output obtained in 871027



Submit a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.