C program: Partial program needed to be completed in c programming language. //
ID: 3747103 • Letter: C
Question
C program:
Partial program needed to be completed in c programming language.
// spiral of integers 0, 1, 2
// command line interface with user
char *comline,*number,*xchars,*ychars, *commaloc; size_t bufsize=LINELIMIT;
size_t numsize=NUMLIMIT;
int whereis (int P, int* Xval, int* Yval) // completed
{
}
int main() {
int P, x, y, i, go_on=1, command,N, cindex;
comline=malloc(bufsize*sizeof(char)); number=malloc(numsize*sizeof(char)); xchars=malloc(numsize*sizeof(char)); ychars=malloc(numsize*sizeof(char));
memset(comline,' ',bufsize); getline(&comline,&bufsize,stdin);
if (memcmp(comline,"quit",strlen("quit"))==0) go_on=0; else if (memcmp(comline,"whereis",strlen("whereis"))==0)
{
strcpy(number,comline+strlen("whereis")); N=atoi(number);
if (N<0) printf("Negative numbers not in spiral "); else {
}
else if (memcmp(comline,"whatsat",strlen("whatsat"))==0)
{
// find comma index = C commaloc=strpbrk(comline,",");
if (commaloc==NULL) printf("comma missing "); else {
// overwrite comma with null byte
*commaloc=0;
// copy first number to xchars strcpy(xchars,comline+strlen("whatsat"));
// copy second number to ychars strcpy(ychars,commaloc+1);
// convert strings to numbers
x=atoi(xchars);
y=atoi(ychars);
// find contents of the spiral at x,y i=whatsat(x,y);
if (i==-1) printf("co-ordinates out of range ");
else printf("%d is at %d,%d ",i,x,y); }
}
else printf("invalid command %s ",comline);
}
can be arranged on a 2-dimensional plane in the form of a The non-negative integers 0, 1, 2, 3 rectangular spiral thus 12 (2.2) 13 14 (0,2) 16 15 3 2 10 5 8 Complete the given C program by adding two functions whereis and whatsat defined as follows:Explanation / Answer
/Submitting solution to Part 1 where is
int whereis (int P, int Xval, int Yval) // to be completed
{
if (P == 0) {
Xval = 0;
Yval = 0;
return 1;
}
else {
int i,k;
k=0;
while( 4*k*k + 2*k < P)
k++;
if(4*k*k + 2*k == P ) {
Xval = -1*k;
Yval = -1*k;
return 1;
}
// Along the x-axis there is a width of 2*k +1 while along y-axis there is a
// length of 2*k
k = k-1;
int diff = P - (4*k*k + 2*k);
// if the left most co-ordinate is -k,-k then total number of points in
// that rectangle is 8*k+5
// distance of 2k+1 right then 2*k+1 upwards, then 2k +2 leftwards
// then 2*k+1 downwards
if( diff < 2*k+1) {
Xval = diff-k;
Yval = -1*k;
}else if (diff > 2*k+1 && diff <= 4*k+2){
Xval = k+1;
Yval = diff - (2*k+1) - k;
} else if (diff > 4*k+2 && diff <= 6*k+4){
Xval = k+1 - (diff - 4*k -2);
Yval = k+1;
}else {
Xval = -1*k -1;
Yval = k+1 - (diff - 6*k-4);
}
return 1;
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.