Write a c program to demonstrate malloc () function
#include<stdio.h>
#include<conio.h>
#include<alloc.h>
void main()
{
int *a, i, n, j, temp;
clrscr();
printf("How many elements?");
scanf("%d",&n);
a=(int *)malloc(n*sizeof(int));
printf("Enter the elements:\n");
for(i=0;i<n;i++)
scanf("%d",(a+i));
printf("The sorted elements are\n");
for(i=0;i<n;i++)
for(j=i+1;j<n;j++)
if(a[i]>a[j])
{
temp=a[i];
a[i]=a[j];
a[j]=temp;
}
for(i=0;i<n;i++)
printf("%d\n",a[i]);
getch();
}
Output:
How many elements?5
Enter the elements:
2
5
1
3
4
The sorted elements are
1
2
3
4
Write a program in c to merge two arrays using dynamic memory allocation
#include<stdio.h>
#include<conio.h>
#include<alloc.h>
void main()
{
int i,n,sum;
int *a, *b, *c; //one-dimensional
arrays
clrscr();
printf("How many elements? ");
scanf("%d",&n);
a=(int *)malloc(n*sizeof(int));
b=(int *)malloc(n*sizeof(int));
c=(int *)malloc(n*sizeof(int));
printf("Enter the elements of first array:\n");
for(i=0;i<n;i++)
scanf("%d",a+i);
printf("Enter the elements of second array:\n");
for(i=0;i<n;i++)
scanf("%d",b+i);
for(i=0;i<n;i++)
*(c+i)=*(a+i)+*(b+i);
printf("The sum of arrays is\n");
for(i=0;i<n;i++)
printf("%d\n",*(c+i));
getch();
}
Output:
How many elements? 4
Enter the elements of first array:
2
4
6
8
Enter the elements of second array:
1
3
5
7
The sum of arrays is
3
7
11
No comments: