-->

Facebook

Jasper Roberts - Blog

Tuesday, April 28, 2015

Write a program using pointer to compare two strings.

#include<stdio.h>

int compare_string(char*, char*);

main()
{
    char first[100], second[100], result;

    printf("Enter first string\n");
    gets(first);

    printf("Enter second string\n");
    gets(second);

    result = compare_string(first, second);

    if ( result == 0 )
      printf("Both strings are same.\n");
    else
      printf("Entered strings are not equal.\n");

    return 0;
}

int compare_string(char *first, char *second)
{
  while(*first==*second)
  {
     if ( *first == '\0' || *second == '\0' )
        break;

     first++;
     second++;
  }
  if( *first == '\0' && *second == '\0' )
     return 0;
  else
     return -1;
}

Output:
Enter first String:HI
Enter Second String:HI
Both string are same

Write a program using pointer to concate two strings.

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

void main()
{
  int i=0;
  char *str1,*str2,*str3;

  puts("Enter first string");
  gets(str1);
  puts("Enter second string");
  gets(str2);

  printf("Before concatenation the strings are\n");
  puts(str1);
  puts(str2);

  while(*str1)
  {
      str3[i++]=*str1++;
  }
  while(*str2){
      str3[i++]=*str2++;
  }

  str3[i]='\0';
  printf("After concatenation the strings are\n");
  puts(str3);
  getch();

}

Write a program using pointer to read an array if integer

#include<stdio.h>
void main()
{
int a[5]={5,4,6,8,9};
int *p=&a[0];
int i;

clrscr();

for(i=0;i<5;i++)
printf("%d",*(p+i));

for(i=0;i<5;i++)
printf(" %u\n",(p+i));

getch();
}

Write a program to find factorial of a number using recursion.

#include<stdio.h>
#include<conio.h>
int fac(int n);

void main()
 {
  int x;
  long int a;
  clrscr();
  printf("enter the no:");
  scanf("%d",&x);
  a=fact(x);
  printf("factorial=%d",a);
  getch();
 }
 int fact(int n)
 {
 if(n==1)
  return 1;
 else
  return n*fact(n-1);
 }

Write a function power that computes x raised to the power y for integer x and y and returns double type value.

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

int power(int a,int b);
void main()
 {
  int x,y;
  clrscr();
  printf("enter the x:");
  scanf("%d",&x);
  printf("enter the y:");
  scanf("%d",&y);
  power(x,y);
  getch();
 }
int power(int a,int b)
 {
  double c;
  c=pow(a,b);
  printf("\n ans=%lf",c);
  return 0;
 }

Write a program using pointer and function to determine the length of string.

#include<stdio.h>

#include<conio.h>
#include<stdio.h>
#include<conio.h>
void ptr();

void main()
{
clrscr();
ptr();
getch();
}
void ptr()
{

    char s[100];
    char *p;
    int length;

    printf("\n Enter the string:");
    scanf("%s",s);

    for(p=s;*p!='\0';p++);

    length=p-s;

    printf("Length of the string is::%d",length);
     }