assignment6
assignment6
#include "stdio.h"
#include "string.h"
#include "stdlib.h"
int main() {
char s[] = "Hello";
char *r = reverse(s);
printf("%s\n", r); // "olleH"
printf("%s\n", s); // "Hello"
free(r);
return 0;
}
O/P:
olleH
Hello
-----------------------------------------------------------------------------------
-----------------------------------------------------------------------------------
---
2) Write a function that takes two strings and returns a string which is a
concatenation of the two strings.
#include "stdio.h"
#include "string.h"
#include "stdlib.h"
int main() {
char s1[] = "Hello";
char s2[] = "World";
char* s3 = concat(s1, s2);
printf("%s\n", s3); // "HelloWorld"
printf("%s\n", s1);
printf("%s\n", s2);
free(s3);
return 0;
}
O/P:
HelloWorld
Hello
World
-----------------------------------------------------------------------------------
-----------------------------------------------------------------------------------
---
3) Write a function that takes int 'n' and returns an int array of size 'n' filled
with first 'n' prime numbers.
#include <stdio.h>
#include "stdlib.h"
int *get_primes(int n) {
int count = 0, num = 2;
int *prime = (int *)malloc(n * sizeof(int));
while (count < n) {
if (is_prime(num)) {
*(prime + count) = num;
count++;
}
num++;
}
return prime;
}
int main() {
int n;
printf("Enter n: ");
scanf("%d", &n);
int* primes = get_primes(n);
for (int i = 0; i < n; i++) {
printf("%d ", primes[i]);
}
// 2 3 5 7 11
printf("\n");
free(primes);
return 0;
}
O/P:
Enter n: 3
2 3 5
-----------------------------------------------------------------------------------
-----------------------------------------------------------------------------------
4) Write a function that takes an int array and returns an array with the
differences between elements of the input array.
#include "stdio.h"
#include "stdlib.h"
int main() {
int arr[] = {1, 7, 4, 10, 5};
int* diffs = get_diffs(arr, 5);
for (int i = 0; i < 4; i++) {
printf("%d ", diffs[i]);
}
// 6 -3 6 -5
printf("\n");
free(diffs);
return 0;
}
O/P:
6 -3 6 -5
-----------------------------------------------------------------------------------
-----------------------------------------------------------------------------------
5) Write a function that takes an int array and returns a new array with the
elements of the input array doubled.
#include "stdio.h"
#include "stdlib.h"
int main() {
int arr[] = {1, 3, 4, 7, 2};
int *doubled = double_elements_new(arr, 5);
for (int i = 0; i < 5; i++) {
printf("%d ", doubled[i]);
}
printf("\n");
free(doubled);
return 0;
}
O/P:
2 6 8 14 4
-----------------------------------------------------------------------------------
-----------------------------------------------------------------------------------
--------------------