My code: #include #include char * repeat_characters(char *s, int n) { printf(\"%
ID: 3686967 • Letter: M
Question
My code:
#include
#include
char * repeat_characters(char *s, int n)
{
printf("%s", s);
char temp;
int length = 0;
int i = 0;
int j = 0;
int k = 0;
char * newString;
while(s[length])
{
length++;
printf("%d", length);
} // finds length of string
newString = (char*) malloc(length*n*sizeof(char));
while(i++ < i*n)
{
temp = s[i];
while (j++ < n)
{
newString[k] = temp;
printf("%c", temp);
k++;
}
}
printf("%s", newString);
return newString;
}
int main ()
{
char * string[100];
int numReps = 0;
printf("Enter a string: ");
scanf("%s", string);
printf(" Enter number of repetitions: ");
scanf("%d", &numReps);
repeat_characters(*string, numReps);
return 0;
}
1. (30 points) Implement a function that takes a string, s, and an integer, n, as arguments. It then creates a new string with each character in s repeated n times in a row. Here are some examples: Input Output repeat characters("abc", 3) repeat characters("a",2) repeat characters("1234",1) repeat characters("1234",0) aaabbbcCC "1234" 4433 Use the following prototype: char repeat characters (char *s, int n) You may not use functions in string.h. Hint: you need to use malloc to allocate storage space for the new string, and return a pointer to the new array.Explanation / Answer
#include<stdio.h>
#include<stdlib.h>
char * repeat_characters(char *s, int n)
{
printf("%s ", s);
int length = 0;
int i = 0;
char * newString;
while(s[length] != '')
{
length++;
} // finds length of string
newString = (char*) malloc(length*n*sizeof(char));
int k = 0;
while(i < length)
{
int j=1;
while(j<=n){
newString[k++] = s[i];
j++;
}
i++;
}
newString[k] = '';
printf("%s", newString);
return newString;
}
int main ()
{
char string[100];
int numReps = 0;
printf("Enter a string: ");
scanf("%s", string);
printf(" Enter number of repetitions: ");
scanf("%d", &numReps);
repeat_characters(string, numReps);
return 0;
}
/*
Sample run:
Enter number of repetitions: 3
abc
aaabbbccc
*/
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.