Think of a built-in function and how you would write a function that does the sa
ID: 3696314 • Letter: T
Question
Think of a built-in function and how you would write a function that does the same job.
As noted before, you should use built-in functions but the point here is about the practice you get from writing functions.
you only need one version of the function, in case the built-in function has many versions.
Please list the built-in function and describe what it is does in no longer than one or two lines, then show your function code.
ex)For a vector x, mean(x) is a built-in function that returns the mean value of the elements in x.
For example, if x = [1 2 3 4 5] then mean(x) returns 3.
CODE:
function output = calcMean(x)
sum = 0;
N = length(x);
for ii = 1:N
sum = sum + x(ii);
end
output = sum / N;
end
please help me, i thought of sample example, but someone else has taken in my class!! please provide me a great example with sample codings!!! may I please get similar to the example but with diffrent functions? or even better coding!!
Explanation / Answer
memcpy function would be an great example
it copies n characters from memory area str2 to memory area str1.
concentrate on how memcpy is used in both of the following cases, you may ignore the other details.
---------------------------------------------------------------
The C library function=>
void *memcpy(void *str1, const void *str2, size_t n)
=>
copies n characters from memory area str2 to memory area str1.
--------------------------
here is the inbuild implementation of the function
#include <stdio.h>
#include <string.h>
int main ()
{
const char src[50] = "http://www.tutorialspoint.com";
char dest[50];
printf("Before memcpy dest = %s ", dest);
memcpy(dest, src, strlen(src)+1);
printf("After memcpy dest = %s ", dest);
return(0);
}
---------------------------------------------------------------
here is the user defined implementation of the function.
-------------------------------------------------------------------
#include<stdio.h>
#include<string.h>
void myMemCpy(void *dest, void *src, size_t n)
{
// Typecast src and dest addresses to (char *)
char *csrc = (char *)src;
char *cdest = (char *)dest;
// Copy contents of src[] to dest[]
for (int i=0; i<n; i++)
cdest[i] = csrc[i];
}
// Driver program
int main()
{
char csrc[] = "GeeksforGeeks";
char cdest[100];
myMemCpy(cdest, csrc, strlen(csrc)+1);
printf("Copied string is %s", cdest);
int isrc[] = {10, 20, 30, 40, 50};
int n = sizeof(isrc)/sizeof(isrc[0]);
int idest[n], i;
myMemCpy(idest, isrc, sizeof(isrc));
printf(" Copied array is ");
for (i=0; i<n; i++)
printf("%d ", idest[i]);
return 0;
}
------------------------------------------------------------------------------------
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.