TRICKY C PROGRAMS

Add and subtract using pointers

/* To add and substract using pointers */

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

void main()
 {
  int *add,*sub,a = 2;
  clrscr();

  add = &a;
  sub = &a;

  printf("\n\n Address of a = %d",add);
  printf("\n\n Value of a = %d",*add);

  add = add + 2;
  sub = sub - 2;

  printf("\n\n\n\n Value of add = %d",add);
  printf("\n\n Address of add = %d",&add);
  printf("\n\n value pointed out by add = %d",*add);
  printf("\n\n\n\n Value of sub = %d",sub);
  printf("\n\n Address of sub = %d",&sub);
  printf("\n\n value pointed out by sub = %d",*sub);

  getch();

 }


Ascii value:


#include <ctype.h>
#include <stdio.h>
void main()
{
printf(" %d   ", toascii('0'));
}

Factorial of number:

/* To find factorial of a number using recursion */

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

void main()
{
 int n,m;
 clrscr();

 printf("\n Enter the number to find the factorial : ");
 scanf("%d",&n);

 m = fact(n);
 printf("\n The factorial of %d is %d ",n,m);

 getch();
}

       int fact (int x)
{
 if (x<=1)
 {
return(1);
 }
 else
 {
return( x * fact(x-1) ) ;
 }
}

Malloc illustration:

/* TO illustrate MALLOC (memory allocation) */

#include<stdio.h>
#include<conio.h>
#include<alloc.h>
void main()
 {
  int i,n,sum,*x,*y,*z;
  clrscr();

  printf("\n\n How many elements in array : ");
  scanf("%d",&n);

  x = (int *) malloc(n*sizeof(int));
  y = (int *) malloc(sizeof(n*2));    /* both type can be used */
  z = (int *) malloc(sizeof(n*2));

  printf("\n\n Enter %d elements of 1st array : \n",n);
  for(i=0;i<n;i++)
  scanf("%d",&x[i]);

  printf("\n\n Enter %d elements of 2nd array : \n",n);
  for(i=0;i<n;i++)
  scanf("%d",&y[i]);

  for(i=0;i<n;i++)
  z[i] = x[i] + y[i];

  printf("\n\n The elements of resultant array : \n");
  for(i=0;i<n;i++)
  printf("%3d",z[i]);


  getch();

 }



Comments