I am only given one hour to code this. [NOTE : NO arrays, pointers, recursion an
ID: 3887691 • Letter: I
Question
I am only given one hour to code this.
[NOTE : NO arrays, pointers, recursion and strings should be used in this code.]
1) How do I go about doing this is under an hour? Please include some thought processes.
2) What's the best way to savage the maximum amount of marks if I don't complete this in under an hour?
Explanation / Answer
#include <stdio.h>
/****************************************************************************
* Name : displayCollatzInternal(n, count)
* Description : Generates the Collatz Sequence, limiting to the count.
* Also, prints the sequence, count of the division excecutions
* & multiplication executions.
* Parameters :
* n - number of which Collatz Sequence is to be generated.
* count - maximum iterations to be performed.
* Output :
* None
****************************************************************************/
void displayCollatzInternal(int n, int count) {
int divCount = 0; // division execution counter
int mulCount = 0; // multiplication execution counter
int itrCount = 0; // iteration counter
// print the first line outside all conditions and loop, so it gets printed
// in the edge case (input as 1)
printf("The collatz sequence is: ");
// exit condition for while loop either n is 1 or
// iteration counter equals the maximum count of iterations passed as input
while ((n != 1) && (itrCount < count)) {
// increment iteration counter
itrCount++;
// mod operator checks for remainder
// so condition to check even numbers
if (n % 2 == 0) {
// even number
// reassign n & increment division execution counter
n = n / 2;
divCount++;
} else {
// odd number
// reassign n & increment multiplication execution counter
n = (3 * n) + 1;
mulCount++;
}
// print value of n for this iteration
// note no new line is added here
// also this should be inside the while loop and at the end, to have modified value
// of n printed
printf("%d ", n);
}
// print division count & multiplication count outside loop, so as to be in the end
// note for new line to be inserted before actually printing the count
printf(" The division statement has been executed %d times.", divCount);
printf(" The multiplication statement has been executed %d times.", mulCount);
}
int main() {
int n=0, count=0;
// get user input
printf("Enter positive numbers for n and count: ");
printf(" ");
scanf("%d %d", &n, &count);
// invoke displayCollatzInternal()
displayCollatzInternal(n, count);
return 0;
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.