CPP All : Loop Applications – Handling numerals
Concept Learning Code Sheets

#### Extracting digits of a number #2104

Loops can be used for extracting the digits one by one by judicious use of  the % and / operators.

#include<iostream>
using namespace std;
int main()
{
int n=1234,digit;
while(n>0)
{
digit=n%10;
cout<<digit<<endl;
n=n/10;
}
return 0 ;
}

#### Sum of digits of a number #2106

Finding the sum of individual digits in a number

#include<iostream>
using namespace std;
int main()
{
int n,digit,sum=0;
cout<<"Give a positive integer: ";
cin>>n;
int nc=n;
while(nc>0)
{
digit=nc%10;
sum=sum+digit;
nc=nc/10;
}
cout<<"Sum of Digits of "<<n<<" = "<<sum<<endl;
return 0 ;
}

#### Reverse printing a number using a loop #2115

Printing a number in reverse order of digit by using digit extraction technique in a loop

#include<iostream>
using namespace std;
int main()
{
int n,digit;
cout<<"Give a positive integer: ";
cin>>n;
cout<<"The reversed number would be : ";
while(n>0)
{
digit=n%10;
cout<<digit;
n=n/10;
}
return 0 ;
}

#### Extracting and printing the first and last digit of a number #2119

Using a loop technique and successive division by 10 to extract first and last digit of a given number and then printing it.

#include<iostream>
using namespace std;
int main()
{
int n,digit;
cout<<"Give a positive integer: ";
cin>>n;
int nc=n;
int last_digit=nc%10;
while(nc>=10)
{
nc=nc/10;
}
int first_digit=nc;
cout<<"First Digit = "<<first_digit<<endl;
cout<<"Last Digit = "<<last_digit<<endl;
return 0 ;
}

#### Find prime factors of a number #3218

Finding prime factors of a number input by the user.

#include <iostream>
using namespace std;
int main()
{
int n;
cout<<"Enter a positive integer: ";
cin>>n;
cout<<"The prime factors are: ";
for (int i=2; i <= n; i++)
{
while(n % i == 0)
{
n /= i;
cout<<i<<" ";
}
}
return 0;
}

Code Sheets:5
×