Answer the question based on this code: # include <stdio .h> # include \" stdafx
ID: 3620681 • Letter: A
Question
Answer the question based on this code:# include <stdio .h>
# include " stdafx .h"
# include " stdlib .h"
int main ( int argc , char ** argv )
{
int n = atoi ( argv [1]);
while (n > 1) {
printf ("%d ", n);
if (n % 2 == 0) {
n /= 2;
} else {
n = 3*n + 1;
}
}
}
Write a program that, given a range of inputs, finds the starting value that produces
the longest sequence. More specifically, write a program that, given an input of n,
finds the starting value between 1 and n that produces the longest sequence. Have it
print out this value and the length of the sequence. For instance,
for an input of 15, it should print out 9 19;
for an input of 16, it should print out 9 19;
for an input of 17, it should print out 9 19;
for an input of 18, it should print out 18 20.
This is my codes. However, when I drag it into the command prompt. The prompt did not show anything and crashed. Can any one fix it?
#include <stdio.h>
#include "stdafx.h"
#include "stdlib.h"
int main(int argc, char **argv)
{
int n = atoi(argv[1]);
int j;
int i = 0;
int a = 0;
int b = 0;
for (j = 1; j <= n; ++j){
while ( j > 1) {
i = i + 1;
if (j % 2 == 0) {
j /=2;
} else {
j = 3*j + 1;
}
}
if (i > a){
a = i;
b = j;
} else {
a = a;
b = b;
}
}
printf ("%d %d", b, a);
}
Explanation / Answer
The problem you are likely encountering is when you don't pass an argument to the executable. This will cause an assert (atleast on Visual Studio 2010). To prevent this from happening you should check to see if the argument is null before calling the atoi function. I am not sure what your program is supposed to do but I can tell you there is an infinite loop because you are reassigning j inside the while loop so you will never see the output. #include #include "stdlib.h" int main(int argc, char **argv) { if(argv[1]==NULL) { printf("Must include argument"); return (0); } int n = atoi(argv[1]); int j; int i = 0; int a = 0; int b = 0; for (j = 1; j 1) { i = i + 1; if (j % 2 == 0) { j /=2; } else { j = 3*j + 1; } } if (i > a) { a = i; b = j; } else { a = a; b = b; } } printf ("%d %d", b, a); return (0); }Related Questions
Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.