You are on page 1of 6

School of Computer Sciences

Semester 2, Academic Session 2016/2017

CPT 111/CPM 111


Principle of Programming

Assignment 3

Name : PNG WEN HAN 130041


(i) Specification Requirements
The program required user to enter a natural number as input
Display Collatz sequence
Display numbers of steps take to reach final value (1)
Display a largest number from the Collatz sequence

(ii) Problem analysis including test data


INPUT
Prompt user to enter a natural number as input

OUTPUT
Display Collatz sequence
Display numbers of steps take to reach final value (1)
Display a largest number from the Collatz sequence

PROCESS

If i is even( i%2==0), divide it by 2 to get n / 2.


If iis odd( i%2!=0), multiply it by 3 and add 1 to get 3n + 1.
Repeat the process indefinitely using while loop.
Use iteration of n within the loop to obtain the number of step
Any number in the Collatz sequence smaller than the previos number will be
replace , and displayed after the loop condition is not full filled.

CONSTRAINT
The user input must be an integer type only

TEST DATA

Starting number: 11
11 34 17 52 26 13 40 20 10 5
16 8 4 2 1

Terminated after 14 steps. The largest value was 52.


(iii) Design (flow chart and pseudocode)

a) Pseudocode
Begin
Prompt user enter a natural number,i
Display the first number in the sequence (the input number)

WHILE i not equal to1


IF zero is the remainder to I divide by 2
i=i/2
ELSE
i=3*i+1
END IF

display i
IF I is larger than the previous larger integer
set largest number as i
END IF

set increment n++


END WHILE
DISPLAY number of steps and largest number in the sequence
End
b) flowchart
c)

Start

User enter a
natural number, i

Display first
number in sequence

i not equal1

yes no
Remainder of 2

i=i/2 i=3i+1

Display i

yes no
Largest number

Largest number =i

Display steps and


largest number

End
(iv) Sample input and output
Starting number: 11
11 34 17 52 26 13 40 20 10 5
16 8 4 2 1

Terminated after 14 steps. The largest value was 52.

(v) References
CPM 111/3 lecture note

(vi) Source code and executables

#include<iostream>
#include<iomanip>
using namespace std;

int main(){

int i,n=0,largest=0;

cout<<"Enter a number: ";


cin>>i;
cout<<setw(8)<<i;

while(i!=1){

if(i%2==0){
i/=2;
}else{
i=3*i+1;
}
cout<<setw(8)<<i;

if(i>largest){
largest=i;
}
n++;
}

cout<<"\n\nTerminated after "<<n<<" steps. The largest value was "<<largest;

return 0;
}
(vii) Print shots of program runs

You might also like