Thursday, January 6, 2011

C Program to find a number of lines,words and characters from a given string

Coding:



#include <stdio.h>
#include <string.h>
#include <conio.h>
void main()
   {
int l=1,w=0,chars=1;
char c;
clrscr();
textcolor(9);
cprintf("\n********Terminate String by pressing the Tab Key followed by Enter Key ********");
printf("\n\nEnter the String :\n\n");
c=getchar();
while(c!= '\t')
{
c=getchar();
chars++;
if(c==' '|| c=='\n'||c=='.')
w++;
if(c=='\n')
l++;
if(c=='\t')
chars--;
}
textbackground(WHITE);
cprintf("\r\n--------------------------  ");
cprintf("\r\nNumber of Lines      =%d    ",l);
cprintf("\r\nNumber of Words      =%d    ",w+1);
cprintf("\r\nNumber of Characters =%d    ",chars);
cprintf("\r\n--------------------------  ");
getch();
}


Output:



Program to find number of Characters and Words in C Programming

Coding:

#include <stdio.h>
#include <string.h>
#include <conio.h>
void main()
   {

char str[200];
int i=0,word=0,ch=0;
clrscr();
textcolor(YELLOW);
printf("\nEnter the String (Max=200 characters): ")  ;
gets(str);
while(str[i]!='\0')
{
if(str[i]==' ')
{
word++;
ch++;
}
else
{
ch++;
}
i++;
}
printf("\nNumber of Characters = ");
cprintf("%d",ch);
printf("\nNumber of Words      = ");
cprintf("%d",word+1);
getch();

}
Output:

Program to find a Prime numbers in C Programming

Coding:

#include<stdio.h>
#include<conio.h>
void main()
{
int n,i,j=0;
clrscr();
printf("\nEnter the number:");
scanf("%d",&n);

// *LOGIC*
for(i=1;i<=n;i++)
{
if(n%i==0)
j++;
}

if(j==2)
{
printf("\nEntered Number");
textcolor(YELLOW);
cprintf("%2d" ,n);
printf("is Prime");
}
else
{
printf("\nEntered Number");
textcolor(YELLOW);
cprintf("%2d",n);
printf(" is not a Prime",n);
}
getch();
}

Output: 








Wednesday, January 5, 2011

Reverse the string in C programming without using temp variable

Coding:

#include<stdio.h>
#include<conio.h>
void main()
{
char s[100];
int i,j;
clrscr();
printf("\nEnter the string : ");
gets(s);
i=0;
j=strlen(s)-1;
while(i < j) 


s[i]=s[i]+s[j];
s[j]=s[i]-s[j];
s[i]=s[i]-s[j--];
i++;

// using built-in function: 
//n=strrev(s);
printf("\nReverse string is : %s",s);
getch();
}


Output:






Reverse the string in C programming with temp variable

Coding:
 
#include<stdio.h>
#include<conio.h>
void main()
{
char s[100],temp;
int i,j;
clrscr();
printf("\n Enter the string :");
gets(s);
i=0;
j=strlen(s)-1;
while(i < j)

{
temp=s[i]; 
s[i]=s[j];
s[j--]=temp;
i++;
}
// using built-in function:
//n=strrev(s); 
printf("\nReverse string is : %s",s);
getch();
}

Output: