Wednesday, 13 June 2018

Print Number Pyramid in C

#include<stdio.h>

int main() {
   int i, j;
   int num;

   printf("Enter the number of Digits :");
   scanf("%d", &num);

   for (i = 0; i <= num; i++) {
      for (j = 0; j < i; j++) {
         printf("%d ", i);
      }
      printf("\n");
   }
   return (0);
}

OUTPUT:-

Tower of Hanoi using recursion

#include<stdio.h>

void TOH(int num, char x, char y, char z);

int main() {
   int num;
   printf("\nEnter number of plates:");
   scanf("%d", &num);

   TOH(num - 1, 'A', 'B', 'C');
   return (0);
}

void TOH(int num, char x, char y, char z) {
   if (num > 0) {
      TOH(num - 1, x, z, y);
      printf("\n%c -> %c", x, y);
      TOH(num - 1, z, y, x);
   }
}

OUTPUT:-

C Program to Write inline assembly language code in C Program

#include<stdio.h>

void main() {

   int a = 9, b = 9, c;

   asm {
      mov ax,a
      mov bx,a
      add ax,bx
      mov c,ax
   }

   printf("%d",c);
}

OUTPUT:- 18

C Program to Accept Paragraph with spaces using scanf

#include<stdio.h>

int main() {
   char para[100];

   printf("Enter Paragraph : ");
   scanf("%[^\t]s", para);

   printf("Accepted Paragraph : %s", para);

   return 0;
}

OUTPUT:-

C Program for sorting the list of names OR Strings

#include<stdio.h>
#include<string.h>
#include<stdlib.h>

int main() {
   char *str[5], *temp;
   int i, j, n;

   printf("\nHow many names do you want to have?");
   scanf("%d", &n);

   for (i = 0; i < n; i++) {
      printf("\nEnter the name %d: ", i);
      flushall();
      gets(str[i]);
   }

   for (i = 0; i < n; i++) {
      for (j = 0; j < n - 1; j++) {
         if (strcmp(str[j], str[j + 1]) > 0) {
            strcpy(temp, str[j]);
            strcpy(str[j], str[j + 1]);
            strcpy(str[j + 1], temp);
         }
      }
   }

   flushall();

   printf("\nSorted List : ");
   for (i = 0; i < n; i++)
      puts(str[i]);

   return (0);
}

OUTPUT:-

Count Number of Words spaces vowels digits and special charecters using C

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

/*low implies that position of pointer is within a word*/
#define low 1

/*high implies that position of pointer is out of word.*/
#define high 0

void main() {
   int nob, now, nod, nov, nos, pos = high;
   char *str;
   nob = now = nod = nov = nos = 0;
   clrscr();

   printf("Enter any string : ");
   gets(str);

   while (*str != '\0') {

      if (*str == ' ') {
         // counting number of blank spaces.
         pos = high;
         ++nob;
      } else if (pos == high) {
         // counting number of words.
         pos = low;
         ++now;
      }

      if (isdigit(*str)) /* counting number of digits. */
         ++nod;
      if (isalpha(*str)) /* counting number of vowels */
         switch (*str) {
            case 'a':
            case 'e':
            case 'i':
            case 'o':
            case 'u':
            case 'A':
            case 'E':
            case 'I':
            case 'O':
            case 'U':
               ++nov;
               break;
         }

      /* counting number of special characters */
      if (!isdigit(*str) && !isalpha(*str))
         ++nos;
      str++;
   }

   printf("\nNumber of words  %d", now);
   printf("\nNumber of spaces %d", nob);
   printf("\nNumber of vowels %d", nov);
   printf("\nNumber of digits %d", nod);
   printf("\nNumber of special characters %d", nos);

   getch();
}

OUTPUT:-



C Program to display mouse pointer

#include<stdio.h>
#include<dos.h>

int initmouse();
void showmouseptr();

union REGS i, o;

int main() {
   int status;
   status = initmouse();

   if (status == 0) {
      printf("Mouse support not available.n");
   } else {
      showmouseptr();
   }

   return 0;
}

int initmouse() {
   i.x.ax = 0;
   int86(0X33, &i, &o);
   return (o.x.ax);
}

void showmouseptr() {
   i.x.ax = 1;
   int86(0X33, &i, &o);
}



Friday, 8 June 2018

C Program to check if input Number is int or float

#include<stdio.h>

#include<conio.h>
#include<string.h>

int main()
{
   char number[10];
    int flag = 0;
    int length, i = 0;

    printf("\n\nEnter a number: ");
    scanf("%s", number);

    length = strlen(number);

    // till string does not end
    while(number[i++] != '\0')    // same as while(length-->0)
    {
        if(number[i] == '.')    // decimal point is present
        {
            flag = 1;
            break;
        }
    }

    // if(0) is same as if(false)
    if(flag)
        printf("\n\n\n\tEntered Number is a Floating point Number\n\n");
    else
        printf("\n\n\n\tEntered Number is a integer Number\n\n");
    return 0;
}


Null Pointer Program

#include<stdio.h>

int main()
{
    int *ptr = NULL;    // ptr is a NULL pointer
    printf("\n\n The value of ptr is: %x ", ptr);
      return 0;
}
Output: The value of ptr is: 0

C Program to check whether a two dimensional array is a Sparse Matrix

#include<stdio.h>

int main()
{
    int n, m, c, d, matrix[10][10];
    int counter = 0;
    printf("\nEnter the number of rows and columns of the matrix \n\n");
    scanf("%d%d",&m,&n);

    printf("\nEnter the %d elements of the matrix \n\n", m*n);
    for(c = 0; c < m; c++)   // to iterate the rows
    {
        for(d = 0; d < n; d++)   // to iterate the columns
        {
            scanf("%d", &matrix[c][d]);
            if(matrix[c][d] == 0)
            counter++;  // same as counter=counter +1
        }
    }

    // printing the matrix
    printf("\n\nThe entered matrix is: \n\n");
    for(c = 0; c < m; c++)   // to iterate the rows
    {
        for(d = 0; d < n; d++)   // to iterate the columns
        {
            printf("%d\t", matrix[c][d]);
        }
    printf("\n"); // to take the control to the next row
    }

    // checking if the matrix is sparse or not
    if(counter > (m*n)/2)
        printf("\n\nThe entered matrix is a sparse matrix\n\n");
    else
        printf("\n\nThe entered matrix is not a sparse matrix\n\n");

    return 0;
}


Dynamic Memory Allocation using malloc()

#include <stdio.h>

int main()
{
    int n, i, *ptr, sum = 0;

    printf("\n\nEnter number of elements: ");
    scanf("%d", &n);

    // dynamic memory allocation using malloc()
    ptr = (int *) malloc(n*sizeof(int));

    if(ptr == NULL) // if empty array
    {
        printf("\n\nError! Memory not allocated\n");
        return 0;   // end of program
    }

    printf("\n\nEnter elements of array: \n\n");
    for(i = 0; i < n; i++)
    {
        // storing elements at contiguous memory locations
        scanf("%d", ptr+i);   
        sum = sum + *(ptr + i);
    }

    // printing the array elements using pointer to the location
    printf("\n\nThe elements of the array are: ");
    for(i = 0; i < n; i++)
    {
        printf("%d  ",ptr[i]);    // ptr[i] is same as *(ptr + i)
    }

    /*
        freeing memory of ptr allocated by malloc
        using the free() method
    */
    free(ptr);
    return 0;
}


find the Size of any File

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

void main()
{
    FILE *fp;
    char ch;
    int size = 0;

    fp = fopen("program.txt", "r");
    if (fp == NULL)
    {
        printf("\nFile unable to open...");
    }
    else
    {
        printf("\nFile opened...");
    }
    fseek(fp, 0, 2);    /* File pointer at the end of file */
    size = ftell(fp);   /* Take a position of file pointer in size variable */
    printf("The size of given file is: %d\n", size);
    fclose(fp);
}


Print names of all Files present in a Directory

#include<stdio.h>
#include<dirent.h>

int main(void)
{
    DIR *d;
    struct dirent *dir;
    d = opendir(".");
    if (d)
    {
        while ((dir = readdir(d)) != NULL)
        {
            printf("%s\n", dir->d_name);
        }
        closedir(d);
    }
    return(0);
}


Program to convert Temparature in Celsius to Fahrenheit

#include<stdio.h>

int main()
{
        float celsius, fahrenheit;
    printf("\n\nEnter temperature in Celsius: ");
    scanf("%f", &celsius);
   
    fahrenheit = (1.8*celsius) + 32;
    printf("\n\n\nTemperature in Fahrenheit is: %f ", fahrenheit);

    return 0;
}


C Program to Calculate Permutation (nPr) and Combination (nCr)

#include<stdio.h>

// function prototype declarations
long factorial(int);
long find_npr(int, int);
long find_ncr(int, int);

int main()
{
     int n, r;
    long npr, ncr;

    printf("Enter the value of n and r respectively: \n\n");
    scanf("%d%d", &n, &r);

    // function calls
    npr = find_npr(n, r);
    ncr = find_ncr(n, r);

    printf("\n\n\n\t\t%dC%d = %ld\n", n, r, ncr);
    printf("\n\n\t\t%dP%d = %ld\n", n, r, npr);

    printf("\n\n\t\t\tCoding is Fun !\n\n\n");
    return 0;
}

/*
    function definition for nCr
*/
long find_ncr(int a, int b)
{
    return (factorial(a)/(factorial(b)*factorial(a-b)));
}

/*
    function definition for nPr
*/
long find_npr(int a, int b)
{
    return (factorial(a)/factorial(a-b));
}

/*
    recursive function definition for finding
    factorial of a number
*/
long factorial(int c)
{
    if(c == 1 || c == 0)
        return 1;
    else
        return c*factorial(c-1);
}

C Program to Display the current Date and Time

#include<stdio.h>
#include<time.h>

void main()
{
  time_t t;   // not a primitive datatype
    time(&t);
clrscr();
    printf("\n\n\t\tStudytonight - Best place to learn\n\n\n");

    printf("\nThis program has been writeen at (date and time): %s", ctime(&t));

    printf("\n\n\t\t\tCoding is Fun !\n\n\n");
getch();
}


C Program to remove Duplicate Element in an Array

#include<stdio.h>
#include<conio.h>
void main()
{
    int a[20], i, j, k, n;
    clrscr();

    printf("\nEnter array size: ");
    scanf("%d", &n);

    printf("\nEnter %d array element: ", n);
    for(i = 0; i < n; i++)
    {
        scanf("%d", &a[i]);
    }

    printf("\nOriginal array is: ");
    for(i = 0; i < n; i++)
    {
        printf(" %d", a[i]);
    }

    printf("\nNew array is: ");
    for(i = 0; i < n; i++)
    {
        for(j = i+1; j < n; )
        {
            if(a[j] == a[i])
            {
                for(k = j; k < n; k++)
                {
                    a[k] = a[k+1];
                }
                n--;
            }
            else
            {
                j++;
            }
        }
    }

    for(i = 0; i < n; i++)
    {
        printf("%d ", a[i]);
    }
    getch();
}

OUTPUT:-

Wednesday, 6 June 2018

Tic-Tac-Toe Game using C program

#include<stdio.h>
#include<conio.h>
void main()
{
int i = 0;                                   /* Loop counter                         */
int player = 0;                              /* Player number - 1 or 2               */
int go = 0;                                  /* Square selection number for turn     */
int row = 0;                                 /* Row index for a square               */
int column = 0;                              /* Column index for a square            */
int line = 0;                                /* Row or column index in checking loop */
int winner = 0;                              /* The winning player                   */
char board[3][3] = {                         /* The board                            */
{'1','2','3'},          /* Initial values are reference numbers */
{'4','5','6'},          /* used to select a vacant square for   */
{'7','8','9'}           /* a turn.                              */
};

clrscr();
/* The main game loop. The game continues for up to 9 turns */
/* As long as there is no winner                            */
for( i = 0; i<9 && winner==0; i++)
{
/* Display the board */
printf("\n\n");
printf(" %c | %c | %c\n", board[0][0], board[0][1], board[0][2]);
printf("---+---+---\n");
printf(" %c | %c | %c\n", board[1][0], board[1][1], board[1][2]);
printf("---+---+---\n");
printf(" %c | %c | %c\n", board[2][0], board[2][1], board[2][2]);

player = i%2 + 1;                           /* Select player */

/* Get valid player square selection */
do
{
printf("\nPlayer %d, please enter the number of the square "
"where you want to place your %c: ", player,(player==1)?'X':'O');
scanf("%d", &go);

row = --go/3;                                 /* Get row index of square      */
column = go%3;                                /* Get column index of square   */
}while(go<0 || go>9 || board[row][column]>'9');

board[row][column] = (player == 1) ? 'X' : 'O';        /* Insert player symbol   */

/* Check for a winning line - diagonals first */
if((board[0][0] == board[1][1] && board[0][0] == board[2][2]) ||
(board[0][2] == board[1][1] && board[0][2] == board[2][0]))
winner = player;
else
/* Check rows and columns for a winning line */
for(line = 0; line <= 2; line ++)
if((board[line][0] == board[line][1] && board[line][0] == board[line][2])||
(board[0][line] == board[1][line] && board[0][line] == board[2][line]))
winner = player;

}
/* Game is over so display the final board */
printf("\n\n");
printf(" %c | %c | %c\n", board[0][0], board[0][1], board[0][2]);
printf("---+---+---\n");
printf(" %c | %c | %c\n", board[1][0], board[1][1], board[1][2]);
printf("---+---+---\n");
printf(" %c | %c | %c\n", board[2][0], board[2][1], board[2][2]);

/* Display result message */
if(winner == 0)
printf("\nHow boring, it is a draw\n");
else
printf("\nCongratulations, player %d, YOU ARE THE WINNER!\n",

winner);
getch():
}


Factorial of large number using C program

#include<stdio.h>

struct fact
{
long long val[10000];
int till;
int zero;
};

typedef struct fact Fact;

Fact input[10000];

int main()
{
long long temp=0,i,j,pro=0;
int va;
input[0].val[0]=1;
input[0].till=1;
for(i=1;i<1010;i++)
{
for(j=0;j<input[i-1].till;j++)
{
pro=(input[i-1].val[j]*(i+1))+temp;
if(pro>=10)
{
input[i].val[j]=(pro%10);
temp=pro/10;
input[i].till=(j+1);
}
else
{
input[i].val[j]=pro;
input[i].till=(j+1);
temp=0;
}
}
if(temp>0)
{
while(temp>0)
{
input[i].val[j]=temp%10;
temp=temp/10;
j++;
input[i].till=j;
}
}
temp=0;
}
scanf("%d",&va);
for(j=input[va-1].till-1;j>=0;j--)
{
printf("%lld",input[va-1].val[j]);
}
return 0;
}
 

Display Calender using C++ program

#include<iostream.h>
#include<conio.h>
char *months[]=

{"Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"

};
void cal(int yr,int mo,int fd,int da);
void main(){
int days[12]={31,28,31,30,31,30,31,31,30,31,30,31};
long int ndays,ldays,tdays,tydays;
int i,y,m,fday,d;
clrscr();
cout<<"Enter the YEAR & MONTH";
cin>>y>>m;
ndays=(y-1)*365l;
ldays=(y-1)/400-(y-1)/100+(y-1)/4;
tdays=ndays+ldays;
if(y%400==0&&y%1001==0||y%4==0)
days[1]=29;
else
days[1]=28;
d=days[m-1];
tydays=0;
for(i=0;i<=m-2;i++)
tydays=tydays+days[i];
tdays=tdays+tydays;
fday=tdays%7;
cal(y,m,fday,d);
}
void cal(int yr,int mo,int fd,int da)
{
int i,r,c;
clrscr();
gotoxy(25,5);
cout<<months[mo-1]<<yr;
gotoxy(5,6);
cout<<"____________________________________________________

_____";
gotoxy(10,7);
cout<<"Mon   Tue   Wed   Thur   Fri   Sat   Sun";
gotoxy(5,8);
cout<<"____________________________________________________

_____";
r=10;
c=11+fd*6;
for(i=1;i<=da;i++){
gotoxy(c,r);
cout<<i;
if(c<=41)
c=c+6;
else
{
c=11;
r=r+1;
}
}
gotoxy(5,16);
cout<<"____________________________________________________

_____";
getch();
}


Snake Game using C program

#include<stdlib.h>
#include<ctype.h>
#include<conio.h>
#include<stdio.h>
#include<time.h>
#include<dos.h>

#define ESC 27
#define UPARR 72
#define LEFTARR 75
#define DOWNARR 80
#define RIGHTARR 77
#define SAVE 60
#define LOAD 61

main()
{
void starting(void);
void make_xy(char **,char **);
void getrand(char *,char *,char *,char *,char *,int,char);
char getkey(char,char);
void savegame(char *,char *,int,char);
int loadgame(char *,char *,char *);
void win_message(void);

char

*x,*y,pos_x,pos_y,num,out=0,old_ch=0,ch=0,new_ch,new_x,new_y,old_nu

m=0;
int i,length=6;

starting();
make_xy(&x,&y);
getrand(&pos_x,&pos_y,&num,x,y,length,ch);

while(!out){
if((new_ch=getkey(old_ch,ch))==ESC)
out=2;
if(out)
break;
if(new_ch==SAVE)
savegame(x,y,length,old_ch);
else if(new_ch==LOAD){
length=loadgame(x,y,&ch);
getrand(&pos_x,&pos_y,&num,x,y,length,ch);
}
else
ch=new_ch;
new_x=x[0];
new_y=y[0];
if(ch==UPARR)
new_y=y[0]-1;
else if(ch==LEFTARR)
new_x=x[0]-1;
else if(ch==DOWNARR)
new_y=y[0]+1;
else if(ch==RIGHTARR)
new_x=x[0]+1;
old_ch=ch;
if((new_x<2)|(new_y<2)|(new_x>79)|(new_y>22))
out=1; /* HIGHEST POSSIBLE SCORE ÷ (78*21-6)*5 = 8160 ÷ 10,000 */
for(i=1;i<length-!old_num;i++) /* NOT "length": TAIL-END MAY MOVE

AWAY! */
if((new_x==x[i])&(new_y==y[i])){
out=1;
break;
}
if((pos_x==new_x)&(pos_y==new_y)){
old_num+=num;
/* x=(char *)realloc(x,(score+6)*sizeof(char));
y=(char *)realloc(y,(score+6)*sizeof(char)); */
/* if((x==0)|(y==0)) */ /* PROBLEM IS NOT HERE */
/* x=x;*//* SOMEHOW realloc ISN'T COPYING PROPERLY */
getrand(&pos_x,&pos_y,&num,x,y,length,ch);
}
if(!old_num){
gotoxy(x[length-1],y[length-1]);
putchar(' ');
}
else{
length++;
if(length==1638){
win_message();
return 0;
}
gotoxy(67,25);
printf("Score = %5d",length-6);
old_num--;
x[i+1]=x[i];
y[i+1]=y[i];
}
for(i=length-1;i>0;i--){
x[i]=x[i-1];
y[i]=y[i-1];
if(i==1){
gotoxy(x[i],y[i]);
putchar('Û');
}
}
x[0]=new_x;
y[0]=new_y;
gotoxy(x[0],y[0]);
printf(" \b"); /* USE THE FUNCTION _setcursortype() */
if(out)
break;
delay(99);
}
if(out==1){
gotoxy(1,24);
printf("The snake collided with the wall or with itself!\n"
"GAME OVER!!\t\t(Press 'q' to terminate...)");
gotoxy(x[0],y[0]);
while(toupper(getch())!='Q');
}
clrscr();
printf("Hope you enjoyed the game\n\n\t\tBye!\n");
return 0;
}

/*-------------------------------------------------------------------------*/

void starting()
{
char i;

clrscr(); /* FIRST TO DRAW A BOUNDARY for THE GAME */
putchar('É');
for(i=0;i<78;i++)
putchar('Í');
putchar('»');
gotoxy(1,23);
putchar('È');
for(i=0;i<78;i++)
putchar('Í');
putchar('¼');
window(1,2,1,23);
for(i=0;i<21;i++)
cprintf("º");
window(80,2,80,23);
for(i=0;i<21;i++)
cprintf("º"); /* THE BOUNDARY IS DRAWN */
window(1,1,80,25);
gotoxy(38,12);
printf("ÛÛÛÛÛ "); /* THE "SNAKE" IS PUT for THE FIRST TIME */
gotoxy(1,24);
printf("Welcome to the game of SNAKE!\n(Press any arrow key to start now,"
" Escape to leave at any time...)"); /* WELCOME MESSAGE */
gotoxy(43,12);
while(!kbhit());
gotoxy(30,24);
delline();delline(); /* REMOVING MESSAGE */
cprintf("\n( EAT THE NUMBER !! ) Score = 0");
gotoxy(43,12); /* GO TO THE HEAD OF THE SNAKE */
}

void make_xy(char **px,char **py)
{
char i;

*px=(char *)malloc(1638*sizeof(char)); /*EARLIER IT WAS 6, NOT 1638;

BUT*/
*py=(char *)malloc(1638*sizeof(char)); /*realloc IS NOT COPYING

PROPERLY*/
for(i=0;i<6;i++){
(*px)[i]=43-i;
(*py)[i]=12;
} /* THE TWO ARRAYS for COORDINATES OF THE SNAKE ARE

SIMULATED */
}

void getrand(char *px,char *py,char *pn,char *x,char *y,int length,char ch)
{
int allowed=0,i; /* i AND length MUST BE int */

while(!allowed){
allowed=1;
srand((unsigned)time(0));
*px=rand()%78+2; /* GENERATING RANDOM POSITIONAL

COORDINATES for */
srand((unsigned)time(0));
*py=rand()%21+2; /* PUTTING A RANDOM NUMBER */
if(ch==UPARR){
if((*px==x[0])&(*py==y[0]-1))
allowed=0;
}
else if(ch==DOWNARR){
if((*px==x[0])&(*py==y[0]+1))
allowed=0;
}
else if(ch==LEFTARR){
if((*px==x[0]-1)&(*py==y[0]))
allowed=0;
}
else if((ch==RIGHTARR)&(*px==x[0]+1)&(*py==y[0]))
allowed=0;
for(i=0;(i<length)&&allowed;i++)
if((*px==x[i])&(*py==y[i]))
allowed=0;
} /* THE RANDOM NUMBER GENERATED SHOULD NOT BE PUT

ON SNAKE'S BODY */
srand((unsigned)time(0));
*pn=rand()%9+1; /* THE NUMBER */
gotoxy(*px,*py);
putchar(*pn+48);
gotoxy(x[0],y[0]);
}

char getkey(char old_ch,char ch)
{
char i;

if(kbhit())
for(i=0;i<5;i++){ /* if i too low, takes too many keystrokes */
while((ch=getch())==0);
if(ch==27){
/* out=2;
i=5;
break;*/return ch;
}
if((ch!=LOAD)&(ch!=SAVE)&(ch!=UPARR)&(ch!=DOWNARR)&
(ch!=LEFTARR)&(ch!=RIGHTARR))
continue;
if((ch!=old_ch)|(!kbhit()))
break;
}
else
for(i=0;(i<12)&(!kbhit());i++)
delay(100);
return ch;
}

void savegame(char *px,char *py,int length,char ch)
{
FILE *fp;
int i;

rename("snake.sav","snake.bak");
fp=fopen("snake.sav","wb");
fprintf(fp,"%d %c",length,ch);
for(i=0;i<length;i++)
fprintf(fp,"%c%c",px[i],py[i]);
fclose(fp);
}

int loadgame(char *px,char *py,char *pch)
{
FILE *fp;
int length,i;

fp=fopen("snake.sav","rb");
if(!fp){
clrscr();
puts("ERROR: no saved game found in current directory!!!\n\n\t\t"
"Exiting...\n");
sleep(3);
exit(1);
}
window(2,2,79,22);
clrscr();
/* fscanf(fp,"%d %c ",&length,pch);*/
fscanf(fp,"%d %c",&length,pch);
for(i=0;i<length;i++){
/* fscanf(fp,"%d %d ",&px[length],&py[length]);*/
fscanf(fp,"%c%c",&px[i],&py[i]);
gotoxy(px[i]-1,py[i]-1);
putchar('Û');
}
window(1,1,80,25);
gotoxy(30,24);
delline();delline(); /* REMOVING MESSAGE */
cprintf("\n( EAT THE NUMBER !! ) Score = %5d",length-6);
gotoxy(px[0],py[0]);
printf(" \b");
fclose(fp);
return length;
}

void win_message()
{
window(1,1,80,25);
gotoxy(1,24);
delline();delline();
textcolor(14);
cprintf("CONGRATULATION!! YOU HAVE COMPLETED THE GAME!!

\r\n"
"(Press any key to terminate...)");
clrscr();
textcolor(7);
}


Battleship game in C

#include <stdio.h>
#include <stdlib.h>

void startBoard(int board[][5])
{
    int line, column;
        for(line=0 ; line < 5 ; line++ )
            for(column=0 ; column < 5 ; column++ )
                board[line][column]=-1;
}

void showBoard(int board[][5])
{

    int line, column;

        printf("\t1 \t2 \t3 \t4 \t5");
        printf("\n");

        for(line=0 ; line < 5 ; line++ ){
            printf("%d",line+1);
            for(column=0 ; column < 5 ; column++ ){
                if(board[line][column]==-1){
                    printf("\t~");
                }else if(board[line][column]==0){
                    printf("\t*");
                }else if(board[line][column]==1){
                    printf("\tX");
                }

            }
            printf("\n");
        }

    }

void startShips(int ships[][2]){
 int ship, last;
    srand(time(NULL));


        for(ship=0 ; ship < 3 ; ship++){
            ships[ship][0]= rand()%5;
            ships[ship][1]= rand()%5;

            //let's check if this shot was not tried
            //if it was, just get out of the 'do while' loop when draws a pair that was not tried
            for(last=0 ; last < ship ; last++){
                if( (ships[ship][0] == ships[last][0])&&(ships[ship][1] == ships[last][1]) )
                    do{
                        ships[ship][0]= rand()%5;
                        ships[ship][1]= rand()%5;
                    }while( (ships[ship][0] == ships[last][0])&&(ships[ship][1] == ships[last][1]) );
            }

        }
    }

void giveShot(int shot[2])
{

        printf("Line: ");
        scanf("%d",&shot[0]);
        shot[0]--;

        printf("Column: ");
        scanf("%d",&shot[1]);
        shot[1]--;

}

int hitship(int shot[2], int ships[][2])
{
    int ship;

        for(ship=0 ; ship < 3 ; ship++){
            if( shot[0]==ships[ship][0] && shot[1]==ships[ship][1]){
                printf("You hit a ship with the shot (%d,%d)\n",shot[0]+1,shot[1]+1);
                return 1;
            }
        }
        return 0;
    }

void tip(int shot[2], int ships[][2], int attempt)
{
        int line=0,
            column=0,
            row;

        //count how many ships there is line/column
        for(row=0 ; row < 3 ; row++){
            if(ships[row][0]==shot[0])
                line++;
            if(ships[row][1]==shot[1])
                column++;
        }

        printf("\nDica %d: \nline %d -> %d ships\ncolumn %d -> %d ships\n",attempt,shot[0]+1,line,shot[1]+1,column);
}

void changeBoard(int shot[2], int ships[][2], int board[][5]){
        if(hitship(shot,ships))
            board[shot[0]][shot[1]]=1;
        else
            board[shot[0]][shot[1]]=0;
    }

int main() {
        int board[5][5];
        int ships[3][2];
        int shot[2];
        int attempts=0,
            hits=0;

        startBoard(board);
        startShips(ships);

        printf("\n");

        do{
            showBoard(board);
            giveShot(shot);
            attempts++;

            if(hitship(shot,ships)){
                tip(shot,ships,attempts);
                hits++;
            }
            else
                tip(shot,ships,attempts);

            changeBoard(shot,ships,board);


        }while(hits!=3);

        printf("\n\n\nFinished game. You hit the three ships in %d attempts", attempts);
        showBoard(board);
    }

Calculator Application

// Calculator example using C code
#include<stdio.h>
#include<conio.h>
#include<math.h>
#include<stdlib.h>

#define KEY "Enter the calculator Operation you want to do:"

// Function prototype declaration
void addition();
void subtraction();
void multiplication();
void division();
void modulus();
void power();
int factorial();
void calculator_operations();

// Start of Main Program
int main()
{
    int X=1;
    char Calc_oprn;

    // Function call
    calculator_operations();

    while(X)
    {
        printf("\n");
        printf("%s : ", KEY);

        Calc_oprn=getche();

        switch(Calc_oprn)
        {
            case '+': addition();
                      break;

            case '-': subtraction();
                      break;

            case '*': multiplication();
                      break;

            case '/': division();
                      break;

            case '?': modulus();
                      break;

            case '!': factorial();
                      break;

            case '^': power();
                      break;

            case 'H':
            case 'h': calculator_operations();
                      break;

            case 'Q':
            case 'q': exit(0);
                      break;
            case 'c':
            case 'C': system("cls");
                      calculator_operations();
                      break;

            default : system("cls");

    printf("\n**********You have entered unavailable option");
    printf("***********\n");
    printf("\n*****Please Enter any one of below available ");
    printf("options****\n");
                      calculator_operations();
        }
    }
}

//Function Definitions

void calculator_operations()
{
    //system("cls");  use system function to clear
    //screen instead of clrscr();
    printf("\n             Welcome to C calculator \n\n");

    printf("******* Press 'Q' or 'q' to quit ");
    printf("the program ********\n");
    printf("***** Press 'H' or 'h' to display ");
    printf("below options *****\n\n");
    printf("Enter 'C' or 'c' to clear the screen and");
    printf(" display available option \n\n");

    printf("Enter + symbol for Addition \n");
    printf("Enter - symbol for Subtraction \n");
    printf("Enter * symbol for Multiplication \n");
    printf("Enter / symbol for Division \n");
    printf("Enter ? symbol for Modulus\n");
    printf("Enter ^ symbol for Power \n");
    printf("Enter ! symbol for Factorial \n\n");
}

void addition()
{
    int n, total=0, k=0, number;
    printf("\nEnter the number of elements you want to add:");
    scanf("%d",&n);
    printf("Please enter %d numbers one by one: \n",n);
    while(k<n)
    {
        scanf("%d",&number);
        total=total+number;
        k=k+1;
    }
    printf("Sum of %d numbers = %d \n",n,total);
}

void subtraction()
{
    int a, b, c = 0;
    printf("\nPlease enter first number  : ");
    scanf("%d", &a);
    printf("Please enter second number : ");
    scanf("%d", &b);
    c = a - b;
    printf("\n%d - %d = %d\n", a, b, c);
}

void multiplication()
{
    int a, b, mul=0;
    printf("\nPlease enter first numb   : ");
    scanf("%d", &a);
    printf("Please enter second number: ");
    scanf("%d", &b);
    mul=a*b;
    printf("\nMultiplication of entered numbers = %d\n",mul);
}

void division()
{
    int a, b, d=0;
    printf("\nPlease enter first number  : ");
    scanf("%d", &a);
    printf("Please enter second number : ");
    scanf("%d", &b);
    d=a/b;
    printf("\nDivision of entered numbers=%d\n",d);
}

void modulus()
{
    int a, b, d=0;
    printf("\nPlease enter first number   : ");
    scanf("%d", &a);
    printf("Please enter second number  : ");
    scanf("%d", &b);
    d=a%b;
    printf("\nModulus of entered numbers = %d\n",d);
}

void power()
{
    double a,num, p;
    printf("\nEnter two numbers to find the power \n");
    printf("number: ");
    scanf("%lf",&a);

    printf("power : ");
    scanf("%lf",&num);

    p=pow(a,num);

    printf("\n%lf to the power %lf = %lf \n",a,num,p);
}

int factorial()
{
    int i,fact=1,num;

    printf("\nEnter a number to find factorial : ");
    scanf("%d",&num);

    if (num<0)
    {
        printf("\nPlease enter a positive number to");
        printf(" find factorial and try again. \n");
        printf("\nFactorial can't be found for negative");
        printf(" values. It can be only positive or 0  \n");
        return 1;
    }              

    for(i=1;i<=num;i++)
    fact=fact*i;
    printf("\n");
    printf("Factorial of entered number %d is:%d\n",num,fact);
    return 0;
}

OUTPUT:-

Program to read text from a file

#include <stdio.h>
#include <stdlib.h> // For exit() function
void main()
{
    char c[1000];
    FILE *fptr;
clrscr();
    if ((fptr = fopen("program.txt", "r")) == NULL)
    {
    printf("Error! opening file");
    // Program exits if file pointer returns NULL.
    exit(1);
    }

    // reads text until newline
    fscanf(fptr,"%[^\n]", c);

    printf("Data from the file:\n%s", c);
    fclose(fptr);
    getch();
}

OUTPUT:-

Calculate Length of String without Using strlen() Function

#include <stdio.h>
void main()
{
    char s[1000], i;
    clrscr();
    printf("Enter a string: ");
    scanf("%s", s);

    for(i = 0; s[i] != '\0'; ++i);

    printf("Length of string: %d", i);
    getch();
}


Remove Characters in String Except Alphabets

#include<stdio.h>

int main()
{
    char line[150];
    int i, j;
    printf("Enter a string: ");
    gets(line);

    for(i = 0; line[i] != '\0'; ++i)
    {
        while (!( (line[i] >= 'a' && line[i] <= 'z') || (line[i] >= 'A' && line[i] <= 'Z') || line[i] == '\0') )
        {
            for(j = i; line[j] != '\0'; ++j)
            {
                line[j] = line[j+1];
            }
            line[j] = '\0';
        }
    }
    printf("Output String: ");
    puts(line);
    return 0;
}

OUTPUT:-

Tuesday, 5 June 2018

C Program without main() function

#include<stdio.h>   
 #define start main   
void start() {   
   printf("Hello");   
}

OUTPUT:-
                         Hello

C Program to convert Number in Characters

#include<stdio.h>   
#include<stdlib.h> 
int main()

   long int n,sum=0,r;   
   system("cls"); 
   printf("enter the number=");   
   scanf("%ld",&n);   
   while(n>0)   
  {   
    r=n%10;   
    sum=sum*10+r;   
    n=n/10;   
   }   
    n=sum;   
    while(n>0)   
    {   
       r=n%10;   
       switch(r)   
      {   
       case 1:   
        printf("one ");   
        break;   
       case 2:   
       printf("two ");   
       break;   
       case 3:   
       printf("three ");   
       break;   
       case 4:   
      printf("four ");   
      break;   
      case 5:   
      printf("five ");   
      break;   
      case 6:   
      printf("six ");   
      break;   
      case 7:   
     printf("seven ");   
     break;   
     case 8:   
     printf("eight ");   
     break;   
     case 9:   
     printf("nine ");   
     break;   
     case 0:   
     printf("zero ");   
     break;   
     default:   
     printf("Invalid choice!");   
     break;   
    }   
    n=n/10;   
  }   
   return 0; 
}  

C Program to print Alphabet Triangle

#include<stdio.h>   
#include<stdlib.h> 
int main(){ 
  int ch=65;   
    int i,j,k,m;   
  system("cls"); 
    for(i=1;i<=5;i++)   
    {   
        for(j=5;j>=i;j--)   
            printf(" ");   
        for(k=1;k<=i;k++)   
            printf("%c",ch++);   
            ch--;   
        for(m=1;m<i;m++)   
            printf("%c",--ch);   
        printf("\n");   
        ch=65;   
    }   
return 0; 


OUTPUT:-


C PROGRAMMING CODE FOR BANK APPLICATION

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

// Structure declaration
struct acc_type
{
     char bank_name[20];
     char bank_branch[20];
     char acc_holder_name[30];
     int acc_number;
     char acc_holder_address[100];
     float available_balance;   
};
struct acc_type account[20];

/*
     printf("The above structure can be declared using
     typedef like below");

     typedef struct acc_type
     {
        char bank_name[20];
        char bank_branch[20];
        char acc_holder_name[30];
        int acc_number;
        char acc_holder_address[100];
        float available_balance;   
     }Acc_detail;

     Acc_detail account[20];
*/

int num_acc;

void Create_new_account();
void Cash_Deposit();
void Cash_withdrawl();
void Account_information();
void Log_out();
void display_options();

/* main program */
int main()
{
    char option;
    char f2f[50] = "http://fresh2refresh.com/";
    num_acc=0;
    while(1)
    {
       printf("\n***** Welcome to Bank Application *****\n");
       printf("\nThis demo program is brought you by %s",f2f);
       display_options();
       printf("Please enter any options (1/2/3/4/5/6) ");
       printf("to continue : ");

        option = getch();
        printf("%c \n", option);
        switch(option)
        {
          case '1': Create_new_account();
                    break;
          case '2': Cash_Deposit();
                    break;
          case '3': Cash_withdrawl();
                    break;
          case '4': Account_information();
                    break;
          case '5': return 0;
          case '6': system("cls");
                    break;
          default : system("cls");
                    printf("Please enter one of the options");
                    printf("(1/2/3/4/5/6) to continue \n ");
                    break;
        }
    }
    return 0;
}

/*Function to display available options in this application*/

void display_options()
{
    printf("\n1. Create new account \n");
    printf("2. Cash Deposit \n");
    printf("3. Cash withdrawl \n");
    printf("4. Account information \n");
    printf("5. Log out \n");
    printf("6. Clear the screen and display available ");
    printf("options \n\n");
}

/* Function to create new account */

void Create_new_account()
{
   char bank_name[20];
   char bank_branch[20];
   char acc_holder_name[30];
   int acc_number;
   char acc_holder_address[100];
   float available_balance = 0;
   fflush(stdin);   
   printf("\nEnter the bank name              : ");
   scanf("%s", &bank_name);
   printf("\nEnter the bank branch            : ");
   scanf("%s", &bank_branch);
   printf("\nEnter the account holder name    : ");
   scanf("%s", &acc_holder_name);
   printf("\nEnter the account number(1 to 10): ");
   scanf("%d", &acc_number);
   printf("\nEnter the account holder address : ");
   scanf("%s", &acc_holder_address);

   strcpy(account[acc_number-1].bank_name,bank_name);
   strcpy(account[acc_number-1].bank_branch,bank_branch);
   strcpy(account[acc_number-1].acc_holder_name,
   acc_holder_name);
   account[acc_number-1].acc_number=acc_number;
   strcpy(account[acc_number-1].acc_holder_address,
   acc_holder_address);
   account[acc_number-1].available_balance=available_balance;

   printf("\nAccount has been created successfully \n\n");
   printf("Bank name              : %s \n" ,
   account[acc_number-1].bank_name);
   printf("Bank branch            : %s \n" ,
   account[acc_number-1].bank_branch);
   printf("Account holder name    : %s \n" ,
   account[acc_number-1].acc_holder_name);
   printf("Account number         : %d \n" ,
   account[acc_number-1].acc_number);
   printf("Account holder address : %s \n" ,
   account[acc_number-1].acc_holder_address);
   printf("Available balance      : %f \n" ,
   account[acc_number-1].available_balance);

   //num_acc++;

}

// Displaying account informations

void Account_information()
{
     register int num_acc = 0;
     //if (!strcmp(customer,account[count].name))
     while(strlen(account[num_acc].bank_name)>0)
     {
         printf("\nBank name                : %s \n" ,
         account[num_acc].bank_name);
         printf("Bank branch              : %s \n" ,
         account[num_acc].bank_branch);
         printf("Account holder name      : %s \n" ,
         account[num_acc].acc_holder_name);
         printf("Account number           : %d \n" ,
         account[num_acc].acc_number);
         printf("Account holder address   : %s \n" ,
         account[num_acc].acc_holder_address);
         printf("Available balance        : %f \n\n" ,
         account[num_acc].available_balance);
         num_acc++;
     }
}

// Function to deposit amount in an account

void Cash_Deposit()
{
   auto int acc_no;
   float add_money;

   printf("Enter account number you want to deposit money:");
   scanf("%d",&acc_no);
   printf("\nThe current balance for account %d is %f \n",
   acc_no, account[acc_no-1].available_balance);
   printf("\nEnter money you want to deposit :  ");
   scanf("%f",&add_money);

   while (acc_no=account[acc_no-1].acc_number)
   {
         account[acc_no-1].available_balance=
         account[acc_no-1].available_balance+add_money;
         printf("\nThe New balance for account %d is %f \n",
         acc_no, account[acc_no-1].available_balance);
         break;
   }acc_no++;
}

// Function to withdraw amount from an account

void Cash_withdrawl()
{
   auto int acc_no;
   float withdraw_money;

   printf("Enter account number you want to withdraw money:");
   scanf("%d",&acc_no);
   printf("\nThe current balance for account %d is %f \n",
   acc_no, account[acc_no-1].available_balance);
   printf("\nEnter money you want to withdraw from account ");
   scanf("%f",&withdraw_money);

   while (acc_no=account[acc_no-1].acc_number)
   {
         account[acc_no-1].available_balance=
         account[acc_no-1].available_balance-withdraw_money;
         printf("\nThe New balance for account %d is %f \n",
         acc_no, account[acc_no-1].available_balance);
         break;
   }acc_no++;
}


C program to print number from 1 to 500 without using any loop conditions:

1. Using recursive functions:

#include<stdio.h>
int recursive(int value)
{
      int i;
      printf("%d\n", value);
      i = value + 1;
      if (i > 500)
          return 0;
      recursive(i);
}

int main() 
{
      recursive(1);
      return 0;
}

2. Using recursive main functions:

#include<stdio.h>
int main() 
{
      static int i = 1;
      if (i <= 500) 
      {
          printf("%d\n", i++);
          main();
      }
      return 0;
}

3. Using goto statement:

#include<stdio.h>
int main() 
{
      int i = 0;
      Start: i = i + 1;
      printf("%d\n", i);
      if (i < 500)
           goto Start;
      return 0;
}

4. Using printf statement (But it's not preferred for printing big numbers):