Computer Programming Lab 6 - PowerPoint PPT Presentation

1 / 9
About This Presentation
Title:

Computer Programming Lab 6

Description:

Lab Exercise 5 Reversing Digits ... of number after it has been reversed once. Is the number that has been reversed twice equal to the original number? 9 ... – PowerPoint PPT presentation

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

less

Transcript and Presenter's Notes

Title: Computer Programming Lab 6


1
Computer ProgrammingLab 6
  • 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
Template (1/4)
  • // CPLab6Template\Main.cpp
  • include ltiostreamgt
  • using stdcout
  • using stdcin
  • using stdendl
  • include ltiomanipgt
  • using stdsetw
  • / write prototype for reverseDigits /
  • / write prototype for width /
  • int main()
  • int number
  • cout ltlt "Enter a number between 1 and 9999 "
  • cin gtgt number

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

6
Template (3/4)
  • // function reverseDigits definition
  • / write function header for reverseDigits /
  • int reverse 0
  • int divisor 1000
  • int multiplier 1
  • while ( n gt 10 )
  • if ( n gt divisor )
  • reverse n / divisor multiplier
  • n divisor
  • / write a line of code that reduces divisor
    by a
  • factor of 10 /
  • / write a line of code that increase
    multiplier by
  • a factor of 10 /
  • else
  • divisor / 10
  • // end while

7
Template (4/4)
  • reverse n multiplier
  • return reverse
  • // end function reverseDigits
  • // function width definition
  • / write function header for width /
  • 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?

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?
Write a Comment
User Comments (0)
About PowerShow.com