Saturday, 26 October 2013

Length of the String without using strlen()

Without using the strlen():-

 #include<stdio.h>
  void  main() 
   { 
   char a[20],i;
   printf("enter the string:-");
   scanf("%s",a); 
   for(i=0; a[i]!='\0'; ++i);
   printf("length of the string: %d",i); 
   }

enter the string:-abc
length of the string:3

Using the strlen():-

#include<stdio.h>
#include<string.h>
void main()
 {
   int len;
   char a[20];
   printf("enter the string:-");
   gets(a);
   len=strlen(a);
   printf("%d",len);
 }

Print String

1:- #include<stdio.h>
void main()
{
char a[]="welcome to C tutorials";
printf("%s",c);
}


2:- #include<stdio.h>
void main()
{
char a[20];
printf("enter the string:-");
scanf("%s",a);
printf("%s",a);
}


3:- #include<stdio.h>
void main()
{
char a[20];
printf("enter the string:-");
gets(a);
puts(a);
}

in program 1 we directly initialize the string at the time of declaration.

in program 2 we use scanf() for the input.

in program 3 we use gets() for the input.

Difference Between scanf() and gets():-

tha main difference between scanf and gets method is that scamf() method does not read the character after the blank spaces ..and gets () read full string including the spaces..

Example:-we use scanf() for input ...string:- "welcome to C tutorial"
on printing it  prints only "welcome" and ignore all the characters after the space..

if we use gets() for input then it prints whole string:-"welcome to C tutorial"


Friday, 25 October 2013

Floyd's Triangle

#include <stdio.h>
void main()
{
int row, i,c,x = 1;
   printf("Enter the no, of row\n");
  scanf("%d", &row);
  for (i = 1; i <= row; i++)
  {
    for (c = 1; c <= i;c++)
    {
      printf("%d ",x);
      x++;
    }
    printf("\n");
  }
}

Pascal Triangle

#include<stdio.h>
#include<conio.h>
int factorial(int);
void main()
{
    int row,i,j;

    printf("enter  number of row: ");
    scanf("%d",&row);

    for(i=0;i<row;i++)
{
         for(j=0;j<row-i-1;j++)
             printf(" ");

         for(j=0;j<=i;j++)
             printf("%d ",fact(i)/(fact(j)*fact(i-j)));
         printf("\n");
      }
 getch();
}

int fact(int num)
{
    int f=1;
    int i=1;
    while(i<=num)
{
         f=f*i;
         i++;
        }
  return f;
 }

Bubble Sort

#include <stdio.h>
#include<conio.h>
 void main()
{
  int a[100], n, i, j,temp;
  printf("Enter no, of element in array\n");
  scanf("%d", &n);
  printf("Enter the elements:-");
  for (i= 0; i < n; i++)
    scanf("%d", &a[i]);
  for (i = 0 ; i < ( n - 1 ); i++)
  {
    for (j = 0 ; j< n - i - 1; j++)
    {
      if (a[j] > a[j+1])
      {
        temp = a[j];
        a[j]= a[j+1];
        a[j+1] = temp;
      }
    }
  }
  printf("Sorted form:-");
  for ( i = 0 ; i < n ; i++ )
     printf("%d\n", a[i]);
}