C++: #CoolCodez

Now, we’ll go through some cool codes, applying all the things we have learned up till now. We will go through such kinds of codes periodically as we learn more and more C++ programming, which is why I created the hashtag.

Situation #1: User enters a number and the program displays the number of digits in the number.

#include<iostream.h>
#include<conio.h>
void main()
{
   clrscr();
   int num, counter=0;
   
   cout<<"\n\t Enter a number: ";
   cin>>num;
   
   while (num>0)
   {
       num=num/10;
       counter++;
   }
  
   cout<<"\n\t No. of digits in number: "<<counter;
   getch();
}

This code works because the program doesn’t store decimals. So, say the number is 69. It divides the number by 10 to get 6 because of the while loop. The counter becomes 1. Since 6 is greater than 0, it continues to divide 6 by 10, which is zero. The counter becomes 2. The process stops as 0 is not greater than 0.

Situation 2: User types in a number and the program breaks it down into each digit and identifies whether it is odd or even.

#include<iostream.h>
#include<conio.h>
void main()
{
 clrscr();
 int num, odd=0, even=0;
 
 cout<<"\n\t Enter a number: ";
 cin>>num;
 
 do
 {
    if(num%2==0)
    {
         even++;
    }
    else
    {
         odd++;
    }
    num=num/10;
 }while(num>0);

 cout<<"\n\t Number of odd digits: "<<odd;
 cout<<"\n\t Number of even digits: "<<even;
 getch();

}

 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s