Sunday, July 31, 2011

Define a pointer to an integer; read a list of n numbers using dynamic memory allocation and find average of these numbers

"
#include<stdio.h>
#include<conio.h>

void main()
{
 int *i,count=1,x=1,sum=0;
 //Enter 0 to terminate input
 i=(int *)malloc(sizeof(int));
 scanf("%d",i);
 sum+=*i;
 while(i[count-1]!=0)
 {
 i=(int *)realloc(i,sizeof(int));
 scanf("%d",&i[count]);
 sum+=i[count];
 count++;
}
count--;
printf("\nAverage is: %d",sum/count);
 getch();
}
 "

Concatenate two strings without using strcat: C source code

"
#include<stdio.h>
#include<conio.h>

void main()
{
 char s1[30],s2[30],s3[30];
 char *x,*y;
 int i=0;
 scanf("%s %s",s1,s2);
 x=s1;
 //first method given in comments(this method uses the third string)
/* while(*x!='\0')
 {
  *(s3+i)=*x;
  x++;i++;
  }
  x=s2;
   while(*x!='\0')
 {
  *(s3+i)=*x;
  x++;i++;
  }
  *(s3+i)='\0';
  printf("%s",s3);
  */
  //second method(uses no external string)
 while(*x!='\0')
 {
  x++;
  }
  y=s2;
  while(*y!='\0')
  {
   *x=*y;
   x++;y++;
   }
   *x='\0';
   printf("%s",s1);
 getch();
}
"