Followers

Saturday, April 1, 2023

Program To Print The Number(4-Digits) In the Reverse Order Separated By Comma

Program:
#include <iostream>  
using namespace std;  
int main() {  
  int num = 0;  
  int reversedNum = 0;  
  cout << "Enter any 4-digits number: ";  
  cin >> num;  
  for(int i=1; i<=4; i++) {  
    if(i!=4) {  
      reversedNum = num % 10;  
      num = num/10;  
      cout << reversedNum << ", ";  
    } else {  
      reversedNum = num % 10;  
      num = num/10;  
      cout << reversedNum << endl;  
    }  
  }  
  cout << endl;  
  return 0;  
}  
Working Of The Program:

This C++ program prompts the user to enter a 4-digit number and then reverses the order of its digits.

The program achieves this by first initializing two integer variables, num and reversedNum, to 0. It then prompts the user to enter a 4-digit number and stores it in the num variable using the cin object.

The program then enters a for loop, which executes 4 times since it starts with i=1 and continues as long as i<=4. Within the loop, the program checks if the current value of i is not equal to 4. If so, it takes the last digit of num using the modulus operator (%) and stores it in reversedNum. It then updates the value of num by dividing it by 10, effectively removing the last digit. Finally, it outputs the value of reversedNum, followed by a comma and space.

If i is equal to 4, the program executes a similar set of operations, but instead of appending a comma and space, it appends a newline character (endl) to the output stream.

After the loop completes, the program outputs an additional newline character and then terminates with a return value of 0.









No comments:

Post a Comment

Program to Find the Length of a String

Program: #include <iostream> using namespace std; int main() { string a; cout<<"Enter the string...