+ 3

Hey friends! Please explain me this code and say why its output is reversed?

#include <iostream> using namespace std; int main() { int N =345,sum =0; while(N>0){ sum=N%10 +sum*10; N /=10; } cout<<sum; return 0; } //output is 543

28th Aug 2018, 4:40 AM
Albert Whittaker :Shaken To Code
Albert Whittaker :Shaken To Code - avatar
4 Antworten
+ 11
N = 345, sum = 0 while(N > 0) { //First iteration (345 > 0) //345 % 10 = 5 // 0 * 10 = 0 sum = 5 + 0 = 5 N /= 10 --> N = 34 //Second iteration (34 > 0) //34 % 10 = 4 //5 * 10 = 50 sum = 50 + 4 = 54 N /= 10 --> N = 3 //Third iteration (3 > 0) //3 % 10 = 3 //54 * 10 = 540 sum = 540 + 3 = 543 N /= 10 --> N = 0 (int) //Fourth iteration (0 > 0) false //Exits from the loop } sum = 543 //Number is reversed
28th Aug 2018, 5:56 AM
blACk sh4d0w
blACk sh4d0w - avatar
+ 6
mod 10 will kind of detach the last number every time.. so you can see first 5 comes out .. similarly 4 and then 3... this is how it is reversed.. take your pen and paper.. start calculating
28th Aug 2018, 5:05 AM
Keerttik Titan
Keerttik Titan - avatar
+ 2
%mod sign is used for taking the reminder if u wanna take last digit to first take the remainder by moduling 10 and after that here number is divided by 10 so that there is no uae of last number as qe preserve in sum
29th Aug 2018, 7:48 AM
Aarav Raj
Aarav Raj - avatar
0
где русские то , ебаный в рот
10th Sep 2018, 6:32 AM
ильдар сулейманов
ильдар сулейманов - avatar