Select Page

# 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

## Introduction

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

## Program

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

int rem1=0;
int new_num=0;
while(n!=0)
{
rem1= n%10;
n=n/10;
if(rem1==8)
{
rem1=0;
}
else if(rem1==9){
rem1=1;
}
else
rem1=rem1+2;

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;
while(new_num!=0)
{
rem2=new_num%10;
result= result*10+rem2;
new_num=new_num/10;
}
cout<<"The number obtained after adding 2 in each digit:\n"<<result;
return 0;
}```

## Explanation

‘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.

while(n!=0)

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.

new_num=new_num*10+rem1;

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