Example of calloc() function
Question:
C program to take input for “n” elements and display them allocate the memory dynamically.
Sol:
#include<stdio.h> #include<stdlib.h> int main() { int n,i,*p; char ch; do { printf("Enter total elements "); scanf("%d",&n); p=(int*)calloc(n,sizeof(int)); if(p==NULL) { printf("Memory allocation failed\n"); getch(); exit(1);//header file : stdlib.h } for(i=0;i<n;i++) { printf("Enter the element "); scanf("%d",(p+i)); } for(i=0;i<n;i++) { printf("%d\n",*(p+i)); } free(p); printf("Like to cont ... (y/n) "); fflush(stdin); ch=getchar();//scanf("%c",&ch); }while(ch=='y' || ch=='Y'); return(0); }
/* Output */ Enter total elements 5 Enter the element 2 Enter the element 2 Enter the element 3 Enter the element 6 Enter the element 4 2 2 3 6 4 Like to cont ... (y/n) y Enter total elements 2 Enter the element 6 Enter the element 3 6 3 Like to cont ... (y/n) n
Question:
C program to take input for “n” elements and display them also calculate and print sum of all the elements, allocate the memory dynamically.
Sol:
#include<stdio.h> #include<stdlib.h> int main() { int n,i,*p,s; char ch; do { printf("Enter total elements "); scanf("%d",&n); p=(int*)calloc(n,sizeof(int)); if(p==NULL) { printf("Memory allocation failed\n"); getch(); exit(1);//header file : stdlib.h } for(i=0;i<n;i++) { printf("Enter the element "); scanf("%d",(p+i)); } s=0; for(i=0;i<n;i++) { printf("%d\n",*(p+i)); s=s+*(p+i); } free(p); printf("sum = %d\n",s); printf("Like to cont ... (y/n) "); fflush(stdin); ch=getchar();//scanf("%c",&ch); }while(ch=='y' || ch=='Y'); return(0); }
/* Output */ Enter total elements 5 Enter the element 10 Enter the element 2 Enter the element 3 Enter the element 6 Enter the element 4 10 2 3 6 4 sum = 25 Like to cont ... (y/n) y Enter total elements 3 Enter the element 2 Enter the element 6 Enter the element 3 2 6 3 sum = 11 Like to cont ... (y/n) n