Wednesday 1 August 2012

How to add first and last digit of a four digit number in C++



Program to read a four digit number from the user and displays the 

sum of first and last digit.


#include<iostream>

#include<conio.h>

using namespace std;

int check_number(int number);

int main()
{
   int number = 0, sum = 0, remainder = 0, counter = 0;

   cout << "\n\t__ Program to add First and Last digit ___" << endl << endl;

   cout << "Enter 4 digit Number - ";

   cin >> number;

   if (check_number(number))
   {
          while(number != 0)
          {
                 remainder = number % 10;

                 number = number / 10;

                 counter++;

                 if ((counter == 1) || (counter == 4))
                 {
                        sum = sum + remainder;
                 }
          }

          cout << "\n\n\t __ Sum of the First and Last Digit is - " << sum << " __";

   }
   else
   {
          cout << "\n\t\t __ Enter 4 Digit Number __ " << endl;
   }

   //__  Both \n and endl can be used for new line __

   getch();

   return 0;
}

int check_number(int number)
{
   int counter = 0;

   while(number != 0)
   {
          number = number / 10;

          counter++;
   }

   if (counter == 4)
   {
          return 1;
   }
   else
   {
          return 0;
   }
}



cin is used to take input from the user. In this program after the number has been scanned or inputted through the keyboard the program checks whether its a 4 digit number or not by passing it to a function. In that function a variable named counter is used to count the number of digits. Inside a while loop, the number is decreased by one place value and counter value is incremented by 1 and the number of digits is 4 i.e. counter is equal to 4, the value 1 gets returned. 

if(1) means if(true) i.e. 1 represents true and 0 represents false. There in main function in true part again a counter variable is used as it is confirmed that the number is of 4 digits. So, if counter is 1 and 4 i.e. first digit and last digit, add them and at last a cout statement is used to display the result.

No comments:

Post a Comment