Computer Science, asked by ritushree55, 1 month ago

wap to enter a number and checkif it is a three digit number if yes then print the sum of first and lastdigit else print the product of last and frist digit. in c++​

Answers

Answered by anindyaadhikari13
1

Required Answer:-

Question:

  • Write a C++ program to enter a number and check if it is a three digit number. If true, print the sum of first and last digit or else, print the product of first and last digit.

Solution:

Here comes the program.

#include <iostream>

using namespace std;

int main()  {

int a,x,y,s;

cout << "Enter a number: ";

cin >> a;

if (a>99 && a<1000)  {

 cout << "Number is a three digit number.\n";

 x=a/100;

 y=a%10;

 s=x+y;

 cout << "Sum of first and last digit: " << s;

}

else  {

 cout << "Number is not a three digit number.\n";

 x=a%10;

 while (a>=9)  {

  a/=10;

 }

 y=a%10;

 s=x*y;

 cout << "Product of first and last digit : "<<s;

}

return 0;

}

Logic:

  • Ask the user to enter a number. If the number is between 100 to 999, it is a three digit number. Calculate the sum of first and last digit. If the number is not a three digit number, calculate the product of first and last digit.
  • First digit is equal to the quotient obtained when the three digit number is divided by 100 and the last digit is equal to the remainder obtained when the number is divided by 10. Add them up and display the result.
  • In case of the numbers which are not a three digit number, calculate the last digit and then repeatedly divide the number by 10 till the number is not a 1 digit number. When it becomes a 1 digit number,divide the number by 10. The result obtained is the first digit. Multiply and display the result.

See the attachment for output ☑.

Attachments:
Similar questions