The Mind Reader Game


/*NOTE THAT THE GAME WORKS ONLY IN TURBO C ENVIRONMENT IF YOU WANT TO RUN THE PROGRAM IN ANY OTHER ENVIRONMENT THEN THEN YOU HAVE TO DOWNLOAD THE WINBGI SOFTWARE AND ALSO FOLLOW THE INSTRUUCTION ONLINE */
#include<conio.h>
#include<stdio.h>
#include<dos.h>
#include<stdlib.h>
void First_Card(void);
void Second_Card(void);
void Third_Card(void);
void Fourth_Card(void);
void Fifth_Card(void);
void Sixth_Card(void);
void Analyze(void);
int Check(void);
int main()
{
      clrscr();
      int ans=0,in=0;
   _setcursortype(_NOCURSOR);
   First_Card();
     in=Check(); if (in==0) ans+=1;
   Second_Card();
     in=Check(); if (in==0) ans+=2;
   Third_Card();
     in=Check(); if (in==0) ans+=4;
   Fourth_Card();
     in=Check(); if (in==0) ans+=8;
   Fifth_Card();
     in=Check(); if (in==0) ans+=16;
   Sixth_Card();
     in=Check(); if (in==0) ans+=32;
     textcolor(WHITE);textbackground(BLACK);
     clrscr(); Analyze();     clrscr();
   if(ans>60) {gotoxy(20,12);printf(“You Entered Incorrect Information.”);}
   else
   {
       gotoxy(28,13);printf(“Your No Is : \”%d\””,ans);}
   gotoxy(20,14);printf(“Thanks For Using This Program… “);
   gotoxy(30,22);printf(“Made By : “);
   gotoxy(37,23);printf(“ANIMESH SHAW”);getch();return 0;
}
void First_Card(void)
{
gotoxy(25,6);  printf(“ÉÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍ»”);
gotoxy(25,7);  printf(“º  C O M P U T E R   G A M E  º”);
gotoxy(25,8);  printf(“ÌÍÍÍÍËÍÍÍÍËÍÍÍÍËÍÍÍÍËÍÍÍÍËÍÍÍ͹”);
gotoxy(25,9);  printf(“º 1  º 3  º 5  º 7  º 9  º 11 º”);
gotoxy(25,10); printf(“ÌÍÍÍÍÎÍÍÍÍÎÍÍÍÍÎÍÍÍÍÎÍÍÍÍÎÍÍÍ͹”);
gotoxy(25,11); printf(“º 13 º 15 º 17 º 19 º 21 º 23 º”);
gotoxy(25,12); printf(“ÌÍÍÍÍÎÍÍÍÍÎÍÍÍÍÎÍÍÍÍÎÍÍÍÍÎÍÍÍ͹”);
gotoxy(25,13); printf(“º 25 º 27 º 29 º 31 º 33 º 35 º”);
gotoxy(25,14); printf(“ÌÍÍÍÍÎÍÍÍÍÎÍÍÍÍÎÍÍÍÍÎÍÍÍÍÎÍÍÍ͹”);
gotoxy(25,15); printf(“º 37 º 39 º 41 º 43 º 45 º 47 º”);
gotoxy(25,16); printf(“ÌÍÍÍÍÎÍÍÍÍÎÍÍÍÍÎÍÍÍÍÎÍÍÍÍÎÍÍÍ͹”);
gotoxy(25,17); printf(“º 49 º 51 º 53 º 55 º 57 º 59 º”);
gotoxy(25,18); printf(“ÈÍÍÍÍÊÍÍÍÍÊÍÍÍÍÊÍÍÍÍÊÍÍÍÍÊÍÍÍͼ”);
}
void Second_Card(void)
{
gotoxy(25,6);  printf(“ÉÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍ»”);
gotoxy(25,7);  printf(“º  C O M P U T E R   G A M E  º”);
gotoxy(25,8);  printf(“ÌÍÍÍÍËÍÍÍÍËÍÍÍÍËÍÍÍÍËÍÍÍÍËÍÍÍ͹”);
gotoxy(25,9);  printf(“º 2  º 3  º 6  º 7  º 10 º 11 º”);
gotoxy(25,10); printf(“ÌÍÍÍÍÎÍÍÍÍÎÍÍÍÍÎÍÍÍÍÎÍÍÍÍÎÍÍÍ͹”);
gotoxy(25,11); printf(“º 14 º 15 º 18 º 19 º 22 º 23 º”);
gotoxy(25,12); printf(“ÌÍÍÍÍÎÍÍÍÍÎÍÍÍÍÎÍÍÍÍÎÍÍÍÍÎÍÍÍ͹”);
gotoxy(25,13); printf(“º 25 º 27 º 30 º 31 º 34 º 35 º”);
gotoxy(25,14); printf(“ÌÍÍÍÍÎÍÍÍÍÎÍÍÍÍÎÍÍÍÍÎÍÍÍÍÎÍÍÍ͹”);
gotoxy(25,15); printf(“º 38 º 39 º 42 º 43 º 46 º 47 º”);
gotoxy(25,16); printf(“ÌÍÍÍÍÎÍÍÍÍÎÍÍÍÍÎÍÍÍÍÎÍÍÍÍÎÍÍÍ͹”);
gotoxy(25,17); printf(“º 50 º 51 º 54 º 55 º 58 º 59 º”);
gotoxy(25,18); printf(“ÈÍÍÍÍÊÍÍÍÍÊÍÍÍÍÊÍÍÍÍÊÍÍÍÍÊÍÍÍͼ”);
}
void Third_Card(void)
{
gotoxy(25,6);  printf(“ÉÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍ»”);
gotoxy(25,7);  printf(“º  C O M P U T E R   G A M E  º”);
gotoxy(25,8);  printf(“ÌÍÍÍÍËÍÍÍÍËÍÍÍÍËÍÍÍÍËÍÍÍÍËÍÍÍ͹”);
gotoxy(25,9);  printf(“º 4  º 5  º 6  º 7  º 12 º 13 º”);
gotoxy(25,10); printf(“ÌÍÍÍÍÎÍÍÍÍÎÍÍÍÍÎÍÍÍÍÎÍÍÍÍÎÍÍÍ͹”);
gotoxy(25,11); printf(“º 14 º 15 º 20 º 21 º 22 º 23 º”);
gotoxy(25,12); printf(“ÌÍÍÍÍÎÍÍÍÍÎÍÍÍÍÎÍÍÍÍÎÍÍÍÍÎÍÍÍ͹”);
gotoxy(25,13); printf(“º 28 º 29 º 30 º 31 º 36 º 37 º”);
gotoxy(25,14); printf(“ÌÍÍÍÍÎÍÍÍÍÎÍÍÍÍÎÍÍÍÍÎÍÍÍÍÎÍÍÍ͹”);
gotoxy(25,15); printf(“º 38 º 39 º 44 º 45 º 46 º 47 º”);
gotoxy(25,16); printf(“ÌÍÍÍÍÎÍÍÍÍÎÍÍÍÍÎÍÍÍÍÎÍÍÍÍÎÍÍÍ͹”);
gotoxy(25,17); printf(“º 52 º 53 º 54 º 55 º 60 º 60 º”);
gotoxy(25,18); printf(“ÈÍÍÍÍÊÍÍÍÍÊÍÍÍÍÊÍÍÍÍÊÍÍÍÍÊÍÍÍͼ”);
}
void Fourth_Card(void)
{
gotoxy(25,6);  printf(“ÉÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍ»”);
gotoxy(25,7);  printf(“º  C O M P U T E R   G A M E  º”);
gotoxy(25,8);  printf(“ÌÍÍÍÍËÍÍÍÍËÍÍÍÍËÍÍÍÍËÍÍÍÍËÍÍÍ͹”);
gotoxy(25,9);  printf(“º 8  º 9  º 10 º 11 º 12 º 13 º”);
gotoxy(25,10); printf(“ÌÍÍÍÍÎÍÍÍÍÎÍÍÍÍÎÍÍÍÍÎÍÍÍÍÎÍÍÍ͹”);
gotoxy(25,11); printf(“º 14 º 15 º 24 º 25 º 26 º 27 º”);
gotoxy(25,12); printf(“ÌÍÍÍÍÎÍÍÍÍÎÍÍÍÍÎÍÍÍÍÎÍÍÍÍÎÍÍÍ͹”);
gotoxy(25,13); printf(“º 28 º 29 º 30 º 31 º 40 º 41 º”);
gotoxy(25,14); printf(“ÌÍÍÍÍÎÍÍÍÍÎÍÍÍÍÎÍÍÍÍÎÍÍÍÍÎÍÍÍ͹”);
gotoxy(25,15); printf(“º 42 º 43 º 44 º 45 º 46 º 47 º”);
gotoxy(25,16); printf(“ÌÍÍÍÍÎÍÍÍÍÎÍÍÍÍÎÍÍÍÍÎÍÍÍÍÎÍÍÍ͹”);
gotoxy(25,17); printf(“º 56 º 57 º 58 º 59 º 60 º 60 º”);
gotoxy(25,18); printf(“ÈÍÍÍÍÊÍÍÍÍÊÍÍÍÍÊÍÍÍÍÊÍÍÍÍÊÍÍÍͼ”);
}
void Fifth_Card(void)
{
gotoxy(25,6);  printf(“ÉÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍ»”);
gotoxy(25,7);  printf(“º  C O M P U T E R   G A M E  º”);
gotoxy(25,8);  printf(“ÌÍÍÍÍËÍÍÍÍËÍÍÍÍËÍÍÍÍËÍÍÍÍËÍÍÍ͹”);
gotoxy(25,9);  printf(“º 16 º 17 º 18 º 19 º 20 º 21 º”);
gotoxy(25,10); printf(“ÌÍÍÍÍÎÍÍÍÍÎÍÍÍÍÎÍÍÍÍÎÍÍÍÍÎÍÍÍ͹”);
gotoxy(25,11); printf(“º 22 º 23 º 24 º 25 º 26 º 27 º”);
gotoxy(25,12); printf(“ÌÍÍÍÍÎÍÍÍÍÎÍÍÍÍÎÍÍÍÍÎÍÍÍÍÎÍÍÍ͹”);
gotoxy(25,13); printf(“º 28 º 29 º 30 º 31 º 48 º 49 º”);
gotoxy(25,14); printf(“ÌÍÍÍÍÎÍÍÍÍÎÍÍÍÍÎÍÍÍÍÎÍÍÍÍÎÍÍÍ͹”);
gotoxy(25,15); printf(“º 50 º 51 º 52 º 53 º 54 º 55 º”);
gotoxy(25,16); printf(“ÌÍÍÍÍÎÍÍÍÍÎÍÍÍÍÎÍÍÍÍÎÍÍÍÍÎÍÍÍ͹”);
gotoxy(25,17); printf(“º 56 º 57 º 58 º 59 º 60 º 60 º”);
gotoxy(25,18); printf(“ÈÍÍÍÍÊÍÍÍÍÊÍÍÍÍÊÍÍÍÍÊÍÍÍÍÊÍÍÍͼ”);
}
void Sixth_Card(void)
{
gotoxy(25,6);  printf(“ÉÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍ»52 º 53 º 54 º 55 º”);
gotoxy(25,16); printf(“ÌÍÍÍÍÎÍÍÍÍÎÍÍÍÍÎÍÍÍÍÎÍÍÍÍÎÍÍÍ͹”);
gotoxy(25,17); printf(“º 56 º 57 º 58 º 59 º 60 º 60 º”);
gotoxy(25,18); printf(“ÈÍÍÍÍÊÍÍÍÍÊÍÍÍÍÊÍÍÍÍÊÍÍÍÍÊÍÍÍͼ”);
}
 int Check(void)
{
  int loop,key,index=0;
  char *menu[]={” Yes “,” No “};
  textcolor(WHITE);
  textbackground(CYAN);
  while(1)
  { for (loop=0;loop<2;loop++)
    { if (loop==index)
textbackground(YELLOW);
      else
textbackground(CYAN);
      gotoxy(33+loop*10,20);cprintf(“%s”,menu[loop]);
    }
    key=getch();
    switch(key)
    { case 75:
index–;if (index<0) index=1;break;
      case 77:
index++;if (index>1) index=0;break;
      case 13: return index;
    }
  }
}
void Analyze(void)
{
 gotoxy(30,10); printf(“Analyzing Result…”);
 gotoxy(25,11); printf(“ÉÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍ»”);
 gotoxy(25,12); printf(“º °°°°°°°°°°°°°°°°°°°°°°°°°°° º”);
 gotoxy(25,13); printf(“ÈÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍͼ”);
 for(int a=27;a<=53;a++)
 { delay(100);
   gotoxy(a,12);printf(“%c”,219);
 }
}

NUMBER MAGIC GAME


#include<stdio.h>
#include<conio.h>
int generate(void);
int fun(int);
main()
{
 int i,a,r;

 printf(“\n\nANIMESH Welcomes You!\n IN THE JARGON OF A NUMBER..”);
 printf(“\nPress any key to continue….”);
 getch();
 printf(“\n\nJust think a number between 1 to 63 in your mind”);
 printf(“\nThink on one”);
 printf(“\nDo not enter that number”);
 printf(“\n\nI will find that number on your mind….”);
 printf(“\n\nPress any key to continue…”);
 getch();
 printf(“\nBy Just answering few questions….”);
 printf(“\n\nIf your number is present in the numbers”);
 printf(“\n\nshown on your screen,Then press P and if not present”);
 printf(“\n\n then press N”);
 printf(“But please be honest while entering the answer…”);
 printf(“\n\nPress any key to continue…”);
 getch();
 r=generate();
 if(r==0)
 {
  printf(“\nYou didn’t think of any number between 1 to 63”);
  printf(“\nSo try again…”);
 }
 else
 {
 printf(“\nYour number is %d”,r);
 printf(“\nSurprised! But friends it is not a magic,”);
 printf(“\nit just involves some mathematical computation….”);
 printf(“\nso guys just try to find out the method.”);
 printf(“\nThank You!”);
 printf(“\nProgrammed By:\n\t\tAnimesh shaw”);
 }
 getch();
}
int generate()
{
 int a,i,j,f,num[6],n,r=0;
 char ch[6];
 for(j=0;j<=5;j++)
 {
  f=fun(j);
  for(i=1;i<=63;i++)
  {
   f=fun(j);
   printf(” %d”,f);
   a=i & f;
   if(a==f)
   printf(” %d”,i);
  }
  printf(“\n\n  Let me remind you if the number is present then”);
  printf(“\n press P otherwise press N”);
  printf(“\nEnter your answer: “);
  ch[j]=getche();
  printf(“\nPress any key to continue….”);
  if(ch[j]==’p’ || ch[j]==’P’)
  {
   num[j]=1;
   n=fun(j);
   r=r+n;
  }
  else
  num[j]=0;
  getch();
 }
 for(j=5;j>=0;j–)
 {
 printf(” %d”,num[j]);
 if(ch[j]==’p’ || ch[j]==’P’)
 num[j]=1;
 else
 num[j]=0;
 }
 printf(” %d”,r);
 return r;
}
int fun(int j)
{
 if(j==0)
 return 1;
 else
 return (2*fun(j-1));
}

HIGH LOW GAME


     /* HIGH/LOW GAME */
#include<iostream.h>
#include<conio.h>
#include<stdlib.h>
/*
This program plays a simple game.The computer picks a random number
from
0 to 100, and the user tries to guess the number.
*/
const int totchan=7;
main()
{
 int number;        //the computer’s random number
 int guess;         //the user’s guess
 int chances=0,score=0,chanscor;        //chanscor stores score for 1 successful chance.
 char ans;
 do
 {
   chances=score=0;
   cout<<“\nWelcome to the High/Low game.”;
   cout<<“\nI will pick a random number from 0 to 100.”;
   cout<<“\nYou must try to guess the number.”;
 
   number=(int)(rand()%100);
   chanscor=100/totchan;        //score for each successful chance
   do
   {
     cout<<“\nWhat is your guess? (0 to 100) “;
     cin>>guess;
     if((guess<0)||(guess>100))
     {
cout<<“Sorry, but your guess “<<guess<<“must be from 0 to 100.”;
     }
     else if(guess < number)
     {
cout<<guess<<” is low.Try a higher number.”;
     }
     else if(guess > number)
     {
cout<<guess<<” is high.Try a lower number.”;
     }
     else //if correct number is guessed
     { //number is correct, and the “do” loop will end below
cout<<guess<<” is correct. Congratulations!”;
score=chanscor*(totchan-chances);   //score calculated for number of chances left
cout<<“Your score is “<<score<<endl;
        break;
     }
     chances++;
     if(guess!=number)
cout<<“Now you have “<<totchan-chances<<“chances left.”<<endl;
     if(chances==totchan)
{ cout<<“Only “<<totchan<<“chances are allowed.Better luck next time”;
  cout<<“\nThe actual number was “<<number<<endl;
  break;
}
     }while (guess!=number);
     cout<<“Thank you for playing High/Low!”;
     cout<<“Want to play it again? (y/n)…”;
     cin>>ans;
   }while(ans==’y’ || ans==’Y’);
 }

FLAMES GAME


/*Program to play the game of comparing to Names and checking out
FLAMES…..Enjoy……*/
//————————ANIMESH SHAW——————————//

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

typedef struct flames
{
char c;
struct flames *next;
}flames;

char* relation(char ch);

main()
{
char s1[20],s2[20],s3[20],s4[20],f[]={“FLAMES”},ch;
int i=0,j=0,k=0,l1,l2,count=0,m=0;
flames *head,*ne2,*ne3,*ne4,*ne5,*ne6,*temp,*p;
char *relate;

printf(“\n\nEnter First Name:: “);
gets(s1);
printf(“\nEnter Second Name:: “);
gets(s2);

strcpy(s3,s1);
strcpy(s4,s2);

for(i=0;i<(l1=strlen(s1));i++)
{
for(j=0;j<(l2=strlen(s2));j++)
{
if(s1[i]==s2[j])
{
s2[j]=-1;
s3[i]=-1;
}

}
}
for(i=0;i<strlen(s3);i++)
{
if(s3[i]!=-1)
count++;
}
for(j=0;j<strlen(s2);j++)
{
if(s2[j]!=-1)
count++;
}
printf(“\n\n”);
puts(s3);
puts(s2);
printf(“\n\nLetters left are %d”,count);
printf(“\nchecking for F L A M E S…………..\n\n”);
/*Creating CLL for flames*/
head=(struct flames*)malloc(sizeof(struct flames));
ne2=(struct flames*)malloc(sizeof(struct flames));
ne3=(struct flames*)malloc(sizeof(struct flames));
ne4=(struct flames*)malloc(sizeof(struct flames));
ne5=(struct flames*)malloc(sizeof(struct flames));
ne6=(struct flames*)malloc(sizeof(struct flames));
head->c=’f’; head->next=ne2;
ne2->c=’l’; ne2->next=ne3;
ne3->c=’a’; ne3->next=ne4;
ne4->c=’m’; ne4->next=ne5;
ne5->c=’e’; ne5->next=ne6;
ne6->c=’s’; ne6->next=head;
/////displaying CLL
temp=head;
i=0;
while(i<6)
{
printf(” %c”,temp->c-32);
temp=temp->next;
i++;
}
printf(“\n”);
temp=head;
while(m<5)
{
for(i=0;i<count-2;i++)
temp=temp->next;
printf(“\nDeleting %c”,temp->next->c);
p=temp->next;
temp->next=temp->next->next;
temp=temp->next;
free(p);
m++;
}
ch=temp->c;
printf(“\n\tSo…..The Relation is :::::: “);
relate=relation(ch);
puts(relate);
printf(“\n\n”);
getch();
}
char* relation(char ch)
{
char *rel;
switch(ch)
{
case ‘f’:
return rel=”FRIENDSHIP”;
case ‘l’:
return rel=”LOVE”;
case ‘a’:
return rel=”ATTRACTION”;
case ‘m’:
return rel=”MARRIAGE”;
      case ‘e’:
return rel=”ENEMY”;
case ‘s’:
return rel=”SISTER”;
}
}

G.K. QUIZ GAME IN C


#include<iostream.h>
#include<conio.h>

main()
{

int x,y,z;
x=y=z=0;
char ch1[100],ch2,ch3,ch4,ch5,ch6,ch7,ch8,ch9,ch10,ch11;
cout<<“ Guest Enter Your Name”;
cin>>ch1;

cout<<“ Welcome “<<ch1<<“. Sobriquet is an unofficial title or name given to someone or something.”;
cout<<” Enter answer in form of ‘a’,’b’ and’c’only.”;
cout<<“ What is called as ‘ THE HOLY LAND’?\na.Jerusalem\nb.Mathura\nc.Meccan\n”;
cin>>ch2;
if(ch2==’a’)
{
x=x+10;
cout<<“\nGood Job.Your score is “<<x;

}
else
cout<<“\nSorry wrong answer.”;
getch();

cout<<“ What is called as ‘ THE ROOF OF THE WORLD’?\na.Nepal\nb.Rome\nc.Tibet”;
cin>>ch2;
if(ch2==’c’)
{
x=x+10;
cout<<“Good Job.Your score is “<<x;

}
else
cout<<“Sorry wrong answer.”;
getch();
cout<<“ What is called as ‘ THE LAND OF RISING
SUN’?
a.Chicago
b.Japan
c.Tibet
“;
cin>>ch2;
if(ch2==’b’)
{
x=x+10;
cout<<“Good Job.
Your score is “<<x;

}
else
cout<<“Sorry wrong answer.”;
getch();

cout<<“

What is called as ‘ THE GIFT OF
NILE’?
a.Chicago
b.Egypt
c.Africa
“;
cin>>ch2;
if(ch2==’b’)
{
x=x+10;
cout<<“
Your score is “<<x;

}
else
cout<<“Sorry wrong answer.”;
getch();

cout<<“

What is called as ‘ THE LAND OF MIDNIGHT
SUN’?
a.Norway
b.Japan
c.Australia
“;
cin>>ch2;
if(ch2==’a’)
{
x=x+10;
cout<<“
Your score is “<<x;

}
else
cout<<“Sorry wrong answer.”;
getch();

cout<<“

What is called as ‘ THE LAND OF
THUNDERBOLT’?
a.Bhutan
b.Canada
c.Arab
“;
cin>>ch2;
if(ch2==’a’)
{
x=x+10;
cout<<“
Your score is “<<x;

}
else
cout<<“Sorry wrong answer.”;
getch();

cout<<“

What is called as ‘ THE WINDY
CITY?
a.Jerusalem
b.Japan
c.Chicago
“;
cin>>ch2;
if(ch2==’c’)
{
x=x+10;
cout<<“
Your score is “<<x;

}
else
cout<<“Sorry wrong answer.”;
getch();

cout<<“

What is called as ‘ THE LAND OF WHITE
ELEPHANTS’?
a.Bangladesh
b.Thailand
c.India
“;
cin>>ch2;
if(ch2==’b’)
{
x=x+10;
cout<<“
Your score is “<<x;

}
else
cout<<“Sorry wrong answer.”;
getch();
cout<<“

What is called as ‘ THE CITY OF SEVEN
HILLS’?
a.Rome
b.Nilgiri Hills
c.Tibet
“;
cin>>ch2;
if(ch2==’a’)
{
x=x+10;
cout<<“
Your score is “<<x;

}
else
cout<<“Sorry wrong answer.”;
getch();

cout<<“

What is called as ‘ THE DARK
CONTIENENT’?
a.Asia
b.Australia
c.Africa
“;
cin>>ch2;
if(ch2==’c’)
{
x=x+10;
cout<<“
Your score is “<<x;

}
else
cout<<“Sorry wrong answer.”;
getch();

if(x==100)
cout<<“No cheating…… You have done this earlier also.”;
if(x==90)
cout<<“You are extremely intelligent
 Your Score is 90″;
if(x==80)
cout<<“You are intelligent
 Your Score is 80″;
if(50==x||x==70||x==60)
cout<<“You are average
 Your Score is “<<x<<“
Better luck next
time”;
else if(x<=40)
cout<<“No use…….. Not even 5 questions right”;
getch();
}

cricket team formation project


#include<iostream.h>
#include<conio.h>
#include<stdio.h>
#include<fstream.h>
#include<string.h>
#include<iomanip.h>
#include<stdlib.h>
class batsman
{
     public:
       char name[20];
       float avg,sr;
       friend team;
};
class bowler
{
    public:
      char name[20],style[5];
      float avg;
      friend team;
};
class team
{
    public:
      char tname[20];
      batsman bat[11];
      bowler bowl[11];
      void load(char *);
      void teame();
      void pedit();
      void save(char*,char*);
};
void team::load(char *fn)
{
   ifstream fin(fn);
   fin>>tname;
   for(int i = 0; i < 11; i++)
    {
       fin>>bat[i].name;
       strcpy(bowl[i].name,bat[i].name);
       fin>>bat[i].avg;
       fin>>bowl[i].avg;
       fin>>bowl[i].style;
       fin>>bat[i].sr;
    }
   fin.close();
}
void team::teame()
{

   
    cout<<“Enter new values for the attribute you want to change, else enter previous values”;
    cout<<“\n\nOld Team Name : “;
    cout<<tname;
    cout<<“\nEnter the new name for team : “;
    cin>>tname;
}
void team::pedit()
{
 
   cout<<“\t\t\t\tPLAYER LIST\n”;
   cout<<“——————————————————————————-“;
   cout<<setiosflags(ios::right);
   cout<<“\n\n”<<setw(2)<<“No”<<setw(20)<<“Name”<<endl;
   for(i = 0; i < 11; i++)
   {
      cout<<“\n”<<setw(2)<<i+1<<setw(20)<<bat[i].name;
   }
   cout<<“\n\nEnter the sr.no of player you want to edit : “;
   cin>>i;
 
   cout<<“\t\t\t\tPLAYER EDITOR\n”;
   for(int j = 0; j < 80; j++)
     cout<<“-“;
   cout<<“\n\nPrevious values : “;
   cout<<“\nPlayer name : “<<bat[i-1].name;
   cout<<“\nBatting avg : “<<bat[i-1].avg;
   cout<<“\nBowling avg : “<<bowl[i-1].avg;
   cout<<“\nBowling style : “<<bowl[i-1].style;
   cout<<“\nBatting strike rate : “<<bat[i-1].sr;
   cout<<“\n\nEnter new values for the attribute you want to change, else enter previous values\n”;
   cout<<“Name : “;
   cin>>bat[i-1].name;
   strcpy(bowl[i-1].name,bat[i-1].name);
   cout<<“Batting avg : “;
   cin>>bat[i-1].avg;
   cout<<“Bowling avg : “;
   cin>>bowl[i-1].avg;
   bostyle:
   cout<<“Bowling style : “;
   cin>>bowl[i-1].style;
   if(strcmp(bowl[i-1].style,”RF”) && strcmp(bowl[i-1].style,”LF”) && strcmp(bowl[i-1].style,”RLS”) && strcmp(bowl[i-1].style,”LLS”) && strcmp(bowl[i-1].style,”ROS”) && strcmp(bowl[i-1].style,”LOS”))
      goto bostyle;
   cout<<“Batting strike rate : “;
   cin>>bat[i-1].sr;
}
void team::save(char nf[7],char of[7] = “”)
{
   ofstream fout(nf);
   fout<<tname<<endl;
   for(int i = 0; i < 11; i++)
   {
      fout<<bat[i].name<<endl;
      fout<<bat[i].avg<<endl;
      fout<<bowl[i].avg<<endl;
      fout<<bowl[i].style<<endl;
      fout<<bat[i].sr<<endl;
   }
   fout.close();
   remove(of);
}

char teams[20][20],teamc[20][7];
void agree();
void create();
void edit();
void del();
void addplay(char*);
void list();
void blist();
void view();
int main()
{
   char choice;
   agree();
   start:
 
   list();
   cout<<“\t\t\t\t\tTEAM EDITOR\n”;
   for(int i = 0; i < 80; i++)
     cout<<“=”;
   cout<<“\n\n\t\t\t\t1.Create team\n\t\t\t\t2.View Teams\n\t\t\t\t3.Edit Team\n\t\t\t\t4.Delete Team\n\t\t\t\t5.Bolwing style codes\n\t\t\t\t6.Exit\n\t\t\t\tYour choice : “;
   choice = getch();
   switch(choice)
   {
      case ‘1’:
create();
goto start;
      case ‘2’:
view();
goto start;
      case ‘3’:
edit();
goto start;
      case ‘4’:
del();
goto start;
      case ‘5’:
blist();
goto start;
      case ‘6’:
break;
      default:
goto start;
   }
   return 0;
}
void agree()
{
 
   for(int i = 0; i < 80; i++)
     cout<<“Í”;
   cout<<“\n\n       \t\t\t\tNOTE\n\n”;
 
     cout<<“ÍIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIII”;
   cout<<“\n\n\n\t This program is meant for editing teams and players. \nYou will be required to input values for the same. It is recommended that you take the back up of \nthe folder in which this game is before editing any team or player because any invalid\n data can lead to incorrect working of the game. \nHowever, if you are confident that data given by you is valid, you need not take the back up. \nPlease note down the bowling style codes before creating or editing player.\n\n Enjoy the game!\n\n”;
   for(i = 0; i < 80; i++)
     cout<<“Í”;
   cout<<“(Press any key to continue)”;
   getch();
}
void list()
{
   int i = 0;
   not = 0;
   ifstream fin(“teams.log”);
   while(fin)
   {
      fin>>teamc[i];
      fin>>teams[i];
      not++;
      i++;
   }
   fin.close();
}
void create()
{
        char fn[7];
    ofstream fout;
    cout<<“\t\t\t\t\tCREATE TEAM\n”;
    for(int i = 0; i < 80; i++)
      cout<<“-“;
    cout<<“\n\nEnter the name of new team : “;
    cin>>t.tname;
    cout<<“Enter the 3 letter code(filename) for the team : “;
    again:
    cin>>fn;
    if(strlen(fn) != 3)
    {
      cout<<“Invalid code. Re-enter it : “;
      goto again;
    }
    else
    {
      strcpy(teams[not],t.tname);
      strcpy(teamc[not],fn);
      fout.open(“teams.log”);
      for(i = 0; i <= not; i++)
      {
fout<<teamc[i]<<endl<<teams[i]<<endl;
      }
      fout.close();
      strcat(fn,”.tem”);
      addplay(fn);
    }
    list();
    getch();
}
void edit()
{
 
   char fn[7],fn1[7],tn[20],tn1[20];
   char tname[20],code[7];
   ifstream fin;
   ofstream fout;
   cout<<“\t\t\t\t\tTEAM EDIT\n”;
   for(int i = 0; i < 80; i++)
     cout<<“-“;
   cout<<setiosflags(ios::left);
   cout<<“\t\t\t”<<setw(20)<<“Team Name”<<setw(5)<<“Code”<<endl<<endl<<endl;
   for(i = 0; i < not; i++)
      cout<<“\t\t\t”<<setw(20)<<teams[i]<<setw(5)<<teamc[i]<<endl;
   cout<<“\n\n\nEnter the team code(type ‘back’to go back to main menu) : “;
   repeat:
   cin>>fn;
   if(strcmp(fn,”back”))
   {
     strcpy(tn,fn);
     strcat(tn,”.tem”);
     fin.open(tn);
     if(fin.good() == 0)
     {
       cout<<“Team does not exist”;
       cout<<“\nRe-enter code : “;
       fin.close();
       goto repeat;
     }
     else
     {
       fin.close();
       cout<<“Loading, please wait…”;
       clrscr();
       t.load(tn);
       cout<<“\t\t\t\t\t”<<t.tname<<endl;
       for(i = 0; i < 80; i++)
cout<<“-“;
       cout<<“\n\n\t\t\t\t1.Edit team\n\t\t\t\t2.Edit Player”;
       switch(getch())
       {
 case ‘1’:
   t.teame();
   cout<<“\n\nOld Team Code : “;
   cout<<fn;
   cout<<“\nEnter the new code for team : “;
   rename:
   cin>>fn1;
   if(strlen(fn1) != 3)
   {
     cout<<“Invalid code. Re – enter code : “;
     goto rename;
   }
   else
   {
     strcpy(tn1,fn1);
     strcat(tn1,”.tem”);
     if(strcmp(fn,fn1))
t.save(tn1,tn);
     else
t.save(tn);
     fin.open(“teams.log”);
     fout.open(“temp.log”);
     while(fin)
     {
fin>>tn;
fin>>tn1;
if(strcmp(fn,tn))
{
  fout<<tn<<endl<<tn1<<endl;
}
else
{
  fout<<fn1<<endl<<t.tname<<endl;
}
     }
     fin.close();
     fout.close();
     remove(“teams.log”);
     rename(“temp.log”,”teams.log”);
     cout<<“Team successfully edited.”;
     list();
   }
   break;
 case ‘2’:
   t.pedit();
   t.save(tn);
   cout<<“Player edited successfully”;
   break;
       }
     }
   }
}
void del()
{
   
     char fn[7],tn[20];
     ofstream fout;
     ifstream fin;
     cout<<“\t\t\t\tDELETE TEAM\n”;
     for(int i = 0; i < 80; i++)
       cout<<“-“;
     cout<<setiosflags(ios::left);
     cout<<“\t\t\t”<<setw(20)<<“Team Name”<<setw(5)<<“Code”<<endl<<endl<<endl;
     for(i = 0; i < not; i++)
      cout<<“\t\t\t”<<setw(20)<<teams[i]<<setw(5)<<teamc[i]<<endl;
     cout<<“\n\n\nEnter the team code(type ‘back’to go back to main menu) : “;
     repeat:
     cin>>fn;
     if(strcmp(fn,”back”))
     {
strcpy(tn,fn);
strcat(tn,”.tem”);
remove(tn);
fin.open(“teams.log”);
fout.open(“temp.log”);
while(fin)
{
 fin>>tn;
 if(strcmp(tn,fn))
 {  fout<<tn<<endl;
    fin>>tn;
    fout<<tn<<endl;
 }
 else
 {
   fin>>tn;
 }
}
fin.close();
fout.close();
remove(“teams.log”);
rename(“temp.log”,”teams.log”);
     }
     list();
}
void addplay(char *fn)
{
    ofstream fout(fn);
   
    fout<<t.tname<<endl;
    cout<<“Enter the name, batting avg ,bowling avg, bowling style and batting strike rate of 11 players : \n”;
    for(int i = 0; i < 11; i++)
    {
       cout<<“\nName : “;
       cin>>t.bat[i].name;
       strcpy(t.bowl[i].name,t.bat[i].name);
       fout<<t.bat[i].name<<endl;
       cout<<“Batting avg : “;
       cin>>t.bat[i].avg;
       if(!strcmp(t.bat[i].name,”D.Bradman”))
t.bat[i].avg = 90;
       fout<<t.bat[i].avg<<endl;
       cout<<“Bowling avg : “;
       cin>>t.bowl[i].avg;
       if(!strcmp(t.bowl[i].name,”G.Mcgrath”))
 t.bowl[i].avg = 5;
       fout<<t.bowl[i].avg<<endl;
       bstyle:
       cin>>t.bowl[i].style;
       if(strcmp(t.bowl[i].style,”RF”) && strcmp(t.bowl[i].style,”LF”) && strcmp(t.bowl[i].style,”RLS”) && strcmp(t.bowl[i].style,”LLS”) && strcmp(t.bowl[i].style,”ROS”) && strcmp(t.bowl[i].style,”LOS”))
goto bstyle;
       fout<<t.bowl[i].style<<endl;
       cout<<“Batting strike rate : “;
       cin>>t.bat[i].sr;
       fout<<t.bat[i].sr<<endl;
    }
    fout.close();
    cout<<“\nTeam successfully created.”;
}
void blist()
{
   
    cout<<“\t\t\t\tBOWLING STYLES LIST\n”;
    for(int i = 0; i < 80; i++)
      cout<<“-“;
    cout<<“\n\n\n\t\t”<<setw(25)<<“STYLE”<<setw(15)<<“CODE”<<endl<<endl;
    cout<<“\t\t”<<setw(25)<<“Right arm fast”<<setw(15)<<“RF”<<endl;
    cout<<“\t\t”<<setw(25)<<“Left arm fast”<<setw(15)<<“LF”<<endl;
    cout<<“\t\t”<<setw(25)<<“Right arm leg spin”<<setw(15)<<“RLS”<<endl;
    cout<<“\t\t”<<setw(25)<<“Left arm leg spin”<<setw(15)<<“LLS”<<endl;
    cout<<“\t\t”<<setw(25)<<“Right arm off spin”<<setw(15)<<“ROS”<<endl;
    cout<<“\t\t”<<setw(25)<<“Left arm off spin”<<setw(15)<<“LOS”<<endl;
    cout<<“\n\n\n(Press any key to continue)”;
    getch();
}
void view()
{
 
   char fn[8],tn[8];
   ifstream fin;
   cout<<“\t\t\t\t\tVIEW TEAMS\n”;
   for(int i=0;i<80;i++)
     cout<<“-“;
     cout<<setiosflags(ios::left)<<setprecision(2);
   cout<<“\t\t\t”<<setw(20)<<“Team Name”<<setw(5)<<“Code”<<endl<<endl<<endl;
   for(i = 0; i < not; i++)
      cout<<“\t\t\t”<<setw(20)<<teams[i]<<setw(5)<<teamc[i]<<endl;
   cout<<“\n\n\nEnter the team code(type ‘back’to go back to main menu) : “;
   repeat10:
   cin>>fn;
   if(strcmp(fn,”back”))
   {
     strcpy(tn,fn);
     strcat(tn,”.tem”);
     fin.open(tn);
     if(fin.good() == 0)
     {
       cout<<“Team does not exist”;
       cout<<“\nRe-enter code : “;
       fin.close();
       goto repeat10;
     }
     else
     {
fin.close();

t.load(tn);
cout<<“\t\t\t\t”<<t.tname<<endl;
for(i = 0; i < 80; i++)
 cout<<“-“;
cout<<“\n\n”<<setw(20)<<“NAME”<<setw(15)<<“Bat. avg.”<<setw(15)<<“bowl.avg.”<<setw(15)<<“Bowl style”<<setw(15)<<“Bat. StrikeRate”;
cout<<endl;
for(i = 0; i < 11; i++)
 cout<<endl<<setw(20)<<t.bat[i].name<<setw(15)<<t.bat[i].avg<<setw(15)<<t.bowl[i].avg<<setw(15)<<t.bowl[i].style<<setw(15)<<t.bat[i].sr;
cout<<“\n\n\n(Press any key to continue)”;
getch();
     }
   }
}

BANKING PROJECT IN C++(TYPE 2)


#include<iostream>
#include<conio.h>
#include<math.h>
#include<stdlib.h>
using namespace std;

int p=1;

class Bank

    {
    public:
    char name[50],address[90],type;
    double ein_betrag, aus_betrag;
   double balance;
   int costumernr, accountnr, birth, tel;
   public:
         void newcostumer();    
         void newaccount();    
         void costumerdel();    
         void accountdel();    
         void deposit();  
         void withdraw();
         void accountinfo();
         void transaction();
};

void Bank::newcostumer()


    {
                 
        cout<<“\n Enter your name : ” << endl;
        cin>>name;
        cout << ” Enter your address: ” << endl;
             cin >>address;
        cout << ” your tel nr please: ” << endl;
        cin >>tel;
        cout << ” Enter your Date of birth: ” << endl;
        cin >>birth;
        cout<<“\n Enter your type of account :\n s for SAVING account \n f for FIXED account : “;
        cin>>type;
        cout<<“\nEnter your starting balance : Rs. “;
        cin>>balance;
             if(balance<10)
       {
       cout<<” The minimum balance is Rs. 100″;
       }
   accountnr=1000+p;
   cout<<” Your account number is : “<<accountnr<<” Always remember it”;
}
void Bank::costumerdel() {
       costumernr = 0;
        birth = 0;
       tel = 0;
       address[90] = 0;
}
void Bank::accountdel() {
        accountnr = 0;
       balance = 0;
       
       };
void Bank::deposit()


   {
   
   unsigned long int x;
   cout<<“\nEnter the amount to be deposited : “;
   cin>>x;
   balance=balance+x;
   cout<<“\n Your new balance is : Rs. “<<balance;
}

void Bank::withdraw()


   {
   
   unsigned long int x;
   cout<<“\n Your balance is : “<<balance;
   if(type==’s’)


        {
       cout<<“\nenter the amount to be withdrawn : “;
       cin>>x;
       if( x<=(balance-10))


           {
           balance-=x;
           cout<<“\nNew account balance is : “<<balance;
       }

        else
           {
           cout<<“\n Not possible for you “;
       }

   }

   else
   cout<<“\n NOT possible for you “;
}

void Bank::accountinfo()

   {
   cout<<“\n Hello “<<name<<” Your account balance is : “<<balance;
}

main()
   {
   
   char ch;int n,x;
   Bank e[100];
   star:cout<<“\n Are you a new user(y/n) : \n Press x To go out of system”;
   cin>>ch;
    if(ch==’y’||ch==’Y’)
        {
       e[p].newcostumer();
       p++;
            getch();      
       goto star;
   }
  else
       {
        if(ch==’x’||ch==’X’)
            {
           goto end;
       }
         else
       cout<<“\n Enter your account no. : “;
       cin>>n;
       n-=1000;
       if(n>0)


           {
            cout<<“\n Enter your choice \n 1.New Account \n 2.Costumer delete \n 3.Account delete \n 4.deposit \n 5.Withdrawal \n 6.Check your account\n 7.exit \n 8.To go out of system:”;
               cin>>x;
           while(x!=8)
               {
               switch(x)


                   {
                   case 1:
                   e[n].newcostumer();break;
                   case 2:
                   e[n].costumerdel();break;
                   case 3:
                   e[n].accountdel();break;
                   case 4:
                   e[n].deposit();break;
                        case 5:
                   e[n].withdraw();break;
                   case 6:
                   e[n].accountinfo();break;
                   case 7:
                             exit(1);
                        case 8:    
                    goto end;
                   default:
                   cout<<“\nInvalid”;
               }

                cout<<“\n Enter your choice \n 1.New Account \n 2.Costumer delete \n 3.Account delete \n 4.deposit \n 5.Withdrawal \n 6.Transaction \n 7.Check your account\n 8.exit \n 9.To go out of system:”;
               cin>>x;
           } goto star;

       }
       else
       cout<<“\nInvalid”;
   }end:;

}

BANKING PROJECT IN C++


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

 class Bank_Client
 {
 int AccountNo,Balance;
 char AccountHolder[20];
 public:
 Bank_Client();
 void withdraw();
 void deposit();
 void display();
 };

 void Bank_Client :: withdraw()
 {
      AccountNo=0;
 int amt,acono;
 cout<<“Enter the Account No=”;
 cin>>acono;
 if(AccountNo==acono)
 {
 cout<<“How much do u want to withdrawn=”;
 cin>>amt;
 if((Balance-amt)>=500)
 {
 Balance=Balance-amt;

 cout<<amt <<” Withdrawn Successfully\nYour balance is “<<Balance;
 }
 else
 {

 cout<<“\nU cannot able To withdrawn because min bal is 500\nUr bal is ” <<Balance;
 }
 }
 else
 {
 cout<<“Invalid Account No\n”;
 }
 }

 void Bank_Client :: deposit()
 {
 int amt,acono;
 cout<<“Enter the Account No=”;
 cin>>acono;
 if(AccountNo==acono)
 {
 cout<<“How much do u want to Deposite=”;
 cin>>amt;
 Balance=Balance+amt;

 cout<< amt <<” Deposited successfully” <<“\nUr balance is ” <<Balance;
 }
 else
 {

 cout<<“Invalid Account No\n”;
 }
 }

 void Bank_Client :: display()
 {
 cout<<“\nAccout No= “<<AccountNo <<“\nAccount Holder name= “<<AccountHolder <<“\nBalance= ” <<Balance;
 }

 Bank_Client :: Bank_Client()
 {
 AccountNo=1;
 strcpy(AccountHolder,”nit”);
 Balance=0;
 }

 main()
 {
 int choice;

 Bank_Client b;
 while(1)
 {
 cout<<“\nBank Operations”;
 cout<<“\n—————“;
 cout<<“\n1:Deposite\n2:Withdrawn\n3:Display\n4:Exit\nEnter ur choice:”;
 cin>>choice;
 switch(choice)
 {
 case 1: b.deposit();
 break;
 case 2: b.withdraw();
 break;
 case 3: b.display();
 break;
 case 4: exit(0);
 default:
 cout<<“\nWrong Choice\n”;
 break;
 }
 }
 getch();
 }

BANKING PROJECT MADE IN C


#include<iostream>
#include<conio.h>
#include<iomanip.h>

class bank
{
      private: int acc_no;
      char acc_ownr[20];
      char acc_type[2];
      int balance;
      public: bank()
              {
                    acc_no=0;
                    strcpy(acc_ownr,””);
                    strcpy(acc_type,””);
                    balance=0;
              }

 void crete_acc()
 { cout<<“\nname:”;
 cin>>acc_ownr;
 cout<<“account type(sv/cr/fd):”;
 cin>>acc_type;
 cout<<“account no.:”;
 cin>>acc_no;
 cout<<“ur account has been created.”;
 }

 void deposit(int dep)
 { balance=balance+dep;
 cout<<“\nRs.”;
 cout<<“\nnew balance:”<<balance; }

 void withdraw(int wit)
 { balance=balance-wit;
 cout<<“\nRs.”;
 cout<<“\nnew balance:”<<balance; }

 void show_acc()
 {
      cout<<“\nname:”<<acc_ownr;
      cout<<“\naccount name:”;
      cout<<“\naccount type:”<<acc_type;
      cout<<“\ncurrent balance:”<<balance;
 }
};

 main()
 { bank acc1;
 int ch,amt,count=0;

 for(;;)
 { if(count>0)
 break;
 else
 {
 cout<<“\nenter the desired operation”;
 cout<<“\n 1. create new account”;
 cout<<“\n 2. show account details”;
 cout<<“\n 3. deposit cash”;
 cout<<“\n 4. withdraw cash”;
 cout<<“\n 5. exit”;
 cout<<“\n ur choice:”;
 cin>>ch;
 switch(ch)
 { case 1: acc1.crete_acc();
 getch();
 break;
 case 2: acc1.show_acc();
 getch();
 break;
 case 3: cout<<“\nenter the amount to deposit:”;
 cin>>amt;
 acc1.deposit(amt);
 getch();
 break;
 case 4: cout<<“enter the amount to withdraw:”;
 cin>>amt;
 acc1.withdraw(amt);
 getch();
 break;
 case 5: count++;
 break;
 }
 }
 }
}

How can C Programs be so Reliable?


C is, today, a unique programming language. Surprisingly few people can really program in C and yet many of us have quite strong opinions about it. Buffer overflows, stack smashing, integer overflows – C has many well publicised flaws, and these terms are often bandied about confidently, even by those unfamiliar with C. Personally I shied away from C for a decade, for one reason or another: originally, compilers were expensive (this being the days before free UNIX clones were readily available) and slow; the culture was intimidatory; and, of course, all the C scare stories made me think that a mere mortal programmer such as myself would never be able to write a reliable C program.

Discounting a couple of tiny C modules that I created largely by blindly cutting and pasting from other places, the first C program I wrote was the Converge VM. Two things from this experience surprised me. First, writing C programs turned out not to be that difficult. With hindsight, I should have realised that a youth misspent writing programs in assembler gave me nearly all the mental tools I needed – after all, C is little more than a high-level assembly language. Once one has understood a concept such as pointers (arguably the trickiest concept in low-level languages, having no simple real-world analogy) in one language, one has understood it in every language. Second, the Converge VM hasn’t been riddled with bugs as I expected.
In fact, ignoring logic errors that would have happened in any language, only two C-specific errors have thus far caused any real problem in the Converge VM (please note, I’m sure there are lots of bugs lurking – but I’m happy not to have hit too many of them yet). One was a list which wasn’t correctly NULL terminated (a classic C error); that took a while to track down. The other was much more subtle, and took several days, spread over a couple of months, to solve. The Converge garbage collector can conservatively garbage collect arbitrary malloc‘d chunks of memory, looking for pointers. In all modern architectures, pointers have to live on word-aligned boundaries. However, malloc‘d chunks of memory are often not word-aligned in length. Thus sometimes the garbage collector would try and read the 4 bytes of memory starting at position 4 in a chunk – even if that chunk that was only 5 bytes long. In other words, the garbage collector tried to read in 1 byte of proper data and 3 bytes of possibly random stuff in an area of memory it didn’t theoretically have access to. The rare, and subtle, errors this led to were almost impossible to reason about. But let’s be honest – in how many languages can one retrospectively add a garbage collector?
My experience with the Converge VM didn’t really fit my previous prejudices. I had implicitly bought into the idea that C programs segfault at random, eat data, and generally act like Vikings on a day trip to Lindisfarne; in contrast, programs written in higher level languages supposedly fail in nice, predictable patterns. Gradually it occurred to me that virtually all of the software that I use on a daily basis – that to which I entrust my most important data – is written in C. And I can’t remember the last time there was a major problem with any of this software – it’s reliable in the sense that it doesn’t crash, and also reliable in the sense that it handles minor failures gracefully. Granted, I am extremely fussy about the software I use (I’ve been an OpenBSD user for 9 years or so, and software doesn’t get much better than that), and there are some obvious reasons as to why it might be so reliable: it’s used by (relatively) large numbers of people, who help shake out bugs; the software has been developed over a long period of time, so previous generations bore the brunt of the bugs; and, if we’re being brutally honest, only fairly competent programmers tend to use C in the first place. But still, the fundamental question remained: why is so much of the software I use in C so reliable?
After a dark period of paper writing, I’ve recently been doing a little bit of C programming. As someone who, at some points, spends far too much time away from home, reliably sending e-mail has always been an issue. For several years I have sent e-mail by piping messages to a sendmail process on a remote machine via ssh. While this solves several problems (e.g. blacklisting), it has the problem that on many networks (particularly wireless networks) a surprising number of network connections get dropped. Checking that each e-mail has been sent is a frustrating process. So, having mulled on its design for a little while, I decided to create a simple utility to robustly send e-mail via ssh. The resulting program – extsmail – has more features than I’d originally expected, but the basic idea is simply to retry sending messages via an external command such as ssh, until the message has been successfully sent. I also wanted the utility to be as frugal with resources as practical, and to be as portable as possible. This inevitably led to extsmail being written in C. I then decided, as an experiment, to try and write this, as far as possible, in the traditional UNIX way: only to rely on features found in all sensible UNIX clones and to be robust against failure. In so doing, I made two observations, new to me, about writing software in C.
The first observation is semi-obvious. Because software written in C can fail in so many ways, I was much more careful than normal when writing it. In particular, anything involved in manipulating chunks of memory raises the prospect of off-by-one type errors – which are particularly dangerous in C. Whereas in a higher-level language I might be lazy and thinkhmm, do I need to subtract 1 from this value when I index into the array? Let’s run it and find out, in C I thought OK, let’s sit down and reason about this. Ironically, the time taken to run-and-discover often seems not to be much different to sit-down-and-think – except the latter is a lot more mentally draining.
The second observation is something I had not previously considered. In C there is no exception handling. If, as in the case of extsmail, one wants to be robust against errors, one has to handle all possible error paths oneself. This is extremely painful in one way – a huge proportion (I would guess at least 40%) of extsmail is dedicated to detecting and recovering from errors – although made easier by the fact that UNIX functions always carefully detail how and when they will fail. In other words, when one calls a function like stat in C, the documentation lists all the failure conditions; the user can then easily choose which errors conditions he wishes his program to recover from, and which are fatal to further execution (in extsmail, out of memory errors are about the only fatal errors). This is a huge difference in mind-set from exception based languages, where the typical philosophy is to write code as normal, only rarely inserting try ... catch blocks to recover from specific errors (which are only sporadically documented). Java, with its checked exceptions, takes a different approach telling the user you must try and catch these specific exceptions when you call this function.
What I realised is that neither exception-based approach is appropriate when one wishes to make software as robust as possible. What one needs is to know exactly which errors / exceptions a function can return / raise, and then deal with each on a case-by-case basis. While it is possible that modern IDEs could (indeed, they may well do, for all I know) automatically show you some of the exceptions that a given function can raise, this can only go so far. Theoretically speaking, sub-classing and polymorphism in OO languages means that pre-compiled libraries can not be sure what exceptions a given function call may raise (since subclasses may overload functions, which can then raise different exceptions). From a practical point of view, I suspect that many functions would claim to raise so many different exceptions that the user would be overwhelmed: in contrast, the UNIX functions are very aware that they need to minimise the amount of errors that they return to the user, either by recovering from internal failure, or by grouping errors. I further suspect that many libraries that rely on exception handling would need to be substantially rewritten to reduce the number of exceptions they raise to a reasonable number. Furthermore, it is the caller of a function who needs to determine which errors are minor and can be recovered from, and which cause more fundamental problems, possibly resulting in the program exiting; checked exceptions, by forcing the caller to deal with certain exceptions, miss the point here.
Henry Spencer said, Those who don’t understand UNIX are doomed to reinvent it, poorly. And that’s probably why so many of the programs written in C are more reliable than our prejudices might suggest – the UNIX culture, the oldest and wisest in mainstream computing, has found ways of turning some of C’s limitations and flaws into advantages. As my experience shows, I am yet another person to slowly realise this. All that said, I don’t recommend using C unless much thought has been given to the decision – the resulting software might be reliable, but it will have taken a significant human effort to produce it.

C program to convert Days into Year months, weeks and leftover days


#include<stdio.h>
#include<conio.h>
main()
{
int days,month,week,year;
clrscr();
year=0;
printf("enter days");
scanf("%d" ,&days);
month=days/30;
days%=30;
week=days/7;
days%=7;
year=month/12;
printf("equivalent months=%d weeks=%d and·
leftoverdays=%d" ,month,week,days);
if (year>0)
{
printf("\n The Years are %d",year);
}
getch();
}

IOStreams in c++


By Manasij Mukherjee

One of the great strengths of C++ is its I/O system, IO Streams. As Bjarne Stroustrup says in his book “The C++ Programming Language”, “Designing and implementing a general input/output facility for a programming language is notoriously difficult”. He did an excellent job, and the C++ IOstreams library is part of the reason for C++’s success. IO streams provide an incredibly flexible yet simple way to design the input/output routines of any application.
IOstreams can be used for a wide variety of data manipulations thanks to the following features:
A ‘stream’ is internally nothing but a series of characters. The characters may be either normal characters (char) or wide characters (wchar_t). Streams provide you with a universal character-based interface to any type of storage medium (for example, a file), without requiring you to know the details of how to write to the storage medium. Any object that can be written to one type of stream, can be written to all types of streams. In other words, as long as an object has a stream representation, any storage medium can accept objects with that stream representation.
Streams work with built-in data types, and you can make user-defined types work with streams byoverloading the insertion operator (<<) to put objects into streams, and the extraction operator (>>) to read objects from streams.
The stream library.s unified approach makes it very friendly to use. Using a consistent interface for outputting to the screen and sending files over a network makes life easier. The programs below will show you what is possible.
The IO stream class hierarchy is quite complicated, so rather than introduce you to the full hierarchy at this point, I’ll start with explaining the concepts of the design and show you examples of streams in action. Once you are familiar with elements of the design and how to apply those concepts to design a robust I/O system for your software, an understanding of what belongs where in the hierarchy will come naturally.
What do input and output really mean?

To get a good idea about what input and output are, think of information as a stream of characters. This makes sense because whatever we enter through a keyboard can only be characters. Suppose the user enters the number 7479….WAIT…! How do you know the user entered a number? The problem is that you don’t really know. All you have is a set of 4 characters: ‘7’, ‘4’, ‘7’ and ‘9’. It is completely up to you, the programmer, whether you want the input to be a number, to be a string, or to be fodder for /dev/random; whether the characters can be valid for the desired type totally depends upon how whether that type can interpret the characters in the input stream as a description for an object of that type.
You have to get the input characters into a recognizable data type for them to be of any use other than as a character array.
IO streams not only defines the relation between a stream of characters and the standard data types but also allows you to define a relationship between a stream of characters and your own classes. It also allows you nearly limitless freedom to manipulate those streams both using object oriented interfaces and working directly on character buffers when necessary. (Of course some of the lower level manipulations may be undefined; for example, you can’t probe forward into an input stream to see the future!)
How do streams work?

Streams are serial interfaces to storage, buffers files, or any other storage medium. The difference between storage media is intentionally hidden by the interface; you may not even know what kind of storage you’re working with but the interface is exactly the same.
The “serial” nature of streams is a very important element of their interface. You cannot directly make random access random reads or writes in a stream (unlike, say, using an array index to access any value you want) although you can seek to a position in a stream and perform a read at that point.
Using a serial representation gives a consistent interface for all devices. Many devices have the capability of both producing and consuming data at the same time; if data is being continually produced, the simplest way to think about reading that data is by doing a fetch of the next characters in a stream. If that data hasn’t been produced yet (the user hasn’t typed anything, or the network is still busy processing a packet), you wait for more data to become available, and the read will return that data. Even if you try to seek past the end (or beginning) of a stream, the stream pointer (i.e. get or put pointer) will remain at the boundary, making the situation safe. (Compare this with accessing data off the end of an array, where the behavior is undefined.)
The underlying low-level interface that corresponds to the actual medium very closely is a character buffer (the stream buffer, technically called the streambuf), which can be thought of as the backbone of the stream. Being a buffer, it does not hold the entire content of the stream, if the stream is large enough, so you can’t use it for random access.
The most important of the basic stream operations are:
First, the stream is initialized with the appropriate type (like a std::string for a stringstream and the filename for an fstream) of values and suitable modes (like ios::in for input and ios::out for output and many more depending on the type of the stream).
After that, you can specify where the I/O should occur, through the get and put pointers. Depending on how you open the stream, the location may already be set appropriately (for example, if you open a file with ios::app, your get pointer set at the end of the stream, allowing appends).
The member functions associated with setting the get and put pointers are:
seekg()and seekp() for .dragging. the get and put pointer, respectively, to the position specified. Both seek methods take an argument (of type streampos) providing a position in the file relative to the beginning of the file (using ios::beg), the end of the file (using ios::end), or the current position (using ios::cur). You may also provide just a specific location, such as io::beg, for the beginning of the file.
tellg() and tellp() provide the current location of the get and put pointers, respectively
The following one-liners should clear up most questions:
1
2
3
4
5
seekg(0); seekg(0,ios::beg);         //sets the get pointer to the beginning.
seekg(5,ios::beg);      //sets the get pointer to 5 chars forward of the beginning.
tellp(); tellg()              //returns the current value of the put/get pointer
seekp(-10,ios::end);   //sets the put pointer to 10 chars before the end
seekp(1,ios::cur);      //proceeds to next char
N.B: Be careful when seeking the put pointer into the middle of in the stream. If you put anything in the stream, it will directly into the stream at the put location, overwriting the previous contents. In other words, if you need to insert data in the middle of a stream, you have to manually move the data that would be overwritten. As a side note, if you’re finding yourself doing that too often, then you may want to use a string representation of your data, which can simplify this kind of random access operation.
Once you’re at the right location in the stream, input and output is done through the << and >> operators. If you want to input an object to the stream, use the << operator; for output, use >>. The class for your object must, of course, have provided overloads for these methods. Here’s a short example:
1
2
3
4
5
6
//Inserts var into string (like objects are displayed by
// putting them to cout)
output_stream<<var;  
//Gets the value from the stream’s characters positioned
// after the get pointer and puts it into var.
input_stream>>var;    
If var is an object (either a built in class or a user defined type), the exact process of the input or output is dependent on the overloaded >> or << operator respectively.
Error handling with IO streams

Handling errors gracefully is important for building a robust system. The ‘errors’ or ‘signals’ (e.g., reaching the end of the file) in this case generally occur when a stream encounters something it didn’t expect.
Whether a stream is currently valid can be checked by simply by using the stream as a Boolean:
1
2
3
4
5
ifstream file( “test.txt” );
if ( ! file )
{
        cout << “An error occurred opening the file” << endl;
}
More detailed status of the stream can be obtained using the good(), bad(), fail() and eof() functions. The clear() function will reset the stream and clear the error, which is necessary to perform any further IO on the stream.
good() returns true when everything is okay.
bad() returns true when a fatal error has occurred.
fail() returns true after an unsuccessful stream operation like an unexpected type of input being encountered.
eof() returns true when the end of file is reached.
You can detect that a particular read or write operation failed by testing the result of the read. For example, to check that a valid integer is read from the user, you can do this:
1
2
3
4
5
int x;
if ( cin >> x )
{
        cout << “Please enter a valid number” << endl;
}
This works because the read operation returns a reference to the stream.
An example of creating a stream-enabled object

Here is a simple example of an utility designed for writing out logfile entries from command line arguments that takes advantage of some important stream facilities. If you don’t understand something, refer to the tutorial on that particular topic.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
#include <iostream>
#include <ctime>
#include <sstream>
#include <fstream>

using namespace std;

// timestamp returns the current time as a string
std::string timestamp();  

class LogStatement;
ostream& operator<<(ostream& ost, const LogStatement& ls);

class LogStatement
{
public:
        LogStatement(std::string s): data(s), time_string( timestamp() )
        { };

        //This method handles all the outputs.  
        friend ostream& operator<<(ostream&, const LogStatement&);
private:
        std::string data;
        std::string time_string;
 
};

ostream& operator<<(ostream& ost, const LogStatement& ls)
{
        ost<<“~|”<<ls.time_string<<‘|'<<ls.data<<“|~”;
        return ost;
}

std::string timestamp()
{
        //Notice the use of a stringstream, yet another useful stream medium!
        ostringstream stream;  
        time_t rawtime;
        tm * timeinfo;

        time(&rawtime);
        timeinfo = localtime( &rawtime );

        stream << (timeinfo->tm_year)+1900<<” “<<timeinfo->tm_mon
        <<” “<<timeinfo->tm_mday<<” “<<timeinfo->tm_hour
        <<” “<<timeinfo->tm_min<<” “<<timeinfo->tm_sec;
        // The str() function of output stringstreams return a std::string.
        return stream.str();
}

int main(int argc, char** argv)
{
        if(argc<2)
        {
              // A return of -1 denotes an error condition.
              return -1;
        }
        ostringstream log_data;
        // This takes all the char arrays in the argv
        // (except the filename) and produces a stream.
        for(int i=1;i<argc;i++)  
        {
               log_data<<argv[i]<<‘ ‘;
        }

        LogStatement log_entry(log_data.str());

        clog<<log_entry<<endl;

        ofstream logfile(“logfile”,ios::app);

        // check for errors opening the file
        if ( ! logfile )    
        {
                return -1;
        }    

        logfile<<log_entry<<endl;
        logfile.close();

        return 0;
}
This example should be pretty straightforward. The only two ‘new’ things here are:
The type ostream, which is the base class for any stream that accepts writes, such as ofstream and ostringstream. The standard stream objects: std::cout, std::cerr, std::clog and their ‘wide’ versions (e.g. std::wcout), are objects of this ostream class.
The use of stringstreams to simplify string handling. See the section on stringstreams below for more details on how stringstreams work.
A few other things to note

The << operator takes in an ostream object, modifies it and returns it, even though it would have been enough to take the ostream object and modify it, with no return value. The value of returning the object is that you can chain operations, as in the following statement:
1
cout<<“Hey, I’m “<< n <<” years old.”;
As the operator accepts an ostream, you can do anything with the data written to the stream simply by choosing a different subclass of ostream. The example shows writing to a file and to the system log console/file. You could also compress it and archive it, send it over a network, parse it later with another program to determine the number of log entries in a specified time interval, etc. Basically, you can use the class for any sort of output operation for which a subclass of ostream exists.
Parts of the IO stream library

Now that you’ve seen the basic problems solved by IO streams and how they work, let’s look at the different elements of the IO streams library, with a few examples of each in action.
Standard Stream Objects for Console I/O: (cout, cin, cerr, clog, etc.)

These are declared in the <iostream> header and provide a consistent interface for console I/O. They allow you a lot of control about the exact way you want to read a value from the stream into the given variable (or write the variable to the stream).
File I/O

File I/O is done by manually declaring objects of the ifstream, ofstream or fstream classes (from the <fstream> header) and then associating a file with the stream by using the stream’s open method with the file’s name as an argument. File I/O is particularly important because files are often used to represent a large variety of media, such as the console, devices, disk files, virtual memory, list of running processes and even the black hole ‘/dev/null’. This is especially true on *nix systems where it is commonly said that “Everything is a file”.
Here is a very very simple example of writing to a file:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <iostream>
#include <fstream>

using namespace std;

int main()
{
        ofstream ofs(“a.txt”,ios::app);
        if(ofs.good())
        {
                ofs<<“Hello a.txt, I’m appending this on you.”;
        }
        return 0;
}
String Streams

Strings are streams and streams are strings. Both are character arrays, but each has a totally different interface (random access strings vs serial stringstreams). By providing both std::string and stringstreams, the C++ standard library ensures that you have the flexibility to choose either interface for your design.
By including the <sstream> header, you can make objects of the istringstream, ostringstream and stringstream types. These objects make certain kinds of string manipulations much easier.
You can, for example, open a string in a stringstream, extract a floating point number from it to do some operations, and put it back in the stream.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#include <iostream>
#include <sstream>

using namespace std;

int main()
{
        stringstream my_stream(ios::in|ios::out);
        std::string dat(“Hey, I have a double : 74.79 .”);

        my_stream.str(dat);
        my_stream.seekg(-7,ios::end);

        double val;
        my_stream>>val;

        val= val*val;

        my_stream.seekp(-7,ios::end);
        my_stream<<val;

        std::string new_val = my_stream.str();
        cout<<new_val;

        return 0;
}
The output is
Hey, I have a double : 5593.54
The lower level, where streams meet buffers

This is the most interesting and confusing part of this library, letting you manipulate streams at their lowest levels, bytes and bits. This is accomplished by the abstract class streambuf from which stringbuf and filebuf are derived. Every stream object has one of those as their backbones. Their function rdbuf() lets you access a pointer to the underlying stream buffer.
Here is a very simple example of copying a file efficiently with those buffers (thankfully, no ultra-complicated manipulation is involved here!).
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <iostream>
#include <fstream>
using namespace std;

int main()
{
        ifstream ifs(“a.txt”);
        //ios::trunc means that the output file will be overwritten if exists
        ofstream ofs(“a.txt.copy”, ios::trunc);
        if (ifs &&  ofs )
        {
                ofs<<ifs.rdbuf();
        }

        return 0;
}

The Hows and Whys of Commenting C and C++ Code


Programs are meant to be beautiful. If someone tells you otherwise, you’d probably do best not to listen to the rest of his advice. A good program is beautiful in both its concept — the algorithm used, the design, the flow of control — but also in its readability. Good code is not replete with question mark colon operators and pointer arithmetic, or at least not when the code doesn’t need to be optimized to save a few seconds every few months of operation. But readable code, while a nice ideal, often requires some help from the English (or from some other) language. Sometimes the algorithm is too complex to be understood rapidly or completely without some explanation, or the code requires some esoteric function call from the C library that has both a cryptic and a misleading name. And if you ever plan to code for a living, you will almost certainly have to go back several years later to modify the one section of code that you didn’t feel like commenting — or someone else will, and will curse your name. Finally, commenting code can also lead to a better understanding of the program and may help uncover bugs before testing. For both aesthetic and practical reasons, good commenting is an essential and often overlooked programming skill.

Before discussing how to comment, a few words of warning: it is possible to comment too much. Just as good writing is spare, so too is good coding. You do not want to include a comment telling the reader something obvious, or something that can be discerned from a single line of code. (You are probably not writing your code to teach someone how to program!) For instance, “int callCount = 0; //declares an integer variable,” conveys no meaningful information. Comments should reveal the underlying structure of the code, not the surface details. A more meaningful comment would be “int callCount = 0; //holds number of calls to [function].”

Comments should not be overly long. Comments should not give details for the sake of details; only when a fact is necessary or interesting should it be brought to the attention of the program’s reader. If you were reading someone else’s program, you would not want to be forced to pick through paragraphs of text describing the intricacies of a for loop’s operation only to realize that you could have discovered the same information simply by having read the for loop.

For the sake of future readers, you should generally include some header information at the top of your program. This information may include your name and contact information, the date the code was last modified, the purpose of the program, and if necessary, a brief exposition of the algorithm used or the design decisions made. You may also want to include a list of known bugs, inefficiencies, or suggestions for improvement. It is convenient to demarcate this section of the program file in a large comment block of the form

/********
* *
* *
********/

This form of comment is best done at the end of the program, except perhaps for an overview of the algorithm, which you may find helps to crystallize your thoughts when you are dealing with new, confusing, or complex concepts.

Second, whenever you create a new class or a new function definition, you should add a comment explaining what the class or function does. For a class, you should explain the purpose of the class, what publicly accessible functions and variables are available, any limitations of the class, and information that the programmer may need if he or she wanted to inherit from the class. When defining a function, you should describe what the function does and whether or not it has side effects such as changing global variables, interacting with the user, or so forth. It is also convenient to describe what sort of arguments the function takes and what, if any, value it returns: e.g., if you have a function findTime(int distance, int speed), you would want to tell the user that the distance is in rods, and the speed is in furlongs per fortnight, and that the function returns the time taken by the travel in epochs.

You could make the variable names more descriptive, but the increased descriptiveness is unnecessary inside the function because the relationship between distance and speed is the significant feature, not the relationship between distanceinrods and speedinfurlongsperfortnight. As you can see, long names are unnecessarily complex and can lead to hard-to-find typos. In general, variable names should be only descriptive enough to express the relationship between variables. Any implementation details should be handled by comments at points where the details may matter. For instance, in the above function, the function’s caller must know the units, but those units do not matter inside the function (except when conversions are being made, but the programmer should make a note of this at the time of the conversion). In order to avoid confusion, you should eschew abbreviations; a word can be abbreviated many ways, and a single abbreviation can describe more than one word. Avoiding abbreviations avoids this problem.

Third, when adding comments directly to your code, be spare. The less you say, the better; if you force yourself to be precise, you will make the comments more helpful, and you will force yourself to synthesize the flow of your program rather than allow yourself to repeat what the code already tells the user. The code should fit seamlessly into the algorithm rather than wrap entirely around it and smother the logic embedded in the C++.

Fourth, good commenting can improve your programming. You can use them as an organizational device by including comments prior to filling in code — for instance, when you have a long block of conditional statements, you may wish to comment what should happen when each conditional is executed before you flesh out the code. In doing so, you save yourself the burden of remembering the details of the entire program, allowing you to concentrate on the implementation of one aspect at a time. Additionally, when you force yourself to comment during the programming process, you cannot get away with writing code that “you hope will work” if you make yourself explain why it works. (Keep in mind that if the code is so complex that you don’t know how it works, then you probably should be commenting it for the sake of both yourself and others.)

Finally, keep in mind that what seems obvious now may not seem obvious later. While you shouldn’t excessively comment, do make sure to comment things that are nonstandard algorithms. You do not need to comment a programming idiom, but you do want to comment an algorithm you designed for the program, no matter how simple it may seem to you. No doubt it will seem foreign three weeks after you write the code, and if you plan (and even if you do not plan) to come back to the code, it will be immeasurably helpful.

Comments are for yourself and others. You may be forced to work with uncommented code, and it helps to comment the code as you work through what it does. This can be as simple as renaming the variable names from, say, r, x, and y to currentNumber, largestPrime, and currentDivisor. With any luck, after one or two of these experiences you will recognize the wisdom of commenting your code. Moreover, you will see the greater elegance of a well-commented, carefully written piece of code in comparison to a hack thrown together only to “work.”

Programming Style, Naming Conventions


Good naming can make a huge difference in program readability. Names like proc1, proc2, and proc3 mean next-to-nothing, but even apparently decent names can be ambiguous. For instance, to name a function that takes two ranges and computes the amount of the first that lies within the second, names like computeRangeWithinRange might sound reasonable. Unfortunately, this name gives no information about the order of arguments to the function. Sometimes this won’t be a problem because an intelligent IDE should help you determine the names of the arguments to the function, but it can be confusing when the code is printed, or when you try to quickly read through the code. A better name might be computeRangeWithinFirstRange, which at least gives a sense of the order of the arguments to the function.

General Naming Conventions

It’s usually best to choose a consistent set of naming conventions for use throughout your code. Naming conventions usually govern things such as how you capitalize your variables, classes, and functions, whether you include a prefix for pointers, static data, or global data, and how you indicate that something is a private field of a class.

There are a lot of common naming conventions for classes, functions and objects. Usually these are broken into several broad categories: c-style naming, camelCase, and CamelCase. C-style naming separates words in a name using underscores: this_is_an_identifer. There are two forms of camelCase: one that begins with a lowercase letter and then capitalizes the first letter of every ensuing word, and one that capitalizes the first letter of every single word.

One popular convention is that leading capital letter CamelCase is used for the names of structs and classes, while normal camelCase is used for the names of functions and variables (although sometimes variables are written in c-style to make the visual separation between functions and variables more clear).

It can be useful to use prefixes for certain types of data to remind you what they are: for instance, if you have a pointer, prefixing it with “p_” tells you that it’s a pointer. If you see an assignment between a variable starting with “p_” and one that doesn’t begin with “p_”, then you immediately know that something fishy is going on. It can also be useful to use a prefix for global or static variables because each of these has a different behavior than a normal local variable. In the case of global variables, it is especially useful to use a prefix in order to prevent naming collisions with local variables (which can lead to confusion).

Finally, a common convention is to prefix the private fields and methods of a class with an underscore: e.g., _private_data. This can make it easier to find out where to look in the body of a class for the declaration of a method, and it also helps keep straight what you should and should not do with a variable. For instance, a common rule is to avoid returning non-const references to fields of a class from functions that are more public than the field. For instance, if _age is a private field, then the public getAge function probably shouldn’t return a non-const reference since doing so effectively grants write access to the field!

Hungarian Notation

Hungarian notation has commonly been associated with prefixing variables with information about their type–for instance, whether a variable is an integer or a double. This is usually not a useful thing to do because your IDE will tell you the type of a variable, and it can lead to bizarre and complicated looking names. The original idea behind Hungarian notation, however, was more general and useful: to create more abstract “types” that describe how the variable is used rather than how the variable is represented. This can be useful for keeping pointers and integers from intermixing, but it can also be a powerful technique for helping to separate concepts that are often used together, but that should not be mixed.

Abbreviations

Abbreviations are dangerous–vowels are useful and can speed up code reading. Resorting to abbreviations can be useful when the name itself is extremely long because names that are too long can be as hard to read as names that are too short. When possible, be consistent about using particular abbreviations, and restrict yourself to using only a small number of them.

Common abbreviations include “itr” for “iterator” or “ptr” for pointer. Even names like i, j, and k are perfectly fine for loop counter variables (primarily because they are so common). Bad abbreviations include things like cmptRngFrmRng, which at the savings of only a few letters eliminates a great deal of readability. If you don’t like typing long names, look into the auto-complete facilities of your text editor. You should rarely need to type out a full identifier. (In fact, you rarely want to do this: typos can be incredibly hard to spot.)

Good Programming Style


Consistency


One of the hallmarks of good programming style is consistency–the fewer surprises, the better. Consistency makes it easier to read the program primarily by reducing distractions. But it also helps guide the reader’s eyes, for example, by being consistent about ordering functions or including files to simplify finding them in the future. It also makes it easier to deal with other style problems by making it easier for the reader to get used to them.

Clarity

Good style is about making your program clear and understandable as well as easily modifiable. When in doubt, choose the most easily understood technique for a problem. Remember that whatever you write, you will likely have to read at some point after you remember exactly what you were thinking. Do your future self a favor and be clear the first time.

Whitespace and Formatting

Whitespace can set things off and reduce the strain on the reader’s eyes. Because the compiler ignores whitespace, you’re free to place things anywhere you want and format it however you want. If you choose wisely, this can be a boon.

Whitespace comes in several forms, including indentation, how you put space around operators, how you lay out function signatures, and where you place arguments to functions. Of course, this is hardly everything covered by whitespace, but it should give you an idea of the many places whitespace can be used to improve readability.

Indentation

If you don’t indent your code, you soon will. It’s just a natural thing to do because it lets you use your eye to quickly pick out the flow of control or mistakes in that flow of control. The quick primer on indentation is that you should indent every block of code:

if ( true )
{
// code block
}

Brace Styles

There are a variety of ways to indent code, and many of them are tied to where you place your braces. Some people prefer the style used above. Some people prefer the style below:

if ( true ) {
// code block
}

Other styles include

if ( true )
{
// code block
}

or even

if ( true )
{
// code block
}

Any brace style you choose is up to you, although I’d recommend using the same brace style as everyone else working on your project. At any rate, there are arguments for each style. A good consideration is to use a brace style that allows you to put as much code on a screen at a time, but consistency with past practices is probably just as important.

Indentation Depth

How far you choose to indent is a matter of personal preference–in any case, it’s usually best to choose an indentation size that’s small enough to comfortably fit your code on one screen. I’ve found that any indentation width from 2 to 8 is reasonable and readable, although I’ve found that anything over four spaces for indentation can lead to lines that are too long.

In general, the best solution to dealing with lines that are too long is to reduce the complexity of the code or at least to pull out some functionality into separate functions. Doing so will reduce the number of levels of indentation and can make the code more readable (if it is done correctly).

Tabs vs. Spaces

There is something of an argument over whether to indent using tabs or spaces. Note that this is not the same as asking whether you indent with the spacebar or the tab–most people let their editors take care of that problem for them (or choose to have tabs expanded to spaces).

The real issue of tabs vs. spaces is what happens when someone else opens your code. Since you can set tabs to take up any number of columns, the person opening your code might not have the same tabstop width. This can play havoc with otherwise well-formatted code. Using only spaces fixes this problem because it will always display the same way for everyone.

Sometimes a decent code formatter, such as might be found in your text editor, can help mitigate this problem by reformatting the code. You can also play with your own tab settings to display the code correctly (although this is obviously annoying).

The best solution, if you do decide to use tabs, is to be very careful with what you use tabs for. The real problem, in fact, comes up when tabs are used not just for indentation but also as a quick way of moving four or eight characters to the right. For instance, let’s look at the following code:

if ( a_long_case_number_one_stretching_across_most_of_the_screen &&
a_long_case_number_two_also_stretching_across_most_of_the_screen )
{
// code
}

If the second condition had been formatted using a tab with a four-space indent followed by a space, then when loaded with a tab-width of eight, it would look ugly:

if ( a_long_case_number_one_stretching_across_most_of_the_screen &&
a_long_case_number_two_also_stretching_across_most_of_the_screen )
{
// code
}

If spaces were used for the formatting, it would open correctly:

if ( a_long_case_number_one_stretching_across_most_of_the_screen &&
a_long_case_number_two_also_stretching_across_most_of_the_screen )
{
// code
}

Mis-Use of Whitespace

How much white space you use is, to some extent, a personal choice. There are some issues to be aware of. First, the more your whitespace helps emphasize the logic of your program, the better; you don’t want your whitespace to “lie”. This might not confuse the you-at-this-moment, but it can confuse the you-of-the-future or just someone else reading your code. What does lying look like?

if ( true )
++i;
++j;

The indentation makes it look like both statements get executed when the if statement executes–but that’s not what actually happens. When you’re tracking down a bug or syntax error in hundreds or thousands of lines of code, you may end up doing a visual scan instead of checking every line carefully. The easier you make it to scan the code and pick out salient details, the faster you can scan without making mistakes.

Programming Style: Writing for Readability


There are a lot of ways to solve the same problem in C or C++. This is both good and bad; it is good because you have flexibility. It’s also bad because you have flexibility–the flexibility to choose different solutions to the same problem when it shows up in different places. This is confusing because it obscures the underlying similarity between the problems.

Using Functions

Unlike prose, where repeating the same word or phrase may seem redundant, in programming, it’s perfectly fine to use the same construction over and over again. Of course, you may want to turn a repeated chunk of code into a function: this is even more readable because it gives the block of code a descriptive name. (At least you ought to make it descriptive!) You can also increase readability by using standard functions and data structures (such as the STL). Doing so avoids the confusion of someone who might ask, “why did you create a new function when you had a perfectly good one already available?” The problem is that people may assume that there’s a reason for the new function and that it somehow differs from the standard version. Moreover, by using standard functions you help your reader understand the names of the arguments to the function. There’s much less need to look at the function prototype to see what the arguments mean, or their order, or whether some arguments have default values.

Use Appropriate Language Features

There are some obvious things to avoid: don’t use a loop as though it were an if statement. Choose the right data type for your data: if you never need decimal places in a number, use an integer. If you mean for a value to be unsigned, used an unsigned number. When you want to indicate that a value should never change, use const to make it so. Try to avoid uncommon constructions unless you have good reason to use them; put another way, don’t use a feature just because the feature exists. One rule of thumb is to avoid do-while loops unless you absolutely need one. People aren’t generally as used to seeing them and, in theory, won’t process them as well. I’ve never run into this problem myself, but think carefully about whether you actually need a do-while loop. Similarly, although the ternary operator is a great way of expressing some ideas, it can also be confusing for programmers who don’t use it very often. A good rule of thumb is to use it only when necessary (for instance, in the initialization list of a constructor) and stick with the more standard if-else construction for everything else. Sure, it’ll make your program four lines longer, but it’ll make it that much easier for most people to read. There are some less obvious ways of using standard features. When you are looping, choose carefully between while, do-while, and for. For loops are best when you can fill in each part (initialization, conditional, and increment) with a fairly short expression. While loops are good for watching a sentinel variable whose value can be set in multiple places or whose value depends on some external event such as a network event. While loops are also better when the update step isn’t really a direct “update” to the control variable–for instance, when reading lines from a text file, it might more sense to use a while loop than a for loop because the control depends on the result of the method call, not the value of the variable of interest:while (fgets(buf, sizeof(buf), fp) != NULL)

{
/* do stuff with buf */


}

It wouldn’t make sense to write this sort of thing as a for loop. (Try it!)

Unpack Complex Expressions

There’s no reason to put everything on a single line. If you have a complex calculation with multiple steps and levels of parentheses, it can be extremely helpful to go from a one-line calculation to one that uses temporary variables. This gives you two advantages; first, it makes it easier to follow the expression. Second, you can give a distinct name to each intermediate step, which can help the reader follow what is happening. Often, you’ll want to reuse those intermediate calculations anyway. In addition to mathematical calculations, this principle also applies to nested function calls. The fewer events that take place on a single line of code, the easier it is to follow exactly what’s happening. Another advantage to unpacking an expression is that you can put more comments in-line to explain what’s going on and why.

Avoid Magic Numbers

Magic numbers are numbers that appear directly in the code without an obvious reason. For instance, what does the number 80 in the following expression mean?for( int i = 0; i < 80; ++i )

{
printf( "-" );


}

It might be the width of the screen, but it might also be the width of a map whose wall is being drawn. You just don’t know. The best solution is to use macros, in C, or constants in C++. This gives you the chance to descriptively name your numbers. Doing so also makes it easier to spot the use of a particular number and differentiate between numbers with the same value that mean different things. Moreover, if you decide you need to change a value, you have a single point where you can make the change, rather than having to sift through your code.

The Stack Data Structure in C and C++


The stack is a common data structure for representing things that need to maintained in a particular order. For instance, when a function calls another function, which in turn calls a third function, it’s important that the third function return back to the second function rather than the first.

One way to think about this implementation is to think of functions as being stacked on top of each other; the last one added to the stack is the first one taken off. In this way, the data structure itself enforces the proper order of calls.

Conceptually, a stack is simple: a data structure that allows adding and removing elements in a particular order. Every time an element is added, it goes on the top of the stack; the only element that can be removed is the element that was at the top of the stack. Consequently, a stack is said to have “first in last out” behavior (or “last in, first out”). The first item added to a stack will be the last item removed from a stack.

So what’s the big deal? Where do stacks come into play? As you’ve already seen, stacks are a useful way to organize our thoughts about how functions are called. In fact, the “call stack” is the term used for the list of functions either executing or waiting for other functions to return.

In a sense, stacks are part of the fundamental language of computer science. When you want to express an idea of the “first in last out” variety, it just makes sense to talk about it using the common terminology. Moreover, such operations show up an awful lot, from theoretical computer science tools such as a push-down automaton to AI, including implementations of depth-first search.

Stacks have some useful terminology associated with them:

  • Push To add an element to the stack
  • Pop To remove an element from the stock
  • Peek To look at elements in the stack without removing them
  • LIFO Refers to the last in, first out behavior of the stack
  • FILO Equivalent to LIFO