Change the actual swapping logic in the scope of the “if” construct, from array
ID: 3348979 • Letter: C
Question
Change the actual swapping logic in the scope of the “if” construct, from array references to pointers. This also includes the “temp” identifier. Watch your data typing.
Do not modify the array “m” declaration.The resulting values in the array “m” will be in descending order. </hint> take the code, compile and link it, run and verify the data in “m” is descending. Then modify one line of code (LOC) to use pointers, comment out the original for reference, compile/link and test. Then change another LOC until all swapping is using pointer identifiers. <hint>
main()
{
char wait;
short m[]={3,5,7,2,5,1,2,2,
6,5,7,2,4,1,3,3,
7,7,3,2,5,7,1,9};
unsigned char temp, i, j;
unsigned char numElements = sizeof(m)/sizeof(m[0])-1;
for (i=0; i<=numElements-1; i++) // change < to <=
{
for(j=i+1; j<=numElements; j++) // change < to <=
{
if ( m[i] <= m[j])
{
temp = m[i]; //was m[j] should be m[i]
m[i] = m[j];
m[j] = temp;
}
}
}
}
Explanation / Answer
The modified code is shown below with the LOC in comments. The declaration of m is not changed. Only the swapping in the if construct is done using pointers.
CODE:
#include<stdio.h>
#include<conio.h>
main()
{
char wait;
short m[]={3,5,7,2,5,1,2,2,6,5,7,2,4,1,3,3,7,7,3,2,5,7,1,9};
unsigned char temp,i,j;
unsigned char numElements = sizeof(m)/sizeof(m[0])-1;
for(i=0;i<=numElements;i++)
{
for(j=i+1;j<=numElements;j++)
{
/* if(m[i] <= m[j]) */
if(*(m+i) <= *(m+j))
{
temp = *(m+i);
*(m+i) = *(m+j);
*(m+j) = temp;
}
}
}
/* The following loop is used to print elements of m*/
/*The below loop can be omitted*/
for(i=0;i<=numElements;i++)
{
printf(" %d",m[i]);
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.