You are viewing our Forum Archives. To view or take place in current topics click here.
Small C program help
Posted:

Small C program helpPosted:

FR0NTLinealpaca
  • Ladder Climber
Status: Offline
Joined: Feb 26, 201212Year Member
Posts: 365
Reputation Power: 15
Status: Offline
Joined: Feb 26, 201212Year Member
Posts: 365
Reputation Power: 15
I am currently learning C as part of a course and I have a task to reverse the order of 3 numbers without using any arithmetic.
I currently have this:

[code]#include <stdio.h>
 
int main()
{
   int n, reverse = 0;
 
   printf("Enter a number to reverse\n");
   scanf("%d", &n);
 
   while (n != 0)
   {
      reverse = reverse * 10;
      reverse = reverse + n%10;
      n       = n/10;
   }
 
   printf("Reverse of entered number is = %d\n", reverse);
 
   return 0;
}[/code]


But this solution uses arithmetic. How can I alter this to complete the task?
#2. Posted:
-Deano
  • Rated Awesome
Status: Offline
Joined: Aug 19, 201014Year Member
Posts: 5,243
Reputation Power: 532
Status: Offline
Joined: Aug 19, 201014Year Member
Posts: 5,243
Reputation Power: 532
You can take the response as a string and output the order of the number.

Excuse the lack of printf and scanf as it's easier to use the iostream. If you aren't allowed to use them, you can easily change it back to the printf/scanf equivalent.


#include <stdio.h>
#include <string>
#include <iostream>
#include <conio.h>
using namespace std;

int main() {
   string number = "";   // Create a string to hold our number and initialise it to be empty.

   cout << "Please enter the number you wish to reverse. ";
   cin >> number;   // Read in the number we want and assign it to the string "number".
   
   cout << "Reverse of entered number is: ";
   for (unsigned i = 0; i < number.length() + 1; i++) {   // Create a for loop. Will go from 0 to however long our number is.
      cout << number[number.length() - i];   // Print the number starting from the last character.
   }
   _getch();   // Captures character input (Used to pause the program until the user presses any key.)
}
Jump to:
You are viewing our Forum Archives. To view or take place in current topics click here.