Computer Programming Lab 6 Solution - PowerPoint PPT Presentation

1 / 9
About This Presentation
Title:

Computer Programming Lab 6 Solution

Description:

Lab Exercise 5 Reversing Digits ... with its digits reversed is: ' setw( width ... Do not store the value of number after it has been reversed once. ... – PowerPoint PPT presentation

Number of Views:31
Avg rating:3.0/5.0
Slides: 10
Provided by: shyhka
Category:

less

Transcript and Presenter's Notes

Title: Computer Programming Lab 6 Solution


1
Computer ProgrammingLab 6 Solution
  • Shyh-Kang Jeng
  • Department of Electrical Engineering/
  • Graduate Institute of Communication Engineering
  • National Taiwan University

2
Lab Exercise 5 Reversing Digits
  • Write a function that takes an integer value and
    returns the number with its digits reversed. For
    simplicity, use integer numbers that do not
    contain zeroes. For example, given the number
    7631, the function should return 1367.

3
Sample Output
Enter a number between 1 and 9999 7631 The
number with its digits reversed is 1367
4
Solution (1/4)
  • // CPLab6Solution\Main.cpp
  • include ltiostreamgt
  • using stdcout
  • using stdcin
  • using stdendl
  • include ltiomanipgt
  • using stdsetw
  • int reverseDigits( int )
  • int width( int )
  • int main()
  • int number
  • cout ltlt "Enter a number between 1 and 9999 "
  • cin gtgt number

5
Solution (2/4)
  • cout ltlt "The number with its digits reversed is
    "
  • ltlt setw( width( number ) )
  • ltlt reverseDigits( number )
  • ltlt endl
  • return 0
  • // end main

6
Solution (3/4)
  • // function reverseDigits definition
  • int reverseDigits( int n )
  • int reverse 0
  • int divisor 1000
  • int multiplier 1
  • while ( n gt 10 )
  • if ( n gt divisor )
  • reverse n / divisor multiplier
  • n divisor
  • divisor / 10
  • multiplier 10
  • else
  • divisor / 10
  • // end while
  • reverse n multiplier
  • return reverse
  • // end function reverseDigits

7
Solution (4/4)
  • // function width definition
  • int width( int n )
  • if ( n / 1000 ) return 4
  • else if ( n / 100 ) return 3
  • else if ( n / 10 ) return 2
  • else return 1
  • // end function width

8
Follow-Up Activity 1
  • Add code to main so that it reverse number twice
    (i.e., reverse it once, then reverse the result
    of the first function call). Do not store the
    value of number after it has been reversed once.
    Is the number that has been reversed twice equal
    to the original number?
  • Answer Yes

9
Follow-Up Activity 2
  • What happens if divisor is initialized to 100
    instead of 1000? Try to solve this problem on
    paper first then compare your answer with the one
    given by the computer. Are they the same?
  • Answer Take 7631 as an example, the result will
    be 76 30 100 206
Write a Comment
User Comments (0)
About PowerShow.com