In: Computer Science
*C PROGRAMMING LANGUAGE*
a) Given an array of size n, sort the array using pointers using malloc or calloc. Examples: Input: n = 5, A= {33,21,2,55,4} Output: {2,4,21,33,55}
b) Write a function that declares an array of 256 doubles and initializes each element in the array to have a value equal to half of the index of that element. That is, the value at index 0 should be 0.0, the value at index 1 should be 0.5, the value at index 2 should be 1.0, and so on. your function must be called in the main. Also, declaring array and the size must be using heap.
SOLUTION A sorting using pointers:
#include<stdio.h>
#include<stdlib.h>
int main(){
int n,i,temp,j;
printf("Enter the number of elements in
array\n");
scanf("%d",&n);
int *a;
a=(int*)malloc(sizeof(int)*n);
if(a==NULL){
printf("Memory is not
allocated\n");
return 0;
}
printf("Enter the elements in array\n");
for(i=0;i<n;i++){
scanf("%d",a+i);//a+i is
address
}
//sorting logic
for(i=0;i<n;i++){
for(j=0;j<n;j++){
if(*(a+i)<*(a+j)){
//swap a[i] and a[j]
temp=*(a+i);
*(a+i)=*(a+j);
*(a+j)=temp;
}
}
}
printf("The sorted array is :\n");
for(i=0;i<n;i++){
printf("%d ",*(a+i));
}
return 0;
}
SCREENSHOT OF THE CODE:
OUTPUT OF THE CODE:
SOLUTION B:
#include<stdio.h>
#include<stdlib.h>
void function(double *a,int n){
double j=0,k=2;
int i;
for(i=0;i<n;i++){
//double/double is always double
only
a[i]=j/k; //values in the array are
half
j++;
}
for(i=0;i<n;i++){
printf("%lf ",a[i]);
}
}
int main(){
double *a;
//declares array of 256 numbers
a=(double*)malloc(sizeof(double)*256);
function(a,256);//calling function
}
SCREENSHOT OF THE CODE:
SCREENSHOT OF THE OUTPUT:
NOTE:
If you are satisfied with my answer please do upvote and
if you have any kind of doubts please post in the comment section.
I'll surely help you there.
Thank You:)